display_server_x11.cpp 112 KB

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