display_server_x11.cpp 142 KB

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