display_server_x11.cpp 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479
  1. /**************************************************************************/
  2. /* display_server_x11.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "display_server_x11.h"
  31. #ifdef X11_ENABLED
  32. #include "x11/detect_prime_x11.h"
  33. #include "x11/key_mapping_x11.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/math/math_funcs.h"
  36. #include "core/string/print_string.h"
  37. #include "core/string/ustring.h"
  38. #include "drivers/png/png_driver_common.h"
  39. #include "main/main.h"
  40. #include "scene/resources/atlas_texture.h"
  41. #if defined(VULKAN_ENABLED)
  42. #include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
  43. #endif
  44. #if defined(GLES3_ENABLED)
  45. #include "drivers/gles3/rasterizer_gles3.h"
  46. #endif
  47. #include <dlfcn.h>
  48. #include <limits.h>
  49. #include <stdio.h>
  50. #include <stdlib.h>
  51. #include <string.h>
  52. #include <sys/stat.h>
  53. #include <sys/types.h>
  54. #include <unistd.h>
  55. #undef CursorShape
  56. #include <X11/XKBlib.h>
  57. // ICCCM
  58. #define WM_NormalState 1L // window normal state
  59. #define WM_IconicState 3L // window minimized
  60. // EWMH
  61. #define _NET_WM_STATE_REMOVE 0L // remove/unset property
  62. #define _NET_WM_STATE_ADD 1L // add/set property
  63. // 2.2 is the first release with multitouch
  64. #define XINPUT_CLIENT_VERSION_MAJOR 2
  65. #define XINPUT_CLIENT_VERSION_MINOR 2
  66. #define VALUATOR_ABSX 0
  67. #define VALUATOR_ABSY 1
  68. #define VALUATOR_PRESSURE 2
  69. #define VALUATOR_TILTX 3
  70. #define VALUATOR_TILTY 4
  71. //#define DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  72. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  73. #define DEBUG_LOG_X11(...) printf(__VA_ARGS__)
  74. #else
  75. #define DEBUG_LOG_X11(...)
  76. #endif
  77. static const double abs_resolution_mult = 10000.0;
  78. static const double abs_resolution_range_mult = 10.0;
  79. // Hints for X11 fullscreen
  80. struct Hints {
  81. unsigned long flags = 0;
  82. unsigned long functions = 0;
  83. unsigned long decorations = 0;
  84. long inputMode = 0;
  85. unsigned long status = 0;
  86. };
  87. static String get_atom_name(Display *p_disp, Atom p_atom) {
  88. char *name = XGetAtomName(p_disp, p_atom);
  89. ERR_FAIL_NULL_V_MSG(name, String(), "Atom is invalid.");
  90. String ret;
  91. ret.parse_utf8(name);
  92. XFree(name);
  93. return ret;
  94. }
  95. bool DisplayServerX11::has_feature(Feature p_feature) const {
  96. switch (p_feature) {
  97. case FEATURE_SUBWINDOWS:
  98. #ifdef TOUCH_ENABLED
  99. case FEATURE_TOUCHSCREEN:
  100. #endif
  101. case FEATURE_MOUSE:
  102. case FEATURE_MOUSE_WARP:
  103. case FEATURE_CLIPBOARD:
  104. case FEATURE_CURSOR_SHAPE:
  105. case FEATURE_CUSTOM_CURSOR_SHAPE:
  106. case FEATURE_IME:
  107. case FEATURE_WINDOW_TRANSPARENCY:
  108. //case FEATURE_HIDPI:
  109. case FEATURE_ICON:
  110. #ifdef DBUS_ENABLED
  111. case FEATURE_NATIVE_DIALOG:
  112. #endif
  113. //case FEATURE_NATIVE_ICON:
  114. case FEATURE_SWAP_BUFFERS:
  115. #ifdef DBUS_ENABLED
  116. case FEATURE_KEEP_SCREEN_ON:
  117. #endif
  118. case FEATURE_CLIPBOARD_PRIMARY:
  119. case FEATURE_TEXT_TO_SPEECH:
  120. case FEATURE_SCREEN_CAPTURE:
  121. return true;
  122. default: {
  123. }
  124. }
  125. return false;
  126. }
  127. String DisplayServerX11::get_name() const {
  128. return "X11";
  129. }
  130. void DisplayServerX11::_update_real_mouse_position(const WindowData &wd) {
  131. Window root_return, child_return;
  132. int root_x, root_y, win_x, win_y;
  133. unsigned int mask_return;
  134. Bool xquerypointer_result = XQueryPointer(x11_display, wd.x11_window, &root_return, &child_return, &root_x, &root_y,
  135. &win_x, &win_y, &mask_return);
  136. if (xquerypointer_result) {
  137. if (win_x > 0 && win_y > 0 && win_x <= wd.size.width && win_y <= wd.size.height) {
  138. last_mouse_pos.x = win_x;
  139. last_mouse_pos.y = win_y;
  140. last_mouse_pos_valid = true;
  141. Input::get_singleton()->set_mouse_position(last_mouse_pos);
  142. }
  143. }
  144. }
  145. bool DisplayServerX11::_refresh_device_info() {
  146. int event_base, error_base;
  147. print_verbose("XInput: Refreshing devices.");
  148. if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) {
  149. print_verbose("XInput extension not available. Please upgrade your distribution.");
  150. return false;
  151. }
  152. int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR;
  153. int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR;
  154. if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) {
  155. print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query));
  156. xi.opcode = 0;
  157. return false;
  158. }
  159. if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) {
  160. print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.",
  161. XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query));
  162. }
  163. xi.absolute_devices.clear();
  164. xi.touch_devices.clear();
  165. xi.pen_inverted_devices.clear();
  166. xi.last_relative_time = 0;
  167. int dev_count;
  168. XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count);
  169. for (int i = 0; i < dev_count; i++) {
  170. XIDeviceInfo *dev = &info[i];
  171. if (!dev->enabled) {
  172. continue;
  173. }
  174. if (!(dev->use == XISlavePointer || dev->use == XIFloatingSlave)) {
  175. continue;
  176. }
  177. bool direct_touch = false;
  178. bool absolute_mode = false;
  179. int resolution_x = 0;
  180. int resolution_y = 0;
  181. double abs_x_min = 0;
  182. double abs_x_max = 0;
  183. double abs_y_min = 0;
  184. double abs_y_max = 0;
  185. double pressure_min = 0;
  186. double pressure_max = 0;
  187. double tilt_x_min = 0;
  188. double tilt_x_max = 0;
  189. double tilt_y_min = 0;
  190. double tilt_y_max = 0;
  191. for (int j = 0; j < dev->num_classes; j++) {
  192. #ifdef TOUCH_ENABLED
  193. if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) {
  194. direct_touch = true;
  195. }
  196. #endif
  197. if (dev->classes[j]->type == XIValuatorClass) {
  198. XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j];
  199. if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) {
  200. resolution_x = class_info->resolution;
  201. abs_x_min = class_info->min;
  202. abs_x_max = class_info->max;
  203. absolute_mode = true;
  204. } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) {
  205. resolution_y = class_info->resolution;
  206. abs_y_min = class_info->min;
  207. abs_y_max = class_info->max;
  208. absolute_mode = true;
  209. } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) {
  210. pressure_min = class_info->min;
  211. pressure_max = class_info->max;
  212. } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) {
  213. tilt_x_min = class_info->min;
  214. tilt_x_max = class_info->max;
  215. } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) {
  216. tilt_y_min = class_info->min;
  217. tilt_y_max = class_info->max;
  218. }
  219. }
  220. }
  221. if (direct_touch) {
  222. xi.touch_devices.push_back(dev->deviceid);
  223. print_verbose("XInput: Using touch device: " + String(dev->name));
  224. }
  225. if (absolute_mode) {
  226. // If no resolution was reported, use the min/max ranges.
  227. if (resolution_x <= 0) {
  228. resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult;
  229. }
  230. if (resolution_y <= 0) {
  231. resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult;
  232. }
  233. xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y);
  234. print_verbose("XInput: Absolute pointing device: " + String(dev->name));
  235. }
  236. xi.pressure = 0;
  237. xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max);
  238. xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max);
  239. xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max);
  240. xi.pen_inverted_devices[dev->deviceid] = String(dev->name).findn("eraser") > 0;
  241. }
  242. XIFreeDeviceInfo(info);
  243. #ifdef TOUCH_ENABLED
  244. if (!xi.touch_devices.size()) {
  245. print_verbose("XInput: No touch devices found.");
  246. }
  247. #endif
  248. return true;
  249. }
  250. void DisplayServerX11::_flush_mouse_motion() {
  251. // Block events polling while flushing motion events.
  252. MutexLock mutex_lock(events_mutex);
  253. for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) {
  254. XEvent &event = polled_events[event_index];
  255. if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  256. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  257. if (event_data->evtype == XI_RawMotion) {
  258. XFreeEventData(x11_display, &event.xcookie);
  259. polled_events.remove_at(event_index--);
  260. continue;
  261. }
  262. XFreeEventData(x11_display, &event.xcookie);
  263. break;
  264. }
  265. }
  266. xi.relative_motion.x = 0;
  267. xi.relative_motion.y = 0;
  268. }
  269. #ifdef SPEECHD_ENABLED
  270. bool DisplayServerX11::tts_is_speaking() const {
  271. ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  272. return tts->is_speaking();
  273. }
  274. bool DisplayServerX11::tts_is_paused() const {
  275. ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  276. return tts->is_paused();
  277. }
  278. TypedArray<Dictionary> DisplayServerX11::tts_get_voices() const {
  279. ERR_FAIL_NULL_V_MSG(tts, TypedArray<Dictionary>(), "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  280. return tts->get_voices();
  281. }
  282. 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) {
  283. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  284. tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
  285. }
  286. void DisplayServerX11::tts_pause() {
  287. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  288. tts->pause();
  289. }
  290. void DisplayServerX11::tts_resume() {
  291. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  292. tts->resume();
  293. }
  294. void DisplayServerX11::tts_stop() {
  295. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  296. tts->stop();
  297. }
  298. #endif
  299. #ifdef DBUS_ENABLED
  300. bool DisplayServerX11::is_dark_mode_supported() const {
  301. return portal_desktop->is_supported();
  302. }
  303. bool DisplayServerX11::is_dark_mode() const {
  304. switch (portal_desktop->get_appearance_color_scheme()) {
  305. case 1:
  306. // Prefers dark theme.
  307. return true;
  308. case 2:
  309. // Prefers light theme.
  310. return false;
  311. default:
  312. // Preference unknown.
  313. return false;
  314. }
  315. }
  316. 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) {
  317. WindowID window_id = last_focused_window;
  318. if (!windows.has(window_id)) {
  319. window_id = MAIN_WINDOW_ID;
  320. }
  321. String xid = vformat("x11:%x", (uint64_t)windows[window_id].x11_window);
  322. 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);
  323. }
  324. 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) {
  325. WindowID window_id = last_focused_window;
  326. if (!windows.has(window_id)) {
  327. window_id = MAIN_WINDOW_ID;
  328. }
  329. String xid = vformat("x11:%x", (uint64_t)windows[window_id].x11_window);
  330. 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);
  331. }
  332. #endif
  333. void DisplayServerX11::mouse_set_mode(MouseMode p_mode) {
  334. _THREAD_SAFE_METHOD_
  335. if (p_mode == mouse_mode) {
  336. return;
  337. }
  338. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  339. XUngrabPointer(x11_display, CurrentTime);
  340. }
  341. // The only modes that show a cursor are VISIBLE and CONFINED
  342. bool show_cursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
  343. bool previously_shown = (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED);
  344. if (show_cursor && !previously_shown) {
  345. WindowID window_id = get_window_at_screen_position(mouse_get_position());
  346. if (window_id != INVALID_WINDOW_ID && window_mouseover_id != window_id) {
  347. if (window_mouseover_id != INVALID_WINDOW_ID) {
  348. _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
  349. }
  350. window_mouseover_id = window_id;
  351. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  352. }
  353. }
  354. for (const KeyValue<WindowID, WindowData> &E : windows) {
  355. if (show_cursor) {
  356. XDefineCursor(x11_display, E.value.x11_window, cursors[current_cursor]); // show cursor
  357. } else {
  358. XDefineCursor(x11_display, E.value.x11_window, null_cursor); // hide cursor
  359. }
  360. }
  361. mouse_mode = p_mode;
  362. if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  363. //flush pending motion events
  364. _flush_mouse_motion();
  365. WindowID window_id = _get_focused_window_or_popup();
  366. if (!windows.has(window_id)) {
  367. window_id = MAIN_WINDOW_ID;
  368. }
  369. WindowData &window = windows[window_id];
  370. if (XGrabPointer(
  371. x11_display, window.x11_window, True,
  372. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  373. GrabModeAsync, GrabModeAsync, window.x11_window, None, CurrentTime) != GrabSuccess) {
  374. ERR_PRINT("NO GRAB");
  375. }
  376. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  377. center.x = window.size.width / 2;
  378. center.y = window.size.height / 2;
  379. XWarpPointer(x11_display, None, window.x11_window,
  380. 0, 0, 0, 0, (int)center.x, (int)center.y);
  381. Input::get_singleton()->set_mouse_position(center);
  382. }
  383. } else {
  384. do_mouse_warp = false;
  385. }
  386. XFlush(x11_display);
  387. }
  388. DisplayServerX11::MouseMode DisplayServerX11::mouse_get_mode() const {
  389. return mouse_mode;
  390. }
  391. void DisplayServerX11::warp_mouse(const Point2i &p_position) {
  392. _THREAD_SAFE_METHOD_
  393. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  394. last_mouse_pos = p_position;
  395. } else {
  396. WindowID window_id = _get_focused_window_or_popup();
  397. if (!windows.has(window_id)) {
  398. window_id = MAIN_WINDOW_ID;
  399. }
  400. XWarpPointer(x11_display, None, windows[window_id].x11_window,
  401. 0, 0, 0, 0, (int)p_position.x, (int)p_position.y);
  402. }
  403. }
  404. Point2i DisplayServerX11::mouse_get_position() const {
  405. int number_of_screens = XScreenCount(x11_display);
  406. for (int i = 0; i < number_of_screens; i++) {
  407. Window root, child;
  408. int root_x, root_y, win_x, win_y;
  409. unsigned int mask;
  410. if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
  411. XWindowAttributes root_attrs;
  412. XGetWindowAttributes(x11_display, root, &root_attrs);
  413. return Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
  414. }
  415. }
  416. return Vector2i();
  417. }
  418. BitField<MouseButtonMask> DisplayServerX11::mouse_get_button_state() const {
  419. return last_button_state;
  420. }
  421. void DisplayServerX11::clipboard_set(const String &p_text) {
  422. _THREAD_SAFE_METHOD_
  423. {
  424. // The clipboard content can be accessed while polling for events.
  425. MutexLock mutex_lock(events_mutex);
  426. internal_clipboard = p_text;
  427. }
  428. XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
  429. XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
  430. }
  431. void DisplayServerX11::clipboard_set_primary(const String &p_text) {
  432. _THREAD_SAFE_METHOD_
  433. if (!p_text.is_empty()) {
  434. {
  435. // The clipboard content can be accessed while polling for events.
  436. MutexLock mutex_lock(events_mutex);
  437. internal_clipboard_primary = p_text;
  438. }
  439. XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
  440. XSetSelectionOwner(x11_display, XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
  441. }
  442. }
  443. Bool DisplayServerX11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) {
  444. if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) {
  445. return True;
  446. } else {
  447. return False;
  448. }
  449. }
  450. Bool DisplayServerX11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) {
  451. if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue && event->xproperty.atom == *(Atom *)arg) {
  452. return True;
  453. } else {
  454. return False;
  455. }
  456. }
  457. String DisplayServerX11::_clipboard_get_impl(Atom p_source, Window x11_window, Atom target) const {
  458. String ret;
  459. Window selection_owner = XGetSelectionOwner(x11_display, p_source);
  460. if (selection_owner == x11_window) {
  461. static const char *target_type = "PRIMARY";
  462. if (p_source != None && get_atom_name(x11_display, p_source) == target_type) {
  463. return internal_clipboard_primary;
  464. } else {
  465. return internal_clipboard;
  466. }
  467. }
  468. if (selection_owner != None) {
  469. // Block events polling while processing selection events.
  470. MutexLock mutex_lock(events_mutex);
  471. Atom selection = XA_PRIMARY;
  472. XConvertSelection(x11_display, p_source, target, selection,
  473. x11_window, CurrentTime);
  474. XFlush(x11_display);
  475. // Blocking wait for predicate to be True and remove the event from the queue.
  476. XEvent event;
  477. XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
  478. // Do not get any data, see how much data is there.
  479. Atom type;
  480. int format, result;
  481. unsigned long len, bytes_left, dummy;
  482. unsigned char *data;
  483. XGetWindowProperty(x11_display, x11_window,
  484. selection, // Tricky..
  485. 0, 0, // offset - len
  486. 0, // Delete 0==FALSE
  487. AnyPropertyType, // flag
  488. &type, // return type
  489. &format, // return format
  490. &len, &bytes_left, // data length
  491. &data);
  492. if (data) {
  493. XFree(data);
  494. }
  495. if (type == XInternAtom(x11_display, "INCR", 0)) {
  496. // Data is going to be received incrementally.
  497. DEBUG_LOG_X11("INCR selection started.\n");
  498. LocalVector<uint8_t> incr_data;
  499. uint32_t data_size = 0;
  500. bool success = false;
  501. // Delete INCR property to notify the owner.
  502. XDeleteProperty(x11_display, x11_window, type);
  503. // Process events from the queue.
  504. bool done = false;
  505. while (!done) {
  506. if (!_wait_for_events()) {
  507. // Error or timeout, abort.
  508. break;
  509. }
  510. // Non-blocking wait for next event and remove it from the queue.
  511. XEvent ev;
  512. while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, (XPointer)&selection)) {
  513. result = XGetWindowProperty(x11_display, x11_window,
  514. selection, // selection type
  515. 0, LONG_MAX, // offset - len
  516. True, // delete property to notify the owner
  517. AnyPropertyType, // flag
  518. &type, // return type
  519. &format, // return format
  520. &len, &bytes_left, // data length
  521. &data);
  522. DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format);
  523. if (result == Success) {
  524. if (data && (len > 0)) {
  525. uint32_t prev_size = incr_data.size();
  526. if (prev_size == 0) {
  527. // First property contains initial data size.
  528. unsigned long initial_size = *(unsigned long *)data;
  529. incr_data.resize(initial_size);
  530. } else {
  531. // New chunk, resize to be safe and append data.
  532. incr_data.resize(MAX(data_size + len, prev_size));
  533. memcpy(incr_data.ptr() + data_size, data, len);
  534. data_size += len;
  535. }
  536. } else {
  537. // Last chunk, process finished.
  538. done = true;
  539. success = true;
  540. }
  541. } else {
  542. print_verbose("Failed to get selection data chunk.");
  543. done = true;
  544. }
  545. if (data) {
  546. XFree(data);
  547. }
  548. if (done) {
  549. break;
  550. }
  551. }
  552. }
  553. if (success && (data_size > 0)) {
  554. ret.parse_utf8((const char *)incr_data.ptr(), data_size);
  555. }
  556. } else if (bytes_left > 0) {
  557. // Data is ready and can be processed all at once.
  558. result = XGetWindowProperty(x11_display, x11_window,
  559. selection, 0, bytes_left, 0,
  560. AnyPropertyType, &type, &format,
  561. &len, &dummy, &data);
  562. if (result == Success) {
  563. ret.parse_utf8((const char *)data);
  564. } else {
  565. print_verbose("Failed to get selection data.");
  566. }
  567. if (data) {
  568. XFree(data);
  569. }
  570. }
  571. }
  572. return ret;
  573. }
  574. Atom DisplayServerX11::_clipboard_get_image_target(Atom p_source, Window x11_window) const {
  575. Atom target = XInternAtom(x11_display, "TARGETS", 0);
  576. Atom png = XInternAtom(x11_display, "image/png", 0);
  577. Atom *valid_targets = nullptr;
  578. unsigned long atom_count = 0;
  579. Window selection_owner = XGetSelectionOwner(x11_display, p_source);
  580. if (selection_owner != None && selection_owner != x11_window) {
  581. // Block events polling while processing selection events.
  582. MutexLock mutex_lock(events_mutex);
  583. Atom selection = XA_PRIMARY;
  584. XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime);
  585. XFlush(x11_display);
  586. // Blocking wait for predicate to be True and remove the event from the queue.
  587. XEvent event;
  588. XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
  589. // Do not get any data, see how much data is there.
  590. Atom type;
  591. int format, result;
  592. unsigned long len, bytes_left, dummy;
  593. XGetWindowProperty(x11_display, x11_window,
  594. selection, // Tricky..
  595. 0, 0, // offset - len
  596. 0, // Delete 0==FALSE
  597. XA_ATOM, // flag
  598. &type, // return type
  599. &format, // return format
  600. &len, &bytes_left, // data length
  601. (unsigned char **)&valid_targets);
  602. if (valid_targets) {
  603. XFree(valid_targets);
  604. valid_targets = nullptr;
  605. }
  606. if (type == XA_ATOM && bytes_left > 0) {
  607. // Data is ready and can be processed all at once.
  608. result = XGetWindowProperty(x11_display, x11_window,
  609. selection, 0, bytes_left / 4, 0,
  610. XA_ATOM, &type, &format,
  611. &len, &dummy, (unsigned char **)&valid_targets);
  612. if (result == Success) {
  613. atom_count = len;
  614. } else {
  615. print_verbose("Failed to get selection data.");
  616. return None;
  617. }
  618. } else {
  619. return None;
  620. }
  621. } else {
  622. return None;
  623. }
  624. for (unsigned long i = 0; i < atom_count; i++) {
  625. Atom atom = valid_targets[i];
  626. if (atom == png) {
  627. XFree(valid_targets);
  628. return png;
  629. }
  630. }
  631. XFree(valid_targets);
  632. return None;
  633. }
  634. String DisplayServerX11::_clipboard_get(Atom p_source, Window x11_window) const {
  635. String ret;
  636. Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True);
  637. if (utf8_atom != None) {
  638. ret = _clipboard_get_impl(p_source, x11_window, utf8_atom);
  639. }
  640. if (ret.is_empty()) {
  641. ret = _clipboard_get_impl(p_source, x11_window, XA_STRING);
  642. }
  643. return ret;
  644. }
  645. String DisplayServerX11::clipboard_get() const {
  646. _THREAD_SAFE_METHOD_
  647. String ret;
  648. ret = _clipboard_get(XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window);
  649. if (ret.is_empty()) {
  650. ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
  651. }
  652. return ret;
  653. }
  654. String DisplayServerX11::clipboard_get_primary() const {
  655. _THREAD_SAFE_METHOD_
  656. String ret;
  657. ret = _clipboard_get(XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window);
  658. if (ret.is_empty()) {
  659. ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
  660. }
  661. return ret;
  662. }
  663. Ref<Image> DisplayServerX11::clipboard_get_image() const {
  664. _THREAD_SAFE_METHOD_
  665. Atom clipboard = XInternAtom(x11_display, "CLIPBOARD", 0);
  666. Window x11_window = windows[MAIN_WINDOW_ID].x11_window;
  667. Ref<Image> ret;
  668. Atom target = _clipboard_get_image_target(clipboard, x11_window);
  669. if (target == None) {
  670. return ret;
  671. }
  672. Window selection_owner = XGetSelectionOwner(x11_display, clipboard);
  673. if (selection_owner != None && selection_owner != x11_window) {
  674. // Block events polling while processing selection events.
  675. MutexLock mutex_lock(events_mutex);
  676. // Identifier for the property the other window
  677. // will send the converted data to.
  678. Atom transfer_prop = XA_PRIMARY;
  679. XConvertSelection(x11_display,
  680. clipboard, // source selection
  681. target, // format to convert to
  682. transfer_prop, // output property
  683. x11_window, CurrentTime);
  684. XFlush(x11_display);
  685. // Blocking wait for predicate to be True and remove the event from the queue.
  686. XEvent event;
  687. XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
  688. // Do not get any data, see how much data is there.
  689. Atom type;
  690. int format, result;
  691. unsigned long len, bytes_left, dummy;
  692. unsigned char *data;
  693. XGetWindowProperty(x11_display, x11_window,
  694. transfer_prop, // Property data is transferred through
  695. 0, 1, // offset, len (4 so we can get the size if INCR is used)
  696. 0, // Delete 0==FALSE
  697. AnyPropertyType, // flag
  698. &type, // return type
  699. &format, // return format
  700. &len, &bytes_left, // data length
  701. &data);
  702. if (type == XInternAtom(x11_display, "INCR", 0)) {
  703. ERR_FAIL_COND_V_MSG(len != 1, ret, "Incremental transfer initial value was not length.");
  704. // Data is going to be received incrementally.
  705. DEBUG_LOG_X11("INCR selection started.\n");
  706. LocalVector<uint8_t> incr_data;
  707. uint32_t data_size = 0;
  708. bool success = false;
  709. // Initial response is the lower bound of the length of the transferred data.
  710. incr_data.resize(*(unsigned long *)data);
  711. XFree(data);
  712. data = nullptr;
  713. // Delete INCR property to notify the owner.
  714. XDeleteProperty(x11_display, x11_window, transfer_prop);
  715. // Process events from the queue.
  716. bool done = false;
  717. while (!done) {
  718. if (!_wait_for_events()) {
  719. // Error or timeout, abort.
  720. break;
  721. }
  722. // Non-blocking wait for next event and remove it from the queue.
  723. XEvent ev;
  724. while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, (XPointer)&transfer_prop)) {
  725. result = XGetWindowProperty(x11_display, x11_window,
  726. transfer_prop, // output property
  727. 0, LONG_MAX, // offset - len
  728. True, // delete property to notify the owner
  729. AnyPropertyType, // flag
  730. &type, // return type
  731. &format, // return format
  732. &len, &bytes_left, // data length
  733. &data);
  734. DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format);
  735. if (result == Success) {
  736. if (data && (len > 0)) {
  737. uint32_t prev_size = incr_data.size();
  738. // New chunk, resize to be safe and append data.
  739. incr_data.resize(MAX(data_size + len, prev_size));
  740. memcpy(incr_data.ptr() + data_size, data, len);
  741. data_size += len;
  742. } else if (!(format == 0 && len == 0)) {
  743. // For unclear reasons the first GetWindowProperty always returns a length and format of 0.
  744. // Otherwise, last chunk, process finished.
  745. done = true;
  746. success = true;
  747. }
  748. } else {
  749. print_verbose("Failed to get selection data chunk.");
  750. done = true;
  751. }
  752. if (data) {
  753. XFree(data);
  754. data = nullptr;
  755. }
  756. if (done) {
  757. break;
  758. }
  759. }
  760. }
  761. if (success && (data_size > 0)) {
  762. ret.instantiate();
  763. PNGDriverCommon::png_to_image(incr_data.ptr(), incr_data.size(), false, ret);
  764. }
  765. } else if (bytes_left > 0) {
  766. if (data) {
  767. XFree(data);
  768. data = nullptr;
  769. }
  770. // Data is ready and can be processed all at once.
  771. result = XGetWindowProperty(x11_display, x11_window,
  772. transfer_prop, 0, bytes_left + 4, 0,
  773. AnyPropertyType, &type, &format,
  774. &len, &dummy, &data);
  775. if (result == Success) {
  776. ret.instantiate();
  777. PNGDriverCommon::png_to_image((uint8_t *)data, bytes_left, false, ret);
  778. } else {
  779. print_verbose("Failed to get selection data.");
  780. }
  781. if (data) {
  782. XFree(data);
  783. }
  784. }
  785. }
  786. return ret;
  787. }
  788. bool DisplayServerX11::clipboard_has_image() const {
  789. Atom target = _clipboard_get_image_target(
  790. XInternAtom(x11_display, "CLIPBOARD", 0),
  791. windows[MAIN_WINDOW_ID].x11_window);
  792. return target != None;
  793. }
  794. Bool DisplayServerX11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) {
  795. if (event->xany.window == *(Window *)arg) {
  796. return (event->type == SelectionRequest) ||
  797. (event->type == SelectionNotify);
  798. } else {
  799. return False;
  800. }
  801. }
  802. void DisplayServerX11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const {
  803. _THREAD_SAFE_METHOD_
  804. Window selection_owner = XGetSelectionOwner(x11_display, p_source);
  805. if (selection_owner != x11_window) {
  806. return;
  807. }
  808. // Block events polling while processing selection events.
  809. MutexLock mutex_lock(events_mutex);
  810. Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False);
  811. Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False);
  812. XConvertSelection(x11_display, clipboard_manager, save_targets, None,
  813. x11_window, CurrentTime);
  814. // Process events from the queue.
  815. while (true) {
  816. if (!_wait_for_events()) {
  817. // Error or timeout, abort.
  818. break;
  819. }
  820. // Non-blocking wait for next event and remove it from the queue.
  821. XEvent ev;
  822. while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) {
  823. switch (ev.type) {
  824. case SelectionRequest:
  825. _handle_selection_request_event(&(ev.xselectionrequest));
  826. break;
  827. case SelectionNotify: {
  828. if (ev.xselection.target == save_targets) {
  829. // Once SelectionNotify is received, we're done whether it succeeded or not.
  830. return;
  831. }
  832. break;
  833. }
  834. }
  835. }
  836. }
  837. }
  838. int DisplayServerX11::get_screen_count() const {
  839. _THREAD_SAFE_METHOD_
  840. int count = 0;
  841. // Using Xinerama Extension
  842. int event_base, error_base;
  843. if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
  844. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  845. XFree(xsi);
  846. } else {
  847. count = XScreenCount(x11_display);
  848. }
  849. return count;
  850. }
  851. int DisplayServerX11::get_primary_screen() const {
  852. int event_base, error_base;
  853. if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
  854. return 0;
  855. } else {
  856. return XDefaultScreen(x11_display);
  857. }
  858. }
  859. int DisplayServerX11::get_keyboard_focus_screen() const {
  860. int count = get_screen_count();
  861. if (count < 2) {
  862. // Early exit with single monitor.
  863. return 0;
  864. }
  865. Window focus = 0;
  866. int revert_to = 0;
  867. XGetInputFocus(x11_display, &focus, &revert_to);
  868. if (focus) {
  869. Window focus_child = 0;
  870. int x = 0, y = 0;
  871. XTranslateCoordinates(x11_display, focus, DefaultRootWindow(x11_display), 0, 0, &x, &y, &focus_child);
  872. XWindowAttributes xwa;
  873. XGetWindowAttributes(x11_display, focus, &xwa);
  874. Rect2i window_rect = Rect2i(x, y, xwa.width, xwa.height);
  875. // Find which monitor has the largest overlap with the given window.
  876. int screen_index = 0;
  877. int max_area = 0;
  878. for (int i = 0; i < count; i++) {
  879. Rect2i screen_rect = _screen_get_rect(i);
  880. Rect2i intersection = screen_rect.intersection(window_rect);
  881. int area = intersection.get_area();
  882. if (area > max_area) {
  883. max_area = area;
  884. screen_index = i;
  885. }
  886. }
  887. return screen_index;
  888. }
  889. return get_primary_screen();
  890. }
  891. Rect2i DisplayServerX11::_screen_get_rect(int p_screen) const {
  892. Rect2i rect(0, 0, 0, 0);
  893. p_screen = _get_screen_index(p_screen);
  894. ERR_FAIL_COND_V(p_screen < 0, rect);
  895. // Using Xinerama Extension.
  896. int event_base, error_base;
  897. if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
  898. int count;
  899. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
  900. // Check if screen is valid.
  901. if (p_screen < count) {
  902. rect.position.x = xsi[p_screen].x_org;
  903. rect.position.y = xsi[p_screen].y_org;
  904. rect.size.width = xsi[p_screen].width;
  905. rect.size.height = xsi[p_screen].height;
  906. } else {
  907. ERR_PRINT("Invalid screen index: " + itos(p_screen) + "(count: " + itos(count) + ").");
  908. }
  909. if (xsi) {
  910. XFree(xsi);
  911. }
  912. } else {
  913. int count = XScreenCount(x11_display);
  914. if (p_screen < count) {
  915. Window root = XRootWindow(x11_display, p_screen);
  916. XWindowAttributes xwa;
  917. XGetWindowAttributes(x11_display, root, &xwa);
  918. rect.position.x = xwa.x;
  919. rect.position.y = xwa.y;
  920. rect.size.width = xwa.width;
  921. rect.size.height = xwa.height;
  922. } else {
  923. ERR_PRINT("Invalid screen index: " + itos(p_screen) + "(count: " + itos(count) + ").");
  924. }
  925. }
  926. return rect;
  927. }
  928. Point2i DisplayServerX11::screen_get_position(int p_screen) const {
  929. _THREAD_SAFE_METHOD_
  930. return _screen_get_rect(p_screen).position;
  931. }
  932. Size2i DisplayServerX11::screen_get_size(int p_screen) const {
  933. _THREAD_SAFE_METHOD_
  934. return _screen_get_rect(p_screen).size;
  935. }
  936. // A Handler to avoid crashing on non-fatal X errors by default.
  937. //
  938. // The original X11 error formatter `_XPrintDefaultError` is defined here:
  939. // https://gitlab.freedesktop.org/xorg/lib/libx11/-/blob/e45ca7b41dcd3ace7681d6897505f85d374640f2/src/XlibInt.c#L1322
  940. // It is not exposed through the API, accesses X11 internals,
  941. // and is much more complex, so this is a less complete simplified error X11 printer.
  942. int default_window_error_handler(Display *display, XErrorEvent *error) {
  943. static char message[1024];
  944. XGetErrorText(display, error->error_code, message, sizeof(message));
  945. ERR_PRINT(vformat("Unhandled XServer error: %s"
  946. "\n Major opcode of failed request: %d"
  947. "\n Serial number of failed request: %d"
  948. "\n Current serial number in output stream: %d",
  949. String::utf8(message), (uint64_t)error->request_code, (uint64_t)error->minor_code, (uint64_t)error->serial));
  950. return 0;
  951. }
  952. bool g_bad_window = false;
  953. int bad_window_error_handler(Display *display, XErrorEvent *error) {
  954. if (error->error_code == BadWindow) {
  955. g_bad_window = true;
  956. } else {
  957. return default_window_error_handler(display, error);
  958. }
  959. return 0;
  960. }
  961. Rect2i DisplayServerX11::screen_get_usable_rect(int p_screen) const {
  962. _THREAD_SAFE_METHOD_
  963. p_screen = _get_screen_index(p_screen);
  964. int screen_count = get_screen_count();
  965. // Check if screen is valid.
  966. ERR_FAIL_INDEX_V(p_screen, screen_count, Rect2i(0, 0, 0, 0));
  967. bool is_multiscreen = screen_count > 1;
  968. // Use full monitor size as fallback.
  969. Rect2i rect = _screen_get_rect(p_screen);
  970. // There's generally only one screen reported by xlib even in multi-screen setup,
  971. // in this case it's just one virtual screen composed of all physical monitors.
  972. int x11_screen_count = ScreenCount(x11_display);
  973. Window x11_window = RootWindow(x11_display, p_screen < x11_screen_count ? p_screen : 0);
  974. Atom type;
  975. int format = 0;
  976. unsigned long remaining = 0;
  977. // Find active desktop for the root window.
  978. unsigned int desktop_index = 0;
  979. Atom desktop_prop = XInternAtom(x11_display, "_NET_CURRENT_DESKTOP", True);
  980. if (desktop_prop != None) {
  981. unsigned long desktop_len = 0;
  982. unsigned char *desktop_data = nullptr;
  983. if (XGetWindowProperty(x11_display, x11_window, desktop_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &desktop_len, &remaining, &desktop_data) == Success) {
  984. if ((format == 32) && (desktop_len > 0) && desktop_data) {
  985. desktop_index = (unsigned int)desktop_data[0];
  986. }
  987. if (desktop_data) {
  988. XFree(desktop_data);
  989. }
  990. }
  991. }
  992. bool use_simple_method = true;
  993. // First check for GTK work area, which is more accurate for multi-screen setup.
  994. if (is_multiscreen) {
  995. // Use already calculated work area when available.
  996. Atom gtk_workareas_prop = XInternAtom(x11_display, "_GTK_WORKAREAS", False);
  997. if (gtk_workareas_prop != None) {
  998. char gtk_workarea_prop_name[32];
  999. snprintf(gtk_workarea_prop_name, 32, "_GTK_WORKAREAS_D%d", desktop_index);
  1000. Atom gtk_workarea_prop = XInternAtom(x11_display, gtk_workarea_prop_name, True);
  1001. if (gtk_workarea_prop != None) {
  1002. unsigned long workarea_len = 0;
  1003. unsigned char *workarea_data = nullptr;
  1004. if (XGetWindowProperty(x11_display, x11_window, gtk_workarea_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &workarea_len, &remaining, &workarea_data) == Success) {
  1005. if ((format == 32) && (workarea_len % 4 == 0) && workarea_data) {
  1006. long *rect_data = (long *)workarea_data;
  1007. for (uint32_t data_offset = 0; data_offset < workarea_len; data_offset += 4) {
  1008. Rect2i workarea_rect;
  1009. workarea_rect.position.x = rect_data[data_offset];
  1010. workarea_rect.position.y = rect_data[data_offset + 1];
  1011. workarea_rect.size.x = rect_data[data_offset + 2];
  1012. workarea_rect.size.y = rect_data[data_offset + 3];
  1013. // Intersect with actual monitor size to find the correct area,
  1014. // because areas are not in the same order as screens from Xinerama.
  1015. if (rect.grow(-1).intersects(workarea_rect)) {
  1016. rect = rect.intersection(workarea_rect);
  1017. XFree(workarea_data);
  1018. return rect;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. if (workarea_data) {
  1024. XFree(workarea_data);
  1025. }
  1026. }
  1027. }
  1028. // Fallback to calculating work area by hand from struts.
  1029. Atom client_list_prop = XInternAtom(x11_display, "_NET_CLIENT_LIST", True);
  1030. if (client_list_prop != None) {
  1031. unsigned long clients_len = 0;
  1032. unsigned char *clients_data = nullptr;
  1033. if (XGetWindowProperty(x11_display, x11_window, client_list_prop, 0, LONG_MAX, False, XA_WINDOW, &type, &format, &clients_len, &remaining, &clients_data) == Success) {
  1034. if ((format == 32) && (clients_len > 0) && clients_data) {
  1035. Window *windows_data = (Window *)clients_data;
  1036. Rect2i desktop_rect;
  1037. bool desktop_valid = false;
  1038. // Get full desktop size.
  1039. {
  1040. Atom desktop_geometry_prop = XInternAtom(x11_display, "_NET_DESKTOP_GEOMETRY", True);
  1041. if (desktop_geometry_prop != None) {
  1042. unsigned long geom_len = 0;
  1043. unsigned char *geom_data = nullptr;
  1044. if (XGetWindowProperty(x11_display, x11_window, desktop_geometry_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &geom_len, &remaining, &geom_data) == Success) {
  1045. if ((format == 32) && (geom_len >= 2) && geom_data) {
  1046. desktop_valid = true;
  1047. long *size_data = (long *)geom_data;
  1048. desktop_rect.size.x = size_data[0];
  1049. desktop_rect.size.y = size_data[1];
  1050. }
  1051. }
  1052. if (geom_data) {
  1053. XFree(geom_data);
  1054. }
  1055. }
  1056. }
  1057. // Get full desktop position.
  1058. if (desktop_valid) {
  1059. Atom desktop_viewport_prop = XInternAtom(x11_display, "_NET_DESKTOP_VIEWPORT", True);
  1060. if (desktop_viewport_prop != None) {
  1061. unsigned long viewport_len = 0;
  1062. unsigned char *viewport_data = nullptr;
  1063. if (XGetWindowProperty(x11_display, x11_window, desktop_viewport_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &viewport_len, &remaining, &viewport_data) == Success) {
  1064. if ((format == 32) && (viewport_len >= 2) && viewport_data) {
  1065. desktop_valid = true;
  1066. long *pos_data = (long *)viewport_data;
  1067. desktop_rect.position.x = pos_data[0];
  1068. desktop_rect.position.y = pos_data[1];
  1069. }
  1070. }
  1071. if (viewport_data) {
  1072. XFree(viewport_data);
  1073. }
  1074. }
  1075. }
  1076. if (desktop_valid) {
  1077. use_simple_method = false;
  1078. // Handle bad window errors silently because there's no other way to check
  1079. // that one of the windows has been destroyed in the meantime.
  1080. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&bad_window_error_handler);
  1081. for (unsigned long win_index = 0; win_index < clients_len; ++win_index) {
  1082. g_bad_window = false;
  1083. // Remove strut size from desktop size to get a more accurate result.
  1084. bool strut_found = false;
  1085. unsigned long strut_len = 0;
  1086. unsigned char *strut_data = nullptr;
  1087. Atom strut_partial_prop = XInternAtom(x11_display, "_NET_WM_STRUT_PARTIAL", True);
  1088. if (strut_partial_prop != None) {
  1089. 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) {
  1090. strut_found = true;
  1091. }
  1092. }
  1093. // Fallback to older strut property.
  1094. if (!g_bad_window && !strut_found) {
  1095. Atom strut_prop = XInternAtom(x11_display, "_NET_WM_STRUT", True);
  1096. if (strut_prop != None) {
  1097. if (XGetWindowProperty(x11_display, windows_data[win_index], strut_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &strut_len, &remaining, &strut_data) == Success) {
  1098. strut_found = true;
  1099. }
  1100. }
  1101. }
  1102. if (!g_bad_window && strut_found && (format == 32) && (strut_len >= 4) && strut_data) {
  1103. long *struts = (long *)strut_data;
  1104. long left = struts[0];
  1105. long right = struts[1];
  1106. long top = struts[2];
  1107. long bottom = struts[3];
  1108. long left_start_y, left_end_y, right_start_y, right_end_y;
  1109. long top_start_x, top_end_x, bottom_start_x, bottom_end_x;
  1110. if (strut_len >= 12) {
  1111. left_start_y = struts[4];
  1112. left_end_y = struts[5];
  1113. right_start_y = struts[6];
  1114. right_end_y = struts[7];
  1115. top_start_x = struts[8];
  1116. top_end_x = struts[9];
  1117. bottom_start_x = struts[10];
  1118. bottom_end_x = struts[11];
  1119. } else {
  1120. left_start_y = 0;
  1121. left_end_y = desktop_rect.size.y;
  1122. right_start_y = 0;
  1123. right_end_y = desktop_rect.size.y;
  1124. top_start_x = 0;
  1125. top_end_x = desktop_rect.size.x;
  1126. bottom_start_x = 0;
  1127. bottom_end_x = desktop_rect.size.x;
  1128. }
  1129. const Point2i &pos = desktop_rect.position;
  1130. const Size2i &size = desktop_rect.size;
  1131. Rect2i left_rect(pos.x, pos.y + left_start_y, left, left_end_y - left_start_y);
  1132. if (left_rect.size.x > 0) {
  1133. Rect2i intersection = rect.intersection(left_rect);
  1134. if (intersection.has_area() && intersection.size.x < rect.size.x) {
  1135. rect.position.x = left_rect.size.x;
  1136. rect.size.x = rect.size.x - intersection.size.x;
  1137. }
  1138. }
  1139. Rect2i right_rect(pos.x + size.x - right, pos.y + right_start_y, right, right_end_y - right_start_y);
  1140. if (right_rect.size.x > 0) {
  1141. Rect2i intersection = rect.intersection(right_rect);
  1142. if (intersection.has_area() && right_rect.size.x < rect.size.x) {
  1143. rect.size.x = intersection.position.x - rect.position.x;
  1144. }
  1145. }
  1146. Rect2i top_rect(pos.x + top_start_x, pos.y, top_end_x - top_start_x, top);
  1147. if (top_rect.size.y > 0) {
  1148. Rect2i intersection = rect.intersection(top_rect);
  1149. if (intersection.has_area() && intersection.size.y < rect.size.y) {
  1150. rect.position.y = top_rect.size.y;
  1151. rect.size.y = rect.size.y - intersection.size.y;
  1152. }
  1153. }
  1154. Rect2i bottom_rect(pos.x + bottom_start_x, pos.y + size.y - bottom, bottom_end_x - bottom_start_x, bottom);
  1155. if (bottom_rect.size.y > 0) {
  1156. Rect2i intersection = rect.intersection(bottom_rect);
  1157. if (intersection.has_area() && right_rect.size.y < rect.size.y) {
  1158. rect.size.y = intersection.position.y - rect.position.y;
  1159. }
  1160. }
  1161. }
  1162. if (strut_data) {
  1163. XFree(strut_data);
  1164. }
  1165. }
  1166. // Restore default error handler.
  1167. XSetErrorHandler(oldHandler);
  1168. }
  1169. }
  1170. }
  1171. if (clients_data) {
  1172. XFree(clients_data);
  1173. }
  1174. }
  1175. }
  1176. // Single screen or fallback for multi screen.
  1177. if (use_simple_method) {
  1178. // Get desktop available size from the global work area.
  1179. Atom workarea_prop = XInternAtom(x11_display, "_NET_WORKAREA", True);
  1180. if (workarea_prop != None) {
  1181. unsigned long workarea_len = 0;
  1182. unsigned char *workarea_data = nullptr;
  1183. if (XGetWindowProperty(x11_display, x11_window, workarea_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &workarea_len, &remaining, &workarea_data) == Success) {
  1184. if ((format == 32) && (workarea_len >= ((desktop_index + 1) * 4)) && workarea_data) {
  1185. long *rect_data = (long *)workarea_data;
  1186. int data_offset = desktop_index * 4;
  1187. Rect2i workarea_rect;
  1188. workarea_rect.position.x = rect_data[data_offset];
  1189. workarea_rect.position.y = rect_data[data_offset + 1];
  1190. workarea_rect.size.x = rect_data[data_offset + 2];
  1191. workarea_rect.size.y = rect_data[data_offset + 3];
  1192. // Intersect with actual monitor size to get a proper approximation in multi-screen setup.
  1193. if (!is_multiscreen) {
  1194. rect = workarea_rect;
  1195. } else if (rect.intersects(workarea_rect)) {
  1196. rect = rect.intersection(workarea_rect);
  1197. }
  1198. }
  1199. }
  1200. if (workarea_data) {
  1201. XFree(workarea_data);
  1202. }
  1203. }
  1204. }
  1205. return rect;
  1206. }
  1207. int DisplayServerX11::screen_get_dpi(int p_screen) const {
  1208. _THREAD_SAFE_METHOD_
  1209. p_screen = _get_screen_index(p_screen);
  1210. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0);
  1211. //Get physical monitor Dimensions through XRandR and calculate dpi
  1212. Size2i sc = screen_get_size(p_screen);
  1213. if (xrandr_ext_ok) {
  1214. int count = 0;
  1215. if (xrr_get_monitors) {
  1216. xrr_monitor_info *monitors = xrr_get_monitors(x11_display, windows[MAIN_WINDOW_ID].x11_window, true, &count);
  1217. if (p_screen < count) {
  1218. double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4;
  1219. double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4;
  1220. xrr_free_monitors(monitors);
  1221. return (xdpi + ydpi) / 2;
  1222. }
  1223. xrr_free_monitors(monitors);
  1224. } else if (p_screen == 0) {
  1225. XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count);
  1226. if (sizes) {
  1227. double xdpi = sc.width / (double)sizes[0].mwidth * 25.4;
  1228. double ydpi = sc.height / (double)sizes[0].mheight * 25.4;
  1229. return (xdpi + ydpi) / 2;
  1230. }
  1231. }
  1232. }
  1233. int width_mm = DisplayWidthMM(x11_display, p_screen);
  1234. int height_mm = DisplayHeightMM(x11_display, p_screen);
  1235. double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0);
  1236. double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0);
  1237. if (xdpi || ydpi) {
  1238. return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1);
  1239. }
  1240. //could not get dpi
  1241. return 96;
  1242. }
  1243. Color DisplayServerX11::screen_get_pixel(const Point2i &p_position) const {
  1244. Point2i pos = p_position;
  1245. int number_of_screens = XScreenCount(x11_display);
  1246. for (int i = 0; i < number_of_screens; i++) {
  1247. Window root = XRootWindow(x11_display, i);
  1248. XWindowAttributes root_attrs;
  1249. XGetWindowAttributes(x11_display, root, &root_attrs);
  1250. 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)) {
  1251. XImage *image = XGetImage(x11_display, root, pos.x, pos.y, 1, 1, AllPlanes, XYPixmap);
  1252. if (image) {
  1253. XColor c;
  1254. c.pixel = XGetPixel(image, 0, 0);
  1255. XFree(image);
  1256. XQueryColor(x11_display, XDefaultColormap(x11_display, i), &c);
  1257. return Color(float(c.red) / 65535.0, float(c.green) / 65535.0, float(c.blue) / 65535.0, 1.0);
  1258. }
  1259. }
  1260. }
  1261. return Color();
  1262. }
  1263. Ref<Image> DisplayServerX11::screen_get_image(int p_screen) const {
  1264. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), Ref<Image>());
  1265. switch (p_screen) {
  1266. case SCREEN_PRIMARY: {
  1267. p_screen = get_primary_screen();
  1268. } break;
  1269. case SCREEN_OF_MAIN_WINDOW: {
  1270. p_screen = window_get_current_screen(MAIN_WINDOW_ID);
  1271. } break;
  1272. default:
  1273. break;
  1274. }
  1275. ERR_FAIL_COND_V(p_screen < 0, Ref<Image>());
  1276. XImage *image = nullptr;
  1277. int event_base, error_base;
  1278. if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
  1279. int xin_count;
  1280. XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &xin_count);
  1281. if (p_screen < xin_count) {
  1282. int x_count = XScreenCount(x11_display);
  1283. for (int i = 0; i < x_count; i++) {
  1284. Window root = XRootWindow(x11_display, i);
  1285. XWindowAttributes root_attrs;
  1286. XGetWindowAttributes(x11_display, root, &root_attrs);
  1287. 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)) {
  1288. 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);
  1289. break;
  1290. }
  1291. }
  1292. } else {
  1293. ERR_FAIL_V_MSG(Ref<Image>(), "Invalid screen index: " + itos(p_screen) + "(count: " + itos(xin_count) + ").");
  1294. }
  1295. } else {
  1296. int x_count = XScreenCount(x11_display);
  1297. if (p_screen < x_count) {
  1298. Window root = XRootWindow(x11_display, p_screen);
  1299. XWindowAttributes root_attrs;
  1300. XGetWindowAttributes(x11_display, root, &root_attrs);
  1301. image = XGetImage(x11_display, root, root_attrs.x, root_attrs.y, root_attrs.width, root_attrs.height, AllPlanes, ZPixmap);
  1302. } else {
  1303. ERR_FAIL_V_MSG(Ref<Image>(), "Invalid screen index: " + itos(p_screen) + "(count: " + itos(x_count) + ").");
  1304. }
  1305. }
  1306. Ref<Image> img;
  1307. if (image) {
  1308. int width = image->width;
  1309. int height = image->height;
  1310. Vector<uint8_t> img_data;
  1311. img_data.resize(height * width * 4);
  1312. uint8_t *sr = (uint8_t *)image->data;
  1313. uint8_t *wr = (uint8_t *)img_data.ptrw();
  1314. if (image->bits_per_pixel == 24 && image->red_mask == 0xff0000 && image->green_mask == 0x00ff00 && image->blue_mask == 0x0000ff) {
  1315. for (int y = 0; y < height; y++) {
  1316. for (int x = 0; x < width; x++) {
  1317. wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 3 + 2];
  1318. wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 3 + 1];
  1319. wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 3 + 0];
  1320. wr[(y * width + x) * 4 + 3] = 255;
  1321. }
  1322. }
  1323. } else if (image->bits_per_pixel == 24 && image->red_mask == 0x0000ff && image->green_mask == 0x00ff00 && image->blue_mask == 0xff0000) {
  1324. for (int y = 0; y < height; y++) {
  1325. for (int x = 0; x < width; x++) {
  1326. wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 3 + 2];
  1327. wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 3 + 1];
  1328. wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 3 + 0];
  1329. wr[(y * width + x) * 4 + 3] = 255;
  1330. }
  1331. }
  1332. } else if (image->bits_per_pixel == 32 && image->red_mask == 0xff0000 && image->green_mask == 0x00ff00 && image->blue_mask == 0x0000ff) {
  1333. for (int y = 0; y < height; y++) {
  1334. for (int x = 0; x < width; x++) {
  1335. wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 4 + 2];
  1336. wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 4 + 1];
  1337. wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 4 + 0];
  1338. wr[(y * width + x) * 4 + 3] = 255;
  1339. }
  1340. }
  1341. } else {
  1342. XFree(image);
  1343. ERR_FAIL_V_MSG(Ref<Image>(), 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));
  1344. }
  1345. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1346. XFree(image);
  1347. }
  1348. return img;
  1349. }
  1350. float DisplayServerX11::screen_get_refresh_rate(int p_screen) const {
  1351. _THREAD_SAFE_METHOD_
  1352. p_screen = _get_screen_index(p_screen);
  1353. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), SCREEN_REFRESH_RATE_FALLBACK);
  1354. //Use xrandr to get screen refresh rate.
  1355. if (xrandr_ext_ok) {
  1356. XRRScreenResources *screen_info = XRRGetScreenResourcesCurrent(x11_display, windows[MAIN_WINDOW_ID].x11_window);
  1357. if (screen_info) {
  1358. RRMode current_mode = 0;
  1359. xrr_monitor_info *monitors = nullptr;
  1360. if (xrr_get_monitors) {
  1361. int count = 0;
  1362. monitors = xrr_get_monitors(x11_display, windows[MAIN_WINDOW_ID].x11_window, true, &count);
  1363. ERR_FAIL_INDEX_V(p_screen, count, SCREEN_REFRESH_RATE_FALLBACK);
  1364. } else {
  1365. ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
  1366. return SCREEN_REFRESH_RATE_FALLBACK;
  1367. }
  1368. bool found_active_mode = false;
  1369. for (int crtc = 0; crtc < screen_info->ncrtc; crtc++) { // Loop through outputs to find which one is currently outputting.
  1370. XRRCrtcInfo *monitor_info = XRRGetCrtcInfo(x11_display, screen_info, screen_info->crtcs[crtc]);
  1371. if (monitor_info->x != monitors[p_screen].x || monitor_info->y != monitors[p_screen].y) { // If X and Y aren't the same as the monitor we're looking for, this isn't the right monitor. Continue.
  1372. continue;
  1373. }
  1374. if (monitor_info->mode != None) {
  1375. current_mode = monitor_info->mode;
  1376. found_active_mode = true;
  1377. break;
  1378. }
  1379. }
  1380. if (found_active_mode) {
  1381. for (int mode = 0; mode < screen_info->nmode; mode++) {
  1382. XRRModeInfo m_info = screen_info->modes[mode];
  1383. if (m_info.id == current_mode) {
  1384. // Snap to nearest 0.01 to stay consistent with other platforms.
  1385. return Math::snapped((float)m_info.dotClock / ((float)m_info.hTotal * (float)m_info.vTotal), 0.01);
  1386. }
  1387. }
  1388. }
  1389. ERR_PRINT("An error occurred while trying to get the screen refresh rate."); // We should have returned the refresh rate by now. An error must have occurred.
  1390. return SCREEN_REFRESH_RATE_FALLBACK;
  1391. } else {
  1392. ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
  1393. return SCREEN_REFRESH_RATE_FALLBACK;
  1394. }
  1395. }
  1396. ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
  1397. return SCREEN_REFRESH_RATE_FALLBACK;
  1398. }
  1399. #ifdef DBUS_ENABLED
  1400. void DisplayServerX11::screen_set_keep_on(bool p_enable) {
  1401. if (screen_is_kept_on() == p_enable) {
  1402. return;
  1403. }
  1404. if (p_enable) {
  1405. screensaver->inhibit();
  1406. } else {
  1407. screensaver->uninhibit();
  1408. }
  1409. keep_screen_on = p_enable;
  1410. }
  1411. bool DisplayServerX11::screen_is_kept_on() const {
  1412. return keep_screen_on;
  1413. }
  1414. #endif
  1415. Vector<DisplayServer::WindowID> DisplayServerX11::get_window_list() const {
  1416. _THREAD_SAFE_METHOD_
  1417. Vector<int> ret;
  1418. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1419. ret.push_back(E.key);
  1420. }
  1421. return ret;
  1422. }
  1423. DisplayServer::WindowID DisplayServerX11::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  1424. _THREAD_SAFE_METHOD_
  1425. WindowID id = _create_window(p_mode, p_vsync_mode, p_flags, p_rect);
  1426. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  1427. if (p_flags & (1 << i)) {
  1428. window_set_flag(WindowFlags(i), true, id);
  1429. }
  1430. }
  1431. return id;
  1432. }
  1433. void DisplayServerX11::show_window(WindowID p_id) {
  1434. _THREAD_SAFE_METHOD_
  1435. const WindowData &wd = windows[p_id];
  1436. popup_open(p_id);
  1437. DEBUG_LOG_X11("show_window: %lu (%u) \n", wd.x11_window, p_id);
  1438. XMapWindow(x11_display, wd.x11_window);
  1439. XSync(x11_display, False);
  1440. _validate_mode_on_map(p_id);
  1441. }
  1442. void DisplayServerX11::delete_sub_window(WindowID p_id) {
  1443. _THREAD_SAFE_METHOD_
  1444. ERR_FAIL_COND(!windows.has(p_id));
  1445. ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted");
  1446. popup_close(p_id);
  1447. WindowData &wd = windows[p_id];
  1448. DEBUG_LOG_X11("delete_sub_window: %lu (%u) \n", wd.x11_window, p_id);
  1449. if (window_mouseover_id == p_id) {
  1450. window_mouseover_id = INVALID_WINDOW_ID;
  1451. _send_window_event(windows[p_id], WINDOW_EVENT_MOUSE_EXIT);
  1452. }
  1453. window_set_rect_changed_callback(Callable(), p_id);
  1454. window_set_window_event_callback(Callable(), p_id);
  1455. window_set_input_event_callback(Callable(), p_id);
  1456. window_set_input_text_callback(Callable(), p_id);
  1457. window_set_drop_files_callback(Callable(), p_id);
  1458. while (wd.transient_children.size()) {
  1459. window_set_transient(*wd.transient_children.begin(), INVALID_WINDOW_ID);
  1460. }
  1461. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1462. window_set_transient(p_id, INVALID_WINDOW_ID);
  1463. }
  1464. #if defined(RD_ENABLED)
  1465. if (context_rd) {
  1466. context_rd->window_destroy(p_id);
  1467. }
  1468. #endif
  1469. #ifdef GLES3_ENABLED
  1470. if (gl_manager) {
  1471. gl_manager->window_destroy(p_id);
  1472. }
  1473. if (gl_manager_egl) {
  1474. gl_manager_egl->window_destroy(p_id);
  1475. }
  1476. #endif
  1477. if (wd.xic) {
  1478. XDestroyIC(wd.xic);
  1479. wd.xic = nullptr;
  1480. }
  1481. XDestroyWindow(x11_display, wd.x11_xim_window);
  1482. #ifdef XKB_ENABLED
  1483. if (xkb_loaded_v05p) {
  1484. if (wd.xkb_state) {
  1485. xkb_compose_state_unref(wd.xkb_state);
  1486. wd.xkb_state = nullptr;
  1487. }
  1488. }
  1489. #endif
  1490. XUnmapWindow(x11_display, wd.x11_window);
  1491. XDestroyWindow(x11_display, wd.x11_window);
  1492. windows.erase(p_id);
  1493. }
  1494. int64_t DisplayServerX11::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  1495. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  1496. switch (p_handle_type) {
  1497. case DISPLAY_HANDLE: {
  1498. return (int64_t)x11_display;
  1499. }
  1500. case WINDOW_HANDLE: {
  1501. return (int64_t)windows[p_window].x11_window;
  1502. }
  1503. case WINDOW_VIEW: {
  1504. return 0; // Not supported.
  1505. }
  1506. #ifdef GLES3_ENABLED
  1507. case OPENGL_CONTEXT: {
  1508. if (gl_manager) {
  1509. return (int64_t)gl_manager->get_glx_context(p_window);
  1510. }
  1511. if (gl_manager_egl) {
  1512. return (int64_t)gl_manager_egl->get_context(p_window);
  1513. }
  1514. return 0;
  1515. }
  1516. #endif
  1517. default: {
  1518. return 0;
  1519. }
  1520. }
  1521. }
  1522. void DisplayServerX11::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  1523. ERR_FAIL_COND(!windows.has(p_window));
  1524. WindowData &wd = windows[p_window];
  1525. wd.instance_id = p_instance;
  1526. }
  1527. ObjectID DisplayServerX11::window_get_attached_instance_id(WindowID p_window) const {
  1528. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  1529. const WindowData &wd = windows[p_window];
  1530. return wd.instance_id;
  1531. }
  1532. DisplayServerX11::WindowID DisplayServerX11::get_window_at_screen_position(const Point2i &p_position) const {
  1533. WindowID found_window = INVALID_WINDOW_ID;
  1534. WindowID parent_window = INVALID_WINDOW_ID;
  1535. unsigned int focus_order = 0;
  1536. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1537. const WindowData &wd = E.value;
  1538. // Discard windows with no focus.
  1539. if (wd.focus_order == 0) {
  1540. continue;
  1541. }
  1542. // Find topmost window which contains the given position.
  1543. WindowID window_id = E.key;
  1544. Rect2i win_rect = Rect2i(window_get_position(window_id), window_get_size(window_id));
  1545. if (win_rect.has_point(p_position)) {
  1546. // For siblings, pick the window which was focused last.
  1547. if ((parent_window != wd.transient_parent) || (wd.focus_order > focus_order)) {
  1548. found_window = window_id;
  1549. parent_window = wd.transient_parent;
  1550. focus_order = wd.focus_order;
  1551. }
  1552. }
  1553. }
  1554. return found_window;
  1555. }
  1556. void DisplayServerX11::window_set_title(const String &p_title, WindowID p_window) {
  1557. _THREAD_SAFE_METHOD_
  1558. ERR_FAIL_COND(!windows.has(p_window));
  1559. WindowData &wd = windows[p_window];
  1560. XStoreName(x11_display, wd.x11_window, p_title.utf8().get_data());
  1561. Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
  1562. Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
  1563. if (_net_wm_name != None && utf8_string != None) {
  1564. XChangeProperty(x11_display, wd.x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
  1565. }
  1566. }
  1567. void DisplayServerX11::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1568. _THREAD_SAFE_METHOD_
  1569. ERR_FAIL_COND(!windows.has(p_window));
  1570. windows[p_window].mpath = p_region;
  1571. _update_window_mouse_passthrough(p_window);
  1572. }
  1573. void DisplayServerX11::_update_window_mouse_passthrough(WindowID p_window) {
  1574. ERR_FAIL_COND(!windows.has(p_window));
  1575. ERR_FAIL_COND(!xshaped_ext_ok);
  1576. const Vector<Vector2> region_path = windows[p_window].mpath;
  1577. int event_base, error_base;
  1578. const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base);
  1579. if (ext_okay) {
  1580. if (windows[p_window].mpass) {
  1581. Region region = XCreateRegion();
  1582. XShapeCombineRegion(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, region, ShapeSet);
  1583. XDestroyRegion(region);
  1584. } else if (region_path.size() == 0) {
  1585. XShapeCombineMask(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, None, ShapeSet);
  1586. } else {
  1587. XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * region_path.size());
  1588. for (int i = 0; i < region_path.size(); i++) {
  1589. points[i].x = region_path[i].x;
  1590. points[i].y = region_path[i].y;
  1591. }
  1592. Region region = XPolygonRegion(points, region_path.size(), EvenOddRule);
  1593. memfree(points);
  1594. XShapeCombineRegion(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, region, ShapeSet);
  1595. XDestroyRegion(region);
  1596. }
  1597. }
  1598. }
  1599. void DisplayServerX11::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1600. _THREAD_SAFE_METHOD_
  1601. ERR_FAIL_COND(!windows.has(p_window));
  1602. WindowData &wd = windows[p_window];
  1603. wd.rect_changed_callback = p_callable;
  1604. }
  1605. void DisplayServerX11::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1606. _THREAD_SAFE_METHOD_
  1607. ERR_FAIL_COND(!windows.has(p_window));
  1608. WindowData &wd = windows[p_window];
  1609. wd.event_callback = p_callable;
  1610. }
  1611. void DisplayServerX11::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1612. _THREAD_SAFE_METHOD_
  1613. ERR_FAIL_COND(!windows.has(p_window));
  1614. WindowData &wd = windows[p_window];
  1615. wd.input_event_callback = p_callable;
  1616. }
  1617. void DisplayServerX11::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1618. _THREAD_SAFE_METHOD_
  1619. ERR_FAIL_COND(!windows.has(p_window));
  1620. WindowData &wd = windows[p_window];
  1621. wd.input_text_callback = p_callable;
  1622. }
  1623. void DisplayServerX11::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1624. _THREAD_SAFE_METHOD_
  1625. ERR_FAIL_COND(!windows.has(p_window));
  1626. WindowData &wd = windows[p_window];
  1627. wd.drop_files_callback = p_callable;
  1628. }
  1629. int DisplayServerX11::window_get_current_screen(WindowID p_window) const {
  1630. _THREAD_SAFE_METHOD_
  1631. int count = get_screen_count();
  1632. if (count < 2) {
  1633. // Early exit with single monitor.
  1634. return 0;
  1635. }
  1636. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  1637. const WindowData &wd = windows[p_window];
  1638. const Rect2i window_rect(wd.position, wd.size);
  1639. // Find which monitor has the largest overlap with the given window.
  1640. int screen_index = 0;
  1641. int max_area = 0;
  1642. for (int i = 0; i < count; i++) {
  1643. Rect2i screen_rect = _screen_get_rect(i);
  1644. Rect2i intersection = screen_rect.intersection(window_rect);
  1645. int area = intersection.get_area();
  1646. if (area > max_area) {
  1647. max_area = area;
  1648. screen_index = i;
  1649. }
  1650. }
  1651. return screen_index;
  1652. }
  1653. void DisplayServerX11::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  1654. #if defined(GLES3_ENABLED)
  1655. if (gl_manager) {
  1656. gl_manager->window_make_current(p_window_id);
  1657. }
  1658. if (gl_manager_egl) {
  1659. gl_manager_egl->window_make_current(p_window_id);
  1660. }
  1661. #endif
  1662. }
  1663. void DisplayServerX11::window_set_current_screen(int p_screen, WindowID p_window) {
  1664. _THREAD_SAFE_METHOD_
  1665. ERR_FAIL_COND(!windows.has(p_window));
  1666. WindowData &wd = windows[p_window];
  1667. p_screen = _get_screen_index(p_screen);
  1668. ERR_FAIL_INDEX(p_screen, get_screen_count());
  1669. if (window_get_current_screen(p_window) == p_screen) {
  1670. return;
  1671. }
  1672. if (window_get_mode(p_window) == WINDOW_MODE_FULLSCREEN) {
  1673. Point2i position = screen_get_position(p_screen);
  1674. Size2i size = screen_get_size(p_screen);
  1675. XMoveResizeWindow(x11_display, wd.x11_window, position.x, position.y, size.x, size.y);
  1676. } else {
  1677. Rect2i srect = screen_get_usable_rect(p_screen);
  1678. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1679. Size2i wsize = window_get_size(p_window);
  1680. wpos += srect.position;
  1681. if (srect != Rect2i()) {
  1682. wpos.x = CLAMP(wpos.x, srect.position.x, srect.position.x + srect.size.width - wsize.width / 3);
  1683. wpos.y = CLAMP(wpos.y, srect.position.y, srect.position.y + srect.size.height - wsize.height / 3);
  1684. }
  1685. window_set_position(wpos, p_window);
  1686. }
  1687. }
  1688. void DisplayServerX11::window_set_transient(WindowID p_window, WindowID p_parent) {
  1689. _THREAD_SAFE_METHOD_
  1690. ERR_FAIL_COND(p_window == p_parent);
  1691. ERR_FAIL_COND(!windows.has(p_window));
  1692. WindowData &wd_window = windows[p_window];
  1693. WindowID prev_parent = wd_window.transient_parent;
  1694. ERR_FAIL_COND(prev_parent == p_parent);
  1695. DEBUG_LOG_X11("window_set_transient: %lu (%u), prev_parent=%u, parent=%u\n", wd_window.x11_window, p_window, prev_parent, p_parent);
  1696. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  1697. if (p_parent == INVALID_WINDOW_ID) {
  1698. //remove transient
  1699. ERR_FAIL_COND(prev_parent == INVALID_WINDOW_ID);
  1700. ERR_FAIL_COND(!windows.has(prev_parent));
  1701. WindowData &wd_parent = windows[prev_parent];
  1702. wd_window.transient_parent = INVALID_WINDOW_ID;
  1703. wd_parent.transient_children.erase(p_window);
  1704. XSetTransientForHint(x11_display, wd_window.x11_window, None);
  1705. XWindowAttributes xwa;
  1706. XSync(x11_display, False);
  1707. XGetWindowAttributes(x11_display, wd_parent.x11_window, &xwa);
  1708. // Set focus to parent sub window to avoid losing all focus when closing a nested sub-menu.
  1709. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  1710. // a subwindow and its parent are both destroyed.
  1711. if (!wd_window.no_focus && !wd_window.is_popup && wd_window.focused) {
  1712. if ((xwa.map_state == IsViewable) && !wd_parent.no_focus && !wd_window.is_popup && _window_focus_check()) {
  1713. _set_input_focus(wd_parent.x11_window, RevertToPointerRoot);
  1714. }
  1715. }
  1716. } else {
  1717. ERR_FAIL_COND(!windows.has(p_parent));
  1718. ERR_FAIL_COND_MSG(prev_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1719. WindowData &wd_parent = windows[p_parent];
  1720. wd_window.transient_parent = p_parent;
  1721. wd_parent.transient_children.insert(p_window);
  1722. XSetTransientForHint(x11_display, wd_window.x11_window, wd_parent.x11_window);
  1723. }
  1724. }
  1725. // Helper method. Assumes that the window id has already been checked and exists.
  1726. void DisplayServerX11::_update_size_hints(WindowID p_window) {
  1727. WindowData &wd = windows[p_window];
  1728. WindowMode window_mode = window_get_mode(p_window);
  1729. XSizeHints *xsh = XAllocSizeHints();
  1730. // Always set the position and size hints - they should be synchronized with the actual values after the window is mapped anyway
  1731. xsh->flags |= PPosition | PSize;
  1732. xsh->x = wd.position.x;
  1733. xsh->y = wd.position.y;
  1734. xsh->width = wd.size.width;
  1735. xsh->height = wd.size.height;
  1736. if (window_mode == WINDOW_MODE_FULLSCREEN || window_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1737. // Do not set any other hints to prevent the window manager from ignoring the fullscreen flags
  1738. } else if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) {
  1739. // If resizing is disabled, use the forced size
  1740. xsh->flags |= PMinSize | PMaxSize;
  1741. xsh->min_width = wd.size.x;
  1742. xsh->max_width = wd.size.x;
  1743. xsh->min_height = wd.size.y;
  1744. xsh->max_height = wd.size.y;
  1745. } else {
  1746. // Otherwise, just respect min_size and max_size
  1747. if (wd.min_size != Size2i()) {
  1748. xsh->flags |= PMinSize;
  1749. xsh->min_width = wd.min_size.x;
  1750. xsh->min_height = wd.min_size.y;
  1751. }
  1752. if (wd.max_size != Size2i()) {
  1753. xsh->flags |= PMaxSize;
  1754. xsh->max_width = wd.max_size.x;
  1755. xsh->max_height = wd.max_size.y;
  1756. }
  1757. }
  1758. XSetWMNormalHints(x11_display, wd.x11_window, xsh);
  1759. XFree(xsh);
  1760. }
  1761. Point2i DisplayServerX11::window_get_position(WindowID p_window) const {
  1762. _THREAD_SAFE_METHOD_
  1763. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1764. const WindowData &wd = windows[p_window];
  1765. return wd.position;
  1766. }
  1767. Point2i DisplayServerX11::window_get_position_with_decorations(WindowID p_window) const {
  1768. _THREAD_SAFE_METHOD_
  1769. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1770. const WindowData &wd = windows[p_window];
  1771. if (wd.fullscreen) {
  1772. return wd.position;
  1773. }
  1774. XWindowAttributes xwa;
  1775. XSync(x11_display, False);
  1776. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1777. int x = wd.position.x;
  1778. int y = wd.position.y;
  1779. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1780. if (prop != None) {
  1781. Atom type;
  1782. int format;
  1783. unsigned long len;
  1784. unsigned long remaining;
  1785. unsigned char *data = nullptr;
  1786. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1787. if (format == 32 && len == 4 && data) {
  1788. long *extents = (long *)data;
  1789. x -= extents[0]; // left
  1790. y -= extents[2]; // top
  1791. }
  1792. XFree(data);
  1793. }
  1794. }
  1795. return Size2i(x, y);
  1796. }
  1797. void DisplayServerX11::window_set_position(const Point2i &p_position, WindowID p_window) {
  1798. _THREAD_SAFE_METHOD_
  1799. ERR_FAIL_COND(!windows.has(p_window));
  1800. WindowData &wd = windows[p_window];
  1801. int x = 0;
  1802. int y = 0;
  1803. if (!window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
  1804. //exclude window decorations
  1805. XSync(x11_display, False);
  1806. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1807. if (prop != None) {
  1808. Atom type;
  1809. int format;
  1810. unsigned long len;
  1811. unsigned long remaining;
  1812. unsigned char *data = nullptr;
  1813. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1814. if (format == 32 && len == 4 && data) {
  1815. long *extents = (long *)data;
  1816. x = extents[0];
  1817. y = extents[2];
  1818. }
  1819. XFree(data);
  1820. }
  1821. }
  1822. }
  1823. XMoveWindow(x11_display, wd.x11_window, p_position.x - x, p_position.y - y);
  1824. _update_real_mouse_position(wd);
  1825. }
  1826. void DisplayServerX11::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1827. _THREAD_SAFE_METHOD_
  1828. ERR_FAIL_COND(!windows.has(p_window));
  1829. WindowData &wd = windows[p_window];
  1830. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1831. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1832. return;
  1833. }
  1834. wd.max_size = p_size;
  1835. _update_size_hints(p_window);
  1836. XFlush(x11_display);
  1837. }
  1838. Size2i DisplayServerX11::window_get_max_size(WindowID p_window) const {
  1839. _THREAD_SAFE_METHOD_
  1840. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1841. const WindowData &wd = windows[p_window];
  1842. return wd.max_size;
  1843. }
  1844. void DisplayServerX11::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1845. _THREAD_SAFE_METHOD_
  1846. ERR_FAIL_COND(!windows.has(p_window));
  1847. WindowData &wd = windows[p_window];
  1848. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1849. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1850. return;
  1851. }
  1852. wd.min_size = p_size;
  1853. _update_size_hints(p_window);
  1854. XFlush(x11_display);
  1855. }
  1856. Size2i DisplayServerX11::window_get_min_size(WindowID p_window) const {
  1857. _THREAD_SAFE_METHOD_
  1858. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1859. const WindowData &wd = windows[p_window];
  1860. return wd.min_size;
  1861. }
  1862. void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) {
  1863. _THREAD_SAFE_METHOD_
  1864. ERR_FAIL_COND(!windows.has(p_window));
  1865. Size2i size = p_size;
  1866. size.x = MAX(1, size.x);
  1867. size.y = MAX(1, size.y);
  1868. WindowData &wd = windows[p_window];
  1869. if (wd.size.width == size.width && wd.size.height == size.height) {
  1870. return;
  1871. }
  1872. XWindowAttributes xwa;
  1873. XSync(x11_display, False);
  1874. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1875. int old_w = xwa.width;
  1876. int old_h = xwa.height;
  1877. // Update our videomode width and height
  1878. wd.size = size;
  1879. // Update the size hints first to make sure the window size can be set
  1880. _update_size_hints(p_window);
  1881. // Resize the window
  1882. XResizeWindow(x11_display, wd.x11_window, size.x, size.y);
  1883. for (int timeout = 0; timeout < 50; ++timeout) {
  1884. XSync(x11_display, False);
  1885. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1886. if (old_w != xwa.width || old_h != xwa.height) {
  1887. break;
  1888. }
  1889. usleep(10000);
  1890. }
  1891. // Keep rendering context window size in sync
  1892. #if defined(RD_ENABLED)
  1893. if (context_rd) {
  1894. context_rd->window_resize(p_window, xwa.width, xwa.height);
  1895. }
  1896. #endif
  1897. #if defined(GLES3_ENABLED)
  1898. if (gl_manager) {
  1899. gl_manager->window_resize(p_window, xwa.width, xwa.height);
  1900. }
  1901. if (gl_manager_egl) {
  1902. gl_manager_egl->window_resize(p_window, xwa.width, xwa.height);
  1903. }
  1904. #endif
  1905. }
  1906. Size2i DisplayServerX11::window_get_size(WindowID p_window) const {
  1907. _THREAD_SAFE_METHOD_
  1908. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1909. const WindowData &wd = windows[p_window];
  1910. return wd.size;
  1911. }
  1912. Size2i DisplayServerX11::window_get_size_with_decorations(WindowID p_window) const {
  1913. _THREAD_SAFE_METHOD_
  1914. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1915. const WindowData &wd = windows[p_window];
  1916. if (wd.fullscreen) {
  1917. return wd.size;
  1918. }
  1919. XWindowAttributes xwa;
  1920. XSync(x11_display, False);
  1921. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  1922. int w = xwa.width;
  1923. int h = xwa.height;
  1924. Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
  1925. if (prop != None) {
  1926. Atom type;
  1927. int format;
  1928. unsigned long len;
  1929. unsigned long remaining;
  1930. unsigned char *data = nullptr;
  1931. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  1932. if (format == 32 && len == 4 && data) {
  1933. long *extents = (long *)data;
  1934. w += extents[0] + extents[1]; // left, right
  1935. h += extents[2] + extents[3]; // top, bottom
  1936. }
  1937. XFree(data);
  1938. }
  1939. }
  1940. return Size2i(w, h);
  1941. }
  1942. // Just a helper to reduce code duplication in `window_is_maximize_allowed`
  1943. // and `_set_wm_maximized`.
  1944. bool DisplayServerX11::_window_maximize_check(WindowID p_window, const char *p_atom_name) const {
  1945. ERR_FAIL_COND_V(!windows.has(p_window), false);
  1946. const WindowData &wd = windows[p_window];
  1947. Atom property = XInternAtom(x11_display, p_atom_name, False);
  1948. Atom type;
  1949. int format;
  1950. unsigned long len;
  1951. unsigned long remaining;
  1952. unsigned char *data = nullptr;
  1953. bool retval = false;
  1954. if (property == None) {
  1955. return false;
  1956. }
  1957. int result = XGetWindowProperty(
  1958. x11_display,
  1959. wd.x11_window,
  1960. property,
  1961. 0,
  1962. 1024,
  1963. False,
  1964. XA_ATOM,
  1965. &type,
  1966. &format,
  1967. &len,
  1968. &remaining,
  1969. &data);
  1970. if (result == Success && data) {
  1971. Atom *atoms = (Atom *)data;
  1972. Atom wm_act_max_horz;
  1973. Atom wm_act_max_vert;
  1974. if (strcmp(p_atom_name, "_NET_WM_STATE") == 0) {
  1975. wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  1976. wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  1977. } else {
  1978. wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False);
  1979. wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False);
  1980. }
  1981. bool found_wm_act_max_horz = false;
  1982. bool found_wm_act_max_vert = false;
  1983. for (uint64_t i = 0; i < len; i++) {
  1984. if (atoms[i] == wm_act_max_horz) {
  1985. found_wm_act_max_horz = true;
  1986. }
  1987. if (atoms[i] == wm_act_max_vert) {
  1988. found_wm_act_max_vert = true;
  1989. }
  1990. if (found_wm_act_max_horz || found_wm_act_max_vert) {
  1991. retval = true;
  1992. break;
  1993. }
  1994. }
  1995. XFree(data);
  1996. }
  1997. return retval;
  1998. }
  1999. bool DisplayServerX11::_window_minimize_check(WindowID p_window) const {
  2000. const WindowData &wd = windows[p_window];
  2001. // Using EWMH instead of ICCCM, might work better for Wayland users.
  2002. Atom property = XInternAtom(x11_display, "_NET_WM_STATE", True);
  2003. Atom hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", True);
  2004. if (property == None || hidden == None) {
  2005. return false;
  2006. }
  2007. Atom type;
  2008. int format;
  2009. unsigned long len;
  2010. unsigned long remaining;
  2011. Atom *atoms = nullptr;
  2012. int result = XGetWindowProperty(
  2013. x11_display,
  2014. wd.x11_window,
  2015. property,
  2016. 0,
  2017. 32,
  2018. False,
  2019. XA_ATOM,
  2020. &type,
  2021. &format,
  2022. &len,
  2023. &remaining,
  2024. (unsigned char **)&atoms);
  2025. if (result == Success && atoms) {
  2026. for (unsigned int i = 0; i < len; i++) {
  2027. if (atoms[i] == hidden) {
  2028. XFree(atoms);
  2029. return true;
  2030. }
  2031. }
  2032. XFree(atoms);
  2033. }
  2034. return false;
  2035. }
  2036. bool DisplayServerX11::_window_fullscreen_check(WindowID p_window) const {
  2037. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2038. const WindowData &wd = windows[p_window];
  2039. // Using EWMH -- Extended Window Manager Hints
  2040. Atom property = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2041. Atom type;
  2042. int format;
  2043. unsigned long len;
  2044. unsigned long remaining;
  2045. unsigned char *data = nullptr;
  2046. bool retval = false;
  2047. if (property == None) {
  2048. return retval;
  2049. }
  2050. int result = XGetWindowProperty(
  2051. x11_display,
  2052. wd.x11_window,
  2053. property,
  2054. 0,
  2055. 1024,
  2056. False,
  2057. XA_ATOM,
  2058. &type,
  2059. &format,
  2060. &len,
  2061. &remaining,
  2062. &data);
  2063. if (result == Success) {
  2064. Atom *atoms = (Atom *)data;
  2065. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  2066. for (uint64_t i = 0; i < len; i++) {
  2067. if (atoms[i] == wm_fullscreen) {
  2068. retval = true;
  2069. break;
  2070. }
  2071. }
  2072. XFree(data);
  2073. }
  2074. return retval;
  2075. }
  2076. void DisplayServerX11::_validate_mode_on_map(WindowID p_window) {
  2077. // Check if we applied any window modes that didn't take effect while unmapped
  2078. const WindowData &wd = windows[p_window];
  2079. if (wd.fullscreen && !_window_fullscreen_check(p_window)) {
  2080. _set_wm_fullscreen(p_window, true, wd.exclusive_fullscreen);
  2081. } else if (wd.maximized && !_window_maximize_check(p_window, "_NET_WM_STATE")) {
  2082. _set_wm_maximized(p_window, true);
  2083. } else if (wd.minimized && !_window_minimize_check(p_window)) {
  2084. _set_wm_minimized(p_window, true);
  2085. }
  2086. if (wd.on_top) {
  2087. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2088. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  2089. XClientMessageEvent xev;
  2090. memset(&xev, 0, sizeof(xev));
  2091. xev.type = ClientMessage;
  2092. xev.window = wd.x11_window;
  2093. xev.message_type = wm_state;
  2094. xev.format = 32;
  2095. xev.data.l[0] = _NET_WM_STATE_ADD;
  2096. xev.data.l[1] = wm_above;
  2097. xev.data.l[3] = 1;
  2098. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  2099. }
  2100. }
  2101. bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const {
  2102. _THREAD_SAFE_METHOD_
  2103. return _window_maximize_check(p_window, "_NET_WM_ALLOWED_ACTIONS");
  2104. }
  2105. void DisplayServerX11::_set_wm_maximized(WindowID p_window, bool p_enabled) {
  2106. ERR_FAIL_COND(!windows.has(p_window));
  2107. WindowData &wd = windows[p_window];
  2108. // Using EWMH -- Extended Window Manager Hints
  2109. XEvent xev;
  2110. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2111. Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
  2112. Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
  2113. memset(&xev, 0, sizeof(xev));
  2114. xev.type = ClientMessage;
  2115. xev.xclient.window = wd.x11_window;
  2116. xev.xclient.message_type = wm_state;
  2117. xev.xclient.format = 32;
  2118. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  2119. xev.xclient.data.l[1] = wm_max_horz;
  2120. xev.xclient.data.l[2] = wm_max_vert;
  2121. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2122. if (p_enabled && window_is_maximize_allowed(p_window)) {
  2123. // Wait for effective resizing (so the GLX context is too).
  2124. // Give up after 0.5s, it's not going to happen on this WM.
  2125. // https://github.com/godotengine/godot/issues/19978
  2126. for (int attempt = 0; window_get_mode(p_window) != WINDOW_MODE_MAXIMIZED && attempt < 50; attempt++) {
  2127. usleep(10000);
  2128. }
  2129. }
  2130. wd.maximized = p_enabled;
  2131. }
  2132. void DisplayServerX11::_set_wm_minimized(WindowID p_window, bool p_enabled) {
  2133. WindowData &wd = windows[p_window];
  2134. // Using ICCCM -- Inter-Client Communication Conventions Manual
  2135. XEvent xev;
  2136. Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
  2137. memset(&xev, 0, sizeof(xev));
  2138. xev.type = ClientMessage;
  2139. xev.xclient.window = wd.x11_window;
  2140. xev.xclient.message_type = wm_change;
  2141. xev.xclient.format = 32;
  2142. xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState;
  2143. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2144. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2145. Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
  2146. memset(&xev, 0, sizeof(xev));
  2147. xev.type = ClientMessage;
  2148. xev.xclient.window = wd.x11_window;
  2149. xev.xclient.message_type = wm_state;
  2150. xev.xclient.format = 32;
  2151. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  2152. xev.xclient.data.l[1] = wm_hidden;
  2153. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2154. wd.minimized = p_enabled;
  2155. }
  2156. void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled, bool p_exclusive) {
  2157. ERR_FAIL_COND(!windows.has(p_window));
  2158. WindowData &wd = windows[p_window];
  2159. if (p_enabled && !window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
  2160. // remove decorations if the window is not already borderless
  2161. Hints hints;
  2162. Atom property;
  2163. hints.flags = 2;
  2164. hints.decorations = 0;
  2165. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  2166. if (property != None) {
  2167. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  2168. }
  2169. }
  2170. if (p_enabled) {
  2171. // Set the window as resizable to prevent window managers to ignore the fullscreen state flag.
  2172. _update_size_hints(p_window);
  2173. }
  2174. // Using EWMH -- Extended Window Manager Hints
  2175. XEvent xev;
  2176. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2177. Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
  2178. memset(&xev, 0, sizeof(xev));
  2179. xev.type = ClientMessage;
  2180. xev.xclient.window = wd.x11_window;
  2181. xev.xclient.message_type = wm_state;
  2182. xev.xclient.format = 32;
  2183. xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  2184. xev.xclient.data.l[1] = wm_fullscreen;
  2185. xev.xclient.data.l[2] = 0;
  2186. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2187. // set bypass compositor hint
  2188. Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
  2189. unsigned long compositing_disable_on = 0; // Use default.
  2190. if (p_enabled) {
  2191. if (p_exclusive) {
  2192. compositing_disable_on = 1; // Force composition OFF to reduce overhead.
  2193. } else {
  2194. compositing_disable_on = 2; // Force composition ON to allow popup windows.
  2195. }
  2196. }
  2197. if (bypass_compositor != None) {
  2198. XChangeProperty(x11_display, wd.x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
  2199. }
  2200. XFlush(x11_display);
  2201. if (!p_enabled) {
  2202. // Reset the non-resizable flags if we un-set these before.
  2203. _update_size_hints(p_window);
  2204. // put back or remove decorations according to the last set borderless state
  2205. Hints hints;
  2206. Atom property;
  2207. hints.flags = 2;
  2208. hints.decorations = wd.borderless ? 0 : 1;
  2209. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  2210. if (property != None) {
  2211. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  2212. }
  2213. }
  2214. }
  2215. void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) {
  2216. _THREAD_SAFE_METHOD_
  2217. ERR_FAIL_COND(!windows.has(p_window));
  2218. WindowData &wd = windows[p_window];
  2219. WindowMode old_mode = window_get_mode(p_window);
  2220. if (old_mode == p_mode) {
  2221. return; // do nothing
  2222. }
  2223. //remove all "extra" modes
  2224. switch (old_mode) {
  2225. case WINDOW_MODE_WINDOWED: {
  2226. //do nothing
  2227. } break;
  2228. case WINDOW_MODE_MINIMIZED: {
  2229. _set_wm_minimized(p_window, false);
  2230. } break;
  2231. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2232. case WINDOW_MODE_FULLSCREEN: {
  2233. //Remove full-screen
  2234. wd.fullscreen = false;
  2235. wd.exclusive_fullscreen = false;
  2236. _set_wm_fullscreen(p_window, false, false);
  2237. //un-maximize required for always on top
  2238. bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window);
  2239. window_set_position(wd.last_position_before_fs, p_window);
  2240. if (on_top) {
  2241. _set_wm_maximized(p_window, false);
  2242. }
  2243. } break;
  2244. case WINDOW_MODE_MAXIMIZED: {
  2245. _set_wm_maximized(p_window, false);
  2246. } break;
  2247. }
  2248. switch (p_mode) {
  2249. case WINDOW_MODE_WINDOWED: {
  2250. //do nothing
  2251. } break;
  2252. case WINDOW_MODE_MINIMIZED: {
  2253. _set_wm_minimized(p_window, true);
  2254. } break;
  2255. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2256. case WINDOW_MODE_FULLSCREEN: {
  2257. wd.last_position_before_fs = wd.position;
  2258. if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) {
  2259. _set_wm_maximized(p_window, true);
  2260. }
  2261. wd.fullscreen = true;
  2262. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2263. wd.exclusive_fullscreen = true;
  2264. _set_wm_fullscreen(p_window, true, true);
  2265. } else {
  2266. wd.exclusive_fullscreen = false;
  2267. _set_wm_fullscreen(p_window, true, false);
  2268. }
  2269. } break;
  2270. case WINDOW_MODE_MAXIMIZED: {
  2271. _set_wm_maximized(p_window, true);
  2272. } break;
  2273. }
  2274. }
  2275. DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) const {
  2276. _THREAD_SAFE_METHOD_
  2277. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  2278. const WindowData &wd = windows[p_window];
  2279. if (wd.fullscreen) { //if fullscreen, it's not in another mode
  2280. if (wd.exclusive_fullscreen) {
  2281. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  2282. } else {
  2283. return WINDOW_MODE_FULLSCREEN;
  2284. }
  2285. }
  2286. // Test maximized.
  2287. // Using EWMH -- Extended Window Manager Hints
  2288. if (_window_maximize_check(p_window, "_NET_WM_STATE")) {
  2289. return WINDOW_MODE_MAXIMIZED;
  2290. }
  2291. {
  2292. if (_window_minimize_check(p_window)) {
  2293. return WINDOW_MODE_MINIMIZED;
  2294. }
  2295. }
  2296. // All other discarded, return windowed.
  2297. return WINDOW_MODE_WINDOWED;
  2298. }
  2299. void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2300. _THREAD_SAFE_METHOD_
  2301. ERR_FAIL_COND(!windows.has(p_window));
  2302. WindowData &wd = windows[p_window];
  2303. switch (p_flag) {
  2304. case WINDOW_FLAG_RESIZE_DISABLED: {
  2305. wd.resize_disabled = p_enabled;
  2306. _update_size_hints(p_window);
  2307. XFlush(x11_display);
  2308. } break;
  2309. case WINDOW_FLAG_BORDERLESS: {
  2310. Hints hints;
  2311. Atom property;
  2312. hints.flags = 2;
  2313. hints.decorations = p_enabled ? 0 : 1;
  2314. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  2315. if (property != None) {
  2316. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  2317. }
  2318. // Preserve window size
  2319. window_set_size(window_get_size(p_window), p_window);
  2320. wd.borderless = p_enabled;
  2321. _update_window_mouse_passthrough(p_window);
  2322. } break;
  2323. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2324. ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID, "Can't make a window transient if the 'on top' flag is active.");
  2325. if (p_enabled && wd.fullscreen) {
  2326. _set_wm_maximized(p_window, true);
  2327. }
  2328. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2329. Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
  2330. XClientMessageEvent xev;
  2331. memset(&xev, 0, sizeof(xev));
  2332. xev.type = ClientMessage;
  2333. xev.window = wd.x11_window;
  2334. xev.message_type = wm_state;
  2335. xev.format = 32;
  2336. xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
  2337. xev.data.l[1] = wm_above;
  2338. xev.data.l[3] = 1;
  2339. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
  2340. if (!p_enabled && !wd.fullscreen) {
  2341. _set_wm_maximized(p_window, false);
  2342. }
  2343. wd.on_top = p_enabled;
  2344. } break;
  2345. case WINDOW_FLAG_TRANSPARENT: {
  2346. wd.layered_window = p_enabled;
  2347. } break;
  2348. case WINDOW_FLAG_NO_FOCUS: {
  2349. wd.no_focus = p_enabled;
  2350. } break;
  2351. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2352. wd.mpass = p_enabled;
  2353. _update_window_mouse_passthrough(p_window);
  2354. } break;
  2355. case WINDOW_FLAG_POPUP: {
  2356. XWindowAttributes xwa;
  2357. XSync(x11_display, False);
  2358. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  2359. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  2360. ERR_FAIL_COND_MSG((xwa.map_state == IsViewable) && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  2361. wd.is_popup = p_enabled;
  2362. } break;
  2363. default: {
  2364. }
  2365. }
  2366. }
  2367. bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2368. _THREAD_SAFE_METHOD_
  2369. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2370. const WindowData &wd = windows[p_window];
  2371. switch (p_flag) {
  2372. case WINDOW_FLAG_RESIZE_DISABLED: {
  2373. return wd.resize_disabled;
  2374. } break;
  2375. case WINDOW_FLAG_BORDERLESS: {
  2376. bool borderless = wd.borderless;
  2377. Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  2378. if (prop != None) {
  2379. Atom type;
  2380. int format;
  2381. unsigned long len;
  2382. unsigned long remaining;
  2383. unsigned char *data = nullptr;
  2384. if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
  2385. if (data && (format == 32) && (len >= 5)) {
  2386. borderless = !(reinterpret_cast<Hints *>(data)->decorations);
  2387. }
  2388. if (data) {
  2389. XFree(data);
  2390. }
  2391. }
  2392. }
  2393. return borderless;
  2394. } break;
  2395. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2396. return wd.on_top;
  2397. } break;
  2398. case WINDOW_FLAG_TRANSPARENT: {
  2399. return wd.layered_window;
  2400. } break;
  2401. case WINDOW_FLAG_NO_FOCUS: {
  2402. return wd.no_focus;
  2403. } break;
  2404. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2405. return wd.mpass;
  2406. } break;
  2407. case WINDOW_FLAG_POPUP: {
  2408. return wd.is_popup;
  2409. } break;
  2410. default: {
  2411. }
  2412. }
  2413. return false;
  2414. }
  2415. void DisplayServerX11::window_request_attention(WindowID p_window) {
  2416. _THREAD_SAFE_METHOD_
  2417. ERR_FAIL_COND(!windows.has(p_window));
  2418. const WindowData &wd = windows[p_window];
  2419. // Using EWMH -- Extended Window Manager Hints
  2420. //
  2421. // Sets the _NET_WM_STATE_DEMANDS_ATTENTION atom for WM_STATE
  2422. // Will be unset by the window manager after user react on the request for attention
  2423. XEvent xev;
  2424. Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
  2425. Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
  2426. memset(&xev, 0, sizeof(xev));
  2427. xev.type = ClientMessage;
  2428. xev.xclient.window = wd.x11_window;
  2429. xev.xclient.message_type = wm_state;
  2430. xev.xclient.format = 32;
  2431. xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
  2432. xev.xclient.data.l[1] = wm_attention;
  2433. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2434. XFlush(x11_display);
  2435. }
  2436. void DisplayServerX11::window_move_to_foreground(WindowID p_window) {
  2437. _THREAD_SAFE_METHOD_
  2438. ERR_FAIL_COND(!windows.has(p_window));
  2439. const WindowData &wd = windows[p_window];
  2440. XEvent xev;
  2441. Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
  2442. memset(&xev, 0, sizeof(xev));
  2443. xev.type = ClientMessage;
  2444. xev.xclient.window = wd.x11_window;
  2445. xev.xclient.message_type = net_active_window;
  2446. xev.xclient.format = 32;
  2447. xev.xclient.data.l[0] = 1;
  2448. xev.xclient.data.l[1] = CurrentTime;
  2449. XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
  2450. XFlush(x11_display);
  2451. }
  2452. DisplayServerX11::WindowID DisplayServerX11::get_focused_window() const {
  2453. return last_focused_window;
  2454. }
  2455. bool DisplayServerX11::window_is_focused(WindowID p_window) const {
  2456. _THREAD_SAFE_METHOD_
  2457. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2458. const WindowData &wd = windows[p_window];
  2459. return wd.focused;
  2460. }
  2461. bool DisplayServerX11::window_can_draw(WindowID p_window) const {
  2462. //this seems to be all that is provided by X11
  2463. return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED;
  2464. }
  2465. bool DisplayServerX11::can_any_window_draw() const {
  2466. _THREAD_SAFE_METHOD_
  2467. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2468. if (window_get_mode(E.key) != WINDOW_MODE_MINIMIZED) {
  2469. return true;
  2470. }
  2471. }
  2472. return false;
  2473. }
  2474. void DisplayServerX11::window_set_ime_active(const bool p_active, WindowID p_window) {
  2475. _THREAD_SAFE_METHOD_
  2476. ERR_FAIL_COND(!windows.has(p_window));
  2477. WindowData &wd = windows[p_window];
  2478. if (!wd.xic) {
  2479. return;
  2480. }
  2481. if (!wd.focused) {
  2482. wd.ime_active = false;
  2483. im_text = String();
  2484. im_selection = Vector2i();
  2485. return;
  2486. }
  2487. // Block events polling while changing input focus
  2488. // because it triggers some event polling internally.
  2489. if (p_active) {
  2490. MutexLock mutex_lock(events_mutex);
  2491. wd.ime_active = true;
  2492. XMapWindow(x11_display, wd.x11_xim_window);
  2493. XWindowAttributes xwa;
  2494. XSync(x11_display, False);
  2495. XGetWindowAttributes(x11_display, wd.x11_xim_window, &xwa);
  2496. if (xwa.map_state == IsViewable && _window_focus_check()) {
  2497. _set_input_focus(wd.x11_xim_window, RevertToParent);
  2498. }
  2499. XSetICFocus(wd.xic);
  2500. } else {
  2501. MutexLock mutex_lock(events_mutex);
  2502. XUnsetICFocus(wd.xic);
  2503. XUnmapWindow(x11_display, wd.x11_xim_window);
  2504. wd.ime_active = false;
  2505. im_text = String();
  2506. im_selection = Vector2i();
  2507. }
  2508. }
  2509. void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2510. _THREAD_SAFE_METHOD_
  2511. ERR_FAIL_COND(!windows.has(p_window));
  2512. WindowData &wd = windows[p_window];
  2513. if (!wd.xic) {
  2514. return;
  2515. }
  2516. if (!wd.focused) {
  2517. return;
  2518. }
  2519. if (wd.ime_active) {
  2520. XWindowAttributes xwa;
  2521. XSync(x11_display, False);
  2522. XGetWindowAttributes(x11_display, wd.x11_xim_window, &xwa);
  2523. if (xwa.map_state == IsViewable) {
  2524. XMoveWindow(x11_display, wd.x11_xim_window, p_pos.x, p_pos.y);
  2525. }
  2526. }
  2527. }
  2528. Point2i DisplayServerX11::ime_get_selection() const {
  2529. return im_selection;
  2530. }
  2531. String DisplayServerX11::ime_get_text() const {
  2532. return im_text;
  2533. }
  2534. void DisplayServerX11::cursor_set_shape(CursorShape p_shape) {
  2535. _THREAD_SAFE_METHOD_
  2536. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2537. if (p_shape == current_cursor) {
  2538. return;
  2539. }
  2540. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2541. if (cursors[p_shape] != None) {
  2542. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2543. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  2544. }
  2545. } else if (cursors[CURSOR_ARROW] != None) {
  2546. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2547. XDefineCursor(x11_display, E.value.x11_window, cursors[CURSOR_ARROW]);
  2548. }
  2549. }
  2550. }
  2551. current_cursor = p_shape;
  2552. }
  2553. DisplayServerX11::CursorShape DisplayServerX11::cursor_get_shape() const {
  2554. return current_cursor;
  2555. }
  2556. void DisplayServerX11::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2557. _THREAD_SAFE_METHOD_
  2558. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2559. if (p_cursor.is_valid()) {
  2560. HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
  2561. if (cursor_c) {
  2562. if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
  2563. cursor_set_shape(p_shape);
  2564. return;
  2565. }
  2566. cursors_cache.erase(p_shape);
  2567. }
  2568. Ref<Texture2D> texture = p_cursor;
  2569. ERR_FAIL_COND(!texture.is_valid());
  2570. Ref<AtlasTexture> atlas_texture = p_cursor;
  2571. Size2i texture_size;
  2572. Rect2i atlas_rect;
  2573. if (atlas_texture.is_valid()) {
  2574. texture = atlas_texture->get_atlas();
  2575. atlas_rect.size.width = texture->get_width();
  2576. atlas_rect.size.height = texture->get_height();
  2577. atlas_rect.position.x = atlas_texture->get_region().position.x;
  2578. atlas_rect.position.y = atlas_texture->get_region().position.y;
  2579. texture_size.width = atlas_texture->get_region().size.x;
  2580. texture_size.height = atlas_texture->get_region().size.y;
  2581. } else {
  2582. texture_size.width = texture->get_width();
  2583. texture_size.height = texture->get_height();
  2584. }
  2585. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  2586. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  2587. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  2588. Ref<Image> image = texture->get_image();
  2589. ERR_FAIL_COND(!image.is_valid());
  2590. if (image->is_compressed()) {
  2591. image = image->duplicate(true);
  2592. Error err = image->decompress();
  2593. ERR_FAIL_COND_MSG(err != OK, "Couldn't decompress VRAM-compressed custom mouse cursor image. Switch to a lossless compression mode in the Import dock.");
  2594. }
  2595. // Create the cursor structure
  2596. XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
  2597. XcursorUInt image_size = texture_size.width * texture_size.height;
  2598. XcursorDim size = sizeof(XcursorPixel) * image_size;
  2599. cursor_image->version = 1;
  2600. cursor_image->size = size;
  2601. cursor_image->xhot = p_hotspot.x;
  2602. cursor_image->yhot = p_hotspot.y;
  2603. // allocate memory to contain the whole file
  2604. cursor_image->pixels = (XcursorPixel *)memalloc(size);
  2605. for (XcursorPixel index = 0; index < image_size; index++) {
  2606. int row_index = floor(index / texture_size.width) + atlas_rect.position.y;
  2607. int column_index = (index % int(texture_size.width)) + atlas_rect.position.x;
  2608. if (atlas_texture.is_valid()) {
  2609. column_index = MIN(column_index, atlas_rect.size.width - 1);
  2610. row_index = MIN(row_index, atlas_rect.size.height - 1);
  2611. }
  2612. *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
  2613. }
  2614. ERR_FAIL_NULL(cursor_image->pixels);
  2615. // Save it for a further usage
  2616. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
  2617. Vector<Variant> params;
  2618. params.push_back(p_cursor);
  2619. params.push_back(p_hotspot);
  2620. cursors_cache.insert(p_shape, params);
  2621. if (p_shape == current_cursor) {
  2622. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2623. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2624. XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
  2625. }
  2626. }
  2627. }
  2628. memfree(cursor_image->pixels);
  2629. XcursorImageDestroy(cursor_image);
  2630. } else {
  2631. // Reset to default system cursor
  2632. if (cursor_img[p_shape]) {
  2633. cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_img[p_shape]);
  2634. }
  2635. cursors_cache.erase(p_shape);
  2636. CursorShape c = current_cursor;
  2637. current_cursor = CURSOR_MAX;
  2638. cursor_set_shape(c);
  2639. }
  2640. }
  2641. int DisplayServerX11::keyboard_get_layout_count() const {
  2642. int _group_count = 0;
  2643. XkbDescRec *kbd = XkbAllocKeyboard();
  2644. if (kbd) {
  2645. kbd->dpy = x11_display;
  2646. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2647. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2648. const Atom *groups = kbd->names->groups;
  2649. if (kbd->ctrls != nullptr) {
  2650. _group_count = kbd->ctrls->num_groups;
  2651. } else {
  2652. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2653. _group_count++;
  2654. }
  2655. }
  2656. XkbFreeKeyboard(kbd, 0, true);
  2657. }
  2658. return _group_count;
  2659. }
  2660. int DisplayServerX11::keyboard_get_current_layout() const {
  2661. XkbStateRec state;
  2662. XkbGetState(x11_display, XkbUseCoreKbd, &state);
  2663. return state.group;
  2664. }
  2665. void DisplayServerX11::keyboard_set_current_layout(int p_index) {
  2666. ERR_FAIL_INDEX(p_index, keyboard_get_layout_count());
  2667. XkbLockGroup(x11_display, XkbUseCoreKbd, p_index);
  2668. }
  2669. String DisplayServerX11::keyboard_get_layout_language(int p_index) const {
  2670. String ret;
  2671. XkbDescRec *kbd = XkbAllocKeyboard();
  2672. if (kbd) {
  2673. kbd->dpy = x11_display;
  2674. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2675. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2676. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  2677. int _group_count = 0;
  2678. const Atom *groups = kbd->names->groups;
  2679. if (kbd->ctrls != nullptr) {
  2680. _group_count = kbd->ctrls->num_groups;
  2681. } else {
  2682. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2683. _group_count++;
  2684. }
  2685. }
  2686. Atom names = kbd->names->symbols;
  2687. if (names != None) {
  2688. Vector<String> info = get_atom_name(x11_display, names).split("+");
  2689. if (p_index >= 0 && p_index < _group_count) {
  2690. if (p_index + 1 < info.size()) {
  2691. ret = info[p_index + 1]; // Skip "pc" at the start and "inet"/"group" at the end of symbols.
  2692. } else {
  2693. ret = "en"; // No symbol for layout fallback to "en".
  2694. }
  2695. } else {
  2696. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  2697. }
  2698. }
  2699. XkbFreeKeyboard(kbd, 0, true);
  2700. }
  2701. return ret.substr(0, 2);
  2702. }
  2703. String DisplayServerX11::keyboard_get_layout_name(int p_index) const {
  2704. String ret;
  2705. XkbDescRec *kbd = XkbAllocKeyboard();
  2706. if (kbd) {
  2707. kbd->dpy = x11_display;
  2708. XkbGetControls(x11_display, XkbAllControlsMask, kbd);
  2709. XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
  2710. XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
  2711. int _group_count = 0;
  2712. const Atom *groups = kbd->names->groups;
  2713. if (kbd->ctrls != nullptr) {
  2714. _group_count = kbd->ctrls->num_groups;
  2715. } else {
  2716. while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
  2717. _group_count++;
  2718. }
  2719. }
  2720. if (p_index >= 0 && p_index < _group_count) {
  2721. ret = get_atom_name(x11_display, groups[p_index]);
  2722. } else {
  2723. ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
  2724. }
  2725. XkbFreeKeyboard(kbd, 0, true);
  2726. }
  2727. return ret;
  2728. }
  2729. Key DisplayServerX11::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2730. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2731. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2732. unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
  2733. KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, keyboard_get_current_layout(), 0);
  2734. if (is_ascii_lower_case(xkeysym)) {
  2735. xkeysym -= ('a' - 'A');
  2736. }
  2737. Key key = KeyMappingX11::get_keycode(xkeysym);
  2738. // If not found, fallback to QWERTY.
  2739. // This should match the behavior of the event pump
  2740. if (key == Key::NONE) {
  2741. return p_keycode;
  2742. }
  2743. return (Key)(key | modifiers);
  2744. }
  2745. Key DisplayServerX11::keyboard_get_label_from_physical(Key p_keycode) const {
  2746. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2747. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2748. unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
  2749. KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, keyboard_get_current_layout(), 0);
  2750. if (is_ascii_lower_case(xkeysym)) {
  2751. xkeysym -= ('a' - 'A');
  2752. }
  2753. Key key = KeyMappingX11::get_keycode(xkeysym);
  2754. #ifdef XKB_ENABLED
  2755. if (xkb_loaded_v08p) {
  2756. String keysym = String::chr(xkb_keysym_to_utf32(xkb_keysym_to_upper(xkeysym)));
  2757. key = fix_key_label(keysym[0], KeyMappingX11::get_keycode(xkeysym));
  2758. }
  2759. #endif
  2760. // If not found, fallback to QWERTY.
  2761. // This should match the behavior of the event pump
  2762. if (key == Key::NONE) {
  2763. return p_keycode;
  2764. }
  2765. return (Key)(key | modifiers);
  2766. }
  2767. DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, Window p_window, Atom p_property) {
  2768. Atom actual_type = None;
  2769. int actual_format = 0;
  2770. unsigned long nitems = 0;
  2771. unsigned long bytes_after = 0;
  2772. unsigned char *ret = nullptr;
  2773. // Keep trying to read the property until there are no bytes unread.
  2774. if (p_property != None) {
  2775. int read_bytes = 1024;
  2776. do {
  2777. if (ret != nullptr) {
  2778. XFree(ret);
  2779. }
  2780. XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
  2781. &actual_type, &actual_format, &nitems, &bytes_after,
  2782. &ret);
  2783. read_bytes *= 2;
  2784. } while (bytes_after != 0);
  2785. }
  2786. Property p = { ret, actual_format, (int)nitems, actual_type };
  2787. return p;
  2788. }
  2789. static Atom pick_target_from_list(Display *p_display, const Atom *p_list, int p_count) {
  2790. static const char *target_type = "text/uri-list";
  2791. for (int i = 0; i < p_count; i++) {
  2792. Atom atom = p_list[i];
  2793. if (atom != None && get_atom_name(p_display, atom) == target_type) {
  2794. return atom;
  2795. }
  2796. }
  2797. return None;
  2798. }
  2799. static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
  2800. static const char *target_type = "text/uri-list";
  2801. if (p_t1 != None && get_atom_name(p_disp, p_t1) == target_type) {
  2802. return p_t1;
  2803. }
  2804. if (p_t2 != None && get_atom_name(p_disp, p_t2) == target_type) {
  2805. return p_t2;
  2806. }
  2807. if (p_t3 != None && get_atom_name(p_disp, p_t3) == target_type) {
  2808. return p_t3;
  2809. }
  2810. return None;
  2811. }
  2812. void DisplayServerX11::_get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
  2813. state->set_shift_pressed((p_x11_state & ShiftMask));
  2814. state->set_ctrl_pressed((p_x11_state & ControlMask));
  2815. state->set_alt_pressed((p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/)); //altgr should not count as alt
  2816. state->set_meta_pressed((p_x11_state & Mod4Mask));
  2817. }
  2818. BitField<MouseButtonMask> DisplayServerX11::_get_mouse_button_state(MouseButton p_x11_button, int p_x11_type) {
  2819. MouseButtonMask mask = mouse_button_to_mask(p_x11_button);
  2820. if (p_x11_type == ButtonPress) {
  2821. last_button_state.set_flag(mask);
  2822. } else {
  2823. last_button_state.clear_flag(mask);
  2824. }
  2825. return last_button_state;
  2826. }
  2827. void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) {
  2828. WindowData &wd = windows[p_window];
  2829. // X11 functions don't know what const is
  2830. XKeyEvent *xkeyevent = p_event;
  2831. if (wd.ime_in_progress) {
  2832. return;
  2833. }
  2834. if (wd.ime_suppress_next_keyup) {
  2835. wd.ime_suppress_next_keyup = false;
  2836. if (xkeyevent->type != KeyPress) {
  2837. return;
  2838. }
  2839. }
  2840. // This code was pretty difficult to write.
  2841. // The docs stink and every toolkit seems to
  2842. // do it in a different way.
  2843. /* Phase 1, obtain a proper keysym */
  2844. // This was also very difficult to figure out.
  2845. // You'd expect you could just use Keysym provided by
  2846. // XKeycodeToKeysym to obtain internationalized
  2847. // input.. WRONG!!
  2848. // you must use XLookupString (???) which not only wastes
  2849. // cycles generating an unnecessary string, but also
  2850. // still works in half the cases. (won't handle deadkeys)
  2851. // For more complex input methods (deadkeys and more advanced)
  2852. // you have to use XmbLookupString (??).
  2853. // So then you have to choose which of both results
  2854. // you want to keep.
  2855. // This is a real bizarreness and cpu waster.
  2856. KeySym keysym_keycode = 0; // keysym used to find a keycode
  2857. KeySym keysym_unicode = 0; // keysym used to find unicode
  2858. // XLookupString returns keysyms usable as nice keycodes.
  2859. char str[256] = {};
  2860. XKeyEvent xkeyevent_no_mod = *xkeyevent;
  2861. xkeyevent_no_mod.state &= ~ShiftMask;
  2862. xkeyevent_no_mod.state &= ~ControlMask;
  2863. XLookupString(xkeyevent, str, 255, &keysym_unicode, nullptr);
  2864. XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr);
  2865. String keysym;
  2866. #ifdef XKB_ENABLED
  2867. if (xkb_loaded_v08p) {
  2868. KeySym keysym_unicode_nm = 0; // keysym used to find unicode
  2869. XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_unicode_nm, nullptr);
  2870. keysym = String::chr(xkb_keysym_to_utf32(xkb_keysym_to_upper(keysym_unicode_nm)));
  2871. }
  2872. #endif
  2873. // Meanwhile, XLookupString returns keysyms useful for unicode.
  2874. if (!xmbstring) {
  2875. // keep a temporary buffer for the string
  2876. xmbstring = (char *)memalloc(sizeof(char) * 8);
  2877. xmblen = 8;
  2878. }
  2879. if (xkeyevent->type == KeyPress && wd.xic) {
  2880. Status status;
  2881. #ifdef X_HAVE_UTF8_STRING
  2882. int utf8len = 8;
  2883. char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
  2884. int utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2885. utf8len - 1, &keysym_unicode, &status);
  2886. if (status == XBufferOverflow) {
  2887. utf8len = utf8bytes + 1;
  2888. utf8string = (char *)memrealloc(utf8string, utf8len);
  2889. utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
  2890. utf8len - 1, &keysym_unicode, &status);
  2891. }
  2892. utf8string[utf8bytes] = '\0';
  2893. if (status == XLookupChars) {
  2894. bool keypress = xkeyevent->type == KeyPress;
  2895. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2896. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2897. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2898. keycode -= 'a' - 'A';
  2899. }
  2900. String tmp;
  2901. tmp.parse_utf8(utf8string, utf8bytes);
  2902. for (int i = 0; i < tmp.length(); i++) {
  2903. Ref<InputEventKey> k;
  2904. k.instantiate();
  2905. if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
  2906. continue;
  2907. }
  2908. if (keycode == Key::NONE) {
  2909. keycode = (Key)physical_keycode;
  2910. }
  2911. _get_key_modifier_state(xkeyevent->state, k);
  2912. k->set_window_id(p_window);
  2913. k->set_pressed(keypress);
  2914. k->set_keycode(keycode);
  2915. k->set_physical_keycode(physical_keycode);
  2916. if (!keysym.is_empty()) {
  2917. k->set_key_label(fix_key_label(keysym[0], keycode));
  2918. } else {
  2919. k->set_key_label(keycode);
  2920. }
  2921. if (keypress) {
  2922. k->set_unicode(fix_unicode(tmp[i]));
  2923. }
  2924. k->set_echo(false);
  2925. if (k->get_keycode() == Key::BACKTAB) {
  2926. //make it consistent across platforms.
  2927. k->set_keycode(Key::TAB);
  2928. k->set_physical_keycode(Key::TAB);
  2929. k->set_shift_pressed(true);
  2930. }
  2931. Input::get_singleton()->parse_input_event(k);
  2932. }
  2933. memfree(utf8string);
  2934. return;
  2935. }
  2936. memfree(utf8string);
  2937. #else
  2938. do {
  2939. int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
  2940. xmbstring[mnbytes] = '\0';
  2941. if (status == XBufferOverflow) {
  2942. xmblen = mnbytes + 1;
  2943. xmbstring = (char *)memrealloc(xmbstring, xmblen);
  2944. }
  2945. } while (status == XBufferOverflow);
  2946. #endif
  2947. #ifdef XKB_ENABLED
  2948. } else if (xkeyevent->type == KeyPress && wd.xkb_state && xkb_loaded_v05p) {
  2949. xkb_compose_feed_result res = xkb_compose_state_feed(wd.xkb_state, keysym_unicode);
  2950. if (res == XKB_COMPOSE_FEED_ACCEPTED) {
  2951. if (xkb_compose_state_get_status(wd.xkb_state) == XKB_COMPOSE_COMPOSED) {
  2952. bool keypress = xkeyevent->type == KeyPress;
  2953. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  2954. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  2955. KeyLocation key_location = KeyMappingX11::get_location(xkeyevent->keycode);
  2956. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  2957. keycode -= 'a' - 'A';
  2958. }
  2959. char str_xkb[256] = {};
  2960. int str_xkb_size = xkb_compose_state_get_utf8(wd.xkb_state, str_xkb, 255);
  2961. String tmp;
  2962. tmp.parse_utf8(str_xkb, str_xkb_size);
  2963. for (int i = 0; i < tmp.length(); i++) {
  2964. Ref<InputEventKey> k;
  2965. k.instantiate();
  2966. if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
  2967. continue;
  2968. }
  2969. if (keycode == Key::NONE) {
  2970. keycode = (Key)physical_keycode;
  2971. }
  2972. _get_key_modifier_state(xkeyevent->state, k);
  2973. k->set_window_id(p_window);
  2974. k->set_pressed(keypress);
  2975. k->set_keycode(keycode);
  2976. k->set_physical_keycode(physical_keycode);
  2977. if (!keysym.is_empty()) {
  2978. k->set_key_label(fix_key_label(keysym[0], keycode));
  2979. } else {
  2980. k->set_key_label(keycode);
  2981. }
  2982. if (keypress) {
  2983. k->set_unicode(fix_unicode(tmp[i]));
  2984. }
  2985. k->set_location(key_location);
  2986. k->set_echo(false);
  2987. if (k->get_keycode() == Key::BACKTAB) {
  2988. //make it consistent across platforms.
  2989. k->set_keycode(Key::TAB);
  2990. k->set_physical_keycode(Key::TAB);
  2991. k->set_shift_pressed(true);
  2992. }
  2993. Input::get_singleton()->parse_input_event(k);
  2994. }
  2995. return;
  2996. }
  2997. }
  2998. #endif
  2999. }
  3000. /* Phase 2, obtain a Godot keycode from the keysym */
  3001. // KeyMappingX11 just translated the X11 keysym to a PIGUI
  3002. // keysym, so it works in all platforms the same.
  3003. Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
  3004. Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
  3005. KeyLocation key_location = KeyMappingX11::get_location(xkeyevent->keycode);
  3006. /* Phase 3, obtain a unicode character from the keysym */
  3007. // KeyMappingX11 also translates keysym to unicode.
  3008. // It does a binary search on a table to translate
  3009. // most properly.
  3010. char32_t unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
  3011. /* Phase 4, determine if event must be filtered */
  3012. // This seems to be a side-effect of using XIM.
  3013. // XFilterEvent looks like a core X11 function,
  3014. // but it's actually just used to see if we must
  3015. // ignore a deadkey, or events XIM determines
  3016. // must not reach the actual gui.
  3017. // Guess it was a design problem of the extension
  3018. bool keypress = xkeyevent->type == KeyPress;
  3019. if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {
  3020. return;
  3021. }
  3022. if (keycode == Key::NONE) {
  3023. keycode = (Key)physical_keycode;
  3024. }
  3025. /* Phase 5, determine modifier mask */
  3026. // No problems here, except I had no way to
  3027. // know Mod1 was ALT and Mod4 was META (applekey/winkey)
  3028. // just tried Mods until i found them.
  3029. //print_verbose("mod1: "+itos(xkeyevent->state&Mod1Mask)+" mod 5: "+itos(xkeyevent->state&Mod5Mask));
  3030. Ref<InputEventKey> k;
  3031. k.instantiate();
  3032. k->set_window_id(p_window);
  3033. _get_key_modifier_state(xkeyevent->state, k);
  3034. /* Phase 6, determine echo character */
  3035. // Echo characters in X11 are a keyrelease and a keypress
  3036. // one after the other with the (almot) same timestamp.
  3037. // To detect them, i compare to the next event in list and
  3038. // check that their difference in time is below a threshold.
  3039. if (xkeyevent->type != KeyPress) {
  3040. p_echo = false;
  3041. // make sure there are events pending,
  3042. // so this call won't block.
  3043. if (p_event_index + 1 < p_events.size()) {
  3044. XEvent &peek_event = p_events[p_event_index + 1];
  3045. // I'm using a threshold of 5 msecs,
  3046. // since sometimes there seems to be a little
  3047. // jitter. I'm still not convinced that all this approach
  3048. // is correct, but the xorg developers are
  3049. // not very helpful today.
  3050. #define ABSDIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y)))
  3051. ::Time threshold = ABSDIFF(peek_event.xkey.time, xkeyevent->time);
  3052. #undef ABSDIFF
  3053. if (peek_event.type == KeyPress && threshold < 5) {
  3054. KeySym rk;
  3055. XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr);
  3056. if (rk == keysym_keycode) {
  3057. // Consume to next event.
  3058. ++p_event_index;
  3059. _handle_key_event(p_window, (XKeyEvent *)&peek_event, p_events, p_event_index, true);
  3060. return; //ignore current, echo next
  3061. }
  3062. }
  3063. // use the time from peek_event so it always works
  3064. }
  3065. // save the time to check for echo when keypress happens
  3066. }
  3067. /* Phase 7, send event to Window */
  3068. k->set_pressed(keypress);
  3069. if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
  3070. keycode -= int('a' - 'A');
  3071. }
  3072. k->set_keycode(keycode);
  3073. k->set_physical_keycode((Key)physical_keycode);
  3074. if (!keysym.is_empty()) {
  3075. k->set_key_label(fix_key_label(keysym[0], keycode));
  3076. } else {
  3077. k->set_key_label(keycode);
  3078. }
  3079. if (keypress) {
  3080. k->set_unicode(fix_unicode(unicode));
  3081. }
  3082. k->set_location(key_location);
  3083. k->set_echo(p_echo);
  3084. if (k->get_keycode() == Key::BACKTAB) {
  3085. //make it consistent across platforms.
  3086. k->set_keycode(Key::TAB);
  3087. k->set_physical_keycode(Key::TAB);
  3088. k->set_shift_pressed(true);
  3089. }
  3090. //don't set mod state if modifier keys are released by themselves
  3091. //else event.is_action() will not work correctly here
  3092. if (!k->is_pressed()) {
  3093. if (k->get_keycode() == Key::SHIFT) {
  3094. k->set_shift_pressed(false);
  3095. } else if (k->get_keycode() == Key::CTRL) {
  3096. k->set_ctrl_pressed(false);
  3097. } else if (k->get_keycode() == Key::ALT) {
  3098. k->set_alt_pressed(false);
  3099. } else if (k->get_keycode() == Key::META) {
  3100. k->set_meta_pressed(false);
  3101. }
  3102. }
  3103. bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_keycode());
  3104. if (k->is_pressed()) {
  3105. if (last_is_pressed) {
  3106. k->set_echo(true);
  3107. }
  3108. }
  3109. Input::get_singleton()->parse_input_event(k);
  3110. }
  3111. Atom DisplayServerX11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property, Atom p_selection) const {
  3112. if (p_target == XInternAtom(x11_display, "TARGETS", 0)) {
  3113. // Request to list all supported targets.
  3114. Atom data[9];
  3115. data[0] = XInternAtom(x11_display, "TARGETS", 0);
  3116. data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0);
  3117. data[2] = XInternAtom(x11_display, "MULTIPLE", 0);
  3118. data[3] = XInternAtom(x11_display, "UTF8_STRING", 0);
  3119. data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
  3120. data[5] = XInternAtom(x11_display, "TEXT", 0);
  3121. data[6] = XA_STRING;
  3122. data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
  3123. data[8] = XInternAtom(x11_display, "text/plain", 0);
  3124. XChangeProperty(x11_display,
  3125. p_requestor,
  3126. p_property,
  3127. XA_ATOM,
  3128. 32,
  3129. PropModeReplace,
  3130. (unsigned char *)&data,
  3131. sizeof(data) / sizeof(data[0]));
  3132. return p_property;
  3133. } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) {
  3134. // Request to check if SAVE_TARGETS is supported, nothing special to do.
  3135. XChangeProperty(x11_display,
  3136. p_requestor,
  3137. p_property,
  3138. XInternAtom(x11_display, "NULL", False),
  3139. 32,
  3140. PropModeReplace,
  3141. nullptr,
  3142. 0);
  3143. return p_property;
  3144. } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
  3145. p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
  3146. p_target == XInternAtom(x11_display, "TEXT", 0) ||
  3147. p_target == XA_STRING ||
  3148. p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
  3149. p_target == XInternAtom(x11_display, "text/plain", 0)) {
  3150. // Directly using internal clipboard because we know our window
  3151. // is the owner during a selection request.
  3152. CharString clip;
  3153. static const char *target_type = "PRIMARY";
  3154. if (p_selection != None && get_atom_name(x11_display, p_selection) == target_type) {
  3155. clip = internal_clipboard_primary.utf8();
  3156. } else {
  3157. clip = internal_clipboard.utf8();
  3158. }
  3159. XChangeProperty(x11_display,
  3160. p_requestor,
  3161. p_property,
  3162. p_target,
  3163. 8,
  3164. PropModeReplace,
  3165. (unsigned char *)clip.get_data(),
  3166. clip.length());
  3167. return p_property;
  3168. } else {
  3169. char *target_name = XGetAtomName(x11_display, p_target);
  3170. print_verbose(vformat("Target '%s' not supported.", target_name));
  3171. if (target_name) {
  3172. XFree(target_name);
  3173. }
  3174. return None;
  3175. }
  3176. }
  3177. void DisplayServerX11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const {
  3178. XEvent respond;
  3179. if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) {
  3180. // Request for multiple target conversions at once.
  3181. Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False);
  3182. respond.xselection.property = None;
  3183. Atom type;
  3184. int format;
  3185. unsigned long len;
  3186. unsigned long remaining;
  3187. unsigned char *data = nullptr;
  3188. if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) {
  3189. if ((len >= 2) && data) {
  3190. Atom *targets = (Atom *)data;
  3191. for (uint64_t i = 0; i < len; i += 2) {
  3192. Atom target = targets[i];
  3193. Atom &property = targets[i + 1];
  3194. property = _process_selection_request_target(target, p_event->requestor, property, p_event->selection);
  3195. }
  3196. XChangeProperty(x11_display,
  3197. p_event->requestor,
  3198. p_event->property,
  3199. atom_pair,
  3200. 32,
  3201. PropModeReplace,
  3202. (unsigned char *)targets,
  3203. len);
  3204. respond.xselection.property = p_event->property;
  3205. }
  3206. XFree(data);
  3207. }
  3208. } else {
  3209. // Request for target conversion.
  3210. respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property, p_event->selection);
  3211. }
  3212. respond.xselection.type = SelectionNotify;
  3213. respond.xselection.display = p_event->display;
  3214. respond.xselection.requestor = p_event->requestor;
  3215. respond.xselection.selection = p_event->selection;
  3216. respond.xselection.target = p_event->target;
  3217. respond.xselection.time = p_event->time;
  3218. XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond);
  3219. XFlush(x11_display);
  3220. }
  3221. int DisplayServerX11::_xim_preedit_start_callback(::XIM xim, ::XPointer client_data,
  3222. ::XPointer call_data) {
  3223. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  3224. WindowID window_id = ds->_get_focused_window_or_popup();
  3225. WindowData &wd = ds->windows[window_id];
  3226. if (wd.ime_active) {
  3227. wd.ime_in_progress = true;
  3228. }
  3229. return -1; // Allow preedit strings of any length (no limit).
  3230. }
  3231. void DisplayServerX11::_xim_preedit_done_callback(::XIM xim, ::XPointer client_data,
  3232. ::XPointer call_data) {
  3233. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  3234. WindowID window_id = ds->_get_focused_window_or_popup();
  3235. WindowData &wd = ds->windows[window_id];
  3236. if (wd.ime_active) {
  3237. wd.ime_in_progress = false;
  3238. wd.ime_suppress_next_keyup = true;
  3239. }
  3240. }
  3241. void DisplayServerX11::_xim_preedit_draw_callback(::XIM xim, ::XPointer client_data,
  3242. ::XIMPreeditDrawCallbackStruct *call_data) {
  3243. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  3244. WindowID window_id = ds->_get_focused_window_or_popup();
  3245. WindowData &wd = ds->windows[window_id];
  3246. XIMText *xim_text = call_data->text;
  3247. if (wd.ime_active) {
  3248. if (xim_text != nullptr) {
  3249. String changed_text;
  3250. if (xim_text->encoding_is_wchar) {
  3251. changed_text = String(xim_text->string.wide_char);
  3252. } else {
  3253. changed_text.parse_utf8(xim_text->string.multi_byte);
  3254. }
  3255. if (call_data->chg_length < 0) {
  3256. ds->im_text = ds->im_text.substr(0, call_data->chg_first) + changed_text;
  3257. } else {
  3258. ds->im_text = ds->im_text.substr(0, call_data->chg_first) + changed_text + ds->im_text.substr(call_data->chg_length);
  3259. }
  3260. // Find the start and end of the selection.
  3261. int start = 0, count = 0;
  3262. for (int i = 0; i < xim_text->length; i++) {
  3263. if (xim_text->feedback[i] & XIMReverse) {
  3264. if (count == 0) {
  3265. start = i;
  3266. count = 1;
  3267. } else {
  3268. count++;
  3269. }
  3270. }
  3271. }
  3272. if (count > 0) {
  3273. ds->im_selection = Point2i(start + call_data->chg_first, count);
  3274. } else {
  3275. ds->im_selection = Point2i(call_data->caret, 0);
  3276. }
  3277. } else {
  3278. ds->im_text = String();
  3279. ds->im_selection = Point2i();
  3280. }
  3281. callable_mp((Object *)OS_Unix::get_singleton()->get_main_loop(), &Object::notification).call_deferred(MainLoop::NOTIFICATION_OS_IME_UPDATE, false);
  3282. }
  3283. }
  3284. void DisplayServerX11::_xim_preedit_caret_callback(::XIM xim, ::XPointer client_data,
  3285. ::XIMPreeditCaretCallbackStruct *call_data) {
  3286. }
  3287. void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data,
  3288. ::XPointer call_data) {
  3289. WARN_PRINT("Input method stopped");
  3290. DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
  3291. ds->xim = nullptr;
  3292. for (KeyValue<WindowID, WindowData> &E : ds->windows) {
  3293. E.value.xic = nullptr;
  3294. }
  3295. }
  3296. void DisplayServerX11::_window_changed(XEvent *event) {
  3297. WindowID window_id = MAIN_WINDOW_ID;
  3298. // Assign the event to the relevant window
  3299. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3300. if (event->xany.window == E.value.x11_window) {
  3301. window_id = E.key;
  3302. break;
  3303. }
  3304. }
  3305. Rect2i new_rect;
  3306. WindowData &wd = windows[window_id];
  3307. if (wd.x11_window != event->xany.window) { // Check if the correct window, in case it was not main window or anything else
  3308. return;
  3309. }
  3310. // Query display server about a possible new window state.
  3311. wd.fullscreen = _window_fullscreen_check(window_id);
  3312. wd.maximized = _window_maximize_check(window_id, "_NET_WM_STATE") && !wd.fullscreen;
  3313. wd.minimized = _window_minimize_check(window_id) && !wd.fullscreen && !wd.maximized;
  3314. // Readjusting the window position if the window is being reparented by the window manager for decoration
  3315. Window root, parent, *children;
  3316. unsigned int nchildren;
  3317. if (XQueryTree(x11_display, wd.x11_window, &root, &parent, &children, &nchildren) && wd.parent != parent) {
  3318. wd.parent = parent;
  3319. window_set_position(wd.position, window_id);
  3320. }
  3321. XFree(children);
  3322. {
  3323. //the position in xconfigure is not useful here, obtain it manually
  3324. int x = 0, y = 0;
  3325. Window child;
  3326. XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
  3327. new_rect.position.x = x;
  3328. new_rect.position.y = y;
  3329. new_rect.size.width = event->xconfigure.width;
  3330. new_rect.size.height = event->xconfigure.height;
  3331. }
  3332. if (new_rect == Rect2i(wd.position, wd.size)) {
  3333. return;
  3334. }
  3335. wd.position = new_rect.position;
  3336. wd.size = new_rect.size;
  3337. #if defined(RD_ENABLED)
  3338. if (context_rd) {
  3339. context_rd->window_resize(window_id, wd.size.width, wd.size.height);
  3340. }
  3341. #endif
  3342. #if defined(GLES3_ENABLED)
  3343. if (gl_manager) {
  3344. gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
  3345. }
  3346. if (gl_manager_egl) {
  3347. gl_manager_egl->window_resize(window_id, wd.size.width, wd.size.height);
  3348. }
  3349. #endif
  3350. if (wd.rect_changed_callback.is_valid()) {
  3351. wd.rect_changed_callback.call(new_rect);
  3352. }
  3353. }
  3354. DisplayServer::WindowID DisplayServerX11::_get_focused_window_or_popup() const {
  3355. const List<WindowID>::Element *E = popup_list.back();
  3356. if (E) {
  3357. return E->get();
  3358. }
  3359. return last_focused_window;
  3360. }
  3361. void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  3362. static_cast<DisplayServerX11 *>(get_singleton())->_dispatch_input_event(p_event);
  3363. }
  3364. void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  3365. {
  3366. List<WindowID>::Element *E = popup_list.back();
  3367. if (E && Object::cast_to<InputEventKey>(*p_event)) {
  3368. // Redirect keyboard input to active popup.
  3369. if (windows.has(E->get())) {
  3370. Callable callable = windows[E->get()].input_event_callback;
  3371. if (callable.is_valid()) {
  3372. callable.call(p_event);
  3373. }
  3374. }
  3375. return;
  3376. }
  3377. }
  3378. Ref<InputEventFromWindow> event_from_window = p_event;
  3379. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  3380. // Send to a single window.
  3381. if (windows.has(event_from_window->get_window_id())) {
  3382. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  3383. if (callable.is_valid()) {
  3384. callable.call(p_event);
  3385. }
  3386. }
  3387. } else {
  3388. // Send to all windows.
  3389. for (KeyValue<WindowID, WindowData> &E : windows) {
  3390. Callable callable = E.value.input_event_callback;
  3391. if (callable.is_valid()) {
  3392. callable.call(p_event);
  3393. }
  3394. }
  3395. }
  3396. }
  3397. void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  3398. if (wd.event_callback.is_valid()) {
  3399. Variant event = int(p_event);
  3400. wd.event_callback.call(event);
  3401. }
  3402. }
  3403. void DisplayServerX11::_set_input_focus(Window p_window, int p_revert_to) {
  3404. Window focused_window;
  3405. int focus_ret_state;
  3406. XGetInputFocus(x11_display, &focused_window, &focus_ret_state);
  3407. // Only attempt to change focus if the window isn't already focused, in order to
  3408. // prevent issues with Godot stealing input focus with alternative window managers.
  3409. if (p_window != focused_window) {
  3410. XSetInputFocus(x11_display, p_window, p_revert_to, CurrentTime);
  3411. }
  3412. }
  3413. void DisplayServerX11::_poll_events_thread(void *ud) {
  3414. DisplayServerX11 *display_server = static_cast<DisplayServerX11 *>(ud);
  3415. display_server->_poll_events();
  3416. }
  3417. Bool DisplayServerX11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) {
  3418. // Just accept all events.
  3419. return True;
  3420. }
  3421. bool DisplayServerX11::_wait_for_events() const {
  3422. int x11_fd = ConnectionNumber(x11_display);
  3423. fd_set in_fds;
  3424. XFlush(x11_display);
  3425. FD_ZERO(&in_fds);
  3426. FD_SET(x11_fd, &in_fds);
  3427. struct timeval tv;
  3428. tv.tv_usec = 0;
  3429. tv.tv_sec = 1;
  3430. // Wait for next event or timeout.
  3431. int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv);
  3432. if (num_ready_fds > 0) {
  3433. // Event received.
  3434. return true;
  3435. } else {
  3436. // Error or timeout.
  3437. if (num_ready_fds < 0) {
  3438. ERR_PRINT("_wait_for_events: select error: " + itos(errno));
  3439. }
  3440. return false;
  3441. }
  3442. }
  3443. void DisplayServerX11::_poll_events() {
  3444. while (!events_thread_done.is_set()) {
  3445. _wait_for_events();
  3446. // Process events from the queue.
  3447. {
  3448. MutexLock mutex_lock(events_mutex);
  3449. _check_pending_events(polled_events);
  3450. }
  3451. }
  3452. }
  3453. void DisplayServerX11::_check_pending_events(LocalVector<XEvent> &r_events) {
  3454. // Flush to make sure to gather all pending events.
  3455. XFlush(x11_display);
  3456. // Non-blocking wait for next event and remove it from the queue.
  3457. XEvent ev = {};
  3458. while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) {
  3459. // Check if the input manager wants to process the event.
  3460. if (XFilterEvent(&ev, None)) {
  3461. // Event has been filtered by the Input Manager,
  3462. // it has to be ignored and a new one will be received.
  3463. continue;
  3464. }
  3465. // Handle selection request events directly in the event thread, because
  3466. // communication through the x server takes several events sent back and forth
  3467. // and we don't want to block other programs while processing only one each frame.
  3468. if (ev.type == SelectionRequest) {
  3469. _handle_selection_request_event(&(ev.xselectionrequest));
  3470. continue;
  3471. }
  3472. r_events.push_back(ev);
  3473. }
  3474. }
  3475. DisplayServer::WindowID DisplayServerX11::window_get_active_popup() const {
  3476. const List<WindowID>::Element *E = popup_list.back();
  3477. if (E) {
  3478. return E->get();
  3479. } else {
  3480. return INVALID_WINDOW_ID;
  3481. }
  3482. }
  3483. void DisplayServerX11::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  3484. _THREAD_SAFE_METHOD_
  3485. ERR_FAIL_COND(!windows.has(p_window));
  3486. WindowData &wd = windows[p_window];
  3487. wd.parent_safe_rect = p_rect;
  3488. }
  3489. Rect2i DisplayServerX11::window_get_popup_safe_rect(WindowID p_window) const {
  3490. _THREAD_SAFE_METHOD_
  3491. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  3492. const WindowData &wd = windows[p_window];
  3493. return wd.parent_safe_rect;
  3494. }
  3495. void DisplayServerX11::popup_open(WindowID p_window) {
  3496. _THREAD_SAFE_METHOD_
  3497. bool has_popup_ancestor = false;
  3498. WindowID transient_root = p_window;
  3499. while (true) {
  3500. WindowID parent = windows[transient_root].transient_parent;
  3501. if (parent == INVALID_WINDOW_ID) {
  3502. break;
  3503. } else {
  3504. transient_root = parent;
  3505. if (windows[parent].is_popup) {
  3506. has_popup_ancestor = true;
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. WindowData &wd = windows[p_window];
  3512. if (wd.is_popup || has_popup_ancestor) {
  3513. // Find current popup parent, or root popup if new window is not transient.
  3514. List<WindowID>::Element *C = nullptr;
  3515. List<WindowID>::Element *E = popup_list.back();
  3516. while (E) {
  3517. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  3518. C = E;
  3519. E = E->prev();
  3520. } else {
  3521. break;
  3522. }
  3523. }
  3524. if (C) {
  3525. _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  3526. }
  3527. time_since_popup = OS::get_singleton()->get_ticks_msec();
  3528. popup_list.push_back(p_window);
  3529. }
  3530. }
  3531. void DisplayServerX11::popup_close(WindowID p_window) {
  3532. _THREAD_SAFE_METHOD_
  3533. List<WindowID>::Element *E = popup_list.find(p_window);
  3534. while (E) {
  3535. List<WindowID>::Element *F = E->next();
  3536. WindowID win_id = E->get();
  3537. popup_list.erase(E);
  3538. _send_window_event(windows[win_id], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  3539. E = F;
  3540. }
  3541. }
  3542. bool DisplayServerX11::mouse_process_popups() {
  3543. _THREAD_SAFE_METHOD_
  3544. if (popup_list.is_empty()) {
  3545. return false;
  3546. }
  3547. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  3548. if (delta < 250) {
  3549. return false;
  3550. }
  3551. int number_of_screens = XScreenCount(x11_display);
  3552. bool closed = false;
  3553. for (int i = 0; i < number_of_screens; i++) {
  3554. Window root, child;
  3555. int root_x, root_y, win_x, win_y;
  3556. unsigned int mask;
  3557. if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
  3558. XWindowAttributes root_attrs;
  3559. XGetWindowAttributes(x11_display, root, &root_attrs);
  3560. Vector2i pos = Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
  3561. if (mask != last_mouse_monitor_mask) {
  3562. if (((mask & Button1Mask) || (mask & Button2Mask) || (mask & Button3Mask) || (mask & Button4Mask) || (mask & Button5Mask))) {
  3563. List<WindowID>::Element *C = nullptr;
  3564. List<WindowID>::Element *E = popup_list.back();
  3565. // Find top popup to close.
  3566. while (E) {
  3567. // Popup window area.
  3568. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  3569. // Area of the parent window, which responsible for opening sub-menu.
  3570. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  3571. if (win_rect.has_point(pos)) {
  3572. break;
  3573. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  3574. break;
  3575. } else {
  3576. C = E;
  3577. E = E->prev();
  3578. }
  3579. }
  3580. if (C) {
  3581. _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
  3582. closed = true;
  3583. }
  3584. }
  3585. }
  3586. last_mouse_monitor_mask = mask;
  3587. }
  3588. }
  3589. return closed;
  3590. }
  3591. bool DisplayServerX11::_window_focus_check() {
  3592. Window focused_window;
  3593. int focus_ret_state;
  3594. XGetInputFocus(x11_display, &focused_window, &focus_ret_state);
  3595. bool has_focus = false;
  3596. for (const KeyValue<int, DisplayServerX11::WindowData> &wid : windows) {
  3597. if (wid.value.x11_window == focused_window) {
  3598. has_focus = true;
  3599. break;
  3600. }
  3601. }
  3602. return has_focus;
  3603. }
  3604. void DisplayServerX11::process_events() {
  3605. _THREAD_SAFE_METHOD_
  3606. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  3607. static int frame = 0;
  3608. ++frame;
  3609. #endif
  3610. bool ignore_events = mouse_process_popups();
  3611. if (app_focused) {
  3612. //verify that one of the windows has focus, else send focus out notification
  3613. bool focus_found = false;
  3614. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3615. if (E.value.focused) {
  3616. focus_found = true;
  3617. break;
  3618. }
  3619. }
  3620. if (!focus_found) {
  3621. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_no_focus;
  3622. if (delta > 250) {
  3623. //X11 can go between windows and have no focus for a while, when creating them or something else. Use this as safety to avoid unnecessary focus in/outs.
  3624. if (OS::get_singleton()->get_main_loop()) {
  3625. DEBUG_LOG_X11("All focus lost, triggering NOTIFICATION_APPLICATION_FOCUS_OUT\n");
  3626. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
  3627. }
  3628. app_focused = false;
  3629. }
  3630. } else {
  3631. time_since_no_focus = OS::get_singleton()->get_ticks_msec();
  3632. }
  3633. }
  3634. do_mouse_warp = false;
  3635. // Is the current mouse mode one where it needs to be grabbed.
  3636. bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN;
  3637. xi.pressure = 0;
  3638. xi.tilt = Vector2();
  3639. xi.pressure_supported = false;
  3640. LocalVector<XEvent> events;
  3641. {
  3642. // Block events polling while flushing events.
  3643. MutexLock mutex_lock(events_mutex);
  3644. events = polled_events;
  3645. polled_events.clear();
  3646. // Check for more pending events to avoid an extra frame delay.
  3647. _check_pending_events(events);
  3648. }
  3649. for (uint32_t event_index = 0; event_index < events.size(); ++event_index) {
  3650. XEvent &event = events[event_index];
  3651. bool ime_window_event = false;
  3652. WindowID window_id = MAIN_WINDOW_ID;
  3653. // Assign the event to the relevant window
  3654. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3655. if (event.xany.window == E.value.x11_window) {
  3656. window_id = E.key;
  3657. break;
  3658. }
  3659. if (event.xany.window == E.value.x11_xim_window) {
  3660. window_id = E.key;
  3661. ime_window_event = true;
  3662. break;
  3663. }
  3664. }
  3665. if (XGetEventData(x11_display, &event.xcookie)) {
  3666. if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
  3667. XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
  3668. switch (event_data->evtype) {
  3669. case XI_HierarchyChanged:
  3670. case XI_DeviceChanged: {
  3671. _refresh_device_info();
  3672. } break;
  3673. case XI_RawMotion: {
  3674. if (ime_window_event || ignore_events) {
  3675. break;
  3676. }
  3677. XIRawEvent *raw_event = (XIRawEvent *)event_data;
  3678. int device_id = raw_event->sourceid;
  3679. // Determine the axis used (called valuators in XInput for some forsaken reason)
  3680. // Mask is a bitmask indicating which axes are involved.
  3681. // We are interested in the values of axes 0 and 1.
  3682. if (raw_event->valuators.mask_len <= 0) {
  3683. break;
  3684. }
  3685. const double *values = raw_event->raw_values;
  3686. double rel_x = 0.0;
  3687. double rel_y = 0.0;
  3688. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) {
  3689. rel_x = *values;
  3690. values++;
  3691. }
  3692. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) {
  3693. rel_y = *values;
  3694. values++;
  3695. }
  3696. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) {
  3697. HashMap<int, Vector2>::Iterator pen_pressure = xi.pen_pressure_range.find(device_id);
  3698. if (pen_pressure) {
  3699. Vector2 pen_pressure_range = pen_pressure->value;
  3700. if (pen_pressure_range != Vector2()) {
  3701. xi.pressure_supported = true;
  3702. xi.pressure = (*values - pen_pressure_range[0]) /
  3703. (pen_pressure_range[1] - pen_pressure_range[0]);
  3704. }
  3705. }
  3706. values++;
  3707. }
  3708. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) {
  3709. HashMap<int, Vector2>::Iterator pen_tilt_x = xi.pen_tilt_x_range.find(device_id);
  3710. if (pen_tilt_x) {
  3711. Vector2 pen_tilt_x_range = pen_tilt_x->value;
  3712. if (pen_tilt_x_range[0] != 0 && *values < 0) {
  3713. xi.tilt.x = *values / -pen_tilt_x_range[0];
  3714. } else if (pen_tilt_x_range[1] != 0) {
  3715. xi.tilt.x = *values / pen_tilt_x_range[1];
  3716. }
  3717. }
  3718. values++;
  3719. }
  3720. if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) {
  3721. HashMap<int, Vector2>::Iterator pen_tilt_y = xi.pen_tilt_y_range.find(device_id);
  3722. if (pen_tilt_y) {
  3723. Vector2 pen_tilt_y_range = pen_tilt_y->value;
  3724. if (pen_tilt_y_range[0] != 0 && *values < 0) {
  3725. xi.tilt.y = *values / -pen_tilt_y_range[0];
  3726. } else if (pen_tilt_y_range[1] != 0) {
  3727. xi.tilt.y = *values / pen_tilt_y_range[1];
  3728. }
  3729. }
  3730. values++;
  3731. }
  3732. HashMap<int, bool>::Iterator pen_inverted = xi.pen_inverted_devices.find(device_id);
  3733. if (pen_inverted) {
  3734. xi.pen_inverted = pen_inverted->value;
  3735. }
  3736. // https://bugs.freedesktop.org/show_bug.cgi?id=71609
  3737. // http://lists.libsdl.org/pipermail/commits-libsdl.org/2015-June/000282.html
  3738. if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) {
  3739. break; // Flush duplicate to avoid overly fast motion
  3740. }
  3741. xi.old_raw_pos.x = xi.raw_pos.x;
  3742. xi.old_raw_pos.y = xi.raw_pos.y;
  3743. xi.raw_pos.x = rel_x;
  3744. xi.raw_pos.y = rel_y;
  3745. HashMap<int, Vector2>::Iterator abs_info = xi.absolute_devices.find(device_id);
  3746. if (abs_info) {
  3747. // Absolute mode device
  3748. Vector2 mult = abs_info->value;
  3749. xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x;
  3750. xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y;
  3751. } else {
  3752. // Relative mode device
  3753. xi.relative_motion.x = xi.raw_pos.x;
  3754. xi.relative_motion.y = xi.raw_pos.y;
  3755. }
  3756. xi.last_relative_time = raw_event->time;
  3757. } break;
  3758. #ifdef TOUCH_ENABLED
  3759. case XI_TouchBegin:
  3760. case XI_TouchEnd: {
  3761. if (ime_window_event || ignore_events) {
  3762. break;
  3763. }
  3764. bool is_begin = event_data->evtype == XI_TouchBegin;
  3765. int index = event_data->detail;
  3766. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  3767. Ref<InputEventScreenTouch> st;
  3768. st.instantiate();
  3769. st->set_window_id(window_id);
  3770. st->set_index(index);
  3771. st->set_position(pos);
  3772. st->set_pressed(is_begin);
  3773. if (is_begin) {
  3774. if (xi.state.has(index)) { // Defensive
  3775. break;
  3776. }
  3777. xi.state[index] = pos;
  3778. if (xi.state.size() == 1) {
  3779. // X11 may send a motion event when a touch gesture begins, that would result
  3780. // in a spurious mouse motion event being sent to Godot; remember it to be able to filter it out
  3781. xi.mouse_pos_to_filter = pos;
  3782. }
  3783. Input::get_singleton()->parse_input_event(st);
  3784. } else {
  3785. if (!xi.state.has(index)) { // Defensive
  3786. break;
  3787. }
  3788. xi.state.erase(index);
  3789. Input::get_singleton()->parse_input_event(st);
  3790. }
  3791. } break;
  3792. case XI_TouchUpdate: {
  3793. if (ime_window_event || ignore_events) {
  3794. break;
  3795. }
  3796. int index = event_data->detail;
  3797. Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
  3798. HashMap<int, Vector2>::Iterator curr_pos_elem = xi.state.find(index);
  3799. if (!curr_pos_elem) { // Defensive
  3800. break;
  3801. }
  3802. if (curr_pos_elem->value != pos) {
  3803. Ref<InputEventScreenDrag> sd;
  3804. sd.instantiate();
  3805. sd->set_window_id(window_id);
  3806. sd->set_index(index);
  3807. sd->set_position(pos);
  3808. sd->set_relative(pos - curr_pos_elem->value);
  3809. Input::get_singleton()->parse_input_event(sd);
  3810. curr_pos_elem->value = pos;
  3811. }
  3812. } break;
  3813. #endif
  3814. }
  3815. }
  3816. }
  3817. XFreeEventData(x11_display, &event.xcookie);
  3818. switch (event.type) {
  3819. case MapNotify: {
  3820. DEBUG_LOG_X11("[%u] MapNotify window=%lu (%u) \n", frame, event.xmap.window, window_id);
  3821. if (ime_window_event) {
  3822. break;
  3823. }
  3824. const WindowData &wd = windows[window_id];
  3825. XWindowAttributes xwa;
  3826. XSync(x11_display, False);
  3827. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3828. // Set focus when menu window is started.
  3829. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  3830. // a subwindow and its parent are both destroyed.
  3831. if ((xwa.map_state == IsViewable) && !wd.no_focus && !wd.is_popup && _window_focus_check()) {
  3832. _set_input_focus(wd.x11_window, RevertToPointerRoot);
  3833. }
  3834. // Have we failed to set fullscreen while the window was unmapped?
  3835. _validate_mode_on_map(window_id);
  3836. } break;
  3837. case Expose: {
  3838. DEBUG_LOG_X11("[%u] Expose window=%lu (%u), count='%u' \n", frame, event.xexpose.window, window_id, event.xexpose.count);
  3839. if (ime_window_event) {
  3840. break;
  3841. }
  3842. windows[window_id].fullscreen = _window_fullscreen_check(window_id);
  3843. Main::force_redraw();
  3844. } break;
  3845. case NoExpose: {
  3846. DEBUG_LOG_X11("[%u] NoExpose drawable=%lu (%u) \n", frame, event.xnoexpose.drawable, window_id);
  3847. if (ime_window_event) {
  3848. break;
  3849. }
  3850. windows[window_id].minimized = true;
  3851. } break;
  3852. case VisibilityNotify: {
  3853. DEBUG_LOG_X11("[%u] VisibilityNotify window=%lu (%u), state=%u \n", frame, event.xvisibility.window, window_id, event.xvisibility.state);
  3854. if (ime_window_event) {
  3855. break;
  3856. }
  3857. windows[window_id].minimized = _window_minimize_check(window_id);
  3858. } break;
  3859. case LeaveNotify: {
  3860. DEBUG_LOG_X11("[%u] LeaveNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  3861. if (ime_window_event) {
  3862. break;
  3863. }
  3864. if (!mouse_mode_grab && window_mouseover_id == window_id) {
  3865. window_mouseover_id = INVALID_WINDOW_ID;
  3866. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
  3867. }
  3868. } break;
  3869. case EnterNotify: {
  3870. DEBUG_LOG_X11("[%u] EnterNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
  3871. if (ime_window_event) {
  3872. break;
  3873. }
  3874. if (!mouse_mode_grab && window_mouseover_id != window_id) {
  3875. if (window_mouseover_id != INVALID_WINDOW_ID) {
  3876. _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
  3877. }
  3878. window_mouseover_id = window_id;
  3879. _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
  3880. }
  3881. } break;
  3882. case FocusIn: {
  3883. DEBUG_LOG_X11("[%u] FocusIn window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  3884. if (ime_window_event || (event.xfocus.detail == NotifyInferior)) {
  3885. break;
  3886. }
  3887. WindowData &wd = windows[window_id];
  3888. last_focused_window = window_id;
  3889. wd.focused = true;
  3890. // Keep track of focus order for overlapping windows.
  3891. static unsigned int focus_order = 0;
  3892. wd.focus_order = ++focus_order;
  3893. _send_window_event(wd, WINDOW_EVENT_FOCUS_IN);
  3894. if (mouse_mode_grab) {
  3895. // Show and update the cursor if confined and the window regained focus.
  3896. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3897. if (mouse_mode == MOUSE_MODE_CONFINED) {
  3898. XUndefineCursor(x11_display, E.value.x11_window);
  3899. } else if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) { // Or re-hide it.
  3900. XDefineCursor(x11_display, E.value.x11_window, null_cursor);
  3901. }
  3902. XGrabPointer(
  3903. x11_display, E.value.x11_window, True,
  3904. ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
  3905. GrabModeAsync, GrabModeAsync, E.value.x11_window, None, CurrentTime);
  3906. }
  3907. }
  3908. #ifdef TOUCH_ENABLED
  3909. // Grab touch devices to avoid OS gesture interference
  3910. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  3911. XIGrabDevice(x11_display, xi.touch_devices[i], x11_window, CurrentTime, None, XIGrabModeAsync, XIGrabModeAsync, False, &xi.touch_event_mask);
  3912. }*/
  3913. #endif
  3914. if (!app_focused) {
  3915. if (OS::get_singleton()->get_main_loop()) {
  3916. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
  3917. }
  3918. app_focused = true;
  3919. }
  3920. } break;
  3921. case FocusOut: {
  3922. DEBUG_LOG_X11("[%u] FocusOut window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
  3923. WindowData &wd = windows[window_id];
  3924. if (ime_window_event || (event.xfocus.detail == NotifyInferior)) {
  3925. break;
  3926. }
  3927. if (wd.ime_active) {
  3928. MutexLock mutex_lock(events_mutex);
  3929. XUnsetICFocus(wd.xic);
  3930. XUnmapWindow(x11_display, wd.x11_xim_window);
  3931. wd.ime_active = false;
  3932. im_text = String();
  3933. im_selection = Vector2i();
  3934. OS_Unix::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  3935. }
  3936. wd.focused = false;
  3937. Input::get_singleton()->release_pressed_events();
  3938. _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT);
  3939. if (mouse_mode_grab) {
  3940. for (const KeyValue<WindowID, WindowData> &E : windows) {
  3941. //dear X11, I try, I really try, but you never work, you do whatever you want.
  3942. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3943. // Show the cursor if we're in captured mode so it doesn't look weird.
  3944. XUndefineCursor(x11_display, E.value.x11_window);
  3945. }
  3946. }
  3947. XUngrabPointer(x11_display, CurrentTime);
  3948. }
  3949. #ifdef TOUCH_ENABLED
  3950. // Ungrab touch devices so input works as usual while we are unfocused
  3951. /*for (int i = 0; i < xi.touch_devices.size(); ++i) {
  3952. XIUngrabDevice(x11_display, xi.touch_devices[i], CurrentTime);
  3953. }*/
  3954. // Release every pointer to avoid sticky points
  3955. for (const KeyValue<int, Vector2> &E : xi.state) {
  3956. Ref<InputEventScreenTouch> st;
  3957. st.instantiate();
  3958. st->set_index(E.key);
  3959. st->set_window_id(window_id);
  3960. st->set_position(E.value);
  3961. Input::get_singleton()->parse_input_event(st);
  3962. }
  3963. xi.state.clear();
  3964. #endif
  3965. } break;
  3966. case ConfigureNotify: {
  3967. 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);
  3968. if (event.xconfigure.window == windows[window_id].x11_xim_window) {
  3969. break;
  3970. }
  3971. const WindowData &wd = windows[window_id];
  3972. XWindowAttributes xwa;
  3973. XSync(x11_display, False);
  3974. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  3975. // Set focus when menu window is re-used.
  3976. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  3977. // a subwindow and its parent are both destroyed.
  3978. if ((xwa.map_state == IsViewable) && !wd.no_focus && !wd.is_popup && _window_focus_check()) {
  3979. _set_input_focus(wd.x11_window, RevertToPointerRoot);
  3980. }
  3981. _window_changed(&event);
  3982. } break;
  3983. case ButtonPress:
  3984. case ButtonRelease: {
  3985. if (ime_window_event || ignore_events) {
  3986. break;
  3987. }
  3988. /* exit in case of a mouse button press */
  3989. last_timestamp = event.xbutton.time;
  3990. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  3991. event.xbutton.x = last_mouse_pos.x;
  3992. event.xbutton.y = last_mouse_pos.y;
  3993. }
  3994. Ref<InputEventMouseButton> mb;
  3995. mb.instantiate();
  3996. mb->set_window_id(window_id);
  3997. _get_key_modifier_state(event.xbutton.state, mb);
  3998. mb->set_button_index((MouseButton)event.xbutton.button);
  3999. if (mb->get_button_index() == MouseButton::RIGHT) {
  4000. mb->set_button_index(MouseButton::MIDDLE);
  4001. } else if (mb->get_button_index() == MouseButton::MIDDLE) {
  4002. mb->set_button_index(MouseButton::RIGHT);
  4003. }
  4004. mb->set_button_mask(_get_mouse_button_state(mb->get_button_index(), event.xbutton.type));
  4005. mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
  4006. mb->set_global_position(mb->get_position());
  4007. mb->set_pressed((event.type == ButtonPress));
  4008. const WindowData &wd = windows[window_id];
  4009. if (event.type == ButtonPress) {
  4010. DEBUG_LOG_X11("[%u] ButtonPress window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  4011. // Ensure window focus on click.
  4012. // RevertToPointerRoot is used to make sure we don't lose all focus in case
  4013. // a subwindow and its parent are both destroyed.
  4014. if (!wd.no_focus && !wd.is_popup) {
  4015. _set_input_focus(wd.x11_window, RevertToPointerRoot);
  4016. }
  4017. uint64_t diff = OS::get_singleton()->get_ticks_usec() / 1000 - last_click_ms;
  4018. if (mb->get_button_index() == last_click_button_index) {
  4019. if (diff < 400 && Vector2(last_click_pos).distance_to(Vector2(event.xbutton.x, event.xbutton.y)) < 5) {
  4020. last_click_ms = 0;
  4021. last_click_pos = Point2i(-100, -100);
  4022. last_click_button_index = MouseButton::NONE;
  4023. mb->set_double_click(true);
  4024. }
  4025. } else if (mb->get_button_index() < MouseButton::WHEEL_UP || mb->get_button_index() > MouseButton::WHEEL_RIGHT) {
  4026. last_click_button_index = mb->get_button_index();
  4027. }
  4028. if (!mb->is_double_click()) {
  4029. last_click_ms += diff;
  4030. last_click_pos = Point2i(event.xbutton.x, event.xbutton.y);
  4031. }
  4032. } else {
  4033. DEBUG_LOG_X11("[%u] ButtonRelease window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
  4034. WindowID window_id_other = INVALID_WINDOW_ID;
  4035. Window wd_other_x11_window;
  4036. if (wd.focused) {
  4037. // Handle cases where an unfocused popup is open that needs to receive button-up events.
  4038. WindowID popup_id = _get_focused_window_or_popup();
  4039. if (popup_id != INVALID_WINDOW_ID && popup_id != window_id) {
  4040. window_id_other = popup_id;
  4041. wd_other_x11_window = windows[popup_id].x11_window;
  4042. }
  4043. } else {
  4044. // Propagate the event to the focused window,
  4045. // because it's received only on the topmost window.
  4046. // Note: This is needed for drag & drop to work between windows,
  4047. // because the engine expects events to keep being processed
  4048. // on the same window dragging started.
  4049. for (const KeyValue<WindowID, WindowData> &E : windows) {
  4050. if (E.value.focused) {
  4051. if (E.key != window_id) {
  4052. window_id_other = E.key;
  4053. wd_other_x11_window = E.value.x11_window;
  4054. }
  4055. break;
  4056. }
  4057. }
  4058. }
  4059. if (window_id_other != INVALID_WINDOW_ID) {
  4060. int x, y;
  4061. Window child;
  4062. XTranslateCoordinates(x11_display, wd.x11_window, wd_other_x11_window, event.xbutton.x, event.xbutton.y, &x, &y, &child);
  4063. mb->set_window_id(window_id_other);
  4064. mb->set_position(Vector2(x, y));
  4065. mb->set_global_position(mb->get_position());
  4066. }
  4067. }
  4068. Input::get_singleton()->parse_input_event(mb);
  4069. } break;
  4070. case MotionNotify: {
  4071. if (ime_window_event || ignore_events) {
  4072. break;
  4073. }
  4074. // The X11 API requires filtering one-by-one through the motion
  4075. // notify events, in order to figure out which event is the one
  4076. // generated by warping the mouse pointer.
  4077. WindowID focused_window_id = _get_focused_window_or_popup();
  4078. if (!windows.has(focused_window_id)) {
  4079. focused_window_id = MAIN_WINDOW_ID;
  4080. }
  4081. while (true) {
  4082. 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) {
  4083. //this is likely the warp event since it was warped here
  4084. center = Vector2(event.xmotion.x, event.xmotion.y);
  4085. break;
  4086. }
  4087. if (event_index + 1 < events.size()) {
  4088. const XEvent &next_event = events[event_index + 1];
  4089. if (next_event.type == MotionNotify) {
  4090. ++event_index;
  4091. event = next_event;
  4092. } else {
  4093. break;
  4094. }
  4095. } else {
  4096. break;
  4097. }
  4098. }
  4099. last_timestamp = event.xmotion.time;
  4100. // Motion is also simple.
  4101. // A little hack is in order
  4102. // to be able to send relative motion events.
  4103. Point2i pos(event.xmotion.x, event.xmotion.y);
  4104. // Avoidance of spurious mouse motion (see handling of touch)
  4105. bool filter = false;
  4106. // Adding some tolerance to match better Point2i to Vector2
  4107. if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) {
  4108. filter = true;
  4109. }
  4110. // Invalidate to avoid filtering a possible legitimate similar event coming later
  4111. xi.mouse_pos_to_filter = Vector2(1e10, 1e10);
  4112. if (filter) {
  4113. break;
  4114. }
  4115. const WindowData &wd = windows[window_id];
  4116. bool focused = wd.focused;
  4117. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4118. if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) {
  4119. break;
  4120. }
  4121. Point2i new_center = pos;
  4122. pos = last_mouse_pos + xi.relative_motion;
  4123. center = new_center;
  4124. do_mouse_warp = focused; // warp the cursor if we're focused in
  4125. }
  4126. if (!last_mouse_pos_valid) {
  4127. last_mouse_pos = pos;
  4128. last_mouse_pos_valid = true;
  4129. }
  4130. // Hackish but relative mouse motion is already handled in the RawMotion event.
  4131. // RawMotion does not provide the absolute mouse position (whereas MotionNotify does).
  4132. // Therefore, RawMotion cannot be the authority on absolute mouse position.
  4133. // RawMotion provides more precision than MotionNotify, which doesn't sense subpixel motion.
  4134. // Therefore, MotionNotify cannot be the authority on relative mouse motion.
  4135. // This means we need to take a combined approach...
  4136. Point2i rel;
  4137. // Only use raw input if in capture mode. Otherwise use the classic behavior.
  4138. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4139. rel = xi.relative_motion;
  4140. } else {
  4141. rel = pos - last_mouse_pos;
  4142. }
  4143. // Reset to prevent lingering motion
  4144. xi.relative_motion.x = 0;
  4145. xi.relative_motion.y = 0;
  4146. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  4147. pos = Point2i(windows[focused_window_id].size.width / 2, windows[focused_window_id].size.height / 2);
  4148. }
  4149. Ref<InputEventMouseMotion> mm;
  4150. mm.instantiate();
  4151. mm->set_window_id(window_id);
  4152. if (xi.pressure_supported) {
  4153. mm->set_pressure(xi.pressure);
  4154. } else {
  4155. mm->set_pressure(bool(mouse_get_button_state().has_flag(MouseButtonMask::LEFT)) ? 1.0f : 0.0f);
  4156. }
  4157. mm->set_tilt(xi.tilt);
  4158. mm->set_pen_inverted(xi.pen_inverted);
  4159. _get_key_modifier_state(event.xmotion.state, mm);
  4160. mm->set_button_mask(mouse_get_button_state());
  4161. mm->set_position(pos);
  4162. mm->set_global_position(pos);
  4163. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  4164. mm->set_relative(rel);
  4165. last_mouse_pos = pos;
  4166. // printf("rel: %d,%d\n", rel.x, rel.y );
  4167. // Don't propagate the motion event unless we have focus
  4168. // this is so that the relative motion doesn't get messed up
  4169. // after we regain focus.
  4170. if (focused) {
  4171. Input::get_singleton()->parse_input_event(mm);
  4172. } else {
  4173. // Propagate the event to the focused window,
  4174. // because it's received only on the topmost window.
  4175. // Note: This is needed for drag & drop to work between windows,
  4176. // because the engine expects events to keep being processed
  4177. // on the same window dragging started.
  4178. for (const KeyValue<WindowID, WindowData> &E : windows) {
  4179. const WindowData &wd_other = E.value;
  4180. if (wd_other.focused) {
  4181. int x, y;
  4182. Window child;
  4183. XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xmotion.x, event.xmotion.y, &x, &y, &child);
  4184. Point2i pos_focused(x, y);
  4185. mm->set_window_id(E.key);
  4186. mm->set_position(pos_focused);
  4187. mm->set_global_position(pos_focused);
  4188. mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  4189. Input::get_singleton()->parse_input_event(mm);
  4190. break;
  4191. }
  4192. }
  4193. }
  4194. } break;
  4195. case KeyPress:
  4196. case KeyRelease: {
  4197. if (ignore_events) {
  4198. break;
  4199. }
  4200. #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
  4201. if (event.type == KeyPress) {
  4202. 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);
  4203. } else {
  4204. 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);
  4205. }
  4206. #endif
  4207. last_timestamp = event.xkey.time;
  4208. // key event is a little complex, so
  4209. // it will be handled in its own function.
  4210. _handle_key_event(window_id, &event.xkey, events, event_index);
  4211. } break;
  4212. case SelectionNotify:
  4213. if (ime_window_event) {
  4214. break;
  4215. }
  4216. if (event.xselection.target == requested) {
  4217. Property p = _read_property(x11_display, windows[window_id].x11_window, XInternAtom(x11_display, "PRIMARY", 0));
  4218. Vector<String> files = String((char *)p.data).split("\r\n", false);
  4219. XFree(p.data);
  4220. for (int i = 0; i < files.size(); i++) {
  4221. files.write[i] = files[i].replace("file://", "").uri_decode();
  4222. }
  4223. if (!windows[window_id].drop_files_callback.is_null()) {
  4224. windows[window_id].drop_files_callback.call(files);
  4225. }
  4226. //Reply that all is well.
  4227. XClientMessageEvent m;
  4228. memset(&m, 0, sizeof(m));
  4229. m.type = ClientMessage;
  4230. m.display = x11_display;
  4231. m.window = xdnd_source_window;
  4232. m.message_type = xdnd_finished;
  4233. m.format = 32;
  4234. m.data.l[0] = windows[window_id].x11_window;
  4235. m.data.l[1] = 1;
  4236. m.data.l[2] = xdnd_action_copy; //We only ever copy.
  4237. XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
  4238. }
  4239. break;
  4240. case ClientMessage:
  4241. if (ime_window_event) {
  4242. break;
  4243. }
  4244. if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) {
  4245. _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
  4246. }
  4247. else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
  4248. //File(s) have been dragged over the window, check for supported target (text/uri-list)
  4249. xdnd_version = (event.xclient.data.l[1] >> 24);
  4250. Window source = event.xclient.data.l[0];
  4251. bool more_than_3 = event.xclient.data.l[1] & 1;
  4252. if (more_than_3) {
  4253. Property p = _read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
  4254. requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
  4255. XFree(p.data);
  4256. } else {
  4257. requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
  4258. }
  4259. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
  4260. //xdnd position event, reply with an XDND status message
  4261. //just depending on type of data for now
  4262. XClientMessageEvent m;
  4263. memset(&m, 0, sizeof(m));
  4264. m.type = ClientMessage;
  4265. m.display = event.xclient.display;
  4266. m.window = event.xclient.data.l[0];
  4267. m.message_type = xdnd_status;
  4268. m.format = 32;
  4269. m.data.l[0] = windows[window_id].x11_window;
  4270. m.data.l[1] = (requested != None);
  4271. m.data.l[2] = 0; //empty rectangle
  4272. m.data.l[3] = 0;
  4273. m.data.l[4] = xdnd_action_copy;
  4274. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  4275. XFlush(x11_display);
  4276. } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
  4277. if (requested != None) {
  4278. xdnd_source_window = event.xclient.data.l[0];
  4279. if (xdnd_version >= 1) {
  4280. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, event.xclient.data.l[2]);
  4281. } else {
  4282. XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, CurrentTime);
  4283. }
  4284. } else {
  4285. //Reply that we're not interested.
  4286. XClientMessageEvent m;
  4287. memset(&m, 0, sizeof(m));
  4288. m.type = ClientMessage;
  4289. m.display = event.xclient.display;
  4290. m.window = event.xclient.data.l[0];
  4291. m.message_type = xdnd_finished;
  4292. m.format = 32;
  4293. m.data.l[0] = windows[window_id].x11_window;
  4294. m.data.l[1] = 0;
  4295. m.data.l[2] = None; //Failed.
  4296. XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
  4297. }
  4298. }
  4299. break;
  4300. default:
  4301. break;
  4302. }
  4303. }
  4304. XFlush(x11_display);
  4305. if (do_mouse_warp) {
  4306. XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window,
  4307. 0, 0, 0, 0, (int)windows[MAIN_WINDOW_ID].size.width / 2, (int)windows[MAIN_WINDOW_ID].size.height / 2);
  4308. /*
  4309. Window root, child;
  4310. int root_x, root_y;
  4311. int win_x, win_y;
  4312. unsigned int mask;
  4313. XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );
  4314. printf("Root: %d,%d\n", root_x, root_y);
  4315. printf("Win: %d,%d\n", win_x, win_y);
  4316. */
  4317. }
  4318. Input::get_singleton()->flush_buffered_events();
  4319. }
  4320. void DisplayServerX11::release_rendering_thread() {
  4321. #if defined(GLES3_ENABLED)
  4322. if (gl_manager) {
  4323. gl_manager->release_current();
  4324. }
  4325. if (gl_manager_egl) {
  4326. gl_manager_egl->release_current();
  4327. }
  4328. #endif
  4329. }
  4330. void DisplayServerX11::make_rendering_thread() {
  4331. #if defined(GLES3_ENABLED)
  4332. if (gl_manager) {
  4333. gl_manager->make_current();
  4334. }
  4335. if (gl_manager_egl) {
  4336. gl_manager_egl->make_current();
  4337. }
  4338. #endif
  4339. }
  4340. void DisplayServerX11::swap_buffers() {
  4341. #if defined(GLES3_ENABLED)
  4342. if (gl_manager) {
  4343. gl_manager->swap_buffers();
  4344. }
  4345. if (gl_manager_egl) {
  4346. gl_manager_egl->swap_buffers();
  4347. }
  4348. #endif
  4349. }
  4350. void DisplayServerX11::_update_context(WindowData &wd) {
  4351. XClassHint *classHint = XAllocClassHint();
  4352. if (classHint) {
  4353. CharString name_str;
  4354. switch (context) {
  4355. case CONTEXT_EDITOR:
  4356. name_str = "Godot_Editor";
  4357. break;
  4358. case CONTEXT_PROJECTMAN:
  4359. name_str = "Godot_ProjectList";
  4360. break;
  4361. case CONTEXT_ENGINE:
  4362. name_str = "Godot_Engine";
  4363. break;
  4364. }
  4365. CharString class_str;
  4366. if (context == CONTEXT_ENGINE) {
  4367. String config_name = GLOBAL_GET("application/config/name");
  4368. if (config_name.length() == 0) {
  4369. class_str = "Godot_Engine";
  4370. } else {
  4371. class_str = config_name.utf8();
  4372. }
  4373. } else {
  4374. class_str = "Godot";
  4375. }
  4376. classHint->res_class = class_str.ptrw();
  4377. classHint->res_name = name_str.ptrw();
  4378. XSetClassHint(x11_display, wd.x11_window, classHint);
  4379. XFree(classHint);
  4380. }
  4381. }
  4382. void DisplayServerX11::set_context(Context p_context) {
  4383. _THREAD_SAFE_METHOD_
  4384. context = p_context;
  4385. for (KeyValue<WindowID, WindowData> &E : windows) {
  4386. _update_context(E.value);
  4387. }
  4388. }
  4389. void DisplayServerX11::set_native_icon(const String &p_filename) {
  4390. WARN_PRINT("Native icon not supported by this display server.");
  4391. }
  4392. bool g_set_icon_error = false;
  4393. int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
  4394. g_set_icon_error = true;
  4395. return 0;
  4396. }
  4397. void DisplayServerX11::set_icon(const Ref<Image> &p_icon) {
  4398. _THREAD_SAFE_METHOD_
  4399. WindowData &wd = windows[MAIN_WINDOW_ID];
  4400. int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
  4401. Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
  4402. if (p_icon.is_valid()) {
  4403. ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
  4404. Ref<Image> img = p_icon->duplicate();
  4405. img->convert(Image::FORMAT_RGBA8);
  4406. while (true) {
  4407. int w = img->get_width();
  4408. int h = img->get_height();
  4409. if (g_set_icon_error) {
  4410. g_set_icon_error = false;
  4411. WARN_PRINT("Icon too large, attempting to resize icon.");
  4412. int new_width, new_height;
  4413. if (w > h) {
  4414. new_width = w / 2;
  4415. new_height = h * new_width / w;
  4416. } else {
  4417. new_height = h / 2;
  4418. new_width = w * new_height / h;
  4419. }
  4420. w = new_width;
  4421. h = new_height;
  4422. if (!w || !h) {
  4423. WARN_PRINT("Unable to set icon.");
  4424. break;
  4425. }
  4426. img->resize(w, h, Image::INTERPOLATE_CUBIC);
  4427. }
  4428. // We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
  4429. Vector<long> pd;
  4430. pd.resize(2 + w * h);
  4431. pd.write[0] = w;
  4432. pd.write[1] = h;
  4433. const uint8_t *r = img->get_data().ptr();
  4434. long *wr = &pd.write[2];
  4435. uint8_t const *pr = r;
  4436. for (int i = 0; i < w * h; i++) {
  4437. long v = 0;
  4438. // A R G B
  4439. v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
  4440. *wr++ = v;
  4441. pr += 4;
  4442. }
  4443. if (net_wm_icon != None) {
  4444. XChangeProperty(x11_display, wd.x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
  4445. }
  4446. if (!g_set_icon_error) {
  4447. break;
  4448. }
  4449. }
  4450. } else {
  4451. XDeleteProperty(x11_display, wd.x11_window, net_wm_icon);
  4452. }
  4453. XFlush(x11_display);
  4454. XSetErrorHandler(oldHandler);
  4455. }
  4456. void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  4457. _THREAD_SAFE_METHOD_
  4458. #if defined(RD_ENABLED)
  4459. if (context_rd) {
  4460. context_rd->set_vsync_mode(p_window, p_vsync_mode);
  4461. }
  4462. #endif
  4463. #if defined(GLES3_ENABLED)
  4464. if (gl_manager) {
  4465. gl_manager->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  4466. }
  4467. if (gl_manager_egl) {
  4468. gl_manager_egl->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  4469. }
  4470. #endif
  4471. }
  4472. DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const {
  4473. _THREAD_SAFE_METHOD_
  4474. #if defined(RD_ENABLED)
  4475. if (context_rd) {
  4476. return context_rd->get_vsync_mode(p_window);
  4477. }
  4478. #endif
  4479. #if defined(GLES3_ENABLED)
  4480. if (gl_manager) {
  4481. return gl_manager->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  4482. }
  4483. if (gl_manager_egl) {
  4484. return gl_manager_egl->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
  4485. }
  4486. #endif
  4487. return DisplayServer::VSYNC_ENABLED;
  4488. }
  4489. Vector<String> DisplayServerX11::get_rendering_drivers_func() {
  4490. Vector<String> drivers;
  4491. #ifdef VULKAN_ENABLED
  4492. drivers.push_back("vulkan");
  4493. #endif
  4494. #ifdef GLES3_ENABLED
  4495. drivers.push_back("opengl3");
  4496. drivers.push_back("opengl3_es");
  4497. #endif
  4498. return drivers;
  4499. }
  4500. 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, Error &r_error) {
  4501. DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, p_screen, r_error));
  4502. if (r_error != OK) {
  4503. if (p_rendering_driver == "vulkan") {
  4504. String executable_name = OS::get_singleton()->get_executable_path().get_file();
  4505. OS::get_singleton()->alert(
  4506. vformat("Your video card drivers seem not to support the required Vulkan version.\n\n"
  4507. "If possible, consider updating your video card drivers or using the OpenGL 3 driver.\n\n"
  4508. "You can enable the OpenGL 3 driver by starting the engine from the\n"
  4509. "command line with the command:\n\n \"%s\" --rendering-driver opengl3\n\n"
  4510. "If you recently updated your video card drivers, try rebooting.",
  4511. executable_name),
  4512. "Unable to initialize Vulkan video driver");
  4513. } else {
  4514. OS::get_singleton()->alert(
  4515. "Your video card drivers seem not to support the required OpenGL 3.3 version.\n\n"
  4516. "If possible, consider updating your video card drivers.\n\n"
  4517. "If you recently updated your video card drivers, try rebooting.",
  4518. "Unable to initialize OpenGL video driver");
  4519. }
  4520. }
  4521. return ds;
  4522. }
  4523. DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  4524. //Create window
  4525. XVisualInfo visualInfo;
  4526. bool vi_selected = false;
  4527. #ifdef GLES3_ENABLED
  4528. if (gl_manager) {
  4529. Error err;
  4530. visualInfo = gl_manager->get_vi(x11_display, err);
  4531. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't acquire visual info from display.");
  4532. vi_selected = true;
  4533. }
  4534. if (gl_manager_egl) {
  4535. XVisualInfo visual_info_template;
  4536. int visual_id = gl_manager_egl->display_get_native_visual_id(x11_display);
  4537. ERR_FAIL_COND_V_MSG(visual_id < 0, INVALID_WINDOW_ID, "Unable to get a visual id.");
  4538. visual_info_template.visualid = (VisualID)visual_id;
  4539. int number_of_visuals = 0;
  4540. XVisualInfo *vi_list = XGetVisualInfo(x11_display, VisualIDMask, &visual_info_template, &number_of_visuals);
  4541. ERR_FAIL_COND_V(number_of_visuals <= 0, INVALID_WINDOW_ID);
  4542. visualInfo = vi_list[0];
  4543. XFree(vi_list);
  4544. }
  4545. #endif
  4546. if (!vi_selected) {
  4547. long visualMask = VisualScreenMask;
  4548. int numberOfVisuals;
  4549. XVisualInfo vInfoTemplate = {};
  4550. vInfoTemplate.screen = DefaultScreen(x11_display);
  4551. XVisualInfo *vi_list = XGetVisualInfo(x11_display, visualMask, &vInfoTemplate, &numberOfVisuals);
  4552. ERR_FAIL_NULL_V(vi_list, INVALID_WINDOW_ID);
  4553. visualInfo = vi_list[0];
  4554. if (OS::get_singleton()->is_layered_allowed()) {
  4555. for (int i = 0; i < numberOfVisuals; i++) {
  4556. XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi_list[i].visual);
  4557. if (!pict_format) {
  4558. continue;
  4559. }
  4560. visualInfo = vi_list[i];
  4561. if (pict_format->direct.alphaMask > 0) {
  4562. break;
  4563. }
  4564. }
  4565. }
  4566. XFree(vi_list);
  4567. }
  4568. Colormap colormap = XCreateColormap(x11_display, RootWindow(x11_display, visualInfo.screen), visualInfo.visual, AllocNone);
  4569. XSetWindowAttributes windowAttributes = {};
  4570. windowAttributes.colormap = colormap;
  4571. windowAttributes.background_pixel = 0xFFFFFFFF;
  4572. windowAttributes.border_pixel = 0;
  4573. windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
  4574. unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;
  4575. if (OS::get_singleton()->is_layered_allowed()) {
  4576. windowAttributes.background_pixmap = None;
  4577. windowAttributes.background_pixel = 0;
  4578. windowAttributes.border_pixmap = None;
  4579. valuemask |= CWBackPixel;
  4580. }
  4581. WindowID id = window_id_counter++;
  4582. WindowData &wd = windows[id];
  4583. if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
  4584. wd.no_focus = true;
  4585. }
  4586. if (p_flags & WINDOW_FLAG_POPUP_BIT) {
  4587. wd.is_popup = true;
  4588. }
  4589. // Setup for menu subwindows:
  4590. // - override_redirect forces the WM not to interfere with the window, to avoid delays due to
  4591. // handling decorations and placement.
  4592. // On the other hand, focus changes need to be handled manually when this is set.
  4593. // - save_under is a hint for the WM to keep the content of windows behind to avoid repaint.
  4594. if (wd.no_focus) {
  4595. windowAttributes.override_redirect = True;
  4596. windowAttributes.save_under = True;
  4597. valuemask |= CWOverrideRedirect | CWSaveUnder;
  4598. }
  4599. int rq_screen = get_screen_from_rect(p_rect);
  4600. if (rq_screen < 0) {
  4601. rq_screen = get_primary_screen(); // Requested window rect is outside any screen bounds.
  4602. }
  4603. Rect2i win_rect = p_rect;
  4604. if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  4605. Rect2i screen_rect = Rect2i(screen_get_position(rq_screen), screen_get_size(rq_screen));
  4606. win_rect = screen_rect;
  4607. } else {
  4608. Rect2i srect = screen_get_usable_rect(rq_screen);
  4609. Point2i wpos = p_rect.position;
  4610. wpos.x = CLAMP(wpos.x, srect.position.x, srect.position.x + srect.size.width - p_rect.size.width / 3);
  4611. wpos.y = CLAMP(wpos.y, srect.position.y, srect.position.y + srect.size.height - p_rect.size.height / 3);
  4612. win_rect.position = wpos;
  4613. }
  4614. // Position and size hints are set from these values before they are updated to the actual
  4615. // window size, so we need to initialize them here.
  4616. wd.position = win_rect.position;
  4617. wd.size = win_rect.size;
  4618. {
  4619. 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);
  4620. wd.parent = RootWindow(x11_display, visualInfo.screen);
  4621. XSetWindowAttributes window_attributes_ime = {};
  4622. window_attributes_ime.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
  4623. wd.x11_xim_window = XCreateWindow(x11_display, wd.x11_window, 0, 0, 1, 1, 0, CopyFromParent, InputOnly, CopyFromParent, CWEventMask, &window_attributes_ime);
  4624. #ifdef XKB_ENABLED
  4625. if (dead_tbl && xkb_loaded_v05p) {
  4626. wd.xkb_state = xkb_compose_state_new(dead_tbl, XKB_COMPOSE_STATE_NO_FLAGS);
  4627. }
  4628. #endif
  4629. // Enable receiving notification when the window is initialized (MapNotify)
  4630. // so the focus can be set at the right time.
  4631. if (!wd.no_focus && !wd.is_popup) {
  4632. XSelectInput(x11_display, wd.x11_window, StructureNotifyMask);
  4633. }
  4634. //associate PID
  4635. // make PID known to X11
  4636. {
  4637. const long pid = OS::get_singleton()->get_process_id();
  4638. Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False);
  4639. if (net_wm_pid != None) {
  4640. XChangeProperty(x11_display, wd.x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
  4641. }
  4642. }
  4643. long im_event_mask = 0;
  4644. {
  4645. XIEventMask all_event_mask;
  4646. XSetWindowAttributes new_attr;
  4647. new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
  4648. ButtonReleaseMask | EnterWindowMask |
  4649. LeaveWindowMask | PointerMotionMask |
  4650. Button1MotionMask |
  4651. Button2MotionMask | Button3MotionMask |
  4652. Button4MotionMask | Button5MotionMask |
  4653. ButtonMotionMask | KeymapStateMask |
  4654. ExposureMask | VisibilityChangeMask |
  4655. StructureNotifyMask |
  4656. SubstructureNotifyMask | SubstructureRedirectMask |
  4657. FocusChangeMask | PropertyChangeMask |
  4658. ColormapChangeMask | OwnerGrabButtonMask |
  4659. im_event_mask;
  4660. XChangeWindowAttributes(x11_display, wd.x11_window, CWEventMask, &new_attr);
  4661. static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  4662. all_event_mask.deviceid = XIAllDevices;
  4663. all_event_mask.mask_len = sizeof(all_mask_data);
  4664. all_event_mask.mask = all_mask_data;
  4665. XISetMask(all_event_mask.mask, XI_HierarchyChanged);
  4666. #ifdef TOUCH_ENABLED
  4667. if (xi.touch_devices.size()) {
  4668. XISetMask(all_event_mask.mask, XI_TouchBegin);
  4669. XISetMask(all_event_mask.mask, XI_TouchUpdate);
  4670. XISetMask(all_event_mask.mask, XI_TouchEnd);
  4671. XISetMask(all_event_mask.mask, XI_TouchOwnership);
  4672. }
  4673. #endif
  4674. XISelectEvents(x11_display, wd.x11_window, &all_event_mask, 1);
  4675. }
  4676. /* set the titlebar name */
  4677. XStoreName(x11_display, wd.x11_window, "Godot");
  4678. XSetWMProtocols(x11_display, wd.x11_window, &wm_delete, 1);
  4679. if (xdnd_aware != None) {
  4680. XChangeProperty(x11_display, wd.x11_window, xdnd_aware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdnd_version, 1);
  4681. }
  4682. if (xim && xim_style) {
  4683. // Block events polling while changing input focus
  4684. // because it triggers some event polling internally.
  4685. MutexLock mutex_lock(events_mutex);
  4686. // Force on-the-spot for the over-the-spot style.
  4687. if ((xim_style & XIMPreeditPosition) != 0) {
  4688. xim_style &= ~XIMPreeditPosition;
  4689. xim_style |= XIMPreeditCallbacks;
  4690. }
  4691. if ((xim_style & XIMPreeditCallbacks) != 0) {
  4692. ::XIMCallback preedit_start_callback;
  4693. preedit_start_callback.client_data = (::XPointer)(this);
  4694. preedit_start_callback.callback = (::XIMProc)(void *)(_xim_preedit_start_callback);
  4695. ::XIMCallback preedit_done_callback;
  4696. preedit_done_callback.client_data = (::XPointer)(this);
  4697. preedit_done_callback.callback = (::XIMProc)(_xim_preedit_done_callback);
  4698. ::XIMCallback preedit_draw_callback;
  4699. preedit_draw_callback.client_data = (::XPointer)(this);
  4700. preedit_draw_callback.callback = (::XIMProc)(_xim_preedit_draw_callback);
  4701. ::XIMCallback preedit_caret_callback;
  4702. preedit_caret_callback.client_data = (::XPointer)(this);
  4703. preedit_caret_callback.callback = (::XIMProc)(_xim_preedit_caret_callback);
  4704. ::XVaNestedList preedit_attributes = XVaCreateNestedList(0,
  4705. XNPreeditStartCallback, &preedit_start_callback,
  4706. XNPreeditDoneCallback, &preedit_done_callback,
  4707. XNPreeditDrawCallback, &preedit_draw_callback,
  4708. XNPreeditCaretCallback, &preedit_caret_callback,
  4709. (char *)nullptr);
  4710. wd.xic = XCreateIC(xim,
  4711. XNInputStyle, xim_style,
  4712. XNClientWindow, wd.x11_xim_window,
  4713. XNFocusWindow, wd.x11_xim_window,
  4714. XNPreeditAttributes, preedit_attributes,
  4715. (char *)nullptr);
  4716. XFree(preedit_attributes);
  4717. } else {
  4718. wd.xic = XCreateIC(xim,
  4719. XNInputStyle, xim_style,
  4720. XNClientWindow, wd.x11_xim_window,
  4721. XNFocusWindow, wd.x11_xim_window,
  4722. (char *)nullptr);
  4723. }
  4724. if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) {
  4725. WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
  4726. XDestroyIC(wd.xic);
  4727. wd.xic = nullptr;
  4728. }
  4729. if (wd.xic) {
  4730. XUnsetICFocus(wd.xic);
  4731. } else {
  4732. WARN_PRINT("XCreateIC couldn't create wd.xic");
  4733. }
  4734. } else {
  4735. wd.xic = nullptr;
  4736. WARN_PRINT("XCreateIC couldn't create wd.xic");
  4737. }
  4738. _update_context(wd);
  4739. if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
  4740. Hints hints;
  4741. Atom property;
  4742. hints.flags = 2;
  4743. hints.decorations = 0;
  4744. property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
  4745. if (property != None) {
  4746. XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
  4747. }
  4748. }
  4749. if (wd.is_popup || wd.no_focus) {
  4750. // Set Utility type to disable fade animations.
  4751. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
  4752. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  4753. if (wt_atom != None && type_atom != None) {
  4754. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  4755. }
  4756. } else {
  4757. Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
  4758. Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
  4759. if (wt_atom != None && type_atom != None) {
  4760. XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
  4761. }
  4762. }
  4763. _update_size_hints(id);
  4764. #if defined(RD_ENABLED)
  4765. if (context_rd) {
  4766. union {
  4767. #ifdef VULKAN_ENABLED
  4768. VulkanContextX11::WindowPlatformData vulkan;
  4769. #endif
  4770. } wpd;
  4771. #ifdef VULKAN_ENABLED
  4772. if (rendering_driver == "vulkan") {
  4773. wpd.vulkan.window = wd.x11_window;
  4774. wpd.vulkan.display = x11_display;
  4775. }
  4776. #endif
  4777. Error err = context_rd->window_create(id, p_vsync_mode, win_rect.size.width, win_rect.size.height, &wpd);
  4778. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, vformat("Can't create a %s window", context_rd->get_api_name()));
  4779. }
  4780. #endif
  4781. #ifdef GLES3_ENABLED
  4782. if (gl_manager) {
  4783. Error err = gl_manager->window_create(id, wd.x11_window, x11_display, win_rect.size.width, win_rect.size.height);
  4784. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL window");
  4785. }
  4786. if (gl_manager_egl) {
  4787. Error err = gl_manager_egl->window_create(id, x11_display, &wd.x11_window, win_rect.size.width, win_rect.size.height);
  4788. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Failed to create an OpenGLES window.");
  4789. }
  4790. window_set_vsync_mode(p_vsync_mode, id);
  4791. #endif
  4792. //set_class_hint(x11_display, wd.x11_window);
  4793. XFlush(x11_display);
  4794. XSync(x11_display, False);
  4795. //XSetErrorHandler(oldHandler);
  4796. }
  4797. window_set_mode(p_mode, id);
  4798. //sync size
  4799. {
  4800. XWindowAttributes xwa;
  4801. XSync(x11_display, False);
  4802. XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
  4803. wd.position.x = xwa.x;
  4804. wd.position.y = xwa.y;
  4805. wd.size.width = xwa.width;
  4806. wd.size.height = xwa.height;
  4807. }
  4808. //set cursor
  4809. if (cursors[current_cursor] != None) {
  4810. XDefineCursor(x11_display, wd.x11_window, cursors[current_cursor]);
  4811. }
  4812. return id;
  4813. }
  4814. static bool _is_xim_style_supported(const ::XIMStyle &p_style) {
  4815. const ::XIMStyle supported_preedit = XIMPreeditCallbacks | XIMPreeditPosition | XIMPreeditNothing | XIMPreeditNone;
  4816. const ::XIMStyle supported_status = XIMStatusNothing | XIMStatusNone;
  4817. // Check preedit style is supported
  4818. if ((p_style & supported_preedit) == 0) {
  4819. return false;
  4820. }
  4821. // Check status style is supported
  4822. if ((p_style & supported_status) == 0) {
  4823. return false;
  4824. }
  4825. return true;
  4826. }
  4827. static ::XIMStyle _get_best_xim_style(const ::XIMStyle &p_style_a, const ::XIMStyle &p_style_b) {
  4828. if (p_style_a == 0) {
  4829. return p_style_b;
  4830. }
  4831. if (p_style_b == 0) {
  4832. return p_style_a;
  4833. }
  4834. const ::XIMStyle preedit = XIMPreeditArea | XIMPreeditCallbacks | XIMPreeditPosition | XIMPreeditNothing | XIMPreeditNone;
  4835. const ::XIMStyle status = XIMStatusArea | XIMStatusCallbacks | XIMStatusNothing | XIMStatusNone;
  4836. ::XIMStyle a = p_style_a & preedit;
  4837. ::XIMStyle b = p_style_b & preedit;
  4838. if (a != b) {
  4839. // Compare preedit styles.
  4840. if ((a | b) & XIMPreeditCallbacks) {
  4841. return a == XIMPreeditCallbacks ? p_style_a : p_style_b;
  4842. } else if ((a | b) & XIMPreeditPosition) {
  4843. return a == XIMPreeditPosition ? p_style_a : p_style_b;
  4844. } else if ((a | b) & XIMPreeditArea) {
  4845. return a == XIMPreeditArea ? p_style_a : p_style_b;
  4846. } else if ((a | b) & XIMPreeditNothing) {
  4847. return a == XIMPreeditNothing ? p_style_a : p_style_b;
  4848. }
  4849. } else {
  4850. // Preedit styles are the same, compare status styles.
  4851. a = p_style_a & status;
  4852. b = p_style_b & status;
  4853. if ((a | b) & XIMStatusCallbacks) {
  4854. return a == XIMStatusCallbacks ? p_style_a : p_style_b;
  4855. } else if ((a | b) & XIMStatusArea) {
  4856. return a == XIMStatusArea ? p_style_a : p_style_b;
  4857. } else if ((a | b) & XIMStatusNothing) {
  4858. return a == XIMStatusNothing ? p_style_a : p_style_b;
  4859. }
  4860. }
  4861. return p_style_a;
  4862. }
  4863. 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, Error &r_error) {
  4864. KeyMappingX11::initialize();
  4865. #ifdef SOWRAP_ENABLED
  4866. #ifdef DEBUG_ENABLED
  4867. int dylibloader_verbose = 1;
  4868. #else
  4869. int dylibloader_verbose = 0;
  4870. #endif
  4871. if (initialize_xlib(dylibloader_verbose) != 0) {
  4872. r_error = ERR_UNAVAILABLE;
  4873. ERR_FAIL_MSG("Can't load Xlib dynamically.");
  4874. }
  4875. if (initialize_xcursor(dylibloader_verbose) != 0) {
  4876. r_error = ERR_UNAVAILABLE;
  4877. ERR_FAIL_MSG("Can't load XCursor dynamically.");
  4878. }
  4879. #ifdef XKB_ENABLED
  4880. bool xkb_loaded = (initialize_xkbcommon(dylibloader_verbose) == 0);
  4881. xkb_loaded_v05p = xkb_loaded;
  4882. 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) {
  4883. xkb_loaded_v05p = false;
  4884. print_verbose("Detected XKBcommon library version older than 0.5, dead key composition and Unicode key labels disabled.");
  4885. }
  4886. xkb_loaded_v08p = xkb_loaded;
  4887. if (!xkb_keysym_to_utf32 || !xkb_keysym_to_upper) {
  4888. xkb_loaded_v08p = false;
  4889. print_verbose("Detected XKBcommon library version older than 0.8, Unicode key labels disabled.");
  4890. }
  4891. #endif
  4892. if (initialize_xext(dylibloader_verbose) != 0) {
  4893. r_error = ERR_UNAVAILABLE;
  4894. ERR_FAIL_MSG("Can't load Xext dynamically.");
  4895. }
  4896. if (initialize_xinerama(dylibloader_verbose) != 0) {
  4897. xinerama_ext_ok = false;
  4898. }
  4899. if (initialize_xrandr(dylibloader_verbose) != 0) {
  4900. xrandr_ext_ok = false;
  4901. }
  4902. if (initialize_xrender(dylibloader_verbose) != 0) {
  4903. r_error = ERR_UNAVAILABLE;
  4904. ERR_FAIL_MSG("Can't load Xrender dynamically.");
  4905. }
  4906. if (initialize_xinput2(dylibloader_verbose) != 0) {
  4907. r_error = ERR_UNAVAILABLE;
  4908. ERR_FAIL_MSG("Can't load Xinput2 dynamically.");
  4909. }
  4910. #else
  4911. #ifdef XKB_ENABLED
  4912. bool xkb_loaded = true;
  4913. xkb_loaded_v05p = true;
  4914. xkb_loaded_v08p = true;
  4915. #endif
  4916. #endif
  4917. #ifdef XKB_ENABLED
  4918. if (xkb_loaded) {
  4919. xkb_ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
  4920. if (xkb_ctx) {
  4921. const char *locale = getenv("LC_ALL");
  4922. if (!locale || !*locale) {
  4923. locale = getenv("LC_CTYPE");
  4924. }
  4925. if (!locale || !*locale) {
  4926. locale = getenv("LANG");
  4927. }
  4928. if (!locale || !*locale) {
  4929. locale = "C";
  4930. }
  4931. dead_tbl = xkb_compose_table_new_from_locale(xkb_ctx, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);
  4932. }
  4933. }
  4934. #endif
  4935. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  4936. r_error = OK;
  4937. #ifdef SOWRAP_ENABLED
  4938. {
  4939. if (!XcursorImageCreate || !XcursorImageLoadCursor || !XcursorImageDestroy || !XcursorGetDefaultSize || !XcursorGetTheme || !XcursorLibraryLoadImage) {
  4940. // There's no API to check version, check if functions are available instead.
  4941. ERR_PRINT("Unsupported Xcursor library version.");
  4942. r_error = ERR_UNAVAILABLE;
  4943. return;
  4944. }
  4945. }
  4946. #endif
  4947. for (int i = 0; i < CURSOR_MAX; i++) {
  4948. cursors[i] = None;
  4949. cursor_img[i] = nullptr;
  4950. }
  4951. XInitThreads(); //always use threads
  4952. /** XLIB INITIALIZATION **/
  4953. x11_display = XOpenDisplay(nullptr);
  4954. if (!x11_display) {
  4955. ERR_PRINT("X11 Display is not available");
  4956. r_error = ERR_UNAVAILABLE;
  4957. return;
  4958. }
  4959. if (xshaped_ext_ok) {
  4960. int version_major = 0;
  4961. int version_minor = 0;
  4962. int rc = XShapeQueryVersion(x11_display, &version_major, &version_minor);
  4963. print_verbose(vformat("Xshape %d.%d detected.", version_major, version_minor));
  4964. if (rc != 1 || version_major < 1) {
  4965. xshaped_ext_ok = false;
  4966. print_verbose("Unsupported Xshape library version.");
  4967. }
  4968. }
  4969. if (xinerama_ext_ok) {
  4970. int version_major = 0;
  4971. int version_minor = 0;
  4972. int rc = XineramaQueryVersion(x11_display, &version_major, &version_minor);
  4973. print_verbose(vformat("Xinerama %d.%d detected.", version_major, version_minor));
  4974. if (rc != 1 || version_major < 1) {
  4975. xinerama_ext_ok = false;
  4976. print_verbose("Unsupported Xinerama library version.");
  4977. }
  4978. }
  4979. if (xrandr_ext_ok) {
  4980. int version_major = 0;
  4981. int version_minor = 0;
  4982. int rc = XRRQueryVersion(x11_display, &version_major, &version_minor);
  4983. print_verbose(vformat("Xrandr %d.%d detected.", version_major, version_minor));
  4984. if (rc != 1 || (version_major == 1 && version_minor < 3) || (version_major < 1)) {
  4985. xrandr_ext_ok = false;
  4986. print_verbose("Unsupported Xrandr library version.");
  4987. }
  4988. }
  4989. {
  4990. int version_major = 0;
  4991. int version_minor = 0;
  4992. int rc = XRenderQueryVersion(x11_display, &version_major, &version_minor);
  4993. print_verbose(vformat("Xrender %d.%d detected.", version_major, version_minor));
  4994. if (rc != 1 || (version_major == 0 && version_minor < 11)) {
  4995. ERR_PRINT("Unsupported Xrender library version.");
  4996. r_error = ERR_UNAVAILABLE;
  4997. XCloseDisplay(x11_display);
  4998. return;
  4999. }
  5000. }
  5001. {
  5002. int version_major = 2; // Report 2.2 as supported by engine, but should work with 2.1 or 2.0 library as well.
  5003. int version_minor = 2;
  5004. int rc = XIQueryVersion(x11_display, &version_major, &version_minor);
  5005. print_verbose(vformat("Xinput %d.%d detected.", version_major, version_minor));
  5006. if (rc != Success || (version_major < 2)) {
  5007. ERR_PRINT("Unsupported Xinput2 library version.");
  5008. r_error = ERR_UNAVAILABLE;
  5009. XCloseDisplay(x11_display);
  5010. return;
  5011. }
  5012. }
  5013. char *modifiers = nullptr;
  5014. Bool xkb_dar = False;
  5015. XAutoRepeatOn(x11_display);
  5016. xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr);
  5017. // Try to support IME if detectable auto-repeat is supported
  5018. if (xkb_dar == True) {
  5019. #ifdef X_HAVE_UTF8_STRING
  5020. // Xutf8LookupString will be used later instead of XmbLookupString before
  5021. // the multibyte sequences can be converted to unicode string.
  5022. modifiers = XSetLocaleModifiers("");
  5023. #endif
  5024. }
  5025. if (modifiers == nullptr) {
  5026. if (OS::get_singleton()->is_stdout_verbose()) {
  5027. WARN_PRINT("IME is disabled");
  5028. }
  5029. XSetLocaleModifiers("@im=none");
  5030. WARN_PRINT("Error setting locale modifiers");
  5031. }
  5032. const char *err;
  5033. int xrandr_major = 0;
  5034. int xrandr_minor = 0;
  5035. int event_base, error_base;
  5036. xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
  5037. xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
  5038. if (!xrandr_handle) {
  5039. err = dlerror();
  5040. // For some arcane reason, NetBSD now ships libXrandr.so.3 while the rest of the world has libXrandr.so.2...
  5041. // In case this happens for other X11 platforms in the future, let's give it a try too before failing.
  5042. xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY);
  5043. if (!xrandr_handle) {
  5044. fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
  5045. }
  5046. }
  5047. if (xrandr_handle) {
  5048. XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
  5049. if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
  5050. xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
  5051. if (!xrr_get_monitors) {
  5052. err = dlerror();
  5053. fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
  5054. } else {
  5055. xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
  5056. if (!xrr_free_monitors) {
  5057. err = dlerror();
  5058. fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
  5059. xrr_get_monitors = nullptr;
  5060. }
  5061. }
  5062. }
  5063. }
  5064. if (!_refresh_device_info()) {
  5065. OS::get_singleton()->alert("Your system does not support XInput 2.\n"
  5066. "Please upgrade your distribution.",
  5067. "Unable to initialize XInput");
  5068. r_error = ERR_UNAVAILABLE;
  5069. return;
  5070. }
  5071. xim = XOpenIM(x11_display, nullptr, nullptr, nullptr);
  5072. if (xim == nullptr) {
  5073. WARN_PRINT("XOpenIM failed");
  5074. xim_style = 0L;
  5075. } else {
  5076. ::XIMCallback im_destroy_callback;
  5077. im_destroy_callback.client_data = (::XPointer)(this);
  5078. im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback);
  5079. if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
  5080. nullptr) != nullptr) {
  5081. WARN_PRINT("Error setting XIM destroy callback");
  5082. }
  5083. ::XIMStyles *xim_styles = nullptr;
  5084. xim_style = 0L;
  5085. char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr);
  5086. if (imvalret != nullptr || xim_styles == nullptr) {
  5087. fprintf(stderr, "Input method doesn't support any styles\n");
  5088. }
  5089. if (xim_styles) {
  5090. xim_style = 0L;
  5091. for (int i = 0; i < xim_styles->count_styles; i++) {
  5092. const ::XIMStyle &style = xim_styles->supported_styles[i];
  5093. if (!_is_xim_style_supported(style)) {
  5094. continue;
  5095. }
  5096. xim_style = _get_best_xim_style(xim_style, style);
  5097. }
  5098. XFree(xim_styles);
  5099. }
  5100. XFree(imvalret);
  5101. }
  5102. /* Atom internment */
  5103. wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
  5104. // Set Xdnd (drag & drop) support.
  5105. xdnd_aware = XInternAtom(x11_display, "XdndAware", False);
  5106. xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
  5107. xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
  5108. xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
  5109. xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
  5110. xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
  5111. xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
  5112. xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
  5113. #ifdef SPEECHD_ENABLED
  5114. // Init TTS
  5115. bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
  5116. if (tts_enabled) {
  5117. tts = memnew(TTS_Linux);
  5118. }
  5119. #endif
  5120. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  5121. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  5122. rendering_driver = p_rendering_driver;
  5123. bool driver_found = false;
  5124. #if defined(RD_ENABLED)
  5125. #if defined(VULKAN_ENABLED)
  5126. if (rendering_driver == "vulkan") {
  5127. context_rd = memnew(VulkanContextX11);
  5128. }
  5129. #endif
  5130. if (context_rd) {
  5131. if (context_rd->initialize() != OK) {
  5132. ERR_PRINT(vformat("Could not initialize %s", context_rd->get_api_name()));
  5133. memdelete(context_rd);
  5134. context_rd = nullptr;
  5135. r_error = ERR_CANT_CREATE;
  5136. return;
  5137. }
  5138. driver_found = true;
  5139. }
  5140. #endif
  5141. // Initialize context and rendering device.
  5142. #if defined(GLES3_ENABLED)
  5143. if (rendering_driver == "opengl3" || rendering_driver == "opengl3_es") {
  5144. if (getenv("DRI_PRIME") == nullptr) {
  5145. int use_prime = -1;
  5146. if (getenv("PRIMUS_DISPLAY") ||
  5147. getenv("PRIMUS_libGLd") ||
  5148. getenv("PRIMUS_libGLa") ||
  5149. getenv("PRIMUS_libGL") ||
  5150. getenv("PRIMUS_LOAD_GLOBAL") ||
  5151. getenv("BUMBLEBEE_SOCKET")) {
  5152. print_verbose("Optirun/primusrun detected. Skipping GPU detection");
  5153. use_prime = 0;
  5154. }
  5155. // Some tools use fake libGL libraries and have them override the real one using
  5156. // LD_LIBRARY_PATH, so we skip them. *But* Steam also sets LD_LIBRARY_PATH for its
  5157. // runtime and includes system `/lib` and `/lib64`... so ignore Steam.
  5158. if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) {
  5159. String ld_library_path(getenv("LD_LIBRARY_PATH"));
  5160. Vector<String> libraries = ld_library_path.split(":");
  5161. for (int i = 0; i < libraries.size(); ++i) {
  5162. if (FileAccess::exists(libraries[i] + "/libGL.so.1") ||
  5163. FileAccess::exists(libraries[i] + "/libGL.so")) {
  5164. print_verbose("Custom libGL override detected. Skipping GPU detection");
  5165. use_prime = 0;
  5166. }
  5167. }
  5168. }
  5169. if (use_prime == -1) {
  5170. print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic.");
  5171. use_prime = detect_prime();
  5172. }
  5173. if (use_prime) {
  5174. print_line("Found discrete GPU, setting DRI_PRIME=1 to use it.");
  5175. print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU.");
  5176. setenv("DRI_PRIME", "1", 1);
  5177. }
  5178. }
  5179. }
  5180. if (rendering_driver == "opengl3") {
  5181. gl_manager = memnew(GLManager_X11(p_resolution, GLManager_X11::GLES_3_0_COMPATIBLE));
  5182. if (gl_manager->initialize(x11_display) != OK || gl_manager->open_display(x11_display) != OK) {
  5183. memdelete(gl_manager);
  5184. gl_manager = nullptr;
  5185. bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_gles");
  5186. if (fallback) {
  5187. WARN_PRINT("Your video card drivers seem not to support the required OpenGL version, switching to OpenGLES.");
  5188. rendering_driver = "opengl3_es";
  5189. } else {
  5190. r_error = ERR_UNAVAILABLE;
  5191. ERR_FAIL_MSG("Could not initialize OpenGL.");
  5192. }
  5193. } else {
  5194. driver_found = true;
  5195. RasterizerGLES3::make_current(true);
  5196. }
  5197. }
  5198. if (rendering_driver == "opengl3_es") {
  5199. gl_manager_egl = memnew(GLManagerEGL_X11);
  5200. if (gl_manager_egl->initialize() != OK) {
  5201. memdelete(gl_manager_egl);
  5202. gl_manager_egl = nullptr;
  5203. r_error = ERR_UNAVAILABLE;
  5204. ERR_FAIL_MSG("Could not initialize OpenGLES.");
  5205. }
  5206. driver_found = true;
  5207. RasterizerGLES3::make_current(false);
  5208. }
  5209. #endif
  5210. if (!driver_found) {
  5211. r_error = ERR_UNAVAILABLE;
  5212. ERR_FAIL_MSG("Video driver not found");
  5213. }
  5214. Point2i window_position;
  5215. if (p_position != nullptr) {
  5216. window_position = *p_position;
  5217. } else {
  5218. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  5219. p_screen = SCREEN_PRIMARY;
  5220. }
  5221. Rect2i scr_rect = screen_get_usable_rect(p_screen);
  5222. window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
  5223. }
  5224. WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution));
  5225. if (main_window == INVALID_WINDOW_ID) {
  5226. r_error = ERR_CANT_CREATE;
  5227. return;
  5228. }
  5229. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  5230. if (p_flags & (1 << i)) {
  5231. window_set_flag(WindowFlags(i), true, main_window);
  5232. }
  5233. }
  5234. show_window(main_window);
  5235. #if defined(RD_ENABLED)
  5236. if (context_rd) {
  5237. rendering_device = memnew(RenderingDevice);
  5238. rendering_device->initialize(context_rd);
  5239. RendererCompositorRD::make_current();
  5240. }
  5241. #endif
  5242. {
  5243. //set all event master mask
  5244. XIEventMask all_master_event_mask;
  5245. static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
  5246. all_master_event_mask.deviceid = XIAllMasterDevices;
  5247. all_master_event_mask.mask_len = sizeof(all_master_mask_data);
  5248. all_master_event_mask.mask = all_master_mask_data;
  5249. XISetMask(all_master_event_mask.mask, XI_DeviceChanged);
  5250. XISetMask(all_master_event_mask.mask, XI_RawMotion);
  5251. XISelectEvents(x11_display, DefaultRootWindow(x11_display), &all_master_event_mask, 1);
  5252. }
  5253. cursor_size = XcursorGetDefaultSize(x11_display);
  5254. cursor_theme = XcursorGetTheme(x11_display);
  5255. if (!cursor_theme) {
  5256. print_verbose("XcursorGetTheme could not get cursor theme");
  5257. cursor_theme = "default";
  5258. }
  5259. for (int i = 0; i < CURSOR_MAX; i++) {
  5260. static const char *cursor_file[] = {
  5261. "left_ptr",
  5262. "xterm",
  5263. "hand2",
  5264. "cross",
  5265. "watch",
  5266. "left_ptr_watch",
  5267. "fleur",
  5268. "dnd-move",
  5269. "crossed_circle",
  5270. "v_double_arrow",
  5271. "h_double_arrow",
  5272. "size_bdiag",
  5273. "size_fdiag",
  5274. "move",
  5275. "row_resize",
  5276. "col_resize",
  5277. "question_arrow"
  5278. };
  5279. cursor_img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
  5280. if (!cursor_img[i]) {
  5281. const char *fallback = nullptr;
  5282. switch (i) {
  5283. case CURSOR_POINTING_HAND:
  5284. fallback = "pointer";
  5285. break;
  5286. case CURSOR_CROSS:
  5287. fallback = "crosshair";
  5288. break;
  5289. case CURSOR_WAIT:
  5290. fallback = "wait";
  5291. break;
  5292. case CURSOR_BUSY:
  5293. fallback = "progress";
  5294. break;
  5295. case CURSOR_DRAG:
  5296. fallback = "grabbing";
  5297. break;
  5298. case CURSOR_CAN_DROP:
  5299. fallback = "hand1";
  5300. break;
  5301. case CURSOR_FORBIDDEN:
  5302. fallback = "forbidden";
  5303. break;
  5304. case CURSOR_VSIZE:
  5305. fallback = "ns-resize";
  5306. break;
  5307. case CURSOR_HSIZE:
  5308. fallback = "ew-resize";
  5309. break;
  5310. case CURSOR_BDIAGSIZE:
  5311. fallback = "fd_double_arrow";
  5312. break;
  5313. case CURSOR_FDIAGSIZE:
  5314. fallback = "bd_double_arrow";
  5315. break;
  5316. case CURSOR_MOVE:
  5317. cursor_img[i] = cursor_img[CURSOR_DRAG];
  5318. break;
  5319. case CURSOR_VSPLIT:
  5320. fallback = "sb_v_double_arrow";
  5321. break;
  5322. case CURSOR_HSPLIT:
  5323. fallback = "sb_h_double_arrow";
  5324. break;
  5325. case CURSOR_HELP:
  5326. fallback = "help";
  5327. break;
  5328. }
  5329. if (fallback != nullptr) {
  5330. cursor_img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size);
  5331. }
  5332. }
  5333. if (cursor_img[i]) {
  5334. cursors[i] = XcursorImageLoadCursor(x11_display, cursor_img[i]);
  5335. } else {
  5336. print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
  5337. }
  5338. }
  5339. {
  5340. // Creating an empty/transparent cursor
  5341. // Create 1x1 bitmap
  5342. Pixmap cursormask = XCreatePixmap(x11_display,
  5343. RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
  5344. // Fill with zero
  5345. XGCValues xgc;
  5346. xgc.function = GXclear;
  5347. GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
  5348. XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
  5349. // Color value doesn't matter. Mask zero means no foreground or background will be drawn
  5350. XColor col = {};
  5351. Cursor cursor = XCreatePixmapCursor(x11_display,
  5352. cursormask, // source (using cursor mask as placeholder, since it'll all be ignored)
  5353. cursormask, // mask
  5354. &col, &col, 0, 0);
  5355. XFreePixmap(x11_display, cursormask);
  5356. XFreeGC(x11_display, gc);
  5357. if (cursor == None) {
  5358. ERR_PRINT("FAILED CREATING CURSOR");
  5359. }
  5360. null_cursor = cursor;
  5361. }
  5362. cursor_set_shape(CURSOR_BUSY);
  5363. // Search the X11 event queue for ConfigureNotify events and process all
  5364. // that are currently queued early, so we can get the final window size
  5365. // for correctly drawing of the bootsplash.
  5366. XEvent config_event;
  5367. while (XCheckTypedEvent(x11_display, ConfigureNotify, &config_event)) {
  5368. _window_changed(&config_event);
  5369. }
  5370. events_thread.start(_poll_events_thread, this);
  5371. _update_real_mouse_position(windows[MAIN_WINDOW_ID]);
  5372. #ifdef DBUS_ENABLED
  5373. screensaver = memnew(FreeDesktopScreenSaver);
  5374. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  5375. portal_desktop = memnew(FreeDesktopPortalDesktop);
  5376. #endif
  5377. XSetErrorHandler(&default_window_error_handler);
  5378. r_error = OK;
  5379. }
  5380. DisplayServerX11::~DisplayServerX11() {
  5381. // Send owned clipboard data to clipboard manager before exit.
  5382. Window x11_main_window = windows[MAIN_WINDOW_ID].x11_window;
  5383. _clipboard_transfer_ownership(XA_PRIMARY, x11_main_window);
  5384. _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_main_window);
  5385. events_thread_done.set();
  5386. events_thread.wait_to_finish();
  5387. //destroy all windows
  5388. for (KeyValue<WindowID, WindowData> &E : windows) {
  5389. #if defined(RD_ENABLED)
  5390. if (context_rd) {
  5391. context_rd->window_destroy(E.key);
  5392. }
  5393. #endif
  5394. #ifdef GLES3_ENABLED
  5395. if (gl_manager) {
  5396. gl_manager->window_destroy(E.key);
  5397. }
  5398. if (gl_manager_egl) {
  5399. gl_manager_egl->window_destroy(E.key);
  5400. }
  5401. #endif
  5402. WindowData &wd = E.value;
  5403. if (wd.xic) {
  5404. XDestroyIC(wd.xic);
  5405. wd.xic = nullptr;
  5406. }
  5407. XDestroyWindow(x11_display, wd.x11_xim_window);
  5408. #ifdef XKB_ENABLED
  5409. if (xkb_loaded_v05p) {
  5410. if (wd.xkb_state) {
  5411. xkb_compose_state_unref(wd.xkb_state);
  5412. wd.xkb_state = nullptr;
  5413. }
  5414. }
  5415. #endif
  5416. XUnmapWindow(x11_display, wd.x11_window);
  5417. XDestroyWindow(x11_display, wd.x11_window);
  5418. }
  5419. #ifdef XKB_ENABLED
  5420. if (xkb_loaded_v05p) {
  5421. if (dead_tbl) {
  5422. xkb_compose_table_unref(dead_tbl);
  5423. }
  5424. if (xkb_ctx) {
  5425. xkb_context_unref(xkb_ctx);
  5426. }
  5427. }
  5428. #endif
  5429. //destroy drivers
  5430. #if defined(RD_ENABLED)
  5431. if (rendering_device) {
  5432. rendering_device->finalize();
  5433. memdelete(rendering_device);
  5434. rendering_device = nullptr;
  5435. }
  5436. if (context_rd) {
  5437. memdelete(context_rd);
  5438. context_rd = nullptr;
  5439. }
  5440. #endif
  5441. #ifdef GLES3_ENABLED
  5442. if (gl_manager) {
  5443. memdelete(gl_manager);
  5444. gl_manager = nullptr;
  5445. }
  5446. if (gl_manager_egl) {
  5447. memdelete(gl_manager_egl);
  5448. gl_manager_egl = nullptr;
  5449. }
  5450. #endif
  5451. if (xrandr_handle) {
  5452. dlclose(xrandr_handle);
  5453. }
  5454. for (int i = 0; i < CURSOR_MAX; i++) {
  5455. if (cursors[i] != None) {
  5456. XFreeCursor(x11_display, cursors[i]);
  5457. }
  5458. if (cursor_img[i] != nullptr) {
  5459. XcursorImageDestroy(cursor_img[i]);
  5460. }
  5461. }
  5462. if (xim) {
  5463. XCloseIM(xim);
  5464. }
  5465. XCloseDisplay(x11_display);
  5466. if (xmbstring) {
  5467. memfree(xmbstring);
  5468. }
  5469. #ifdef SPEECHD_ENABLED
  5470. if (tts) {
  5471. memdelete(tts);
  5472. }
  5473. #endif
  5474. #ifdef DBUS_ENABLED
  5475. memdelete(screensaver);
  5476. memdelete(portal_desktop);
  5477. #endif
  5478. }
  5479. void DisplayServerX11::register_x11_driver() {
  5480. register_create_function("x11", create_func, get_rendering_drivers_func);
  5481. }
  5482. #endif // X11 enabled