display_server_x11.cpp 126 KB

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