display_server_x11.cpp 197 KB

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