llwindowsdl.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303
  1. /**
  2. * @file llwindowsdl.cpp
  3. * @brief SDL implementation of LLWindow class
  4. * @author This module has many fathers, and it shows.
  5. *
  6. * $LicenseInfo:firstyear=2001&license=viewergpl$
  7. *
  8. * Copyright (c) 2001-2009, Linden Research, Inc.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #if LL_LINUX
  34. #include "linden_common.h"
  35. #include "indra_constants.h"
  36. #include <stdlib.h>
  37. #include <unistd.h>
  38. #include <sys/types.h>
  39. #include <sys/wait.h>
  40. #include "fontconfig/fontconfig.h"
  41. #include "llwindowsdl.h"
  42. #include <regex> // For regex in x11_detect_vram_kb_from_file()
  43. #include "lldir.h"
  44. #include "llfasttimer.h"
  45. #include "llfindlocale.h"
  46. #include "llgl.h"
  47. #include "llglslshader.h"
  48. #include "llkeyboardsdl.h"
  49. #include "llstring.h"
  50. #include "lltimer.h"
  51. // *HACK: stash a pointer to the LLWindowSDL object here and maintain in the
  52. // constructor and destructor. This assumes that there will be only one object
  53. // of this class at any time. Currently this is true.
  54. static LLWindowSDL* sWindowImplementation = NULL;
  55. // *HACK: to avoid white screen flickering; defined in llviewerdisplay.cpp
  56. extern U32 gFrameSleepTime;
  57. bool gXlibThreadSafe = false;
  58. bool gXWayland = false;
  59. bool gUseFullDesktop = false;
  60. constexpr S32 MAX_NUM_RESOLUTIONS = 200;
  61. S32 exec_cmd(const std::string& cmd, const std::string& arg)
  62. {
  63. char* const argv[] = { (char*)cmd.c_str(), (char*)arg.c_str(), NULL };
  64. fflush(NULL);
  65. pid_t pid = fork();
  66. if (pid == 0)
  67. {
  68. // Child path. Disconnect from stdin/stdout/stderr, or child will
  69. // keep our output pipe undesirably alive if it outlives us.
  70. close(0);
  71. close(1);
  72. close(2);
  73. // End ourself by running the command
  74. execv(cmd.c_str(), argv);
  75. // If execv returns at all, there was a problem.
  76. llwarns << "execv() failure when trying to start: " << cmd << llendl;
  77. _exit(1); // _exit because we do not want atexit() clean-up !
  78. }
  79. else if (pid > 0)
  80. {
  81. // Parent path. Wait for child to die.
  82. int child_exit_status;
  83. waitpid(pid, &child_exit_status, 0);
  84. return child_exit_status;
  85. }
  86. else
  87. {
  88. llwarns << "Fork failure." << llendl;
  89. }
  90. return -1;
  91. }
  92. //static
  93. void LLWindowSDL::initXlibThreads()
  94. {
  95. // Ensure Xlib is started in thread-safe state, so that the NVIDIA drivers
  96. // can use multi-threading.
  97. if (!gXlibThreadSafe)
  98. {
  99. gXlibThreadSafe = XInitThreads();
  100. if (gXlibThreadSafe)
  101. {
  102. llinfos << "Xlib successfully initialized in thread-safe state"
  103. << llendl;
  104. }
  105. else
  106. {
  107. llwarns << "Failed to initialize Xlib in thread-safe state: NVIDIA drivers will run single-threaded."
  108. << llendl;
  109. }
  110. }
  111. }
  112. //static
  113. Window LLWindowSDL::getSDLXWindowID()
  114. {
  115. if (sWindowImplementation)
  116. {
  117. return sWindowImplementation->mSDL_XWindowID;
  118. }
  119. return None;
  120. }
  121. //static
  122. Display* LLWindowSDL::getSDLDisplay()
  123. {
  124. if (sWindowImplementation)
  125. {
  126. return sWindowImplementation->mSDL_Display;
  127. }
  128. return NULL;
  129. }
  130. LLWindowSDL::LLWindowSDL(const std::string& title, S32 x, S32 y, U32 width,
  131. U32 height, U32 flags, bool fullscreen,
  132. bool disable_vsync, U32 fsaa_samples)
  133. : LLWindow(fullscreen, flags),
  134. mWindow(NULL),
  135. mSDLFlags(0),
  136. mInitialPosX(x),
  137. mInitialPosY(y),
  138. mPosOffsetX(-1),
  139. mPosOffsetY(-1),
  140. mCustomGammaSet(false),
  141. mKeyVirtualKey(0),
  142. mKeyModifiers(KMOD_NONE),
  143. mCaptured(false),
  144. mGrabbyKeyFlags(0),
  145. mFSAASamples(fsaa_samples),
  146. mOriginalAspectRatio(4.f / 3.f), // Assume 4:3 until we know better
  147. mWindowTitle(title.empty() ? "SL viewer" : title)
  148. {
  149. // Initialize the keyboard. Note that we cannot set up key-repeat until
  150. // after SDL has initialized the video
  151. gKeyboardp = new LLKeyboardSDL();
  152. // This should have already been called in LLSplashScreenSDL, but better
  153. // safe than sorry...
  154. initXlibThreads();
  155. // Wayland *SUCKS*, and XWayland is *NOT* 100% X11-compatible...
  156. char* wayland_env = getenv("WAYLAND_DISPLAY");
  157. gXWayland = wayland_env && wayland_env[0];
  158. if (gXWayland)
  159. {
  160. llwarns << "XWayland compatibility mode detected. This will cause unexpected behaviours. The viewer is a genuine X11 application, not a Wayland one, please run it under a genuine X11 server. NO SUPPORT provided for viewer sessions ran under XWayland !"
  161. << llendl;
  162. }
  163. mSDL_XWindowID = None;
  164. mSDL_Display = NULL;
  165. mContext = {};
  166. memset(mCurrentGammaRamp, 0, sizeof(mCurrentGammaRamp));
  167. memset(mPrevGammaRamp, 0, sizeof(mPrevGammaRamp));
  168. // Create the GL context and set it up for windowed or fullscreen, as
  169. // appropriate.
  170. if (createContext(x, y, width, height, 32, fullscreen, disable_vsync))
  171. {
  172. if (!gGLManager.initGL())
  173. {
  174. setupFailure("Could not properly initialize OpenGL !");
  175. }
  176. // Start with arrow cursor
  177. initCursors();
  178. setCursor(UI_CURSOR_ARROW);
  179. }
  180. stop_glerror();
  181. sWindowImplementation = this;
  182. mFlashing = false;
  183. initialiseX11Clipboard();
  184. }
  185. //virtual
  186. LLWindowSDL::~LLWindowSDL()
  187. {
  188. quitCursors();
  189. destroyContext();
  190. if (mSupportedResolutions)
  191. {
  192. delete[] mSupportedResolutions;
  193. mSupportedResolutions = NULL;
  194. }
  195. sWindowImplementation = NULL;
  196. }
  197. static SDL_Surface* load_bmp_resource(const char* basename)
  198. {
  199. constexpr S32 PATH_BUFFER_SIZE = 1000;
  200. char path_buffer[PATH_BUFFER_SIZE];
  201. // Figure out where our BMP is living on the disk
  202. snprintf(path_buffer, PATH_BUFFER_SIZE - 1, "%s/res-sdl/%s",
  203. gDirUtil.getAppRODataDir().c_str(), basename);
  204. path_buffer[PATH_BUFFER_SIZE - 1] = '\0';
  205. return SDL_LoadBMP(path_buffer);
  206. }
  207. // This function scans the Xorg log to determine the amount of VRAM available
  208. // to the system.
  209. // Returns -1 if it could not open the file.
  210. // 0 if it could open the file but could not detect the amount of
  211. // VRAM.
  212. // >0 (VRAM amount in kilobytes) if successful.
  213. static S32 x11_detect_vram_kb_from_file(const std::string& filename)
  214. {
  215. std::ifstream in(filename.c_str());
  216. if (!in.is_open())
  217. {
  218. LL_DEBUGS("Window") << "Could not open file: " << filename << LL_ENDL;
  219. return -1;
  220. }
  221. std::regex pattern(".*?(VRAM|Memory|Video\\s?RAM)\\D*(\\d+)\\s?([kK]B?)");
  222. S32 amount = 0;
  223. std::string line;
  224. while (std::getline(in, line))
  225. {
  226. std::cmatch match;
  227. if (std::regex_search(line.c_str(), match, pattern))
  228. {
  229. amount = atoi(std::string(match[2]).c_str());
  230. LL_DEBUGS("Window") << "Match found in line: " << line
  231. << "VRAM amount: " << amount << LL_ENDL;
  232. }
  233. }
  234. in.close();
  235. return amount;
  236. }
  237. static S32 x11_detect_vram_kb()
  238. {
  239. S32 amount = 0;
  240. // Let the user override the detection in case it fails on their system.
  241. // They can specify the amount of VRAM in megabytes, via the LL_VRAM_MB
  242. // environment variable.
  243. char* vram_override = getenv("LL_VRAM_MB");
  244. if (vram_override)
  245. {
  246. amount = atoi(vram_override);
  247. if (amount > 0)
  248. {
  249. llinfos << "Amount of VRAM overridden via the LL_VRAM_MB environment variable; detection step skipped."
  250. << llendl;
  251. return 1024 * amount; // Converted to kilobytes
  252. }
  253. }
  254. // We parse VGL_DISPLAY first so we can grab the right Xorg filename if we
  255. // are using VirtualGL (like Optimus systems do).
  256. char* display_env = getenv("VGL_DISPLAY"); // e.g. :0 or :0.0 or :1.0 etc
  257. if (!display_env)
  258. {
  259. display_env = getenv("DISPLAY");
  260. }
  261. // Parse DISPLAY number so we can go grab the right log file
  262. S32 display_num = 0;
  263. if (display_env && display_env[0] == ':' && display_env[1] >= '0' &&
  264. display_env[1] <= '9')
  265. {
  266. display_num = display_env[1] - '0';
  267. }
  268. // *TODO: we could be smarter and see which of Xorg/XFree86 has the
  269. // freshest time-stamp.
  270. // Try Xorg log first
  271. std::string x_log_location = "/var/log/";
  272. std::string fname = x_log_location + "Xorg.";
  273. fname += ('0' + display_num);
  274. fname += ".log";
  275. llinfos << "Looking in " << fname << " for VRAM info..." << llendl;
  276. amount = x11_detect_vram_kb_from_file(fname);
  277. if (amount < 0)
  278. {
  279. llinfos << "Could not open " << fname << " - skipped." << llendl;
  280. // Try old XFree86 log otherwise
  281. fname = x_log_location + "XFree86.";
  282. fname += ('0' + display_num);
  283. fname += ".log";
  284. amount = x11_detect_vram_kb_from_file(fname);
  285. if (amount < 0)
  286. {
  287. llinfos << "Could not open " << fname << " - skipped." << llendl;
  288. amount = 0;
  289. }
  290. }
  291. if (amount > 0)
  292. {
  293. llinfos << "X11 log-parser detected " << amount / 1024 << "MB VRAM."
  294. << llendl;
  295. }
  296. else
  297. {
  298. llwarns << "VRAM amount detection failed. You could use the LL_VRAM_MB environment variable to specify it. "
  299. << llendl;
  300. }
  301. return amount;
  302. }
  303. //virtual
  304. void LLWindowSDL::setWindowTitle(const std::string& title)
  305. {
  306. // Remember the new title, for when we switch context
  307. mWindowTitle = title;
  308. if (mWindow)
  309. {
  310. SDL_SetWindowTitle(mWindow, title.c_str());
  311. }
  312. }
  313. //virtual
  314. bool LLWindowSDL::getFullScreenSize(S32& width, S32& height)
  315. {
  316. // When width and height are not 0, consider we already know what size we
  317. // can use.
  318. if (width != 0 && height != 0)
  319. {
  320. return true;
  321. }
  322. // Scan through the list of modes, looking for one which has height between
  323. // 700 and 800 and aspect ratio closest to the user's original mode.
  324. S32 res_count = 0;
  325. LLWindowResolution* res_list = getSupportedResolutions(res_count);
  326. if (res_list)
  327. {
  328. F32 closest_aspect = 0.f;
  329. S32 closest_width = 0;
  330. S32 closest_height = 0;
  331. llinfos << "Searching for a display mode, original aspect is "
  332. << mOriginalAspectRatio << llendl;
  333. for (S32 i = 0; i < res_count; ++i)
  334. {
  335. S32 h = res_list[i].mHeight;
  336. S32 w = res_list[i].mWidth;
  337. F32 aspect = (F32)w / (F32)h;
  338. llinfos << "width = " << w << " - height = " << h << " - aspect = "
  339. << aspect;
  340. if (h >= 700 && h <= 800 &&
  341. fabs(aspect - mOriginalAspectRatio) <
  342. fabs(closest_aspect - mOriginalAspectRatio))
  343. {
  344. llcont << " (new closest mode)";
  345. closest_width = w;
  346. closest_height = h;
  347. closest_aspect = aspect;
  348. }
  349. llcont << llendl;
  350. }
  351. width = closest_width;
  352. height = closest_height;
  353. }
  354. if (width == 0 || height == 0)
  355. {
  356. // Mode search failed: used some common/acceptable default.
  357. width = 1024;
  358. height = 768;
  359. return false;
  360. }
  361. return true;
  362. }
  363. // The Cool VL Viewer window icon is opaque, so no need to bother about the
  364. // transparency code... HB
  365. #define WINDOW_ICON_TANSPARENCY 0
  366. // Reimplementation of SDL1's mask generation for SDL_WM_SetIcon()
  367. static Uint8* generate_icon_mask(SDL_Surface* icon)
  368. {
  369. S32 width = icon->w;
  370. S32 height = icon->h;
  371. S32 bpl = (width + 7) / 8; // Bytes per line
  372. S32 mask_len = height * bpl;
  373. Uint8* mask = (Uint8*)malloc(mask_len);
  374. if (!mask)
  375. {
  376. return NULL;
  377. }
  378. // Set as an opaque mask (all bits at 1 in the mask)
  379. memset((void*)mask, ~0, mask_len);
  380. #if WINDOW_ICON_TANSPARENCY
  381. Uint32 colorkey;
  382. if (SDL_GetColorKey(icon, &colorkey) == 0)
  383. {
  384. S32 picth = icon->pitch;
  385. switch (icon->format->BytesPerPixel)
  386. {
  387. case 1:
  388. {
  389. for (S32 y = 0; y < height; ++y)
  390. {
  391. Uint8* pixels = (Uint8*)icon->pixels + y * picth;
  392. for (S32 x = 0; x < width; ++x)
  393. {
  394. if (*pixels++ == colorkey)
  395. {
  396. mask[y * bpl + x / 8] &= ~(1 << (7 - x % 8));
  397. }
  398. }
  399. }
  400. break;
  401. }
  402. case 2:
  403. {
  404. for (S32 y = 0; y < height; ++y)
  405. {
  406. Uint16* pixels = (Uint16*)icon->pixels + y * picth / 2;
  407. for (S32 x = 0; x < width; ++x)
  408. {
  409. if (*pixels++ == colorkey)
  410. {
  411. mask[y * bpl + x / 8] &= ~(1 << (7 - x % 8));
  412. }
  413. }
  414. }
  415. break;
  416. }
  417. case 4:
  418. {
  419. for (S32 y = 0; y < height; ++y)
  420. {
  421. Uint32* pixels = (Uint32*)icon->pixels + y * picth / 4;
  422. for (S32 x = 0; x < width; ++x)
  423. {
  424. if (*pixels++ == colorkey)
  425. {
  426. mask[y * bpl + x / 8] &= ~(1 << (7 - x % 8));
  427. }
  428. }
  429. }
  430. break;
  431. }
  432. default: // Invalid icon ?... Return an opaque mask
  433. return mask;
  434. }
  435. // We need the mask as given, except in LSBfirst format instead of
  436. // MSBfirst. Reverse the bits in each byte.
  437. Uint8* lsb_mask = (Uint8*)malloc(mask_len);
  438. if (!lsb_mask)
  439. {
  440. free(mask);
  441. return NULL;
  442. }
  443. memset((void*)lsb_mask, 0, mask_len);
  444. for (S32 i = 0; i < mask_len; ++i)
  445. {
  446. Uint8 x = mask[i];
  447. x = (x & 0xaa) >> 1 | (x & 0x55) << 1;
  448. x = (x & 0xcc) >> 2 | (x & 0x33) << 2;
  449. x = (x & 0xf0) >> 4 | (x & 0x0f) << 4;
  450. lsb_mask[i] = x;
  451. }
  452. free(mask);
  453. return lsb_mask;
  454. }
  455. #endif
  456. // Opaque mask.
  457. return mask;
  458. }
  459. // This method must be called at the end of createContext() so that
  460. // mSDL_Display and mSDL_XWindowID got initialized...
  461. void LLWindowSDL::setWindowIcon()
  462. {
  463. #if 0 // Does not seem to make any difference...
  464. // Give an icon name hint to X11
  465. static const char* icon_hint = "cvlv_icon";
  466. XTextProperty icon_prop;
  467. XStringListToTextProperty((char**)&icon_hint, 1, &icon_prop);
  468. XSetWMIconName(mSDL_Display, mSDL_XWindowID, &icon_prop);
  469. XFree(icon_prop.value);
  470. #endif
  471. // Set the application icon.
  472. S32 icon_size = 48;
  473. char* envvar = getenv("LL_WINDOW_ICON_SIZE");
  474. if (envvar)
  475. {
  476. icon_size = atoi(envvar);
  477. if (icon_size != 32 && icon_size != 48 && icon_size != 64 &&
  478. icon_size != 128 && icon_size != 256)
  479. {
  480. icon_size = 48;
  481. }
  482. }
  483. std::string icon_name = llformat("cvlv_icon%d.bmp", icon_size);
  484. SDL_Surface* icon = load_bmp_resource(icon_name.c_str());
  485. if (!icon)
  486. {
  487. return;
  488. }
  489. #if WINDOW_ICON_TANSPARENCY
  490. // This attempts to give a black-keyed mask to the icon.
  491. SDL_SetColorKey(icon, SDL_TRUE, SDL_MapRGB(icon->format, 0, 0, 0));
  492. #endif
  493. bool success = false;
  494. // Reimplementation of SDL1's SDL_WM_SetIcon() for X11
  495. do
  496. {
  497. // *FIXME: 32 bits is what *appears* to be needed, although the default
  498. // visual depth is 24 bits... There is some voodoo magic performed by
  499. // SDL1 with available visuals and their possible depths to determine
  500. // the right pixel format, but implementing it seems quite an overkill:
  501. // 32 bits *should* work for everyone ! HB
  502. S32 bpp = 32;
  503. // And just in case, the LL_WINDOW_ICON_BPP environment variable allows
  504. // to change that value at runtime...
  505. envvar = getenv("LL_WINDOW_ICON_BPP");
  506. if (envvar)
  507. {
  508. bpp = atoi(envvar);
  509. if (bpp != 32 && bpp != 24 && bpp != 16 && bpp != 15)
  510. {
  511. // We would not deal with those... Let's try and fallback to
  512. // SDL_SetWindowIcon() for them.
  513. break;
  514. }
  515. llinfos << "Using " << bpp
  516. << " bits per pixel for the window icon." << llendl;
  517. }
  518. // Various X11 data needed below...
  519. S32 screen = DefaultScreen(mSDL_Display);
  520. S32 default_depth = DefaultDepth(mSDL_Display, screen);
  521. if (default_depth == 8)
  522. {
  523. break;
  524. }
  525. Visual* default_visual = DefaultVisual(mSDL_Display, screen);
  526. S32 root_window = RootWindow(mSDL_Display, screen);
  527. S32 width = icon->w;
  528. S32 height = icon->h;
  529. SDL_Surface* sicon = SDL_CreateRGBSurface(0, width, height, bpp,
  530. default_visual->red_mask,
  531. default_visual->green_mask,
  532. default_visual->blue_mask,
  533. 0);
  534. if (!sicon)
  535. {
  536. break;
  537. }
  538. // At this point, I skip all the 8 bits depth conversion code, since we
  539. // excluded this case above already... HB
  540. SDL_Rect bounds;
  541. bounds.x = 0;
  542. bounds.y = 0;
  543. bounds.w = width;
  544. bounds.h = height;
  545. if (SDL_LowerBlit(icon, &bounds, sicon, &bounds) != 0)
  546. {
  547. SDL_FreeSurface(sicon);
  548. break;
  549. }
  550. // Generate a mask.
  551. Uint8* mask = generate_icon_mask(icon);
  552. if (!mask)
  553. {
  554. SDL_FreeSurface(sicon);
  555. break;
  556. }
  557. Pixmap mask_pixmap = XCreatePixmapFromBitmapData(mSDL_Display,
  558. mSDL_XWindowID,
  559. (char*)mask,
  560. width, height,
  561. 1L, 0L, 1);
  562. free(mask);
  563. // Transfer the image to an X11 pixmap
  564. XImage* icon_image = XCreateImage(mSDL_Display, default_visual,
  565. default_depth, ZPixmap, 0,
  566. (char*)sicon->pixels, width, height,
  567. 32, 0);
  568. if (!icon_image)
  569. {
  570. SDL_FreeSurface(sicon);
  571. break;
  572. }
  573. #if LL_BIG_ENDIAN
  574. icon_image->byte_order = MSBFirst;
  575. #else
  576. icon_image->byte_order = LSBFirst;
  577. #endif
  578. Pixmap icon_pixmap = XCreatePixmap(mSDL_Display, root_window,
  579. width, height, default_depth);
  580. XGCValues gc_values;
  581. GC gc = XCreateGC(mSDL_Display, icon_pixmap, 0, &gc_values);
  582. XPutImage(mSDL_Display, icon_pixmap, gc, icon_image, 0, 0, 0, 0,
  583. width, height);
  584. XFreeGC(mSDL_Display, gc);
  585. sicon->pixels = NULL;
  586. // I skip the SDL_VIDEO_X11_ICONWIN fix here, which was only for use
  587. // with some old buggy versions of Enlightenment... HB
  588. // Set the window icon to the icon pixmap and associated mask
  589. XWMHints* wmhints = XAllocWMHints();
  590. wmhints->flags = IconPixmapHint | IconMaskHint | InputHint;
  591. wmhints->icon_pixmap = icon_pixmap;
  592. wmhints->icon_mask = mask_pixmap;
  593. wmhints->input = True;
  594. XSetWMHints(mSDL_Display, mSDL_XWindowID, wmhints);
  595. XFree(wmhints);
  596. XSync(mSDL_Display, False);
  597. success = true;
  598. }
  599. while (false);
  600. // Fallback code, using SDL2's SDL_SetWindowIcon()
  601. if (!success)
  602. {
  603. // SDL2's SDL_SetWindowIcon() fails to set the application menu button
  604. // in the title bar (and Meta-TAB window cycler, unless the BMP icon
  605. // size is exactly 32x32 pixels for the latter... Go figure !), while
  606. // SDL1's SDL_WM_SetIcon() works fine in this respect ! :-( HB
  607. SDL_Surface* icon2 = load_bmp_resource("cvlv_icon32.bmp");
  608. if (icon2)
  609. {
  610. SDL_FreeSurface(icon);
  611. icon = icon2;
  612. #if WINDOW_ICON_TANSPARENCY
  613. // This attempts to give a black-keyed mask to the icon.
  614. SDL_SetColorKey(icon, SDL_TRUE, SDL_MapRGB(icon->format, 0, 0, 0));
  615. #endif
  616. }
  617. SDL_SetWindowIcon(mWindow, icon);
  618. }
  619. SDL_FreeSurface(icon);
  620. }
  621. bool LLWindowSDL::createContext(S32 x, S32 y, S32 width, S32 height, S32 bits,
  622. bool fullscreen, bool disable_vsync)
  623. {
  624. llinfos << "Fullscreen = " << fullscreen << " - Size = " << width << "x"
  625. << height << llendl;
  626. // Captures do not survive contexts
  627. mGrabbyKeyFlags = 0;
  628. mCaptured = false;
  629. if (SDL_Init(SDL_INIT_VIDEO) < 0)
  630. {
  631. llinfos << "sdl_init() failed ! " << SDL_GetError() << llendl;
  632. setupFailure("sdl_init() failure, window creation error");
  633. return false;
  634. }
  635. SDL_version c_sdl_version;
  636. SDL_VERSION(&c_sdl_version);
  637. llinfos << "Compiled against SDL " << S32(c_sdl_version.major) << "."
  638. << S32(c_sdl_version.minor) << "." << S32(c_sdl_version.patch)
  639. << llendl;
  640. SDL_version r_sdl_version;
  641. SDL_GetVersion(&r_sdl_version);
  642. llinfos << "Running against SDL " << S32(r_sdl_version.major) << "."
  643. << S32(r_sdl_version.minor) << "." << S32(r_sdl_version.patch)
  644. << llendl;
  645. SDL_DisplayMode dm;
  646. if (SDL_GetDesktopDisplayMode(0, &dm) == 0)
  647. {
  648. if (dm.h > 0)
  649. {
  650. mOriginalAspectRatio = (F32)dm.w / (F32)dm.h;
  651. llinfos << "Original aspect ratio was " << dm.w << ":" << dm.h
  652. << " = " << mOriginalAspectRatio << llendl;
  653. }
  654. }
  655. if (width == 0)
  656. {
  657. width = 1024;
  658. }
  659. if (height == 0)
  660. {
  661. height = 768;
  662. }
  663. mFullscreen = fullscreen;
  664. mSDLFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
  665. #if 0
  666. if (fullscreen)
  667. {
  668. mSDLFlags |= SDL_WINDOW_FULLSCREEN;
  669. getFullScreenSize(width, height);
  670. }
  671. #endif
  672. GLint alpha_bits = 8;
  673. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, alpha_bits);
  674. GLint red_bits = 8;
  675. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, red_bits);
  676. GLint green_bits = 8;
  677. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, green_bits);
  678. GLint blue_bits = 8;
  679. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, blue_bits);
  680. GLint depth_bits = bits <= 16 ? 16 : 24;
  681. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depth_bits);
  682. // Note: we need stencil support for a few (minor) things.
  683. GLint stencil_bits = 8;
  684. if (getenv("LL_GL_NO_STENCIL"))
  685. {
  686. stencil_bits = 0;
  687. }
  688. else
  689. {
  690. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencil_bits);
  691. }
  692. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  693. if (mFSAASamples > 0)
  694. {
  695. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  696. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, mFSAASamples);
  697. }
  698. U32 context_flags = gDebugGL ? SDL_GL_CONTEXT_DEBUG_FLAG : 0;
  699. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, context_flags);
  700. if (LLRender::sGLCoreProfile)
  701. {
  702. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
  703. SDL_GL_CONTEXT_PROFILE_CORE);
  704. }
  705. // Request shared context support.
  706. SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
  707. mWindow = SDL_CreateWindow(mWindowTitle.c_str(), x, y, width, height,
  708. mSDLFlags);
  709. if (!mWindow)
  710. {
  711. llwarns << "Window creation failure. SDL error: " << SDL_GetError()
  712. << llendl;
  713. setupFailure("Window creation failure.");
  714. return false;
  715. }
  716. // Clear the window (in the two buffers)
  717. glClearColor(0.f, 0.f, 0.f, 1.f);
  718. glClear(GL_COLOR_BUFFER_BIT);
  719. SDL_GL_SwapWindow(mWindow);
  720. glClearColor(0.f, 0.f, 0.f, 1.f);
  721. glClear(GL_COLOR_BUFFER_BIT);
  722. if (mFullscreen)
  723. {
  724. #if 0 // This should be OK, now that we forbid changes during sessions. HB
  725. if (LLRender::sGLCoreProfile)
  726. {
  727. // Full screen mode crashes the viewer when core GL profile is
  728. // enabled... Use full desktop mode instead. HB
  729. gUseFullDesktop = true;
  730. }
  731. #endif
  732. U32 flags = gUseFullDesktop ? SDL_WINDOW_FULLSCREEN_DESKTOP
  733. : SDL_WINDOW_FULLSCREEN;
  734. mFullscreen = SDL_SetWindowFullscreen(mWindow, flags) == 0;
  735. if (!mFullscreen && !gUseFullDesktop)
  736. {
  737. gUseFullDesktop = true; // For next time...
  738. llwarns << "Failed to set real full screen mode, trying full desktop mode..."
  739. << llendl;
  740. flags = SDL_WINDOW_FULLSCREEN_DESKTOP;
  741. mFullscreen = SDL_SetWindowFullscreen(mWindow, flags) == 0;
  742. }
  743. if (!mFullscreen)
  744. {
  745. llwarns << "Failure to set up full screen window " << width << "x"
  746. << height << llendl;
  747. }
  748. }
  749. if (mFullscreen)
  750. {
  751. llinfos << "Setting up fullscreen " << width << "x" << height
  752. << llendl;
  753. SDL_DisplayMode target_mode;
  754. SDL_zero(target_mode);
  755. target_mode.w = width;
  756. target_mode.h = height;
  757. SDL_DisplayMode closest_mode;
  758. SDL_zero(closest_mode);
  759. SDL_GetClosestDisplayMode(SDL_GetWindowDisplayIndex(mWindow),
  760. &target_mode, &closest_mode);
  761. if (SDL_SetWindowDisplayMode(mWindow, &closest_mode) == 0)
  762. {
  763. SDL_DisplayMode mode;
  764. SDL_GetWindowDisplayMode(mWindow, &mode);
  765. mFullscreenWidth = mode.w;
  766. mFullscreenHeight = mode.h;
  767. mFullscreenBits = SDL_BITSPERPIXEL(mode.format);
  768. mFullscreenRefresh = mode.refresh_rate;
  769. llinfos << "Running at " << mFullscreenWidth << "x"
  770. << mFullscreenHeight << "x" << mFullscreenBits << " @ "
  771. << mFullscreenRefresh << "Hz" << llendl;
  772. }
  773. else
  774. {
  775. llwarns << "Fullscreen creation failure. SDL error: "
  776. << SDL_GetError() << llendl;
  777. // No fullscreen support
  778. mFullscreen = false;
  779. mFullscreenWidth = -1;
  780. mFullscreenHeight = -1;
  781. mFullscreenBits = -1;
  782. mFullscreenRefresh = -1;
  783. SDL_SetWindowFullscreen(mWindow, 0);
  784. SDL_SetWindowResizable(mWindow, SDL_TRUE);
  785. std::string error =
  786. llformat("Unable to run fullscreen at %d x %d.", width,
  787. height);
  788. setupFailure(error);
  789. return false;
  790. }
  791. }
  792. if (LLRender::sGLCoreProfile)
  793. {
  794. U32 major = 4;
  795. U32 minor = 6;
  796. while (true)
  797. {
  798. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
  799. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
  800. mContext = SDL_GL_CreateContext(mWindow);
  801. if (mContext)
  802. {
  803. llinfos << "Activated core GL profile v" << major << "."
  804. << minor << llendl;
  805. break; // Success !
  806. }
  807. if (minor > 0)
  808. {
  809. --minor;
  810. }
  811. else if (major == 4)
  812. {
  813. // Continue from 3.3 downwards
  814. major = minor = 3;
  815. }
  816. else
  817. {
  818. break; // Failed to set core GL profile...
  819. }
  820. }
  821. }
  822. else
  823. {
  824. mContext = SDL_GL_CreateContext(mWindow);
  825. }
  826. if (!mContext)
  827. {
  828. llwarns << "Cannot create GL context: " << SDL_GetError() << llendl;
  829. setupFailure("GL context creation error");
  830. return false;
  831. }
  832. // Detect video memory size.
  833. S32 vram_mb = x11_detect_vram_kb() / 1024;
  834. if (vram_mb > 0 && !gGLManager.mVRAM)
  835. {
  836. gGLManager.mVRAM = vram_mb;
  837. }
  838. // If VRAM is not detected, that is handled later
  839. SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &red_bits);
  840. SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &green_bits);
  841. SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &blue_bits);
  842. SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alpha_bits);
  843. SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth_bits);
  844. SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil_bits);
  845. llinfos << "GL buffer:" << llendl;
  846. llinfos << " Red bits " << S32(red_bits) << llendl;
  847. llinfos << " Green bits " << S32(green_bits) << llendl;
  848. llinfos << " Blue bits " << S32(blue_bits) << llendl;
  849. llinfos << " Alpha bits " << S32(alpha_bits) << llendl;
  850. llinfos << " Depth bits " << S32(depth_bits) << llendl;
  851. llinfos << " Stencil bits " << S32(stencil_bits) << llendl;
  852. GLint color_bits = red_bits + green_bits + blue_bits + alpha_bits;
  853. // *FIXME: actually it is REALLY important for picking that we get at least
  854. // 8 bits each of red,green,blue. Alpha we can be a bit more relaxed about
  855. // if we have to.
  856. if (color_bits < 32)
  857. {
  858. close();
  859. setupFailure(
  860. "Second Life requires True Color (32 bits) to run in a window.\n"
  861. "Please go to Control Panels -> Display -> Settings and\n"
  862. "set the screen to 32 bits color.\n"
  863. "Alternately, if you choose to run fullscreen, Second Life\n"
  864. "will automatically adjust the screen each time it runs.");
  865. return false;
  866. }
  867. // Grab the window manager specific information
  868. SDL_SysWMinfo info;
  869. SDL_VERSION(&info.version);
  870. if (SDL_GetWindowWMInfo(mWindow, &info))
  871. {
  872. // Save the information for later use
  873. if (info.subsystem == SDL_SYSWM_X11)
  874. {
  875. mSDL_Display = info.info.x11.display;
  876. mSDL_XWindowID = info.info.x11.window;
  877. }
  878. else
  879. {
  880. llwarns << "We are not running under X11 !" << llendl;
  881. }
  882. }
  883. else
  884. {
  885. llwarns << "We are not running under any known WM !" << llendl;
  886. }
  887. // Set the application icon.
  888. setWindowIcon();
  889. SDL_StartTextInput();
  890. // Make sure multisampling is disabled by default
  891. glDisable(GL_MULTISAMPLE);
  892. // We do not need to get the current gamma, since there is a call that
  893. // restores it to the system defaults.
  894. return true;
  895. }
  896. // Changes fullscreen resolution, or switches between windowed and fullscreen
  897. // modes.
  898. //virtual
  899. bool LLWindowSDL::switchContext(bool fullscreen, const LLCoordScreen& size,
  900. bool disable_vsync,
  901. const LLCoordScreen* const posp)
  902. {
  903. llinfos << "Fullscreen: " << (fullscreen ? "yes" : "no") << llendl;
  904. // Just nuke the context and start over.
  905. destroyContext();
  906. bool result = createContext(0, 0, size.mX, size.mY, 32, fullscreen,
  907. disable_vsync);
  908. if (result)
  909. {
  910. if (!gGLManager.initGL())
  911. {
  912. setupFailure("Could not properly reinitialize OpenGL !");
  913. }
  914. // Start with arrow cursor
  915. initCursors();
  916. setCursor(UI_CURSOR_ARROW);
  917. }
  918. stop_glerror();
  919. return result;
  920. }
  921. struct LLSharedOpenGLContext
  922. {
  923. SDL_GLContext mContext;
  924. };
  925. //virtual
  926. void* LLWindowSDL::createSharedContext()
  927. {
  928. LLSharedOpenGLContext* context = new LLSharedOpenGLContext;
  929. context->mContext = SDL_GL_CreateContext(mWindow);
  930. if (context->mContext)
  931. {
  932. // Do not use VSYNC on any shared context since they are not used for
  933. // actual rendering. HB
  934. SDL_GL_SetSwapInterval(0);
  935. }
  936. // Make our main (renderer) context current again (even if the new context
  937. // creation failed, since SDL2 documentation does not say anything about
  938. // what happens to the current context selection in this case). HB
  939. SDL_GL_MakeCurrent(mWindow, mContext);
  940. if (!context->mContext)
  941. {
  942. // Something went (very) wrong... Free the structure and return a NULL
  943. // pointer to signify we do not have a GL context available. HB
  944. llwarns_sparse << "Failed to create a new shared GL context."
  945. << llendl;
  946. delete context;
  947. return NULL;
  948. }
  949. // *HACK: this will cause a proper screen refresh by triggering a full
  950. // redraw event at the SDL level. Without this hack, you get a "blocky"
  951. // UI until SDL receives a redraw event (which may take seconds). HB
  952. refresh();
  953. return (void*)context;
  954. }
  955. //virtual
  956. void LLWindowSDL::makeContextCurrent(void* context)
  957. {
  958. if (context)
  959. {
  960. SDL_GL_MakeCurrent(mWindow,
  961. ((LLSharedOpenGLContext*)context)->mContext);
  962. }
  963. else
  964. {
  965. // Restore main GL thread context.
  966. SDL_GL_MakeCurrent(mWindow, mContext);
  967. }
  968. }
  969. //virtual
  970. void LLWindowSDL::destroySharedContext(void* context)
  971. {
  972. if (context) // Ignore attempts to destroy invalid contexts. HB
  973. {
  974. LLSharedOpenGLContext* sc = (LLSharedOpenGLContext*)context;
  975. SDL_GL_DeleteContext(sc->mContext);
  976. delete sc;
  977. }
  978. }
  979. //virtual
  980. void LLWindowSDL::destroyContext()
  981. {
  982. SDL_StopTextInput();
  983. mSDL_Display = NULL;
  984. mSDL_XWindowID = None;
  985. // Clean up remaining GL state before blowing away window
  986. llinfos << "Shutting down GL..." << llendl;
  987. gGLManager.shutdownGL();
  988. if (mContext)
  989. {
  990. llinfos << "Destroying context..." << llendl;
  991. SDL_GL_DeleteContext(mContext);
  992. mContext = NULL;
  993. }
  994. if (mWindow)
  995. {
  996. llinfos << "Destroying window..." << llendl;
  997. SDL_DestroyWindow(mWindow);
  998. }
  999. mWindow = NULL;
  1000. llinfos << "Quitting SDL video sub-system..." << llendl;
  1001. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  1002. }
  1003. // Destroys all OS-specific code associated with a window. Usually called from
  1004. // LLWindow::destroyWindow()
  1005. //virtual
  1006. void LLWindowSDL::close()
  1007. {
  1008. #if 0 // Is window is already closed ?
  1009. if (!mWindow)
  1010. {
  1011. return;
  1012. }
  1013. #endif
  1014. // Make sure cursor is visible and we have not mangled the clipping state
  1015. setMouseClipping(false);
  1016. showCursor();
  1017. destroyContext();
  1018. }
  1019. //virtual
  1020. void LLWindowSDL::minimize()
  1021. {
  1022. if (mWindow)
  1023. {
  1024. SDL_MinimizeWindow(mWindow);
  1025. }
  1026. }
  1027. //virtual
  1028. void LLWindowSDL::restore()
  1029. {
  1030. if (mWindow)
  1031. {
  1032. SDL_RestoreWindow(mWindow);
  1033. }
  1034. }
  1035. //virtual
  1036. bool LLWindowSDL::getVisible()
  1037. {
  1038. return mWindow && (SDL_GetWindowFlags(mWindow) & SDL_WINDOW_SHOWN);
  1039. }
  1040. //virtual
  1041. bool LLWindowSDL::getMinimized()
  1042. {
  1043. return mWindow && (SDL_GetWindowFlags(mWindow) & SDL_WINDOW_MINIMIZED);
  1044. }
  1045. //virtual
  1046. void LLWindowSDL::calculateBordersOffsets()
  1047. {
  1048. if (!mWindow || mFullscreen)
  1049. {
  1050. return;
  1051. }
  1052. int x, y;
  1053. SDL_GetWindowPosition(mWindow, &x, &y);
  1054. mPosOffsetX = x - mInitialPosX;
  1055. mPosOffsetY = y - mInitialPosY;
  1056. // *TODO: make the max border size configurable ? The 25 and 50 fixed
  1057. // values should cover all themes, but who knows ?...
  1058. if (mPosOffsetX < 0 || mPosOffsetY < 0 || mPosOffsetX > 25 ||
  1059. mPosOffsetX > 50)
  1060. {
  1061. // This could happen if the window manager overrides the position of
  1062. // the window or lets the user move it around on creation. In this
  1063. // case, we must report a 0,0 position with getPosition() (since the
  1064. // saved window position would not be used anyway, in such a window
  1065. // manager configuration). HB
  1066. llwarns << "Incoherent window borders offsets found: x = "
  1067. << mPosOffsetX << " - y = " << mPosOffsetY
  1068. << ". Did you move the window on creation ? Window position will always been reported as 0,0."
  1069. << llendl;
  1070. mPosOffsetX = mPosOffsetY = -1; // Flag for "report 0,0"
  1071. }
  1072. else
  1073. {
  1074. llinfos << "Window borders offsets: x = " << mPosOffsetX << " - y = "
  1075. << mPosOffsetY << llendl;
  1076. }
  1077. }
  1078. //virtual
  1079. bool LLWindowSDL::getPosition(LLCoordScreen* position)
  1080. {
  1081. if (position && mWindow)
  1082. {
  1083. // Problem: the window coordinates returned by SDL_GetWindowPosition()
  1084. // are offset by the size of the window borders (but only after the
  1085. // window got fully decorated by the window manager, which happens
  1086. // some time after it is created), while SDL_CreateWindow() needs the
  1087. // absolute coordinates... Since getPosition() is used on viewer exit,
  1088. // wrong coordinates would be stored in saved settings.
  1089. // This is the reason why we need the mPosOffsetX and mPosOffsetY
  1090. // offsets, computing them with calculateBordersOffsets() above just
  1091. // after the window is decorated (i.e. before the user would have a
  1092. // chance to move it manually). HB
  1093. int x, y;
  1094. SDL_GetWindowPosition(mWindow, &x, &y);
  1095. #if 0 // Saddly, this does not work, or at least not with all window managers
  1096. // (I always seen it return top = left = 0)... HB
  1097. int top, left;
  1098. if (SDL_GetWindowBordersSize(mWindow, &top, &left, NULL, NULL) == 0)
  1099. {
  1100. x -= left;
  1101. y -= top;
  1102. }
  1103. #else
  1104. // Report a 0,0 (like with SDL1) position if we do not know what the
  1105. // borders offsets are or if in full screen mode.
  1106. if (mFullscreen || mPosOffsetX < 0)
  1107. {
  1108. position->mX = position->mY = 0;
  1109. }
  1110. else
  1111. {
  1112. position->mX = x - mPosOffsetX;
  1113. position->mY = y - mPosOffsetY;
  1114. }
  1115. #endif
  1116. return true;
  1117. }
  1118. return false;
  1119. }
  1120. //virtual
  1121. bool LLWindowSDL::getSize(LLCoordScreen* size)
  1122. {
  1123. if (mWindow && size)
  1124. {
  1125. SDL_GetWindowSize(mWindow, &size->mX, &size->mY);
  1126. return true;
  1127. }
  1128. return false;
  1129. }
  1130. //virtual
  1131. bool LLWindowSDL::getSize(LLCoordWindow* size)
  1132. {
  1133. if (mWindow && size)
  1134. {
  1135. SDL_GetWindowSize(mWindow, &size->mX, &size->mY);
  1136. return true;
  1137. }
  1138. return false;
  1139. }
  1140. //virtual
  1141. bool LLWindowSDL::setSize(const LLCoordScreen size)
  1142. {
  1143. if (!mWindow)
  1144. {
  1145. return false;
  1146. }
  1147. if (SDL_GetWindowFlags(mWindow) & SDL_WINDOW_MAXIMIZED)
  1148. {
  1149. SDL_RestoreWindow(mWindow);
  1150. }
  1151. SDL_SetWindowSize(mWindow, size.mX, size.mY);
  1152. SDL_Event event;
  1153. event.type = SDL_WINDOWEVENT;
  1154. event.window.event = SDL_WINDOWEVENT_RESIZED;
  1155. event.window.windowID = SDL_GetWindowID(mWindow);
  1156. event.window.data1 = size.mX;
  1157. event.window.data2 = size.mY;
  1158. SDL_PushEvent(&event);
  1159. return true;
  1160. }
  1161. // *HACK: this method causes a proper screen refresh by triggering a full
  1162. // redraw event at the SDL level. HB
  1163. //virtual
  1164. void LLWindowSDL::refresh()
  1165. {
  1166. LLCoordScreen size;
  1167. if (getSize(&size))
  1168. {
  1169. setSize(size);
  1170. }
  1171. }
  1172. //virtual
  1173. void LLWindowSDL::swapBuffers()
  1174. {
  1175. if (mWindow)
  1176. {
  1177. LL_FAST_TIMER(FTM_SWAP);
  1178. SDL_GL_SwapWindow(mWindow);
  1179. }
  1180. }
  1181. //virtual
  1182. bool LLWindowSDL::restoreGamma()
  1183. {
  1184. if (!mCustomGammaSet)
  1185. {
  1186. return true;
  1187. }
  1188. mCustomGammaSet = false;
  1189. return mWindow && SDL_SetWindowGammaRamp(mWindow, mPrevGammaRamp[0],
  1190. mPrevGammaRamp[1],
  1191. mPrevGammaRamp[2]) == 0;
  1192. }
  1193. //virtual
  1194. bool LLWindowSDL::setGamma(F32 gamma)
  1195. {
  1196. LL_DEBUGS("Window") << "Setting gamma to " << gamma << LL_ENDL;
  1197. mCurrentGamma = llclamp(gamma, 0.01f, 10.f);
  1198. if (!mWindow)
  1199. {
  1200. return false;
  1201. }
  1202. // Get the previous gamma ramp to restore later.
  1203. if (!mCustomGammaSet)
  1204. {
  1205. if (SDL_GetWindowGammaRamp(mWindow, mPrevGammaRamp[0],
  1206. mPrevGammaRamp[1], mPrevGammaRamp[2]) != 0)
  1207. {
  1208. llwarns << "Failed to get the previous gamma ramp." << llendl;
  1209. // Use a gamma ramp with default gamma = 1.f
  1210. SDL_CalculateGammaRamp(1.f, mPrevGammaRamp[0]);
  1211. SDL_CalculateGammaRamp(1.f, mPrevGammaRamp[1]);
  1212. SDL_CalculateGammaRamp(1.f, mPrevGammaRamp[2]);
  1213. }
  1214. mCustomGammaSet = true;
  1215. }
  1216. SDL_CalculateGammaRamp(mCurrentGamma, mCurrentGammaRamp);
  1217. return SDL_SetWindowGammaRamp(mWindow, mCurrentGammaRamp,
  1218. mCurrentGammaRamp, mCurrentGammaRamp) == 0;
  1219. }
  1220. // Constrains the mouse to the window.
  1221. //virtual
  1222. void LLWindowSDL::setMouseClipping(bool b)
  1223. {
  1224. #if 0
  1225. SDL_WM_GrabInput(b ? SDL_GRAB_ON : SDL_GRAB_OFF);
  1226. #endif
  1227. }
  1228. //virtual
  1229. bool LLWindowSDL::setCursorPosition(const LLCoordWindow& position)
  1230. {
  1231. LLCoordScreen screen_pos;
  1232. if (!convertCoords(position, &screen_pos))
  1233. {
  1234. return false;
  1235. }
  1236. // Do the actual forced cursor move.
  1237. if (mWindow)
  1238. {
  1239. SDL_WarpMouseInWindow(mWindow, screen_pos.mX, screen_pos.mY);
  1240. }
  1241. return true;
  1242. }
  1243. //virtual
  1244. bool LLWindowSDL::getCursorPosition(LLCoordWindow* position)
  1245. {
  1246. // Point cursor_point
  1247. LLCoordScreen screen_pos;
  1248. int x, y;
  1249. SDL_GetMouseState(&x, &y);
  1250. screen_pos.mX = x;
  1251. screen_pos.mY = y;
  1252. return convertCoords(screen_pos, position);
  1253. }
  1254. //virtual
  1255. F32 LLWindowSDL::getNativeAspectRatio()
  1256. {
  1257. #if 0
  1258. // RN: this hack presumes that the largest supported resolution is
  1259. // monitor-limited and that pixels in that mode are square, therefore
  1260. // defining the native aspect ratio of the monitor... this seems to work to
  1261. // a close approximation for most CRTs/LCDs
  1262. S32 num_resolutions;
  1263. LLWindowResolution* resolutions = getSupportedResolutions(num_resolutions);
  1264. return (F32)resolutions[num_resolutions - 1].mWidth /
  1265. (F32)resolutions[num_resolutions - 1].mHeight;
  1266. #endif
  1267. // MBW: there are a couple of bad assumptions here. One is that the display
  1268. // list would not include ridiculous resolutions nobody would ever use. The
  1269. // other is that the list is in order.
  1270. // New assumptions:
  1271. // - pixels are square (the only reasonable choice, really)
  1272. // - The user runs their display at a native resolution, so the resolution
  1273. // of the display when the app is launched has an aspect ratio that
  1274. // matches the monitor.
  1275. // RN: actually, the assumption that there are no ridiculous resolutions
  1276. // (above the display's native capabilities) has been born out in my
  1277. // experience.
  1278. // Pixels are often not square (just ask the people who run their LCDs at
  1279. // 1024x768 or 800x600 when running fullscreen, like me).
  1280. // The ordering of display list is a blind assumption though, so we should
  1281. // check for max values.
  1282. // Things might be different on the Mac though, so I'll defer to MBW
  1283. // The constructor for this class grabs the aspect ratio of the monitor
  1284. // before doing any resolution switching, and stashes it in
  1285. // mOriginalAspectRatio. Here, we just return it.
  1286. return mOverrideAspectRatio > 0.f ? mOverrideAspectRatio
  1287. : mOriginalAspectRatio;
  1288. }
  1289. //virtual
  1290. F32 LLWindowSDL::getPixelAspectRatio()
  1291. {
  1292. F32 pixel_aspect = 1.f;
  1293. if (getFullscreen())
  1294. {
  1295. LLCoordScreen screen_size;
  1296. if (getSize(&screen_size))
  1297. {
  1298. pixel_aspect = getNativeAspectRatio() * (F32)screen_size.mY /
  1299. (F32)screen_size.mX;
  1300. }
  1301. }
  1302. return pixel_aspect;
  1303. }
  1304. // This is to support 'temporarily windowed' mode so that dialogs are still
  1305. // usable in fullscreen.
  1306. //virtual
  1307. void LLWindowSDL::beforeDialog()
  1308. {
  1309. llinfos << "called" << llendl;
  1310. if (SDLReallyCaptureInput(false)) // Must un-grab input so popup works !
  1311. {
  1312. if (mFullscreen)
  1313. {
  1314. // Need to temporarily go non-fullscreen; bless SDL for providing a
  1315. // SDL_WM_ToggleFullScreen() - though it only works in X11
  1316. if (mSDL_XWindowID != None && mWindow)
  1317. {
  1318. SDL_SetWindowFullscreen(mWindow, 0);
  1319. }
  1320. }
  1321. }
  1322. if (mSDL_Display)
  1323. {
  1324. // Everything that we/SDL asked for should happen before we potentially
  1325. // hand control over to GTK.
  1326. XSync(mSDL_Display, False);
  1327. }
  1328. }
  1329. //virtual
  1330. void LLWindowSDL::afterDialog()
  1331. {
  1332. llinfos << "called." << llendl;
  1333. if (mFullscreen)
  1334. {
  1335. // Need to restore fullscreen mode after dialog; only works in X11
  1336. if (mSDL_XWindowID != None && mWindow)
  1337. {
  1338. SDL_SetWindowFullscreen(mWindow, 0);
  1339. }
  1340. }
  1341. }
  1342. // Sets/reset the XWMHints flag for 'urgency' that usually makes the icon flash
  1343. void LLWindowSDL::x11_set_urgent(bool urgent)
  1344. {
  1345. if (mSDL_Display && !mFullscreen)
  1346. {
  1347. LL_DEBUGS("Window") << "X11 hint for urgency, " << urgent << LL_ENDL;
  1348. XWMHints* wm_hints = XGetWMHints(mSDL_Display, mSDL_XWindowID);
  1349. if (!wm_hints)
  1350. {
  1351. wm_hints = XAllocWMHints();
  1352. }
  1353. if (urgent)
  1354. {
  1355. wm_hints->flags |= XUrgencyHint;
  1356. }
  1357. else
  1358. {
  1359. wm_hints->flags &= ~XUrgencyHint;
  1360. }
  1361. XSetWMHints(mSDL_Display, mSDL_XWindowID, wm_hints);
  1362. XFree(wm_hints);
  1363. XSync(mSDL_Display, False);
  1364. }
  1365. }
  1366. //virtual
  1367. void LLWindowSDL::flashIcon(F32 seconds)
  1368. {
  1369. LL_DEBUGS("Window") << "Flashing icon for " << seconds << " seconds"
  1370. << LL_ENDL;
  1371. F32 remaining_time = mFlashTimer.getRemainingTimeF32();
  1372. if (remaining_time < seconds)
  1373. {
  1374. remaining_time = seconds;
  1375. }
  1376. mFlashTimer.reset();
  1377. mFlashTimer.setTimerExpirySec(remaining_time);
  1378. x11_set_urgent(true);
  1379. mFlashing = true;
  1380. }
  1381. ///////////////////////////////////////////////////////////////////////////////
  1382. // Clipboards (primary and secondary) implementation (c)2015 Henri Beauchamp
  1383. ///////////////////////////////////////////////////////////////////////////////
  1384. static Atom XA_CLIPBOARD;
  1385. static Atom XA_COMPOUND_TEXT;
  1386. static Atom XA_UTF8_STRING;
  1387. static Atom XA_TARGETS;
  1388. static Atom PVT_PASTE_BUFFER;
  1389. // Filters through SDL_Events searching for clipboard requests from the X
  1390. // server. evt is the event to filter.
  1391. static int x11_clipboard_filter(void*, SDL_Event* evt)
  1392. {
  1393. Display* display = LLWindowSDL::getSDLDisplay();
  1394. if (!display) return 1;
  1395. // We are only interested in window manager events
  1396. if (evt->type == SDL_SYSWMEVENT)
  1397. {
  1398. XEvent xevent = evt->syswm.msg->msg.x11.event;
  1399. // See if the event is a selection/clipboard request
  1400. if (xevent.type == SelectionRequest)
  1401. {
  1402. // Get the request in question
  1403. XSelectionRequestEvent* request = &xevent.xselectionrequest;
  1404. if (!request) return 1; // Paranoia
  1405. LL_DEBUGS("Window") << "Caught event type SelectionRequest. Request target: "
  1406. << request->target << " - Selection type: "
  1407. << request->selection << LL_ENDL;
  1408. // Generate a reply to the selection request
  1409. XSelectionEvent reply;
  1410. reply.type = SelectionNotify;
  1411. reply.serial = xevent.xany.serial;
  1412. reply.send_event = xevent.xany.send_event;
  1413. reply.display = display;
  1414. reply.requestor = request->requestor;
  1415. reply.selection = request->selection;
  1416. reply.target = request->target;
  1417. reply.property = request->property;
  1418. reply.time = request->time;
  1419. // They want to know what we can provide/offer
  1420. if (request->target == XA_TARGETS)
  1421. {
  1422. LL_DEBUGS("Window") << "Request is XA_TARGETS" << LL_ENDL;
  1423. Atom possibleTargets[] =
  1424. {
  1425. XA_STRING,
  1426. XA_UTF8_STRING,
  1427. XA_COMPOUND_TEXT
  1428. };
  1429. XChangeProperty(display, request->requestor, request->property,
  1430. XA_ATOM, 32, PropModeReplace,
  1431. (unsigned char*)possibleTargets, 3);
  1432. }
  1433. // They want a string (all we can provide)
  1434. else if (request->target == XA_STRING ||
  1435. request->target == XA_UTF8_STRING ||
  1436. request->target == XA_COMPOUND_TEXT)
  1437. {
  1438. std::string utf8;
  1439. if (request->selection == XA_PRIMARY)
  1440. {
  1441. LL_DEBUGS("Window") << "Primary selection request"
  1442. << LL_ENDL;
  1443. utf8 =
  1444. wstring_to_utf8str(sWindowImplementation->getPrimaryText());
  1445. }
  1446. else
  1447. {
  1448. LL_DEBUGS("Window") << "Clipboard request" << LL_ENDL;
  1449. utf8 =
  1450. wstring_to_utf8str(sWindowImplementation->getSecondaryText());
  1451. }
  1452. XChangeProperty(display, request->requestor, request->property,
  1453. request->target, 8, PropModeReplace,
  1454. (unsigned char*)utf8.c_str(), utf8.length());
  1455. }
  1456. else if (request->selection == XA_CLIPBOARD)
  1457. {
  1458. LL_DEBUGS("Window") << "Unhandled request" << LL_ENDL;
  1459. // Did not have what they wanted, so no property set
  1460. reply.property = None;
  1461. }
  1462. else
  1463. {
  1464. LL_DEBUGS("Window") << "Unknown selection request. Ignoring."
  1465. << LL_ENDL;
  1466. return 1;
  1467. }
  1468. // Dispatch the event
  1469. XSendEvent(request->display, request->requestor, False,
  1470. NoEventMask, (XEvent*)&reply);
  1471. XSync(display, False);
  1472. }
  1473. else if (xevent.type == SelectionClear)
  1474. {
  1475. // Get the request in question
  1476. XSelectionRequestEvent* request = &xevent.xselectionrequest;
  1477. if (!request) return 1; // Paranoia
  1478. // We no longer own the clipboard: clear our stored data.
  1479. if (request->selection == XA_PRIMARY)
  1480. {
  1481. LL_DEBUGS("Window") << "Someone else took the ownership of the primary selection; clearing our primary selection buffer."
  1482. << LL_ENDL;
  1483. sWindowImplementation->clearPrimaryText();
  1484. }
  1485. else if (request->selection == XA_CLIPBOARD)
  1486. {
  1487. LL_DEBUGS("Window") << "Someone else took the ownership of the clipboard; clearing our clipboard buffer."
  1488. << LL_ENDL;
  1489. sWindowImplementation->clearSecondaryText();
  1490. }
  1491. }
  1492. }
  1493. return 1;
  1494. }
  1495. void LLWindowSDL::initialiseX11Clipboard()
  1496. {
  1497. if (mSDL_Display)
  1498. {
  1499. LL_DEBUGS("Window") << "Initializing the X11 clipboard" << LL_ENDL;
  1500. // Register the event filter
  1501. SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE);
  1502. SDL_SetEventFilter(x11_clipboard_filter, NULL);
  1503. // Get the clipboard atom (it is not defined by default)
  1504. XA_CLIPBOARD = XInternAtom(mSDL_Display, "CLIPBOARD", False);
  1505. // Get the compound text type atom
  1506. XA_COMPOUND_TEXT = XInternAtom(mSDL_Display, "COMPOUND_TEXT", False);
  1507. // UTF-8 string atom
  1508. XA_UTF8_STRING = XInternAtom(mSDL_Display, "UTF8_STRING", False);
  1509. // TARGETS atom
  1510. XA_TARGETS = XInternAtom(mSDL_Display, "TARGETS", False);
  1511. // SL_PASTE_BUFFER atom
  1512. PVT_PASTE_BUFFER = XInternAtom(mSDL_Display, "SL_PASTE_BUFFER", False);
  1513. }
  1514. }
  1515. static bool grab_property(Display* display, Window window, Atom selection,
  1516. Atom target)
  1517. {
  1518. XDeleteProperty(display, window, PVT_PASTE_BUFFER);
  1519. XFlush(display);
  1520. XConvertSelection(display, selection, target, PVT_PASTE_BUFFER, window,
  1521. CurrentTime);
  1522. // We now need to wait for a response from the window that owns the
  1523. // clipboard.
  1524. LL_DEBUGS("Window") << "Waiting for the selection owner to provide its text..."
  1525. << LL_ENDL;
  1526. SDL_Event event;
  1527. XEvent xevent;
  1528. Uint32 start = SDL_GetTicks();
  1529. constexpr Uint32 maxticks = 1000; // 1 second
  1530. bool response = false;
  1531. while (!response && SDL_GetTicks() - start < maxticks)
  1532. {
  1533. // Wait for an event
  1534. SDL_WaitEvent(&event);
  1535. // If the event is a window manager event
  1536. if (event.type == SDL_SYSWMEVENT)
  1537. {
  1538. xevent = event.syswm.msg->msg.x11.event;
  1539. // See if it is a response to our request
  1540. if (xevent.type == SelectionNotify &&
  1541. xevent.xselection.requestor == window)
  1542. {
  1543. response = true;
  1544. }
  1545. }
  1546. }
  1547. bool ret = response && xevent.xselection.property != None;
  1548. LL_DEBUGS("Window") << "... " << (ret ? "Succeeded" : "Failed") << " !"
  1549. << LL_ENDL;
  1550. return ret;
  1551. }
  1552. bool LLWindowSDL::getSelectionText(Atom selection, LLWString& text)
  1553. {
  1554. if (!mSDL_Display) return false;
  1555. // Get the owner of the clipboard selection.
  1556. Window owner = XGetSelectionOwner(mSDL_Display, selection);
  1557. if (owner == None)
  1558. {
  1559. // Only the primary selection may be owned by None, in the cut buffer
  1560. // (legacy, xterm way of dealing with selections). Else, it means the
  1561. // selection is empty...
  1562. if (selection != XA_PRIMARY)
  1563. {
  1564. // The clipboard is empty...
  1565. text.clear();
  1566. return false;
  1567. }
  1568. LL_DEBUGS("Window") << "No owner for current selection. Using default root window and XA_CUT_BUFFER0"
  1569. << LL_ENDL;
  1570. owner = DefaultRootWindow(mSDL_Display);
  1571. selection = XA_CUT_BUFFER0;
  1572. }
  1573. // Ask the window that currently owns the clipboard to convert it
  1574. LL_DEBUGS("Window") << "Requesting conversion to XA_UTF8_STRING"
  1575. << LL_ENDL;
  1576. if (!grab_property(mSDL_Display, mSDL_XWindowID, selection,
  1577. XA_UTF8_STRING))
  1578. {
  1579. #if 0 // We do not support ISO 2022 encoding in the viewer, so...
  1580. LL_DEBUGS("Window") << "Requesting conversion to XA_COMPOUND_TEXT"
  1581. << LL_ENDL;
  1582. if (!grab_property(mSDL_Display, mSDL_XWindowID, selection,
  1583. XA_COMPOUND_TEXT))
  1584. #endif
  1585. {
  1586. LL_DEBUGS("Window") << "Requesting conversion to XA_STRING"
  1587. << LL_ENDL;
  1588. if (!grab_property(mSDL_Display, mSDL_XWindowID, selection,
  1589. XA_STRING))
  1590. {
  1591. // The clipboard does not contains any valid text.
  1592. text.clear();
  1593. return false;
  1594. }
  1595. }
  1596. }
  1597. // Recover any paste buffer text (using S32_MAX for max length).
  1598. Atom type;
  1599. int format = 0;
  1600. unsigned long len = 0;
  1601. unsigned long remaining = 0;
  1602. unsigned char* data = NULL;
  1603. int res = XGetWindowProperty(mSDL_Display, mSDL_XWindowID,
  1604. PVT_PASTE_BUFFER, 0, S32_MAX, False,
  1605. AnyPropertyType, &type, &format, &len,
  1606. &remaining, &data);
  1607. if (data && len)
  1608. {
  1609. if (format == 8)
  1610. {
  1611. std::string tmp;
  1612. tmp.assign((const char*)data);
  1613. text = LLWString(utf8str_to_wstring(tmp));
  1614. }
  1615. else
  1616. {
  1617. // This should not happen since we asked above for 8 bits encoding
  1618. // conversions only...
  1619. llwarns << "Unsupported clipboard text format type: "
  1620. << format << " bits characters instead of 8." << llendl;
  1621. len = 0;
  1622. }
  1623. }
  1624. if (!len)
  1625. {
  1626. text.clear();
  1627. }
  1628. // Note: XGetWindowProperty() is documented as always allocating at least
  1629. // one "extra byte", even if the property is zero-length, so we need to
  1630. // free any allocated data, even for len == 0.
  1631. if (data)
  1632. {
  1633. XFree(data);
  1634. }
  1635. return res == Success;
  1636. }
  1637. bool LLWindowSDL::setSelectionText(Atom selection, const LLWString& text)
  1638. {
  1639. std::string utf8 = wstring_to_utf8str(text);
  1640. if (selection == XA_PRIMARY)
  1641. {
  1642. // Copy the text into the root window's cut buffer
  1643. XStoreBytes(mSDL_Display, utf8.c_str(), utf8.length() + 1);
  1644. mPrimaryClipboard = text;
  1645. LL_DEBUGS("Window") << "Setting the primary selection text" << LL_ENDL;
  1646. }
  1647. else
  1648. {
  1649. mSecondaryClipboard = text;
  1650. LL_DEBUGS("Window") << "Setting the clipboard text" << LL_ENDL;
  1651. }
  1652. // Set ourself as the owner of the selection atom
  1653. XSetSelectionOwner(mSDL_Display, selection, mSDL_XWindowID, CurrentTime);
  1654. // Check if we acquired ownership or not
  1655. Window owner = XGetSelectionOwner(mSDL_Display, selection);
  1656. return owner == mSDL_XWindowID;
  1657. }
  1658. //virtual
  1659. bool LLWindowSDL::isClipboardTextAvailable()
  1660. {
  1661. return mSDL_Display &&
  1662. XGetSelectionOwner(mSDL_Display, XA_CLIPBOARD) != None;
  1663. }
  1664. //virtual
  1665. bool LLWindowSDL::pasteTextFromClipboard(LLWString& text)
  1666. {
  1667. return getSelectionText(XA_CLIPBOARD, text);
  1668. }
  1669. //virtual
  1670. bool LLWindowSDL::copyTextToClipboard(const LLWString& text)
  1671. {
  1672. return setSelectionText(XA_CLIPBOARD, text);
  1673. }
  1674. //virtual
  1675. bool LLWindowSDL::isPrimaryTextAvailable()
  1676. {
  1677. if (mSDL_Display)
  1678. {
  1679. LLWString text;
  1680. return getSelectionText(XA_PRIMARY, text);
  1681. }
  1682. return false; // failure
  1683. }
  1684. //virtual
  1685. bool LLWindowSDL::pasteTextFromPrimary(LLWString& text)
  1686. {
  1687. return getSelectionText(XA_PRIMARY, text);
  1688. }
  1689. //virtual
  1690. bool LLWindowSDL::copyTextToPrimary(const LLWString& text)
  1691. {
  1692. return setSelectionText(XA_PRIMARY, text);
  1693. }
  1694. ///////////////////////////////////////////////////////////////////////////////
  1695. //virtual
  1696. LLWindow::LLWindowResolution* LLWindowSDL::getSupportedResolutions(S32& num_resolutions)
  1697. {
  1698. if (!mSupportedResolutions)
  1699. {
  1700. mSupportedResolutions = new LLWindowResolution[MAX_NUM_RESOLUTIONS];
  1701. mNumSupportedResolutions = 0;
  1702. // *TODO: get count from display corresponding to mWindow
  1703. S32 count = llclamp(0, (S32)SDL_GetNumDisplayModes(0),
  1704. MAX_NUM_RESOLUTIONS);
  1705. for (S32 i = 0; i < count; ++i)
  1706. {
  1707. SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
  1708. if (SDL_GetDisplayMode(0 , i, &mode) != 0)
  1709. {
  1710. continue;
  1711. }
  1712. S32 w = mode.w;
  1713. S32 h = mode.h;
  1714. if (w >= 800 && h >= 600)
  1715. {
  1716. // Make sure we do not add the same resolution multiple times !
  1717. bool resolution_exists = false;
  1718. for (S32 i = 0; i < mNumSupportedResolutions; ++i)
  1719. {
  1720. if (mSupportedResolutions[i].mWidth == w &&
  1721. mSupportedResolutions[i].mHeight == h)
  1722. {
  1723. resolution_exists = true;
  1724. break;
  1725. }
  1726. }
  1727. if (!resolution_exists)
  1728. {
  1729. mSupportedResolutions[mNumSupportedResolutions].mWidth = w;
  1730. mSupportedResolutions[mNumSupportedResolutions++].mHeight = h;
  1731. }
  1732. }
  1733. }
  1734. }
  1735. num_resolutions = mNumSupportedResolutions;
  1736. return mSupportedResolutions;
  1737. }
  1738. //virtual
  1739. bool LLWindowSDL::convertCoords(LLCoordGL from, LLCoordWindow* to)
  1740. {
  1741. if (to && mWindow)
  1742. {
  1743. to->mX = from.mX;
  1744. S32 height;
  1745. SDL_GetWindowSize(mWindow, NULL, &height);
  1746. to->mY = height - from.mY - 1;
  1747. return true;
  1748. }
  1749. return false;
  1750. }
  1751. //virtual
  1752. bool LLWindowSDL::convertCoords(LLCoordWindow from, LLCoordGL* to)
  1753. {
  1754. if (to && mWindow)
  1755. {
  1756. to->mX = from.mX;
  1757. S32 height;
  1758. SDL_GetWindowSize(mWindow, NULL, &height);
  1759. to->mY = height - from.mY - 1;
  1760. return true;
  1761. }
  1762. return false;
  1763. }
  1764. //virtual
  1765. bool LLWindowSDL::convertCoords(LLCoordScreen from, LLCoordWindow* to)
  1766. {
  1767. if (to)
  1768. {
  1769. // In the fullscreen case, window and screen coordinates are the same.
  1770. to->mX = from.mX;
  1771. to->mY = from.mY;
  1772. return true;
  1773. }
  1774. return false;
  1775. }
  1776. //virtual
  1777. bool LLWindowSDL::convertCoords(LLCoordWindow from, LLCoordScreen* to)
  1778. {
  1779. if (to)
  1780. {
  1781. // In the fullscreen case, window and screen coordinates are the same.
  1782. to->mX = from.mX;
  1783. to->mY = from.mY;
  1784. return true;
  1785. }
  1786. return false;
  1787. }
  1788. //virtual
  1789. bool LLWindowSDL::convertCoords(LLCoordScreen from, LLCoordGL* to)
  1790. {
  1791. LLCoordWindow wcoord;
  1792. return convertCoords(from, &wcoord) && convertCoords(wcoord, to);
  1793. }
  1794. //virtual
  1795. bool LLWindowSDL::convertCoords(LLCoordGL from, LLCoordScreen* to)
  1796. {
  1797. LLCoordWindow wcoord;
  1798. return convertCoords(from, &wcoord) && convertCoords(wcoord, to);
  1799. }
  1800. void LLWindowSDL::setupFailure(const std::string& text)
  1801. {
  1802. destroyContext();
  1803. OSMessageBox(text);
  1804. }
  1805. bool LLWindowSDL::SDLReallyCaptureInput(bool capture)
  1806. {
  1807. mCaptured = capture;
  1808. bool newgrab = capture;
  1809. // Only bother if we are windowed
  1810. if (!mFullscreen && mSDL_Display)
  1811. {
  1812. // We dirtily mix raw X11 with SDL so that our pointer is not (as
  1813. // often) constrained to the limits of the window while grabbed, which
  1814. // feels nicer and hopefully eliminates some reported 'sticky pointer'
  1815. // problems. We use raw X11 instead of SDL_WM_GrabInput() because the
  1816. // latter constrains the pointer to the window and also steals all
  1817. // *keyboard* input from the window manager, which was frustrating
  1818. // users.
  1819. if (capture)
  1820. {
  1821. newgrab = XGrabPointer(mSDL_Display, mSDL_XWindowID, True, 0,
  1822. GrabModeAsync, GrabModeAsync, None, None,
  1823. CurrentTime) == GrabSuccess;
  1824. }
  1825. else
  1826. {
  1827. XUngrabPointer(mSDL_Display, CurrentTime);
  1828. // Make sure the ungrab happens RIGHT NOW.
  1829. XSync(mSDL_Display, False);
  1830. newgrab = false;
  1831. }
  1832. }
  1833. // Return boolean success for whether we ended up in the desired state
  1834. return capture == newgrab;
  1835. }
  1836. U32 LLWindowSDL::SDLCheckGrabbyKeys(U32 keysym, bool gain)
  1837. {
  1838. // Part of the fix for SL-13243: Some popular window managers like to
  1839. // totally eat alt-drag for the purposes of moving windows. We spoil their
  1840. // day by acquiring the exclusive X11 mouse lock for as long as ALT is held
  1841. // down, so the window manager cannot easily see what is happening. Tested
  1842. // successfully with Metacity. And... do the same with CTRL, for other darn
  1843. // WMs. We do not care about other metakeys as SL does not use them with
  1844. // dragging (for now).
  1845. // We maintain a bitmap of critical keys which are up and down instead of
  1846. // simply key-counting, because SDL sometimes reports misbalanced
  1847. // keyup/keydown event pairs to us for whatever reason.
  1848. U32 mask = 0;
  1849. switch (keysym)
  1850. {
  1851. case SDLK_LALT:
  1852. mask = 1U << 0;
  1853. break;
  1854. case SDLK_RALT:
  1855. mask = 1U << 1;
  1856. break;
  1857. case SDLK_LCTRL:
  1858. mask = 1U << 2;
  1859. break;
  1860. case SDLK_RCTRL:
  1861. mask = 1U << 3;
  1862. break;
  1863. default:
  1864. break;
  1865. }
  1866. if (gain)
  1867. {
  1868. mGrabbyKeyFlags |= mask;
  1869. }
  1870. else
  1871. {
  1872. mGrabbyKeyFlags &= ~mask;
  1873. }
  1874. // 0 means we do not need to mousegrab, otherwise grab.
  1875. return mGrabbyKeyFlags;
  1876. }
  1877. //virtual
  1878. void LLWindowSDL::gatherInput()
  1879. {
  1880. constexpr Uint32 CLICK_THRESHOLD = 300; // milliseconds
  1881. static S32 left_click = 0;
  1882. static S32 right_click = 0;
  1883. static Uint32 last_left_down = 0;
  1884. static Uint32 last_right_down = 0;
  1885. SDL_Event event;
  1886. // Handle all outstanding SDL events
  1887. while (SDL_PollEvent(&event))
  1888. {
  1889. switch (event.type)
  1890. {
  1891. case SDL_MOUSEWHEEL:
  1892. {
  1893. if (event.wheel.y != 0)
  1894. {
  1895. mCallbacks->handleScrollWheel(this, -event.wheel.y);
  1896. }
  1897. break;
  1898. }
  1899. case SDL_MOUSEMOTION:
  1900. {
  1901. LLCoordWindow win_coord(event.button.x, event.button.y);
  1902. LLCoordGL open_gl_coord;
  1903. convertCoords(win_coord, &open_gl_coord);
  1904. MASK mask = gKeyboardp ? gKeyboardp->currentMask(true) : 0;
  1905. mCallbacks->handleMouseMove(this, open_gl_coord, mask);
  1906. break;
  1907. }
  1908. case SDL_TEXTINPUT:
  1909. {
  1910. auto str = utf8str_to_utf16str(event.text.text);
  1911. mKeyVirtualKey = str[0];
  1912. mKeyModifiers = SDL_GetModState();
  1913. MASK mask = gKeyboardp ? gKeyboardp->currentMask(false)
  1914. : 0;
  1915. for (const auto& key : str)
  1916. {
  1917. handleUnicodeUTF16(key, mask);
  1918. }
  1919. break;
  1920. }
  1921. case SDL_KEYDOWN:
  1922. {
  1923. mKeyVirtualKey = event.key.keysym.sym;
  1924. mKeyModifiers = event.key.keysym.mod;
  1925. if (mKeyVirtualKey == SDLK_KP_ENTER)
  1926. {
  1927. mKeyVirtualKey = SDLK_RETURN; // For CEF to get it right
  1928. }
  1929. if (gKeyboardp)
  1930. {
  1931. gKeyboardp->handleKeyDown(mKeyVirtualKey, mKeyModifiers);
  1932. }
  1933. // Because, with SDL2, RETURN (and key pad ENTER, but it was
  1934. // already turned into SDLK_RETURN above) is not part of the
  1935. // text characters sent via the SDL_TEXTINPUT event, in excess
  1936. // of handleKeyDown() we also must invoke handleUnicodeUTF16()
  1937. // with the SDLK_RETURN virtual key, since this is where the
  1938. // viewer code deals with RETURN/ENTER...
  1939. if (mKeyVirtualKey == SDLK_RETURN)
  1940. {
  1941. MASK mask = gKeyboardp ? gKeyboardp->currentMask(false)
  1942. : 0;
  1943. handleUnicodeUTF16(SDLK_RETURN, mask);
  1944. }
  1945. // Part of the fix for SL-13243
  1946. if (SDLCheckGrabbyKeys(event.key.keysym.sym, true) != 0)
  1947. {
  1948. SDLReallyCaptureInput(true);
  1949. }
  1950. break;
  1951. }
  1952. case SDL_KEYUP:
  1953. {
  1954. mKeyVirtualKey = event.key.keysym.sym;
  1955. if (mKeyVirtualKey == SDLK_KP_ENTER)
  1956. {
  1957. mKeyVirtualKey = SDLK_RETURN; // For CEF to get it right
  1958. }
  1959. mKeyModifiers = event.key.keysym.mod;
  1960. // Part of the fix for SL-13243
  1961. if (SDLCheckGrabbyKeys(mKeyVirtualKey, false) == 0)
  1962. {
  1963. SDLReallyCaptureInput(false);
  1964. }
  1965. if (gKeyboardp)
  1966. {
  1967. gKeyboardp->handleKeyUp(mKeyVirtualKey, mKeyModifiers);
  1968. }
  1969. break;
  1970. }
  1971. case SDL_MOUSEBUTTONDOWN:
  1972. {
  1973. bool is_double_click = false;
  1974. LLCoordWindow win_coord(event.button.x, event.button.y);
  1975. LLCoordGL open_gl_coord;
  1976. convertCoords(win_coord, &open_gl_coord);
  1977. MASK mask = gKeyboardp ? gKeyboardp->currentMask(true) : 0;
  1978. if (event.button.button == SDL_BUTTON_LEFT)
  1979. {
  1980. // SDL does not manage double clicking...
  1981. Uint32 now = SDL_GetTicks();
  1982. if (now - last_left_down > CLICK_THRESHOLD)
  1983. {
  1984. left_click = 1;
  1985. }
  1986. else if (++left_click >= 2)
  1987. {
  1988. left_click = 0;
  1989. is_double_click = true;
  1990. }
  1991. last_left_down = now;
  1992. }
  1993. else if (event.button.button == SDL_BUTTON_RIGHT)
  1994. {
  1995. Uint32 now = SDL_GetTicks();
  1996. if (now - last_right_down > CLICK_THRESHOLD)
  1997. {
  1998. right_click = 1;
  1999. }
  2000. else if (++right_click >= 2)
  2001. {
  2002. right_click = 0;
  2003. is_double_click = true;
  2004. }
  2005. last_right_down = now;
  2006. }
  2007. if (event.button.button == SDL_BUTTON_LEFT) // left
  2008. {
  2009. if (is_double_click)
  2010. {
  2011. mCallbacks->handleDoubleClick(this, open_gl_coord,
  2012. mask);
  2013. }
  2014. else
  2015. {
  2016. mCallbacks->handleMouseDown(this, open_gl_coord, mask);
  2017. }
  2018. }
  2019. else if (event.button.button == SDL_BUTTON_RIGHT) // right
  2020. {
  2021. mCallbacks->handleRightMouseDown(this, open_gl_coord, mask);
  2022. }
  2023. else if (event.button.button == SDL_BUTTON_MIDDLE) // middle
  2024. {
  2025. mCallbacks->handleMiddleMouseDown(this, open_gl_coord, mask);
  2026. }
  2027. else if (event.button.button == 4)
  2028. {
  2029. // Mousewheel up...thanks to X11 for making SDL consider
  2030. // these "buttons".
  2031. mCallbacks->handleScrollWheel(this, -1);
  2032. }
  2033. else if (event.button.button == 5)
  2034. {
  2035. // Mousewheel down...thanks to X11 for making SDL consider
  2036. // these "buttons".
  2037. mCallbacks->handleScrollWheel(this, 1);
  2038. }
  2039. break;
  2040. }
  2041. case SDL_MOUSEBUTTONUP:
  2042. {
  2043. LLCoordWindow win_coord(event.button.x, event.button.y);
  2044. LLCoordGL open_gl_coord;
  2045. convertCoords(win_coord, &open_gl_coord);
  2046. MASK mask = gKeyboardp ? gKeyboardp->currentMask(true) : 0;
  2047. if (event.button.button == SDL_BUTTON_LEFT)
  2048. {
  2049. mCallbacks->handleMouseUp(this, open_gl_coord, mask);
  2050. }
  2051. else if (event.button.button == SDL_BUTTON_RIGHT)
  2052. {
  2053. mCallbacks->handleRightMouseUp(this, open_gl_coord, mask);
  2054. }
  2055. else if (event.button.button == SDL_BUTTON_MIDDLE)
  2056. {
  2057. mCallbacks->handleMiddleMouseUp(this, open_gl_coord, mask);
  2058. }
  2059. // Do not handle mousewheel here...
  2060. break;
  2061. }
  2062. case SDL_WINDOWEVENT:
  2063. {
  2064. Uint8 ev = event.window.event;
  2065. if (ev == SDL_WINDOWEVENT_FOCUS_GAINED)
  2066. {
  2067. mCallbacks->handleFocus(this);
  2068. }
  2069. else if (ev == SDL_WINDOWEVENT_FOCUS_LOST)
  2070. {
  2071. mCallbacks->handleFocusLost(this);
  2072. }
  2073. else if (ev == SDL_WINDOWEVENT_RESIZED)
  2074. {
  2075. if (!mWindow)
  2076. {
  2077. // *FIXME: More informative dialog ?
  2078. llinfos << "Could not recreate context after resize ! Quitting..."
  2079. << llendl;
  2080. if (mCallbacks->handleCloseRequest(this))
  2081. {
  2082. // Get the app to initiate cleanup.
  2083. mCallbacks->handleQuit(this);
  2084. // The app is responsible for calling destroyWindow
  2085. // when done with GL
  2086. }
  2087. break;
  2088. }
  2089. S32 width = event.window.data1;
  2090. S32 height = event.window.data2;
  2091. LL_DEBUGS("Window") << "Handling a resize event: " << width
  2092. << "x" << height << LL_ENDL;
  2093. if (gFrameSleepTime > 0)
  2094. {
  2095. // *HACK: clear the window to black to avoid a white
  2096. // flickering when resizing the viewer window while not
  2097. // logged in or when yieding each frame to the OS, due
  2098. // to the volontary throttling of the frame rate with
  2099. // ms_sleep(), and only in this case. Sadly, and unlike
  2100. // SLD1, SDL2 clears the screen to white (instead of
  2101. // black) on resize, so if we do not redraw immediately
  2102. // after a resize event, we get a rather flashy and
  2103. // totally ugly flickering effect. HB
  2104. glClearColor(0.f, 0.f, 0.f, 1.f);
  2105. glClear(GL_COLOR_BUFFER_BIT);
  2106. }
  2107. mCallbacks->handleResize(this, width, height);
  2108. }
  2109. else if (ev == SDL_WINDOWEVENT_RESTORED)
  2110. {
  2111. bool minimized = SDL_GetWindowFlags(mWindow) &
  2112. SDL_WINDOW_MINIMIZED;
  2113. llinfos << "SDL minimized state switched to "
  2114. << !minimized << llendl;
  2115. mCallbacks->handleActivate(this, !minimized);
  2116. }
  2117. else if (ev == SDL_WINDOWEVENT_EXPOSED)
  2118. {
  2119. // Repaint the whole window.
  2120. S32 width = 0;
  2121. S32 height = 0;
  2122. SDL_GetWindowSize(mWindow, &width, &height);
  2123. mCallbacks->handlePaint(this, 0, 0, width, height);
  2124. }
  2125. break;
  2126. }
  2127. case SDL_QUIT:
  2128. {
  2129. if (mCallbacks->handleCloseRequest(this))
  2130. {
  2131. // Get the app to initiate cleanup.
  2132. mCallbacks->handleQuit(this);
  2133. // The app is responsible for calling destroyWindow when
  2134. // done with GL
  2135. }
  2136. break;
  2137. }
  2138. default:
  2139. {
  2140. LL_DEBUGS("Window") << "Unhandled SDL event type "
  2141. << event.type << LL_ENDL;
  2142. }
  2143. }
  2144. }
  2145. // This is a good time to stop flashing the icon if our mFlashTimer has
  2146. // expired.
  2147. if (mFlashing && mFlashTimer.hasExpired())
  2148. {
  2149. x11_set_urgent(false);
  2150. mFlashing = false;
  2151. }
  2152. }
  2153. //virtual
  2154. void LLWindowSDL::setCursor(ECursorType cursor)
  2155. {
  2156. if (mCursorFrozen)
  2157. {
  2158. return;
  2159. }
  2160. if (cursor == UI_CURSOR_ARROW && mBusyCount > 0)
  2161. {
  2162. cursor = UI_CURSOR_WORKING;
  2163. }
  2164. if (mCurrentCursor != cursor)
  2165. {
  2166. if (cursor < UI_CURSOR_COUNT)
  2167. {
  2168. SDL_Cursor* sdlcursor = mSDLCursors[cursor];
  2169. // Try to default to the arrow for any cursors that did not load
  2170. // correctly.
  2171. if (!sdlcursor && mSDLCursors[UI_CURSOR_ARROW])
  2172. {
  2173. sdlcursor = mSDLCursors[UI_CURSOR_ARROW];
  2174. }
  2175. if (sdlcursor)
  2176. {
  2177. SDL_SetCursor(sdlcursor);
  2178. }
  2179. }
  2180. else
  2181. {
  2182. llwarns << "Tried to set invalid cursor number " << cursor
  2183. << llendl;
  2184. }
  2185. mCurrentCursor = cursor;
  2186. }
  2187. }
  2188. static SDL_Cursor* sdl_cursor_from_bmp(const char* fname, int hotx = 0,
  2189. int hoty = 0)
  2190. {
  2191. SDL_Cursor* sdlcursor = NULL;
  2192. // Load cursor pixel data from BMP file
  2193. SDL_Surface* bmpsurface = load_bmp_resource(fname);
  2194. if (bmpsurface && bmpsurface->w % 8 == 0)
  2195. {
  2196. LL_DEBUGS("Window") << "Loaded cursor file " << fname << " "
  2197. << bmpsurface->w << "x" << bmpsurface->h
  2198. << LL_ENDL;
  2199. SDL_Surface* cursurface =
  2200. SDL_CreateRGBSurface(SDL_SWSURFACE, bmpsurface->w, bmpsurface->h,
  2201. 32, SDL_SwapLE32(0xFFU),
  2202. SDL_SwapLE32(0xFF00U),
  2203. SDL_SwapLE32(0xFF0000U),
  2204. SDL_SwapLE32(0xFF000000U));
  2205. SDL_FillRect(cursurface, NULL, SDL_SwapLE32(0x00000000U));
  2206. // Blit the cursor pixel data onto a 32 bits RGBA surface so we
  2207. // only have to cope with processing one type of pixel format.
  2208. if (SDL_BlitSurface(bmpsurface, NULL, cursurface, NULL) == 0)
  2209. {
  2210. // NB: we already checked that width is a multiple of 8.
  2211. const int bitmap_bytes = cursurface->w * cursurface->h / 8;
  2212. unsigned char* cursor_data = new unsigned char[bitmap_bytes];
  2213. unsigned char* cursor_mask = new unsigned char[bitmap_bytes];
  2214. memset(cursor_data, 0, bitmap_bytes);
  2215. memset(cursor_mask, 0, bitmap_bytes);
  2216. // Walk the RGBA cursor pixel data, extracting both data and
  2217. // mask to build SDL-friendly cursor bitmaps from. The mask
  2218. // is inferred by color-keying against 200,200,200
  2219. for (S32 i = 0; i < cursurface->h; ++i)
  2220. {
  2221. for (S32 j = 0; j < cursurface->w; ++j)
  2222. {
  2223. U8* pixelp = ((U8*)cursurface->pixels) +
  2224. cursurface->pitch * i +
  2225. j * cursurface->format->BytesPerPixel;
  2226. U8 srcred = pixelp[0];
  2227. U8 srcgreen = pixelp[1];
  2228. U8 srcblue = pixelp[2];
  2229. bool mask_bit = srcred != 200 || srcgreen != 200 ||
  2230. srcblue != 200;
  2231. bool data_bit = mask_bit && srcgreen <= 80; // not 0x80
  2232. unsigned char bit_offset = cursurface->w / 8 * i + j / 8;
  2233. cursor_data[bit_offset] |= ((U8)data_bit) << (7 - (j & 7));
  2234. cursor_mask[bit_offset] |= ((U8)mask_bit) << (7 - (j & 7));
  2235. }
  2236. }
  2237. sdlcursor = SDL_CreateCursor((Uint8*)cursor_data,
  2238. (Uint8*)cursor_mask,
  2239. cursurface->w, cursurface->h,
  2240. hotx, hoty);
  2241. delete[] cursor_data;
  2242. delete[] cursor_mask;
  2243. }
  2244. else
  2245. {
  2246. llwarns << "Cursor blit failure for: " << fname << llendl;
  2247. }
  2248. SDL_FreeSurface(cursurface);
  2249. SDL_FreeSurface(bmpsurface);
  2250. }
  2251. else
  2252. {
  2253. llwarns << "Cursor load failure for: " << fname << llendl;
  2254. }
  2255. return sdlcursor;
  2256. }
  2257. void LLWindowSDL::initCursors()
  2258. {
  2259. // Blank the cursor pointer array for those we may miss.
  2260. for (S32 i = 0; i < UI_CURSOR_COUNT; ++i)
  2261. {
  2262. mSDLCursors[i] = NULL;
  2263. }
  2264. // Pre-make an SDL cursor for each of the known cursor types. We hardcode
  2265. // the hotspots - to avoid that we would have to write a .cur file loader.
  2266. // NOTE: SDL does not load RLE-compressed BMP files.
  2267. if (getenv("LL_USE_SYSTEM_CURSORS"))
  2268. {
  2269. // Use the user's theme cursors where possible.
  2270. mSDLCursors[UI_CURSOR_ARROW] =
  2271. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
  2272. mSDLCursors[UI_CURSOR_WAIT] =
  2273. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAIT);
  2274. mSDLCursors[UI_CURSOR_HAND] =
  2275. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
  2276. mSDLCursors[UI_CURSOR_IBEAM] =
  2277. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
  2278. mSDLCursors[UI_CURSOR_CROSS] =
  2279. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR);
  2280. mSDLCursors[UI_CURSOR_SIZENWSE] =
  2281. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
  2282. mSDLCursors[UI_CURSOR_SIZENESW] =
  2283. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
  2284. mSDLCursors[UI_CURSOR_SIZEWE] =
  2285. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
  2286. mSDLCursors[UI_CURSOR_SIZENS] =
  2287. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
  2288. mSDLCursors[UI_CURSOR_NO] =
  2289. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
  2290. mSDLCursors[UI_CURSOR_WORKING] =
  2291. SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_WAITARROW);
  2292. }
  2293. else // Use our custom cursors instead.
  2294. {
  2295. mSDLCursors[UI_CURSOR_ARROW] = sdl_cursor_from_bmp("llarrow.bmp");
  2296. mSDLCursors[UI_CURSOR_WAIT] = sdl_cursor_from_bmp("wait.bmp", 12, 15);
  2297. mSDLCursors[UI_CURSOR_HAND] = sdl_cursor_from_bmp("hand.bmp", 7, 10);
  2298. mSDLCursors[UI_CURSOR_IBEAM] = sdl_cursor_from_bmp("ibeam.bmp",
  2299. 15, 16);
  2300. mSDLCursors[UI_CURSOR_CROSS] = sdl_cursor_from_bmp("cross.bmp",
  2301. 16, 14);
  2302. mSDLCursors[UI_CURSOR_SIZENWSE] = sdl_cursor_from_bmp("sizenwse.bmp",
  2303. 14, 17);
  2304. mSDLCursors[UI_CURSOR_SIZENESW] = sdl_cursor_from_bmp("sizenesw.bmp",
  2305. 17, 17);
  2306. mSDLCursors[UI_CURSOR_SIZEWE] = sdl_cursor_from_bmp("sizewe.bmp",
  2307. 16, 14);
  2308. mSDLCursors[UI_CURSOR_SIZENS] = sdl_cursor_from_bmp("sizens.bmp",
  2309. 17, 16);
  2310. mSDLCursors[UI_CURSOR_NO] = sdl_cursor_from_bmp("llno.bmp", 8, 8);
  2311. mSDLCursors[UI_CURSOR_WORKING] = sdl_cursor_from_bmp("working.bmp",
  2312. 12, 15);
  2313. }
  2314. mSDLCursors[UI_CURSOR_TOOLGRAB] = sdl_cursor_from_bmp("lltoolgrab.bmp",
  2315. 2, 13);
  2316. mSDLCursors[UI_CURSOR_TOOLLAND] = sdl_cursor_from_bmp("lltoolland.bmp",
  2317. 1, 6);
  2318. mSDLCursors[UI_CURSOR_TOOLFOCUS] = sdl_cursor_from_bmp("lltoolfocus.bmp",
  2319. 8, 5);
  2320. mSDLCursors[UI_CURSOR_TOOLCREATE] = sdl_cursor_from_bmp("lltoolcreate.bmp",
  2321. 7, 7);
  2322. mSDLCursors[UI_CURSOR_ARROWDRAG] = sdl_cursor_from_bmp("arrowdrag.bmp");
  2323. mSDLCursors[UI_CURSOR_ARROWCOPY] = sdl_cursor_from_bmp("arrowcop.bmp");
  2324. mSDLCursors[UI_CURSOR_ARROWDRAGMULTI] =
  2325. sdl_cursor_from_bmp("llarrowdragmulti.bmp");
  2326. mSDLCursors[UI_CURSOR_ARROWCOPYMULTI] =
  2327. sdl_cursor_from_bmp("arrowcopmulti.bmp", 0, 0);
  2328. mSDLCursors[UI_CURSOR_NOLOCKED] = sdl_cursor_from_bmp("llnolocked.bmp",
  2329. 8, 8);
  2330. mSDLCursors[UI_CURSOR_ARROWLOCKED] =
  2331. sdl_cursor_from_bmp("llarrowlocked.bmp");
  2332. mSDLCursors[UI_CURSOR_GRABLOCKED] = sdl_cursor_from_bmp("llgrablocked.bmp",
  2333. 2, 13);
  2334. mSDLCursors[UI_CURSOR_TOOLTRANSLATE] =
  2335. sdl_cursor_from_bmp("lltooltranslate.bmp");
  2336. mSDLCursors[UI_CURSOR_TOOLROTATE] =
  2337. sdl_cursor_from_bmp("lltoolrotate.bmp");
  2338. mSDLCursors[UI_CURSOR_TOOLSCALE] = sdl_cursor_from_bmp("lltoolscale.bmp");
  2339. mSDLCursors[UI_CURSOR_TOOLCAMERA] = sdl_cursor_from_bmp("lltoolcamera.bmp",
  2340. 7, 5);
  2341. mSDLCursors[UI_CURSOR_TOOLPAN] = sdl_cursor_from_bmp("lltoolpan.bmp",
  2342. 7, 5);
  2343. mSDLCursors[UI_CURSOR_TOOLZOOMIN] = sdl_cursor_from_bmp("lltoolzoomin.bmp",
  2344. 7, 5);
  2345. mSDLCursors[UI_CURSOR_TOOLPICKOBJECT3] =
  2346. sdl_cursor_from_bmp("toolpickobject3.bmp");
  2347. mSDLCursors[UI_CURSOR_TOOLSIT] = sdl_cursor_from_bmp("toolsit.bmp");
  2348. mSDLCursors[UI_CURSOR_TOOLBUY] = sdl_cursor_from_bmp("toolbuy.bmp");
  2349. mSDLCursors[UI_CURSOR_TOOLPAY] = sdl_cursor_from_bmp("toolpay.bmp");
  2350. mSDLCursors[UI_CURSOR_TOOLOPEN] = sdl_cursor_from_bmp("toolopen.bmp");
  2351. mSDLCursors[UI_CURSOR_TOOLPLAY] = sdl_cursor_from_bmp("toolplay.bmp");
  2352. mSDLCursors[UI_CURSOR_TOOLPAUSE] = sdl_cursor_from_bmp("toolpause.bmp");
  2353. mSDLCursors[UI_CURSOR_TOOLMEDIAOPEN] =
  2354. sdl_cursor_from_bmp("toolmediaopen.bmp");
  2355. mSDLCursors[UI_CURSOR_PIPETTE] = sdl_cursor_from_bmp("lltoolpipette.bmp",
  2356. 2, 28);
  2357. mSDLCursors[UI_CURSOR_TOOLPATHFINDING] =
  2358. sdl_cursor_from_bmp("lltoolpathfinding.bmp", 16, 16);
  2359. mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_START] =
  2360. sdl_cursor_from_bmp("lltoolpathfindingpathstart.bmp", 16, 16);
  2361. mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_START_ADD] =
  2362. sdl_cursor_from_bmp("lltoolpathfindingpathstartadd.bmp", 16, 16);
  2363. mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_END] =
  2364. sdl_cursor_from_bmp("lltoolpathfindingpathend.bmp", 16, 16);
  2365. mSDLCursors[UI_CURSOR_TOOLPATHFINDING_PATH_END_ADD] =
  2366. sdl_cursor_from_bmp("lltoolpathfindingpathendadd.bmp", 16, 16);
  2367. mSDLCursors[UI_CURSOR_TOOLNO] = sdl_cursor_from_bmp("llno.bmp", 8, 8);
  2368. }
  2369. void LLWindowSDL::quitCursors()
  2370. {
  2371. if (mWindow)
  2372. {
  2373. for (S32 i = 0; i < UI_CURSOR_COUNT; ++i)
  2374. {
  2375. if (mSDLCursors[i])
  2376. {
  2377. SDL_FreeCursor(mSDLCursors[i]);
  2378. mSDLCursors[i] = NULL;
  2379. }
  2380. }
  2381. }
  2382. else
  2383. {
  2384. // SDL does not refcount cursors, so if the window has already been
  2385. // destroyed then the cursors have gone with it.
  2386. llinfos << "Skipping quitCursors: mWindow already gone." << llendl;
  2387. for (S32 i = 0; i < UI_CURSOR_COUNT; ++i)
  2388. {
  2389. mSDLCursors[i] = NULL;
  2390. }
  2391. }
  2392. }
  2393. //virtual
  2394. void LLWindowSDL::captureMouse()
  2395. {
  2396. // SDL already enforces the semantics that captureMouse is used for, i.e.
  2397. // that we continue to get mouse events as long as a button is down
  2398. // regardless of whether we left the window, and in a less obnoxious way
  2399. // than SDL_WM_GrabInput which would confine the cursor to the window too.
  2400. LL_DEBUGS("Window") << "called" << LL_ENDL;
  2401. }
  2402. //virtual
  2403. void LLWindowSDL::releaseMouse()
  2404. {
  2405. // See comment in LWindowSDL::captureMouse()
  2406. LL_DEBUGS("Window") << "called" << LL_ENDL;
  2407. }
  2408. //virtual
  2409. void LLWindowSDL::hideCursor()
  2410. {
  2411. if (!mCursorHidden)
  2412. {
  2413. mCursorHidden = true;
  2414. mHideCursorPermanent = true;
  2415. SDL_ShowCursor(0);
  2416. }
  2417. }
  2418. //virtual
  2419. void LLWindowSDL::showCursor()
  2420. {
  2421. if (mCursorHidden)
  2422. {
  2423. mCursorHidden = false;
  2424. mHideCursorPermanent = false;
  2425. SDL_ShowCursor(1);
  2426. }
  2427. }
  2428. //virtual
  2429. void LLWindowSDL::showCursorFromMouseMove()
  2430. {
  2431. if (!mHideCursorPermanent)
  2432. {
  2433. showCursor();
  2434. }
  2435. }
  2436. //virtual
  2437. void LLWindowSDL::hideCursorUntilMouseMove()
  2438. {
  2439. if (!mHideCursorPermanent)
  2440. {
  2441. hideCursor();
  2442. mHideCursorPermanent = false;
  2443. }
  2444. }
  2445. // Make the raw keyboard data available - used to poke through to CEF so that
  2446. // the embedded browser has access to the virtual keycodes etc that it needs.
  2447. //virtual
  2448. LLSD LLWindowSDL::getNativeKeyData()
  2449. {
  2450. LLSD result = LLSD::emptyMap();
  2451. result["virtual_key"] = (S32)mKeyVirtualKey;
  2452. // Genuine native SDL modifiers.
  2453. result["sdl_modifiers"] = (S32)mKeyModifiers;
  2454. return result;
  2455. }
  2456. // Open a URL with the user's default web browser.
  2457. // Must begin with protocol identifier.
  2458. //virtual
  2459. void LLWindowSDL::spawnWebBrowser(const std::string& escaped_url, bool async)
  2460. {
  2461. bool found = false;
  2462. for (S32 i = 0; i < gURLProtocolWhitelistCount; ++i)
  2463. {
  2464. if (escaped_url.find(gURLProtocolWhitelist[i]) != std::string::npos)
  2465. {
  2466. found = true;
  2467. break;
  2468. }
  2469. }
  2470. if (!found)
  2471. {
  2472. llwarns << "spawn_web_browser called for url with protocol not on whitelist: "
  2473. << escaped_url << llendl;
  2474. return;
  2475. }
  2476. llinfos << "Spawning browser with URL: " << escaped_url << llendl;
  2477. if (mSDL_Display)
  2478. {
  2479. // Just in case - before forking.
  2480. XSync(mSDL_Display, False);
  2481. }
  2482. std::string cmd = gDirUtil.getAppRODataDir() + "/bin/launch_url.sh";
  2483. std::string arg = escaped_url;
  2484. exec_cmd(cmd, arg);
  2485. llinfos << "Returned from web browser launch." << llendl;
  2486. }
  2487. //virtual
  2488. void* LLWindowSDL::getPlatformWindow()
  2489. {
  2490. return NULL;
  2491. }
  2492. // This method is currently used when we are 'launched' via an SLURL or, with
  2493. // SDL2, before taking snapshots (so that the latter does not get ruined with
  2494. // dirty (unrefreshed) rectangles due to other overlapping windows). HB
  2495. //virtual
  2496. void LLWindowSDL::bringToFront()
  2497. {
  2498. if (mWindow)
  2499. {
  2500. llinfos << "Bringing viewer window to front" << llendl;
  2501. SDL_RaiseWindow(mWindow);
  2502. }
  2503. if (mFullscreen || !mSDL_Display)
  2504. {
  2505. return;
  2506. }
  2507. llinfos << "Bringing viewer window to front" << llendl;
  2508. // We must find the frame window Id used by the window manager, but if we
  2509. // cannot find any WM window frame, use our own window... HB
  2510. Window wm_window = mSDL_XWindowID;
  2511. Window root, parent;
  2512. Window* childlist = NULL;
  2513. unsigned int num_children;
  2514. int res = XQueryTree(mSDL_Display, mSDL_XWindowID, &root, &parent,
  2515. &childlist, &num_children);
  2516. if (res && parent && parent != mSDL_XWindowID)
  2517. {
  2518. wm_window = parent;
  2519. llinfos << "Found WM frame window Id: " << wm_window << llendl;
  2520. }
  2521. if (childlist)
  2522. {
  2523. XFree(childlist);
  2524. }
  2525. // Now raise the frame to the top of the window stack (which will raise all
  2526. // its chidren with it, our own root window included).
  2527. XRaiseWindow(mSDL_Display, wm_window);
  2528. XMapRaised(mSDL_Display, wm_window);
  2529. // This could be needed by some window managers which would ignore the X11
  2530. // request, on the condition they are configured to raise focused windows
  2531. // on top... HB
  2532. XEvent event = { 0 };
  2533. event.xclient.type = ClientMessage;
  2534. event.xclient.serial = 0;
  2535. event.xclient.send_event = True;
  2536. event.xclient.message_type = XInternAtom(mSDL_Display,
  2537. "_NET_ACTIVE_WINDOW", False);
  2538. event.xclient.window = wm_window;
  2539. event.xclient.format = 32;
  2540. XSendEvent(mSDL_Display, DefaultRootWindow(mSDL_Display), False,
  2541. SubstructureRedirectMask | SubstructureNotifyMask, &event);
  2542. XSync(mSDL_Display, False);
  2543. }
  2544. //static
  2545. std::vector<std::string> LLWindowSDL::getDynamicFallbackFontList()
  2546. {
  2547. // Use libfontconfig to find us a nice ordered list of fallback fonts
  2548. // specific to this system.
  2549. std::string final_fallback = "/usr/share/fonts/TTF/dejavu/DejaVuSans.ttf";
  2550. // Fonts are expensive in the current system, do not enumerate too many of
  2551. // them
  2552. constexpr size_t max_font_count_cutoff = 40;
  2553. // Our 'ideal' font properties which define the sorting results.
  2554. // slant=0 means Roman, index=0 means the first face in a font file (the
  2555. // one we actually use), weight=80 means medium weight, spacing=0 means
  2556. // proportional spacing.
  2557. std::string sort_order("slant=0:index=0:weight=80:spacing=0");
  2558. // elide_unicode_coverage removes fonts from the list whose unicode range
  2559. // is covered by fonts earlier in the list. This usually removes ~90% of
  2560. // the fonts as redundant (which is great because the font list can be
  2561. // huge), but might unnecessarily reduce the renderable range if for some
  2562. // reason our FreeType actually fails to use some of the fonts we want it
  2563. // to.
  2564. constexpr bool elide_unicode_coverage = true;
  2565. std::vector<std::string> rtns;
  2566. FcFontSet* fs = NULL;
  2567. FcPattern* sortpat = NULL;
  2568. llinfos << "Getting system font list from FontConfig..." << llendl;
  2569. // If the user has a system-wide language preference, then favor fonts from
  2570. // that language group. This does not affect the types of languages that
  2571. // can be displayed, but ensures that their preferred language is rendered
  2572. // from a single consistent font where possible.
  2573. FL_Locale* locale = NULL;
  2574. FL_Success success = FL_FindLocale(&locale, FL_MESSAGES);
  2575. if (success != 0)
  2576. {
  2577. if (success >= 2 && locale->lang) // confident!
  2578. {
  2579. llinfos << "Language " << locale->lang << llendl;
  2580. llinfos << "Location " << locale->country << llendl;
  2581. llinfos << "Variant " << locale->variant << llendl;
  2582. llinfos << "Preferring fonts of language: " << locale->lang
  2583. << llendl;
  2584. sort_order = "lang=" + std::string(locale->lang) + ":" + sort_order;
  2585. }
  2586. }
  2587. FL_FreeLocale(&locale);
  2588. if (!FcInit())
  2589. {
  2590. llwarns << "FontConfig failed to initialize." << llendl;
  2591. rtns.emplace_back(final_fallback);
  2592. return rtns;
  2593. }
  2594. sortpat = FcNameParse((FcChar8*)sort_order.c_str());
  2595. if (sortpat)
  2596. {
  2597. // Sort the list of system fonts from most-to-least-desirable.
  2598. FcResult result;
  2599. fs = FcFontSort(NULL, sortpat, elide_unicode_coverage, NULL, &result);
  2600. FcPatternDestroy(sortpat);
  2601. }
  2602. int found_font_count = 0;
  2603. if (fs)
  2604. {
  2605. // Get the full pathnames to the fonts, where available, which is what
  2606. // we really want.
  2607. std::string lc_name;
  2608. found_font_count = fs->nfont;
  2609. for (int i = 0; i < fs->nfont; ++i)
  2610. {
  2611. FcChar8* filename;
  2612. if (FcResultMatch == FcPatternGetString(fs->fonts[i], FC_FILE, 0,
  2613. &filename)
  2614. && filename)
  2615. {
  2616. std::string name((const char*)filename);
  2617. lc_name = name;
  2618. LLStringUtil::toLower(lc_name);
  2619. size_t len = lc_name.length();
  2620. if (lc_name.rfind(".pcf") == len - 4 ||
  2621. lc_name.rfind(".pcf.gz") == len - 7)
  2622. {
  2623. // Not a true type font, skip it !
  2624. LL_DEBUGS("Window") << name
  2625. << " is a bitmap font, skipping..."
  2626. << LL_ENDL;
  2627. continue;
  2628. }
  2629. rtns.emplace_back(name);
  2630. if (rtns.size() >= max_font_count_cutoff)
  2631. {
  2632. break; // hit limit
  2633. }
  2634. }
  2635. }
  2636. FcFontSetDestroy(fs);
  2637. }
  2638. LL_DEBUGS("Window") << "Using font list: ";
  2639. for (size_t i = 0, count = rtns.size(); i < count; ++i)
  2640. {
  2641. LL_CONT << " " << rtns[i];
  2642. }
  2643. LL_CONT << LL_ENDL;
  2644. llinfos << "Using " << rtns.size() << "/" << found_font_count
  2645. << " system fonts." << llendl;
  2646. rtns.emplace_back(final_fallback);
  2647. return rtns;
  2648. }
  2649. ///////////////////////////////////////////////////////////////////////////////
  2650. // Splash screen implementation (c)2020-2021 Henri Beauchamp
  2651. ///////////////////////////////////////////////////////////////////////////////
  2652. class HBSplashScreenSDLImpl
  2653. {
  2654. public:
  2655. HBSplashScreenSDLImpl();
  2656. ~HBSplashScreenSDLImpl();
  2657. void show();
  2658. void hide();
  2659. void update(const std::string& msg);
  2660. private:
  2661. Display* mDisplay;
  2662. Window mWindow;
  2663. XColor mShadow;
  2664. GC mGC;
  2665. S32 mScreen;
  2666. S32 mWidth;
  2667. S32 mHeight;
  2668. S32 mTextXOffset;
  2669. S32 mTextYOffset;
  2670. };
  2671. // Default splash screen size. Must be smaller than the splash background that
  2672. // contains an icon on the left: if the splash pixmap can be created, its size
  2673. // will be used instead.
  2674. #define SPLASH_WIDTH 220
  2675. #define SPLASH_HEIGHT 50
  2676. // Offsets for the text in the splash screen
  2677. #define SPLASH_TEXT_X_OFFSET 15
  2678. #define SPLASH_TEXT_Y_OFFSET 28
  2679. HBSplashScreenSDLImpl::HBSplashScreenSDLImpl()
  2680. : mWidth(SPLASH_WIDTH),
  2681. mHeight(SPLASH_HEIGHT),
  2682. mTextXOffset(SPLASH_TEXT_X_OFFSET),
  2683. mTextYOffset(SPLASH_TEXT_Y_OFFSET)
  2684. {
  2685. // Open a connection to the X11 server
  2686. mDisplay = XOpenDisplay(NULL);
  2687. if (!mDisplay)
  2688. {
  2689. llwarns << "Could not open the X11 display !" << llendl;
  2690. return;
  2691. }
  2692. mScreen = DefaultScreen(mDisplay);
  2693. S32 root_window = RootWindow(mDisplay, mScreen);
  2694. // Try to create a pixmap from our splash bitmap file
  2695. Pixmap splash_pixmap = {};
  2696. bool has_spash_pixmap = false;
  2697. while (true)
  2698. {
  2699. SDL_Surface* splash = load_bmp_resource("splash.bmp");
  2700. if (!splash)
  2701. {
  2702. llwarns << "Could not load the splash background." << llendl;
  2703. break;
  2704. }
  2705. Visual* default_visual = DefaultVisual(mDisplay, mScreen);
  2706. S32 width = splash->w;
  2707. S32 height = splash->h;
  2708. SDL_Surface* surf = SDL_CreateRGBSurface(0, width, height, 32,
  2709. default_visual->red_mask,
  2710. default_visual->green_mask,
  2711. default_visual->blue_mask, 0);
  2712. if (!surf)
  2713. {
  2714. llwarns << "Could not create the splash surface." << llendl;
  2715. SDL_FreeSurface(splash);
  2716. break;
  2717. }
  2718. SDL_Rect bounds;
  2719. bounds.x = 0;
  2720. bounds.y = 0;
  2721. bounds.w = width;
  2722. bounds.h = height;
  2723. if (SDL_LowerBlit(splash, &bounds, surf, &bounds) != 0)
  2724. {
  2725. llwarns << "Could not blit the splash surface." << llendl;
  2726. SDL_FreeSurface(splash);
  2727. SDL_FreeSurface(surf);
  2728. break;
  2729. }
  2730. S32 default_depth = DefaultDepth(mDisplay, mScreen);
  2731. XImage* splash_img = XCreateImage(mDisplay, default_visual,
  2732. default_depth, ZPixmap, 0,
  2733. (char*)surf->pixels,
  2734. width, height, 32, 0);
  2735. if (!splash_img)
  2736. {
  2737. llwarns << "Could not create the splash image." << llendl;
  2738. SDL_FreeSurface(splash);
  2739. SDL_FreeSurface(surf);
  2740. break;
  2741. }
  2742. #if LL_BIG_ENDIAN
  2743. splash_img->byte_order = MSBFirst;
  2744. #else
  2745. splash_img->byte_order = LSBFirst;
  2746. #endif
  2747. splash_pixmap = XCreatePixmap(mDisplay, root_window, width, height,
  2748. default_depth);
  2749. XGCValues gc_values;
  2750. GC gc = XCreateGC(mDisplay, splash_pixmap, 0, &gc_values);
  2751. XPutImage(mDisplay, splash_pixmap, gc, splash_img, 0, 0, 0, 0,
  2752. width, height);
  2753. XFreeGC(mDisplay, gc);
  2754. surf->pixels = NULL;
  2755. SDL_FreeSurface(splash);
  2756. SDL_FreeSurface(surf);
  2757. // We have a splash background, adjust the window size and text offsets
  2758. // accordingly.
  2759. has_spash_pixmap = true;
  2760. // Assuming the difference is the icon width on left:
  2761. mTextXOffset += width - mWidth;
  2762. // Half the difference since we want the text vertically centered
  2763. mTextYOffset += (height - mHeight) / 2;
  2764. mWidth = width;
  2765. mHeight = height;
  2766. break;
  2767. }
  2768. // *TODO: use a nice and adequately sized font...
  2769. // Create a custom color map for the grey background.
  2770. Colormap colormap = DefaultColormap(mDisplay, mScreen);
  2771. XColor grey;
  2772. XParseColor(mDisplay, colormap, "#D8D8D8", &grey);
  2773. XAllocColor(mDisplay, colormap, &grey);
  2774. // Create an X11 window
  2775. mWindow = XCreateSimpleWindow(mDisplay, root_window, 0, 0, mWidth, mHeight,
  2776. 0, BlackPixel(mDisplay, mScreen),
  2777. grey.pixel);
  2778. if (!mWindow)
  2779. {
  2780. llwarns << "Could not open an X11 window !" << llendl;
  2781. XCloseDisplay(mDisplay);
  2782. mDisplay = NULL;
  2783. return;
  2784. }
  2785. // Specify the type of window (splash screen).
  2786. // Note: the splash screen should automatically be centered by the window
  2787. // manager, based on the _NET_WM_WINDOW_TYPE_SPLASH property set here. It
  2788. // will also not have any window decoration.
  2789. Atom type = XInternAtom(mDisplay, "_NET_WM_WINDOW_TYPE", False);
  2790. Atom value = XInternAtom(mDisplay, "_NET_WM_WINDOW_TYPE_SPLASH", False);
  2791. XChangeProperty(mDisplay, mWindow, type, XA_ATOM, 32, PropModeReplace,
  2792. reinterpret_cast<unsigned char*>(&value), 1);
  2793. if (has_spash_pixmap)
  2794. {
  2795. XSetWindowBackgroundPixmap(mDisplay, mWindow, splash_pixmap);
  2796. mGC = NULL;
  2797. }
  2798. else
  2799. {
  2800. llwarns << "Could not create the background pixmap. The icon will be missing from the splash."
  2801. << llendl;
  2802. // Create a custom GC for drawing the 3D borders in update()
  2803. unsigned long valuemask = 0;
  2804. XGCValues values;
  2805. mGC = XCreateGC(mDisplay, mWindow, valuemask, &values);
  2806. if (mGC)
  2807. {
  2808. XSetLineAttributes(mDisplay, mGC, 1, LineSolid, CapButt,
  2809. JoinBevel);
  2810. // Color for the shadow line in the 3D borders.
  2811. XParseColor(mDisplay, colormap, "#606060", &mShadow);
  2812. XAllocColor(mDisplay, colormap, &mShadow);
  2813. }
  2814. else
  2815. {
  2816. llwarns << "Could not create a graphics context. The borders will be missing from the splash."
  2817. << llendl;
  2818. }
  2819. }
  2820. // Select the only event we care for (Expose)
  2821. XSelectInput(mDisplay, mWindow, ExposureMask);
  2822. }
  2823. HBSplashScreenSDLImpl::~HBSplashScreenSDLImpl()
  2824. {
  2825. hide();
  2826. }
  2827. void HBSplashScreenSDLImpl::show()
  2828. {
  2829. if (mDisplay)
  2830. {
  2831. XMapWindow(mDisplay, mWindow);
  2832. // Wait for the window to be displayed
  2833. XEvent e;
  2834. while (!XCheckTypedEvent(mDisplay, Expose, &e)) ;
  2835. }
  2836. }
  2837. void HBSplashScreenSDLImpl::hide()
  2838. {
  2839. if (mDisplay)
  2840. {
  2841. if (mGC)
  2842. {
  2843. XFreeGC(mDisplay, mGC);
  2844. }
  2845. XUnmapWindow(mDisplay, mWindow);
  2846. XDestroyWindow(mDisplay, mWindow);
  2847. XFlush(mDisplay);
  2848. XCloseDisplay(mDisplay);
  2849. mDisplay = NULL;
  2850. }
  2851. }
  2852. void HBSplashScreenSDLImpl::update(const std::string& msg)
  2853. {
  2854. if (!mDisplay) return;
  2855. // Clear old contents
  2856. XClearWindow(mDisplay, mWindow);
  2857. // Draw the text itself
  2858. XDrawString(mDisplay, mWindow, DefaultGC(mDisplay, mScreen),
  2859. mTextXOffset, mTextYOffset, msg.c_str(), msg.size());
  2860. // Draw a 3D-like border around the window when we could not create a
  2861. // background from the pixmap...
  2862. if (mGC)
  2863. {
  2864. // First, a black "outer" rectangle (to ensure proper contrast when
  2865. // the window is drawn above a light background).
  2866. XSetForeground(mDisplay, mGC, BlackPixel(mDisplay, mScreen));
  2867. XDrawLine(mDisplay, mWindow, mGC, 0, 0, mWidth - 1, 0);
  2868. XDrawLine(mDisplay, mWindow, mGC, mWidth - 1, 0,
  2869. mWidth - 1, mHeight);
  2870. XDrawLine(mDisplay, mWindow, mGC, mWidth, mHeight - 1,
  2871. 0, mHeight - 1);
  2872. XDrawLine(mDisplay, mWindow, mGC, 0, mHeight, 0, 0);
  2873. // Then, the lower right, "inner" shadow corner
  2874. XSetForeground(mDisplay, mGC, mShadow.pixel);
  2875. XDrawLine(mDisplay, mWindow, mGC, mWidth - 2, 2,
  2876. mWidth - 2, mHeight - 1);
  2877. XDrawLine(mDisplay, mWindow, mGC, mWidth - 2,
  2878. mHeight - 2, 2, mHeight - 2);
  2879. // Finally, the upper left, "inner" lit corner
  2880. XSetForeground(mDisplay, mGC, WhitePixel(mDisplay, mScreen));
  2881. XDrawLine(mDisplay, mWindow, mGC, 1, mHeight - 2, 1, 1);
  2882. XDrawLine(mDisplay, mWindow, mGC, 1, 1, mWidth - 2, 1);
  2883. }
  2884. XFlush(mDisplay);
  2885. //sleep(1); // For debugging, to let some time to read it !
  2886. }
  2887. LLSplashScreenSDL::LLSplashScreenSDL()
  2888. : mImpl(NULL)
  2889. {
  2890. // Since LLSplashScreen is invoked before creating the main window, we must
  2891. // call this here ! HB
  2892. LLWindowSDL::initXlibThreads();
  2893. mImpl = new HBSplashScreenSDLImpl;
  2894. }
  2895. LLSplashScreenSDL::~LLSplashScreenSDL()
  2896. {
  2897. if (mImpl)
  2898. {
  2899. delete mImpl;
  2900. mImpl = NULL;
  2901. }
  2902. }
  2903. void LLSplashScreenSDL::showImpl()
  2904. {
  2905. if (mImpl)
  2906. {
  2907. mImpl->show();
  2908. }
  2909. }
  2910. void LLSplashScreenSDL::updateImpl(const std::string& msg)
  2911. {
  2912. if (mImpl)
  2913. {
  2914. mImpl->update(msg);
  2915. }
  2916. }
  2917. void LLSplashScreenSDL::hideImpl()
  2918. {
  2919. if (mImpl)
  2920. {
  2921. mImpl->hide();
  2922. }
  2923. }
  2924. ///////////////////////////////////////////////////////////////////////////////
  2925. // Message box implementation (c)2015 Henri Beauchamp
  2926. ///////////////////////////////////////////////////////////////////////////////
  2927. S32 OSMessageBoxSDL(const std::string& text, const std::string& caption,
  2928. U32 type)
  2929. {
  2930. #if 0 // Sadly, this does not work ("No message system available" or
  2931. // "msgbox child process failed", depending on SDL2 version), and yes
  2932. // I did also try with the "full" SDL_ShowMessageBox() function, with the
  2933. // same result... HB
  2934. // SDL2 implements a simple message box with just one OK button.
  2935. // This is the only type currently used by the Linux viewer anyway.
  2936. if (type == OSMB_OK)
  2937. {
  2938. std::string lc_caption = caption;
  2939. LLStringUtil::toLower(lc_caption);
  2940. U32 sdl_type;
  2941. if (lc_caption.find("error") != std::string::npos)
  2942. {
  2943. sdl_type = SDL_MESSAGEBOX_ERROR;
  2944. }
  2945. else
  2946. {
  2947. sdl_type = SDL_MESSAGEBOX_INFORMATION;
  2948. }
  2949. S32 ret = SDL_ShowSimpleMessageBox(sdl_type, caption.c_str(),
  2950. text.c_str(), NULL);
  2951. if (ret == 0)
  2952. {
  2953. return OSBTN_OK;
  2954. }
  2955. llwarns << "Error creating SDL dialog: " << SDL_GetError() << llendl;
  2956. // Else, fall-back to the generic message box code below...
  2957. }
  2958. #endif
  2959. setenv("MESSAGE_BOX_CAPTION", caption.c_str(), 1);
  2960. const std::string typestr = llformat("%d", type);
  2961. setenv("MESSAGE_BOX_TYPE", typestr.c_str(), 1);
  2962. std::string cmd = gDirUtil.getAppRODataDir() + "/bin/messagebox.sh";
  2963. S32 ret = exec_cmd(cmd, text);
  2964. if (ret == -1)
  2965. {
  2966. llwarns << "MSGBOX (" << type << "): " << caption << ": " << text
  2967. << llendl;
  2968. }
  2969. return ret;
  2970. }
  2971. #endif // LL_LINUX