display_server_x11.cpp 144 KB

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