display_server_x11.cpp 104 KB

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