display_server_x11.cpp 172 KB

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