display_server_x11.cpp 130 KB

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