display_server_x11.cpp 98 KB

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