display_server_x11.cpp 122 KB

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