display_server_x11.cpp 111 KB

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