display_server_x11.cpp 112 KB

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