2
0

display_server_x11.cpp 115 KB

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