Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_linux_Windowing.cpp 123KB

10 years ago
10 years ago
10 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. extern Display* display;
  18. extern XContext windowHandleXContext;
  19. typedef void (*WindowMessageReceiveCallback) (XEvent&);
  20. extern WindowMessageReceiveCallback dispatchWindowMessage;
  21. //==============================================================================
  22. struct Atoms
  23. {
  24. Atoms()
  25. {
  26. Protocols = getIfExists ("WM_PROTOCOLS");
  27. ProtocolList [TAKE_FOCUS] = getIfExists ("WM_TAKE_FOCUS");
  28. ProtocolList [DELETE_WINDOW] = getIfExists ("WM_DELETE_WINDOW");
  29. ProtocolList [PING] = getIfExists ("_NET_WM_PING");
  30. ChangeState = getIfExists ("WM_CHANGE_STATE");
  31. State = getIfExists ("WM_STATE");
  32. UserTime = getCreating ("_NET_WM_USER_TIME");
  33. ActiveWin = getCreating ("_NET_ACTIVE_WINDOW");
  34. Pid = getCreating ("_NET_WM_PID");
  35. WindowType = getIfExists ("_NET_WM_WINDOW_TYPE");
  36. WindowState = getIfExists ("_NET_WM_STATE");
  37. XdndAware = getCreating ("XdndAware");
  38. XdndEnter = getCreating ("XdndEnter");
  39. XdndLeave = getCreating ("XdndLeave");
  40. XdndPosition = getCreating ("XdndPosition");
  41. XdndStatus = getCreating ("XdndStatus");
  42. XdndDrop = getCreating ("XdndDrop");
  43. XdndFinished = getCreating ("XdndFinished");
  44. XdndSelection = getCreating ("XdndSelection");
  45. XdndTypeList = getCreating ("XdndTypeList");
  46. XdndActionList = getCreating ("XdndActionList");
  47. XdndActionCopy = getCreating ("XdndActionCopy");
  48. XdndActionPrivate = getCreating ("XdndActionPrivate");
  49. XdndActionDescription = getCreating ("XdndActionDescription");
  50. allowedMimeTypes[0] = getCreating ("UTF8_STRING");
  51. allowedMimeTypes[1] = getCreating ("text/plain;charset=utf-8");
  52. allowedMimeTypes[2] = getCreating ("text/plain");
  53. allowedMimeTypes[3] = getCreating ("text/uri-list");
  54. externalAllowedFileMimeTypes[0] = getCreating ("text/uri-list");
  55. externalAllowedTextMimeTypes[0] = getCreating ("text/plain");
  56. allowedActions[0] = getCreating ("XdndActionMove");
  57. allowedActions[1] = XdndActionCopy;
  58. allowedActions[2] = getCreating ("XdndActionLink");
  59. allowedActions[3] = getCreating ("XdndActionAsk");
  60. allowedActions[4] = XdndActionPrivate;
  61. }
  62. static const Atoms& get()
  63. {
  64. static Atoms atoms;
  65. return atoms;
  66. }
  67. enum ProtocolItems
  68. {
  69. TAKE_FOCUS = 0,
  70. DELETE_WINDOW = 1,
  71. PING = 2
  72. };
  73. Atom Protocols, ProtocolList[3], ChangeState, State, UserTime,
  74. ActiveWin, Pid, WindowType, WindowState,
  75. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  76. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  77. XdndActionDescription, XdndActionCopy, XdndActionPrivate,
  78. allowedActions[5],
  79. allowedMimeTypes[4],
  80. externalAllowedFileMimeTypes[1],
  81. externalAllowedTextMimeTypes[1];
  82. static const unsigned long DndVersion;
  83. static Atom getIfExists (const char* name) { return XInternAtom (display, name, True); }
  84. static Atom getCreating (const char* name) { return XInternAtom (display, name, False); }
  85. static String getName (const Atom atom)
  86. {
  87. if (atom == None)
  88. return "None";
  89. return String (XGetAtomName (display, atom));
  90. }
  91. static bool isMimeTypeFile (const Atom atom) { return getName (atom).equalsIgnoreCase ("text/uri-list"); }
  92. };
  93. const unsigned long Atoms::DndVersion = 3;
  94. //==============================================================================
  95. struct GetXProperty
  96. {
  97. GetXProperty (Window window, Atom atom, long offset, long length, bool shouldDelete, Atom requestedType)
  98. : data (nullptr)
  99. {
  100. success = (XGetWindowProperty (display, window, atom, offset, length,
  101. (Bool) shouldDelete, requestedType, &actualType,
  102. &actualFormat, &numItems, &bytesLeft, &data) == Success)
  103. && data != nullptr;
  104. }
  105. ~GetXProperty()
  106. {
  107. if (data != nullptr)
  108. XFree (data);
  109. }
  110. bool success;
  111. unsigned char* data;
  112. unsigned long numItems, bytesLeft;
  113. Atom actualType;
  114. int actualFormat;
  115. };
  116. //==============================================================================
  117. namespace Keys
  118. {
  119. enum MouseButtons
  120. {
  121. NoButton = 0,
  122. LeftButton = 1,
  123. MiddleButton = 2,
  124. RightButton = 3,
  125. WheelUp = 4,
  126. WheelDown = 5
  127. };
  128. static int AltMask = 0;
  129. static int NumLockMask = 0;
  130. static bool numLock = false;
  131. static bool capsLock = false;
  132. static char keyStates [32];
  133. static const int extendedKeyModifier = 0x10000000;
  134. }
  135. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  136. {
  137. int keysym;
  138. if (keyCode & Keys::extendedKeyModifier)
  139. {
  140. keysym = 0xff00 | (keyCode & 0xff);
  141. }
  142. else
  143. {
  144. keysym = keyCode;
  145. if (keysym == (XK_Tab & 0xff)
  146. || keysym == (XK_Return & 0xff)
  147. || keysym == (XK_Escape & 0xff)
  148. || keysym == (XK_BackSpace & 0xff))
  149. {
  150. keysym |= 0xff00;
  151. }
  152. }
  153. ScopedXLock xlock;
  154. const int keycode = XKeysymToKeycode (display, keysym);
  155. const int keybyte = keycode >> 3;
  156. const int keybit = (1 << (keycode & 7));
  157. return (Keys::keyStates [keybyte] & keybit) != 0;
  158. }
  159. //==============================================================================
  160. #if JUCE_USE_XSHM
  161. namespace XSHMHelpers
  162. {
  163. static int trappedErrorCode = 0;
  164. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  165. {
  166. trappedErrorCode = err->error_code;
  167. return 0;
  168. }
  169. static bool isShmAvailable() noexcept
  170. {
  171. static bool isChecked = false;
  172. static bool isAvailable = false;
  173. if (! isChecked)
  174. {
  175. isChecked = true;
  176. int major, minor;
  177. Bool pixmaps;
  178. ScopedXLock xlock;
  179. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  180. {
  181. trappedErrorCode = 0;
  182. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  183. XShmSegmentInfo segmentInfo;
  184. zerostruct (segmentInfo);
  185. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  186. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  187. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  188. xImage->bytes_per_line * xImage->height,
  189. IPC_CREAT | 0777)) >= 0)
  190. {
  191. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  192. if (segmentInfo.shmaddr != (void*) -1)
  193. {
  194. segmentInfo.readOnly = False;
  195. xImage->data = segmentInfo.shmaddr;
  196. XSync (display, False);
  197. if (XShmAttach (display, &segmentInfo) != 0)
  198. {
  199. XSync (display, False);
  200. XShmDetach (display, &segmentInfo);
  201. isAvailable = true;
  202. }
  203. }
  204. XFlush (display);
  205. XDestroyImage (xImage);
  206. shmdt (segmentInfo.shmaddr);
  207. }
  208. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  209. XSetErrorHandler (oldHandler);
  210. if (trappedErrorCode != 0)
  211. isAvailable = false;
  212. }
  213. }
  214. return isAvailable;
  215. }
  216. }
  217. #endif
  218. //==============================================================================
  219. #if JUCE_USE_XRENDER
  220. namespace XRender
  221. {
  222. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  223. typedef XRenderPictFormat* (*tXRenderFindStandardFormat) (Display*, int);
  224. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  225. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  226. static tXRenderQueryVersion xRenderQueryVersion = nullptr;
  227. static tXRenderFindStandardFormat xRenderFindStandardFormat = nullptr;
  228. static tXRenderFindFormat xRenderFindFormat = nullptr;
  229. static tXRenderFindVisualFormat xRenderFindVisualFormat = nullptr;
  230. static bool isAvailable()
  231. {
  232. static bool hasLoaded = false;
  233. if (! hasLoaded)
  234. {
  235. ScopedXLock xlock;
  236. hasLoaded = true;
  237. if (void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW))
  238. {
  239. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  240. xRenderFindStandardFormat = (tXRenderFindStandardFormat) dlsym (h, "XRenderFindStandardFormat");
  241. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  242. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  243. }
  244. if (xRenderQueryVersion != nullptr
  245. && xRenderFindStandardFormat != nullptr
  246. && xRenderFindFormat != nullptr
  247. && xRenderFindVisualFormat != nullptr)
  248. {
  249. int major, minor;
  250. if (xRenderQueryVersion (display, &major, &minor))
  251. return true;
  252. }
  253. xRenderQueryVersion = nullptr;
  254. }
  255. return xRenderQueryVersion != nullptr;
  256. }
  257. static XRenderPictFormat* findPictureFormat()
  258. {
  259. ScopedXLock xlock;
  260. XRenderPictFormat* pictFormat = nullptr;
  261. if (isAvailable())
  262. {
  263. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  264. if (pictFormat == nullptr)
  265. {
  266. XRenderPictFormat desiredFormat;
  267. desiredFormat.type = PictTypeDirect;
  268. desiredFormat.depth = 32;
  269. desiredFormat.direct.alphaMask = 0xff;
  270. desiredFormat.direct.redMask = 0xff;
  271. desiredFormat.direct.greenMask = 0xff;
  272. desiredFormat.direct.blueMask = 0xff;
  273. desiredFormat.direct.alpha = 24;
  274. desiredFormat.direct.red = 16;
  275. desiredFormat.direct.green = 8;
  276. desiredFormat.direct.blue = 0;
  277. pictFormat = xRenderFindFormat (display,
  278. PictFormatType | PictFormatDepth
  279. | PictFormatRedMask | PictFormatRed
  280. | PictFormatGreenMask | PictFormatGreen
  281. | PictFormatBlueMask | PictFormatBlue
  282. | PictFormatAlphaMask | PictFormatAlpha,
  283. &desiredFormat,
  284. 0);
  285. }
  286. }
  287. return pictFormat;
  288. }
  289. }
  290. #endif
  291. //==============================================================================
  292. namespace Visuals
  293. {
  294. static Visual* findVisualWithDepth (const int desiredDepth) noexcept
  295. {
  296. ScopedXLock xlock;
  297. Visual* visual = nullptr;
  298. int numVisuals = 0;
  299. long desiredMask = VisualNoMask;
  300. XVisualInfo desiredVisual;
  301. desiredVisual.screen = DefaultScreen (display);
  302. desiredVisual.depth = desiredDepth;
  303. desiredMask = VisualScreenMask | VisualDepthMask;
  304. if (desiredDepth == 32)
  305. {
  306. desiredVisual.c_class = TrueColor;
  307. desiredVisual.red_mask = 0x00FF0000;
  308. desiredVisual.green_mask = 0x0000FF00;
  309. desiredVisual.blue_mask = 0x000000FF;
  310. desiredVisual.bits_per_rgb = 8;
  311. desiredMask |= VisualClassMask;
  312. desiredMask |= VisualRedMaskMask;
  313. desiredMask |= VisualGreenMaskMask;
  314. desiredMask |= VisualBlueMaskMask;
  315. desiredMask |= VisualBitsPerRGBMask;
  316. }
  317. XVisualInfo* xvinfos = XGetVisualInfo (display,
  318. desiredMask,
  319. &desiredVisual,
  320. &numVisuals);
  321. if (xvinfos != nullptr)
  322. {
  323. for (int i = 0; i < numVisuals; i++)
  324. {
  325. if (xvinfos[i].depth == desiredDepth)
  326. {
  327. visual = xvinfos[i].visual;
  328. break;
  329. }
  330. }
  331. XFree (xvinfos);
  332. }
  333. return visual;
  334. }
  335. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) noexcept
  336. {
  337. Visual* visual = nullptr;
  338. if (desiredDepth == 32)
  339. {
  340. #if JUCE_USE_XSHM
  341. if (XSHMHelpers::isShmAvailable())
  342. {
  343. #if JUCE_USE_XRENDER
  344. if (XRender::isAvailable())
  345. {
  346. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  347. if (pictFormat != 0)
  348. {
  349. int numVisuals = 0;
  350. XVisualInfo desiredVisual;
  351. desiredVisual.screen = DefaultScreen (display);
  352. desiredVisual.depth = 32;
  353. desiredVisual.bits_per_rgb = 8;
  354. XVisualInfo* xvinfos = XGetVisualInfo (display,
  355. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  356. &desiredVisual, &numVisuals);
  357. if (xvinfos != nullptr)
  358. {
  359. for (int i = 0; i < numVisuals; ++i)
  360. {
  361. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  362. if (pictVisualFormat != nullptr
  363. && pictVisualFormat->type == PictTypeDirect
  364. && pictVisualFormat->direct.alphaMask)
  365. {
  366. visual = xvinfos[i].visual;
  367. matchedDepth = 32;
  368. break;
  369. }
  370. }
  371. XFree (xvinfos);
  372. }
  373. }
  374. }
  375. #endif
  376. if (visual == nullptr)
  377. {
  378. visual = findVisualWithDepth (32);
  379. if (visual != nullptr)
  380. matchedDepth = 32;
  381. }
  382. }
  383. #endif
  384. }
  385. if (visual == nullptr && desiredDepth >= 24)
  386. {
  387. visual = findVisualWithDepth (24);
  388. if (visual != nullptr)
  389. matchedDepth = 24;
  390. }
  391. if (visual == nullptr && desiredDepth >= 16)
  392. {
  393. visual = findVisualWithDepth (16);
  394. if (visual != nullptr)
  395. matchedDepth = 16;
  396. }
  397. return visual;
  398. }
  399. }
  400. //==============================================================================
  401. class XBitmapImage : public ImagePixelData
  402. {
  403. public:
  404. XBitmapImage (const Image::PixelFormat format, const int w, const int h,
  405. const bool clearImage, const int imageDepth_, Visual* visual)
  406. : ImagePixelData (format, w, h),
  407. imageDepth (imageDepth_),
  408. gc (None)
  409. {
  410. jassert (format == Image::RGB || format == Image::ARGB);
  411. pixelStride = (format == Image::RGB) ? 3 : 4;
  412. lineStride = ((w * pixelStride + 3) & ~3);
  413. ScopedXLock xlock;
  414. #if JUCE_USE_XSHM
  415. usingXShm = false;
  416. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  417. {
  418. zerostruct (segmentInfo);
  419. segmentInfo.shmid = -1;
  420. segmentInfo.shmaddr = (char *) -1;
  421. segmentInfo.readOnly = False;
  422. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  423. if (xImage != nullptr)
  424. {
  425. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  426. xImage->bytes_per_line * xImage->height,
  427. IPC_CREAT | 0777)) >= 0)
  428. {
  429. if (segmentInfo.shmid != -1)
  430. {
  431. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  432. if (segmentInfo.shmaddr != (void*) -1)
  433. {
  434. segmentInfo.readOnly = False;
  435. xImage->data = segmentInfo.shmaddr;
  436. imageData = (uint8*) segmentInfo.shmaddr;
  437. if (XShmAttach (display, &segmentInfo) != 0)
  438. usingXShm = true;
  439. else
  440. jassertfalse;
  441. }
  442. else
  443. {
  444. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  445. }
  446. }
  447. }
  448. }
  449. }
  450. if (! usingXShm)
  451. #endif
  452. {
  453. imageDataAllocated.allocate (lineStride * h, format == Image::ARGB && clearImage);
  454. imageData = imageDataAllocated;
  455. xImage = (XImage*) ::calloc (1, sizeof (XImage));
  456. xImage->width = w;
  457. xImage->height = h;
  458. xImage->xoffset = 0;
  459. xImage->format = ZPixmap;
  460. xImage->data = (char*) imageData;
  461. xImage->byte_order = ImageByteOrder (display);
  462. xImage->bitmap_unit = BitmapUnit (display);
  463. xImage->bitmap_bit_order = BitmapBitOrder (display);
  464. xImage->bitmap_pad = 32;
  465. xImage->depth = pixelStride * 8;
  466. xImage->bytes_per_line = lineStride;
  467. xImage->bits_per_pixel = pixelStride * 8;
  468. xImage->red_mask = 0x00FF0000;
  469. xImage->green_mask = 0x0000FF00;
  470. xImage->blue_mask = 0x000000FF;
  471. if (imageDepth == 16)
  472. {
  473. const int pixelStride = 2;
  474. const int lineStride = ((w * pixelStride + 3) & ~3);
  475. imageData16Bit.malloc (lineStride * h);
  476. xImage->data = imageData16Bit;
  477. xImage->bitmap_pad = 16;
  478. xImage->depth = pixelStride * 8;
  479. xImage->bytes_per_line = lineStride;
  480. xImage->bits_per_pixel = pixelStride * 8;
  481. xImage->red_mask = visual->red_mask;
  482. xImage->green_mask = visual->green_mask;
  483. xImage->blue_mask = visual->blue_mask;
  484. }
  485. if (! XInitImage (xImage))
  486. jassertfalse;
  487. }
  488. }
  489. ~XBitmapImage()
  490. {
  491. ScopedXLock xlock;
  492. if (gc != None)
  493. XFreeGC (display, gc);
  494. #if JUCE_USE_XSHM
  495. if (usingXShm)
  496. {
  497. XShmDetach (display, &segmentInfo);
  498. XFlush (display);
  499. XDestroyImage (xImage);
  500. shmdt (segmentInfo.shmaddr);
  501. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  502. }
  503. else
  504. #endif
  505. {
  506. xImage->data = nullptr;
  507. XDestroyImage (xImage);
  508. }
  509. }
  510. LowLevelGraphicsContext* createLowLevelContext() override
  511. {
  512. sendDataChangeMessage();
  513. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  514. }
  515. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  516. {
  517. bitmap.data = imageData + x * pixelStride + y * lineStride;
  518. bitmap.pixelFormat = pixelFormat;
  519. bitmap.lineStride = lineStride;
  520. bitmap.pixelStride = pixelStride;
  521. if (mode != Image::BitmapData::readOnly)
  522. sendDataChangeMessage();
  523. }
  524. ImagePixelData* clone() override
  525. {
  526. jassertfalse;
  527. return nullptr;
  528. }
  529. ImageType* createType() const override { return new NativeImageType(); }
  530. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  531. {
  532. ScopedXLock xlock;
  533. if (gc == None)
  534. {
  535. XGCValues gcvalues;
  536. gcvalues.foreground = None;
  537. gcvalues.background = None;
  538. gcvalues.function = GXcopy;
  539. gcvalues.plane_mask = AllPlanes;
  540. gcvalues.clip_mask = None;
  541. gcvalues.graphics_exposures = False;
  542. gc = XCreateGC (display, window,
  543. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  544. &gcvalues);
  545. }
  546. if (imageDepth == 16)
  547. {
  548. const uint32 rMask = xImage->red_mask;
  549. const uint32 gMask = xImage->green_mask;
  550. const uint32 bMask = xImage->blue_mask;
  551. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  552. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  553. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  554. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  555. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  556. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  557. const Image::BitmapData srcData (Image (this), Image::BitmapData::readOnly);
  558. for (int y = sy; y < sy + dh; ++y)
  559. {
  560. const uint8* p = srcData.getPixelPointer (sx, y);
  561. for (int x = sx; x < sx + dw; ++x)
  562. {
  563. const PixelRGB* const pixel = (const PixelRGB*) p;
  564. p += srcData.pixelStride;
  565. XPutPixel (xImage, x, y,
  566. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  567. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  568. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  569. }
  570. }
  571. }
  572. // blit results to screen.
  573. #if JUCE_USE_XSHM
  574. if (usingXShm)
  575. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  576. else
  577. #endif
  578. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  579. }
  580. private:
  581. //==============================================================================
  582. XImage* xImage;
  583. const int imageDepth;
  584. HeapBlock <uint8> imageDataAllocated;
  585. HeapBlock <char> imageData16Bit;
  586. int pixelStride, lineStride;
  587. uint8* imageData;
  588. GC gc;
  589. #if JUCE_USE_XSHM
  590. XShmSegmentInfo segmentInfo;
  591. bool usingXShm;
  592. #endif
  593. static int getShiftNeeded (const uint32 mask) noexcept
  594. {
  595. for (int i = 32; --i >= 0;)
  596. if (((mask >> i) & 1) != 0)
  597. return i - 7;
  598. jassertfalse;
  599. return 0;
  600. }
  601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage)
  602. };
  603. //==============================================================================
  604. namespace PixmapHelpers
  605. {
  606. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  607. {
  608. ScopedXLock xlock;
  609. const int width = image.getWidth();
  610. const int height = image.getHeight();
  611. HeapBlock <uint32> colour (width * height);
  612. int index = 0;
  613. for (int y = 0; y < height; ++y)
  614. for (int x = 0; x < width; ++x)
  615. colour[index++] = image.getPixelAt (x, y).getARGB();
  616. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  617. 0, reinterpret_cast<char*> (colour.getData()),
  618. width, height, 32, 0);
  619. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  620. width, height, 24);
  621. GC gc = XCreateGC (display, pixmap, 0, 0);
  622. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  623. XFreeGC (display, gc);
  624. return pixmap;
  625. }
  626. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  627. {
  628. ScopedXLock xlock;
  629. const int width = image.getWidth();
  630. const int height = image.getHeight();
  631. const int stride = (width + 7) >> 3;
  632. HeapBlock <char> mask;
  633. mask.calloc (stride * height);
  634. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  635. for (int y = 0; y < height; ++y)
  636. {
  637. for (int x = 0; x < width; ++x)
  638. {
  639. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  640. const int offset = y * stride + (x >> 3);
  641. if (image.getPixelAt (x, y).getAlpha() >= 128)
  642. mask[offset] |= bit;
  643. }
  644. }
  645. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  646. mask.getData(), width, height, 1, 0, 1);
  647. }
  648. }
  649. static void* createDraggingHandCursor()
  650. {
  651. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  652. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0, 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  653. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217, 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  654. const int dragHandDataSize = 99;
  655. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7).create();
  656. }
  657. //==============================================================================
  658. static int numAlwaysOnTopPeers = 0;
  659. bool juce_areThereAnyAlwaysOnTopWindows()
  660. {
  661. return numAlwaysOnTopPeers > 0;
  662. }
  663. //==============================================================================
  664. class LinuxComponentPeer : public ComponentPeer
  665. {
  666. public:
  667. LinuxComponentPeer (Component& comp, const int windowStyleFlags, Window parentToAddTo)
  668. : ComponentPeer (comp, windowStyleFlags),
  669. windowH (0), parentWindow (0),
  670. fullScreen (false), mapped (false),
  671. visual (nullptr), depth (0),
  672. isAlwaysOnTop (comp.isAlwaysOnTop())
  673. {
  674. // it's dangerous to create a window on a thread other than the message thread..
  675. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  676. dispatchWindowMessage = windowMessageReceive;
  677. repainter = new LinuxRepaintManager (*this);
  678. if (isAlwaysOnTop)
  679. ++numAlwaysOnTopPeers;
  680. createWindow (parentToAddTo);
  681. setTitle (component.getName());
  682. }
  683. ~LinuxComponentPeer()
  684. {
  685. // it's dangerous to delete a window on a thread other than the message thread..
  686. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  687. deleteIconPixmaps();
  688. destroyWindow();
  689. windowH = 0;
  690. if (isAlwaysOnTop)
  691. --numAlwaysOnTopPeers;
  692. }
  693. // (this callback is hooked up in the messaging code)
  694. static void windowMessageReceive (XEvent& event)
  695. {
  696. if (event.xany.window != None)
  697. {
  698. if (LinuxComponentPeer* const peer = getPeerFor (event.xany.window))
  699. peer->handleWindowMessage (event);
  700. }
  701. else if (event.xany.type == KeymapNotify)
  702. {
  703. const XKeymapEvent& keymapEvent = (const XKeymapEvent&) event.xkeymap;
  704. memcpy (Keys::keyStates, keymapEvent.key_vector, 32);
  705. }
  706. }
  707. //==============================================================================
  708. void* getNativeHandle() const override
  709. {
  710. return (void*) windowH;
  711. }
  712. static LinuxComponentPeer* getPeerFor (Window windowHandle) noexcept
  713. {
  714. XPointer peer = nullptr;
  715. ScopedXLock xlock;
  716. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  717. if (peer != nullptr && ! ComponentPeer::isValidPeer (reinterpret_cast <LinuxComponentPeer*> (peer)))
  718. peer = nullptr;
  719. return reinterpret_cast <LinuxComponentPeer*> (peer);
  720. }
  721. void setVisible (bool shouldBeVisible) override
  722. {
  723. ScopedXLock xlock;
  724. if (shouldBeVisible)
  725. XMapWindow (display, windowH);
  726. else
  727. XUnmapWindow (display, windowH);
  728. }
  729. void setTitle (const String& title) override
  730. {
  731. XTextProperty nameProperty;
  732. char* strings[] = { const_cast <char*> (title.toRawUTF8()) };
  733. ScopedXLock xlock;
  734. if (XStringListToTextProperty (strings, 1, &nameProperty))
  735. {
  736. XSetWMName (display, windowH, &nameProperty);
  737. XSetWMIconName (display, windowH, &nameProperty);
  738. XFree (nameProperty.value);
  739. }
  740. }
  741. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  742. {
  743. if (fullScreen && ! isNowFullScreen)
  744. {
  745. // When transitioning back from fullscreen, we might need to remove
  746. // the FULLSCREEN window property
  747. Atom fs = Atoms::getIfExists ("_NET_WM_STATE_FULLSCREEN");
  748. if (fs != None)
  749. {
  750. Window root = RootWindow (display, DefaultScreen (display));
  751. XClientMessageEvent clientMsg;
  752. clientMsg.display = display;
  753. clientMsg.window = windowH;
  754. clientMsg.type = ClientMessage;
  755. clientMsg.format = 32;
  756. clientMsg.message_type = Atoms::get().WindowState;
  757. clientMsg.data.l[0] = 0; // Remove
  758. clientMsg.data.l[1] = fs;
  759. clientMsg.data.l[2] = 0;
  760. clientMsg.data.l[3] = 1; // Normal Source
  761. ScopedXLock xlock;
  762. XSendEvent (display, root, false,
  763. SubstructureRedirectMask | SubstructureNotifyMask,
  764. (XEvent*) &clientMsg);
  765. }
  766. }
  767. fullScreen = isNowFullScreen;
  768. if (windowH != 0)
  769. {
  770. bounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
  771. jmax (1, newBounds.getHeight()));
  772. WeakReference<Component> deletionChecker (&component);
  773. ScopedXLock xlock;
  774. XSizeHints* const hints = XAllocSizeHints();
  775. hints->flags = USSize | USPosition;
  776. hints->x = bounds.getX();
  777. hints->y = bounds.getY();
  778. hints->width = bounds.getWidth();
  779. hints->height = bounds.getHeight();
  780. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  781. {
  782. hints->min_width = hints->max_width = hints->width;
  783. hints->min_height = hints->max_height = hints->height;
  784. hints->flags |= PMinSize | PMaxSize;
  785. }
  786. XSetWMNormalHints (display, windowH, hints);
  787. XFree (hints);
  788. XMoveResizeWindow (display, windowH,
  789. bounds.getX() - windowBorder.getLeft(),
  790. bounds.getY() - windowBorder.getTop(),
  791. bounds.getWidth(),
  792. bounds.getHeight());
  793. if (deletionChecker != nullptr)
  794. {
  795. updateBorderSize();
  796. handleMovedOrResized();
  797. }
  798. }
  799. }
  800. Rectangle<int> getBounds() const override { return bounds; }
  801. Point<int> localToGlobal (Point<int> relativePosition) override
  802. {
  803. return relativePosition + bounds.getPosition();
  804. }
  805. Point<int> globalToLocal (Point<int> screenPosition) override
  806. {
  807. return screenPosition - bounds.getPosition();
  808. }
  809. void setAlpha (float /* newAlpha */) override
  810. {
  811. //xxx todo!
  812. }
  813. StringArray getAvailableRenderingEngines() override
  814. {
  815. return StringArray ("Software Renderer");
  816. }
  817. void setMinimised (bool shouldBeMinimised) override
  818. {
  819. if (shouldBeMinimised)
  820. {
  821. Window root = RootWindow (display, DefaultScreen (display));
  822. XClientMessageEvent clientMsg;
  823. clientMsg.display = display;
  824. clientMsg.window = windowH;
  825. clientMsg.type = ClientMessage;
  826. clientMsg.format = 32;
  827. clientMsg.message_type = Atoms::get().ChangeState;
  828. clientMsg.data.l[0] = IconicState;
  829. ScopedXLock xlock;
  830. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  831. }
  832. else
  833. {
  834. setVisible (true);
  835. }
  836. }
  837. bool isMinimised() const override
  838. {
  839. ScopedXLock xlock;
  840. const Atoms& atoms = Atoms::get();
  841. GetXProperty prop (windowH, atoms.State, 0, 64, false, atoms.State);
  842. return prop.success
  843. && prop.actualType == atoms.State
  844. && prop.actualFormat == 32
  845. && prop.numItems > 0
  846. && ((unsigned long*) prop.data)[0] == IconicState;
  847. }
  848. void setFullScreen (const bool shouldBeFullScreen) override
  849. {
  850. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  851. setMinimised (false);
  852. if (fullScreen != shouldBeFullScreen)
  853. {
  854. if (shouldBeFullScreen)
  855. r = Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  856. if (! r.isEmpty())
  857. setBounds (r, shouldBeFullScreen);
  858. component.repaint();
  859. }
  860. }
  861. bool isFullScreen() const override
  862. {
  863. return fullScreen;
  864. }
  865. bool isChildWindowOf (Window possibleParent) const
  866. {
  867. Window* windowList = nullptr;
  868. uint32 windowListSize = 0;
  869. Window parent, root;
  870. ScopedXLock xlock;
  871. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  872. {
  873. if (windowList != nullptr)
  874. XFree (windowList);
  875. return parent == possibleParent;
  876. }
  877. return false;
  878. }
  879. bool isFrontWindow() const
  880. {
  881. Window* windowList = nullptr;
  882. uint32 windowListSize = 0;
  883. bool result = false;
  884. ScopedXLock xlock;
  885. Window parent, root = RootWindow (display, DefaultScreen (display));
  886. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  887. {
  888. for (int i = windowListSize; --i >= 0;)
  889. {
  890. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  891. if (peer != 0)
  892. {
  893. result = (peer == this);
  894. break;
  895. }
  896. }
  897. }
  898. if (windowList != nullptr)
  899. XFree (windowList);
  900. return result;
  901. }
  902. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  903. {
  904. if (! bounds.withZeroOrigin().contains (localPos))
  905. return false;
  906. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  907. {
  908. Component* const c = Desktop::getInstance().getComponent (i);
  909. if (c == &component)
  910. break;
  911. // TODO: needs scaling correctly
  912. if (c->contains (localPos + bounds.getPosition() - c->getScreenPosition()))
  913. return false;
  914. }
  915. if (trueIfInAChildWindow)
  916. return true;
  917. ::Window root, child;
  918. int wx, wy;
  919. unsigned int ww, wh, bw, depth;
  920. ScopedXLock xlock;
  921. return XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth)
  922. && XTranslateCoordinates (display, windowH, windowH, localPos.getX(), localPos.getY(), &wx, &wy, &child)
  923. && child == None;
  924. }
  925. BorderSize<int> getFrameSize() const override
  926. {
  927. return BorderSize<int>();
  928. }
  929. bool setAlwaysOnTop (bool /* alwaysOnTop */) override
  930. {
  931. return false;
  932. }
  933. void toFront (bool makeActive) override
  934. {
  935. if (makeActive)
  936. {
  937. setVisible (true);
  938. grabFocus();
  939. }
  940. {
  941. ScopedXLock xlock;
  942. XEvent ev;
  943. ev.xclient.type = ClientMessage;
  944. ev.xclient.serial = 0;
  945. ev.xclient.send_event = True;
  946. ev.xclient.message_type = Atoms::get().ActiveWin;
  947. ev.xclient.window = windowH;
  948. ev.xclient.format = 32;
  949. ev.xclient.data.l[0] = 2;
  950. ev.xclient.data.l[1] = getUserTime();
  951. ev.xclient.data.l[2] = 0;
  952. ev.xclient.data.l[3] = 0;
  953. ev.xclient.data.l[4] = 0;
  954. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  955. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  956. XWindowAttributes attr;
  957. XGetWindowAttributes (display, windowH, &attr);
  958. if (component.isAlwaysOnTop())
  959. XRaiseWindow (display, windowH);
  960. XSync (display, False);
  961. }
  962. handleBroughtToFront();
  963. }
  964. void toBehind (ComponentPeer* other) override
  965. {
  966. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  967. jassert (otherPeer != nullptr); // wrong type of window?
  968. if (otherPeer != nullptr)
  969. {
  970. setMinimised (false);
  971. Window newStack[] = { otherPeer->windowH, windowH };
  972. ScopedXLock xlock;
  973. XRestackWindows (display, newStack, 2);
  974. }
  975. }
  976. bool isFocused() const override
  977. {
  978. int revert = 0;
  979. Window focusedWindow = 0;
  980. ScopedXLock xlock;
  981. XGetInputFocus (display, &focusedWindow, &revert);
  982. return focusedWindow == windowH;
  983. }
  984. void grabFocus() override
  985. {
  986. XWindowAttributes atts;
  987. ScopedXLock xlock;
  988. if (windowH != 0
  989. && XGetWindowAttributes (display, windowH, &atts)
  990. && atts.map_state == IsViewable
  991. && ! isFocused())
  992. {
  993. XSetInputFocus (display, windowH, RevertToParent, getUserTime());
  994. isActiveApplication = true;
  995. }
  996. }
  997. void textInputRequired (const Point<int>&) override {}
  998. void repaint (const Rectangle<int>& area) override
  999. {
  1000. repainter->repaint (area.getIntersection (component.getLocalBounds()));
  1001. }
  1002. void performAnyPendingRepaintsNow() override
  1003. {
  1004. repainter->performAnyPendingRepaintsNow();
  1005. }
  1006. void setIcon (const Image& newIcon) override
  1007. {
  1008. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  1009. HeapBlock <unsigned long> data (dataSize);
  1010. int index = 0;
  1011. data[index++] = (unsigned long) newIcon.getWidth();
  1012. data[index++] = (unsigned long) newIcon.getHeight();
  1013. for (int y = 0; y < newIcon.getHeight(); ++y)
  1014. for (int x = 0; x < newIcon.getWidth(); ++x)
  1015. data[index++] = (unsigned long) newIcon.getPixelAt (x, y).getARGB();
  1016. ScopedXLock xlock;
  1017. xchangeProperty (windowH, Atoms::getCreating ("_NET_WM_ICON"), XA_CARDINAL, 32, data.getData(), dataSize);
  1018. deleteIconPixmaps();
  1019. XWMHints* wmHints = XGetWMHints (display, windowH);
  1020. if (wmHints == nullptr)
  1021. wmHints = XAllocWMHints();
  1022. wmHints->flags |= IconPixmapHint | IconMaskHint;
  1023. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  1024. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  1025. XSetWMHints (display, windowH, wmHints);
  1026. XFree (wmHints);
  1027. XSync (display, False);
  1028. }
  1029. void deleteIconPixmaps()
  1030. {
  1031. ScopedXLock xlock;
  1032. XWMHints* wmHints = XGetWMHints (display, windowH);
  1033. if (wmHints != nullptr)
  1034. {
  1035. if ((wmHints->flags & IconPixmapHint) != 0)
  1036. {
  1037. wmHints->flags &= ~IconPixmapHint;
  1038. XFreePixmap (display, wmHints->icon_pixmap);
  1039. }
  1040. if ((wmHints->flags & IconMaskHint) != 0)
  1041. {
  1042. wmHints->flags &= ~IconMaskHint;
  1043. XFreePixmap (display, wmHints->icon_mask);
  1044. }
  1045. XSetWMHints (display, windowH, wmHints);
  1046. XFree (wmHints);
  1047. }
  1048. }
  1049. //==============================================================================
  1050. void handleWindowMessage (XEvent& event)
  1051. {
  1052. switch (event.xany.type)
  1053. {
  1054. case KeyPressEventType: handleKeyPressEvent (event.xkey); break;
  1055. case KeyRelease: handleKeyReleaseEvent (event.xkey); break;
  1056. case ButtonPress: handleButtonPressEvent (event.xbutton); break;
  1057. case ButtonRelease: handleButtonReleaseEvent (event.xbutton); break;
  1058. case MotionNotify: handleMotionNotifyEvent (event.xmotion); break;
  1059. case EnterNotify: handleEnterNotifyEvent (event.xcrossing); break;
  1060. case LeaveNotify: handleLeaveNotifyEvent (event.xcrossing); break;
  1061. case FocusIn: handleFocusInEvent(); break;
  1062. case FocusOut: handleFocusOutEvent(); break;
  1063. case Expose: handleExposeEvent (event.xexpose); break;
  1064. case MappingNotify: handleMappingNotify (event.xmapping); break;
  1065. case ClientMessage: handleClientMessageEvent (event.xclient, event); break;
  1066. case SelectionNotify: handleDragAndDropSelection (event); break;
  1067. case ConfigureNotify: handleConfigureNotifyEvent (event.xconfigure); break;
  1068. case ReparentNotify: handleReparentNotifyEvent(); break;
  1069. case GravityNotify: handleGravityNotify(); break;
  1070. case SelectionClear: handleExternalSelectionClear(); break;
  1071. case SelectionRequest: handleExternalSelectionRequest (event); break;
  1072. case CirculateNotify:
  1073. case CreateNotify:
  1074. case DestroyNotify:
  1075. // Think we can ignore these
  1076. break;
  1077. case MapNotify:
  1078. mapped = true;
  1079. handleBroughtToFront();
  1080. break;
  1081. case UnmapNotify:
  1082. mapped = false;
  1083. break;
  1084. default:
  1085. #if JUCE_USE_XSHM
  1086. {
  1087. ScopedXLock xlock;
  1088. if (event.xany.type == XShmGetEventBase (display))
  1089. repainter->notifyPaintCompleted();
  1090. }
  1091. #endif
  1092. break;
  1093. }
  1094. }
  1095. void handleKeyPressEvent (XKeyEvent& keyEvent)
  1096. {
  1097. char utf8 [64] = { 0 };
  1098. juce_wchar unicodeChar = 0;
  1099. int keyCode = 0;
  1100. bool keyDownChange = false;
  1101. KeySym sym;
  1102. {
  1103. ScopedXLock xlock;
  1104. updateKeyStates (keyEvent.keycode, true);
  1105. String oldLocale (::setlocale (LC_ALL, 0));
  1106. ::setlocale (LC_ALL, "");
  1107. XLookupString (&keyEvent, utf8, sizeof (utf8), &sym, 0);
  1108. if (oldLocale.isNotEmpty())
  1109. ::setlocale (LC_ALL, oldLocale.toRawUTF8());
  1110. unicodeChar = *CharPointer_UTF8 (utf8);
  1111. keyCode = (int) unicodeChar;
  1112. if (keyCode < 0x20)
  1113. keyCode = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, currentModifiers.isShiftDown() ? 1 : 0);
  1114. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  1115. }
  1116. const ModifierKeys oldMods (currentModifiers);
  1117. bool keyPressed = false;
  1118. if ((sym & 0xff00) == 0xff00 || sym == XK_ISO_Left_Tab)
  1119. {
  1120. switch (sym) // Translate keypad
  1121. {
  1122. case XK_KP_Add: keyCode = XK_plus; break;
  1123. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  1124. case XK_KP_Divide: keyCode = XK_slash; break;
  1125. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  1126. case XK_KP_Enter: keyCode = XK_Return; break;
  1127. case XK_KP_Insert: keyCode = XK_Insert; break;
  1128. case XK_Delete:
  1129. case XK_KP_Delete: keyCode = XK_Delete; break;
  1130. case XK_KP_Left: keyCode = XK_Left; break;
  1131. case XK_KP_Right: keyCode = XK_Right; break;
  1132. case XK_KP_Up: keyCode = XK_Up; break;
  1133. case XK_KP_Down: keyCode = XK_Down; break;
  1134. case XK_KP_Home: keyCode = XK_Home; break;
  1135. case XK_KP_End: keyCode = XK_End; break;
  1136. case XK_KP_Page_Down: keyCode = XK_Page_Down; break;
  1137. case XK_KP_Page_Up: keyCode = XK_Page_Up; break;
  1138. case XK_KP_0: keyCode = XK_0; break;
  1139. case XK_KP_1: keyCode = XK_1; break;
  1140. case XK_KP_2: keyCode = XK_2; break;
  1141. case XK_KP_3: keyCode = XK_3; break;
  1142. case XK_KP_4: keyCode = XK_4; break;
  1143. case XK_KP_5: keyCode = XK_5; break;
  1144. case XK_KP_6: keyCode = XK_6; break;
  1145. case XK_KP_7: keyCode = XK_7; break;
  1146. case XK_KP_8: keyCode = XK_8; break;
  1147. case XK_KP_9: keyCode = XK_9; break;
  1148. default: break;
  1149. }
  1150. switch (keyCode)
  1151. {
  1152. case XK_Left:
  1153. case XK_Right:
  1154. case XK_Up:
  1155. case XK_Down:
  1156. case XK_Page_Up:
  1157. case XK_Page_Down:
  1158. case XK_End:
  1159. case XK_Home:
  1160. case XK_Delete:
  1161. case XK_Insert:
  1162. keyPressed = true;
  1163. keyCode = (keyCode & 0xff) | Keys::extendedKeyModifier;
  1164. break;
  1165. case XK_Tab:
  1166. case XK_Return:
  1167. case XK_Escape:
  1168. case XK_BackSpace:
  1169. keyPressed = true;
  1170. keyCode &= 0xff;
  1171. break;
  1172. default:
  1173. if (sym >= XK_F1 && sym <= XK_F16)
  1174. {
  1175. keyPressed = true;
  1176. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  1177. }
  1178. break;
  1179. }
  1180. }
  1181. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  1182. keyPressed = true;
  1183. if (oldMods != currentModifiers)
  1184. handleModifierKeysChange();
  1185. if (keyDownChange)
  1186. handleKeyUpOrDown (true);
  1187. if (keyPressed)
  1188. handleKeyPress (keyCode, unicodeChar);
  1189. }
  1190. static bool isKeyReleasePartOfAutoRepeat (const XKeyEvent& keyReleaseEvent)
  1191. {
  1192. if (XPending (display))
  1193. {
  1194. XEvent e;
  1195. XPeekEvent (display, &e);
  1196. // Look for a subsequent key-down event with the same timestamp and keycode
  1197. return e.type == KeyPressEventType
  1198. && e.xkey.keycode == keyReleaseEvent.keycode
  1199. && e.xkey.time == keyReleaseEvent.time;
  1200. }
  1201. return false;
  1202. }
  1203. void handleKeyReleaseEvent (const XKeyEvent& keyEvent)
  1204. {
  1205. if (! isKeyReleasePartOfAutoRepeat (keyEvent))
  1206. {
  1207. updateKeyStates (keyEvent.keycode, false);
  1208. KeySym sym;
  1209. {
  1210. ScopedXLock xlock;
  1211. sym = XkbKeycodeToKeysym (display, keyEvent.keycode, 0, 0);
  1212. }
  1213. const ModifierKeys oldMods (currentModifiers);
  1214. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  1215. if (oldMods != currentModifiers)
  1216. handleModifierKeysChange();
  1217. if (keyDownChange)
  1218. handleKeyUpOrDown (false);
  1219. }
  1220. }
  1221. template <typename EventType>
  1222. static Point<int> getMousePos (const EventType& e) noexcept
  1223. {
  1224. return Point<int> (e.x, e.y);
  1225. }
  1226. void handleWheelEvent (const XButtonPressedEvent& buttonPressEvent, const float amount)
  1227. {
  1228. MouseWheelDetails wheel;
  1229. wheel.deltaX = 0.0f;
  1230. wheel.deltaY = amount;
  1231. wheel.isReversed = false;
  1232. wheel.isSmooth = false;
  1233. handleMouseWheel (0, getMousePos (buttonPressEvent), getEventTime (buttonPressEvent), wheel);
  1234. }
  1235. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent, int buttonModifierFlag)
  1236. {
  1237. currentModifiers = currentModifiers.withFlags (buttonModifierFlag);
  1238. toFront (true);
  1239. handleMouseEvent (0, getMousePos (buttonPressEvent), currentModifiers, getEventTime (buttonPressEvent));
  1240. }
  1241. void handleButtonPressEvent (const XButtonPressedEvent& buttonPressEvent)
  1242. {
  1243. updateKeyModifiers (buttonPressEvent.state);
  1244. switch (pointerMap [buttonPressEvent.button - Button1])
  1245. {
  1246. case Keys::WheelUp: handleWheelEvent (buttonPressEvent, 50.0f / 256.0f); break;
  1247. case Keys::WheelDown: handleWheelEvent (buttonPressEvent, -50.0f / 256.0f); break;
  1248. case Keys::LeftButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::leftButtonModifier); break;
  1249. case Keys::RightButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::rightButtonModifier); break;
  1250. case Keys::MiddleButton: handleButtonPressEvent (buttonPressEvent, ModifierKeys::middleButtonModifier); break;
  1251. default: break;
  1252. }
  1253. clearLastMousePos();
  1254. }
  1255. void handleButtonReleaseEvent (const XButtonReleasedEvent& buttonRelEvent)
  1256. {
  1257. updateKeyModifiers (buttonRelEvent.state);
  1258. if (parentWindow != 0)
  1259. updateWindowBounds();
  1260. switch (pointerMap [buttonRelEvent.button - Button1])
  1261. {
  1262. case Keys::LeftButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier); break;
  1263. case Keys::RightButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier); break;
  1264. case Keys::MiddleButton: currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier); break;
  1265. default: break;
  1266. }
  1267. if (dragState.dragging)
  1268. handleExternalDragButtonReleaseEvent();
  1269. handleMouseEvent (0, getMousePos (buttonRelEvent), currentModifiers, getEventTime (buttonRelEvent));
  1270. clearLastMousePos();
  1271. }
  1272. void handleMotionNotifyEvent (const XPointerMovedEvent& movedEvent)
  1273. {
  1274. updateKeyModifiers (movedEvent.state);
  1275. lastMousePos = Point<int> (movedEvent.x_root, movedEvent.y_root);
  1276. if (dragState.dragging)
  1277. handleExternalDragMotionNotify();
  1278. handleMouseEvent (0, getMousePos (movedEvent), currentModifiers, getEventTime (movedEvent));
  1279. }
  1280. void handleEnterNotifyEvent (const XEnterWindowEvent& enterEvent)
  1281. {
  1282. if (parentWindow != 0)
  1283. updateWindowBounds();
  1284. clearLastMousePos();
  1285. if (! currentModifiers.isAnyMouseButtonDown())
  1286. {
  1287. updateKeyModifiers (enterEvent.state);
  1288. handleMouseEvent (0, getMousePos (enterEvent), currentModifiers, getEventTime (enterEvent));
  1289. }
  1290. }
  1291. void handleLeaveNotifyEvent (const XLeaveWindowEvent& leaveEvent)
  1292. {
  1293. // Suppress the normal leave if we've got a pointer grab, or if
  1294. // it's a bogus one caused by clicking a mouse button when running
  1295. // in a Window manager
  1296. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent.mode == NotifyNormal)
  1297. || leaveEvent.mode == NotifyUngrab)
  1298. {
  1299. updateKeyModifiers (leaveEvent.state);
  1300. handleMouseEvent (0, getMousePos (leaveEvent), currentModifiers, getEventTime (leaveEvent));
  1301. }
  1302. }
  1303. void handleFocusInEvent()
  1304. {
  1305. isActiveApplication = true;
  1306. if (isFocused())
  1307. handleFocusGain();
  1308. }
  1309. void handleFocusOutEvent()
  1310. {
  1311. isActiveApplication = false;
  1312. if (! isFocused())
  1313. handleFocusLoss();
  1314. }
  1315. void handleExposeEvent (XExposeEvent& exposeEvent)
  1316. {
  1317. // Batch together all pending expose events
  1318. XEvent nextEvent;
  1319. ScopedXLock xlock;
  1320. if (exposeEvent.window != windowH)
  1321. {
  1322. Window child;
  1323. XTranslateCoordinates (display, exposeEvent.window, windowH,
  1324. exposeEvent.x, exposeEvent.y, &exposeEvent.x, &exposeEvent.y,
  1325. &child);
  1326. }
  1327. repaint (Rectangle<int> (exposeEvent.x, exposeEvent.y,
  1328. exposeEvent.width, exposeEvent.height));
  1329. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  1330. {
  1331. XPeekEvent (display, &nextEvent);
  1332. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent.window)
  1333. break;
  1334. XNextEvent (display, &nextEvent);
  1335. const XExposeEvent& nextExposeEvent = (const XExposeEvent&) nextEvent.xexpose;
  1336. repaint (Rectangle<int> (nextExposeEvent.x, nextExposeEvent.y,
  1337. nextExposeEvent.width, nextExposeEvent.height));
  1338. }
  1339. }
  1340. void handleConfigureNotifyEvent (XConfigureEvent& confEvent)
  1341. {
  1342. updateWindowBounds();
  1343. updateBorderSize();
  1344. handleMovedOrResized();
  1345. // if the native title bar is dragged, need to tell any active menus, etc.
  1346. if ((styleFlags & windowHasTitleBar) != 0
  1347. && component.isCurrentlyBlockedByAnotherModalComponent())
  1348. {
  1349. if (Component* const currentModalComp = Component::getCurrentlyModalComponent())
  1350. currentModalComp->inputAttemptWhenModal();
  1351. }
  1352. if (confEvent.window == windowH
  1353. && confEvent.above != 0
  1354. && isFrontWindow())
  1355. {
  1356. handleBroughtToFront();
  1357. }
  1358. }
  1359. void handleReparentNotifyEvent()
  1360. {
  1361. parentWindow = 0;
  1362. Window wRoot = 0;
  1363. Window* wChild = nullptr;
  1364. unsigned int numChildren;
  1365. {
  1366. ScopedXLock xlock;
  1367. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  1368. }
  1369. if (parentWindow == windowH || parentWindow == wRoot)
  1370. parentWindow = 0;
  1371. handleGravityNotify();
  1372. }
  1373. void handleGravityNotify()
  1374. {
  1375. updateWindowBounds();
  1376. updateBorderSize();
  1377. handleMovedOrResized();
  1378. }
  1379. void handleMappingNotify (XMappingEvent& mappingEvent)
  1380. {
  1381. if (mappingEvent.request != MappingPointer)
  1382. {
  1383. // Deal with modifier/keyboard mapping
  1384. ScopedXLock xlock;
  1385. XRefreshKeyboardMapping (&mappingEvent);
  1386. updateModifierMappings();
  1387. }
  1388. }
  1389. void handleClientMessageEvent (XClientMessageEvent& clientMsg, XEvent& event)
  1390. {
  1391. const Atoms& atoms = Atoms::get();
  1392. if (clientMsg.message_type == atoms.Protocols && clientMsg.format == 32)
  1393. {
  1394. const Atom atom = (Atom) clientMsg.data.l[0];
  1395. if (atom == atoms.ProtocolList [Atoms::PING])
  1396. {
  1397. Window root = RootWindow (display, DefaultScreen (display));
  1398. clientMsg.window = root;
  1399. XSendEvent (display, root, False, NoEventMask, &event);
  1400. XFlush (display);
  1401. }
  1402. else if (atom == atoms.ProtocolList [Atoms::TAKE_FOCUS])
  1403. {
  1404. if ((getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0)
  1405. {
  1406. XWindowAttributes atts;
  1407. ScopedXLock xlock;
  1408. if (clientMsg.window != 0
  1409. && XGetWindowAttributes (display, clientMsg.window, &atts))
  1410. {
  1411. if (atts.map_state == IsViewable)
  1412. XSetInputFocus (display, clientMsg.window, RevertToParent, clientMsg.data.l[1]);
  1413. }
  1414. }
  1415. }
  1416. else if (atom == atoms.ProtocolList [Atoms::DELETE_WINDOW])
  1417. {
  1418. handleUserClosingWindow();
  1419. }
  1420. }
  1421. else if (clientMsg.message_type == atoms.XdndEnter)
  1422. {
  1423. handleDragAndDropEnter (clientMsg);
  1424. }
  1425. else if (clientMsg.message_type == atoms.XdndLeave)
  1426. {
  1427. handleDragExit (dragInfo);
  1428. resetDragAndDrop();
  1429. }
  1430. else if (clientMsg.message_type == atoms.XdndPosition)
  1431. {
  1432. handleDragAndDropPosition (clientMsg);
  1433. }
  1434. else if (clientMsg.message_type == atoms.XdndDrop)
  1435. {
  1436. handleDragAndDropDrop (clientMsg);
  1437. }
  1438. else if (clientMsg.message_type == atoms.XdndStatus)
  1439. {
  1440. handleExternalDragAndDropStatus (clientMsg);
  1441. }
  1442. else if (clientMsg.message_type == atoms.XdndFinished)
  1443. {
  1444. externalResetDragAndDrop();
  1445. }
  1446. }
  1447. bool externalDragTextInit (const String& text)
  1448. {
  1449. if (dragState.dragging)
  1450. return false;
  1451. return externalDragInit (true, text);
  1452. }
  1453. bool externalDragFileInit (const StringArray& files, bool /*canMoveFiles*/)
  1454. {
  1455. if (dragState.dragging)
  1456. return false;
  1457. StringArray uriList;
  1458. for (int i = 0; i < files.size(); ++i)
  1459. {
  1460. const String& f = files[i];
  1461. if (f.matchesWildcard ("?*://*", false))
  1462. uriList.add (f);
  1463. else
  1464. uriList.add ("file://" + f);
  1465. }
  1466. return externalDragInit (false, uriList.joinIntoString ("\r\n"));
  1467. }
  1468. //==============================================================================
  1469. void showMouseCursor (Cursor cursor) noexcept
  1470. {
  1471. ScopedXLock xlock;
  1472. XDefineCursor (display, windowH, cursor);
  1473. }
  1474. //==============================================================================
  1475. bool dontRepaint;
  1476. static ModifierKeys currentModifiers;
  1477. static bool isActiveApplication;
  1478. private:
  1479. //==============================================================================
  1480. class LinuxRepaintManager : public Timer
  1481. {
  1482. public:
  1483. LinuxRepaintManager (LinuxComponentPeer& p)
  1484. : peer (p), lastTimeImageUsed (0)
  1485. {
  1486. #if JUCE_USE_XSHM
  1487. shmPaintsPending = 0;
  1488. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  1489. if (useARGBImagesForRendering)
  1490. {
  1491. ScopedXLock xlock;
  1492. XShmSegmentInfo segmentinfo;
  1493. XImage* const testImage
  1494. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  1495. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  1496. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  1497. XDestroyImage (testImage);
  1498. }
  1499. #endif
  1500. }
  1501. void timerCallback() override
  1502. {
  1503. #if JUCE_USE_XSHM
  1504. if (shmPaintsPending != 0)
  1505. return;
  1506. #endif
  1507. if (! regionsNeedingRepaint.isEmpty())
  1508. {
  1509. stopTimer();
  1510. performAnyPendingRepaintsNow();
  1511. }
  1512. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  1513. {
  1514. stopTimer();
  1515. image = Image::null;
  1516. }
  1517. }
  1518. void repaint (const Rectangle<int>& area)
  1519. {
  1520. if (! isTimerRunning())
  1521. startTimer (repaintTimerPeriod);
  1522. regionsNeedingRepaint.add (area);
  1523. }
  1524. void performAnyPendingRepaintsNow()
  1525. {
  1526. #if JUCE_USE_XSHM
  1527. if (shmPaintsPending != 0)
  1528. {
  1529. startTimer (repaintTimerPeriod);
  1530. return;
  1531. }
  1532. #endif
  1533. RectangleList<int> originalRepaintRegion (regionsNeedingRepaint);
  1534. regionsNeedingRepaint.clear();
  1535. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  1536. if (! totalArea.isEmpty())
  1537. {
  1538. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  1539. || image.getHeight() < totalArea.getHeight())
  1540. {
  1541. #if JUCE_USE_XSHM
  1542. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  1543. : Image::RGB,
  1544. #else
  1545. image = Image (new XBitmapImage (Image::RGB,
  1546. #endif
  1547. (totalArea.getWidth() + 31) & ~31,
  1548. (totalArea.getHeight() + 31) & ~31,
  1549. false, peer.depth, peer.visual));
  1550. }
  1551. startTimer (repaintTimerPeriod);
  1552. RectangleList<int> adjustedList (originalRepaintRegion);
  1553. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  1554. if (peer.depth == 32)
  1555. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1556. image.clear (*i - totalArea.getPosition());
  1557. {
  1558. ScopedPointer<LowLevelGraphicsContext> context (peer.getComponent().getLookAndFeel()
  1559. .createGraphicsContext (image, -totalArea.getPosition(), adjustedList));
  1560. peer.handlePaint (*context);
  1561. }
  1562. for (const Rectangle<int>* i = originalRepaintRegion.begin(), * const e = originalRepaintRegion.end(); i != e; ++i)
  1563. {
  1564. #if JUCE_USE_XSHM
  1565. ++shmPaintsPending;
  1566. #endif
  1567. static_cast<XBitmapImage*> (image.getPixelData())
  1568. ->blitToWindow (peer.windowH,
  1569. i->getX(), i->getY(), i->getWidth(), i->getHeight(),
  1570. i->getX() - totalArea.getX(), i->getY() - totalArea.getY());
  1571. }
  1572. }
  1573. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  1574. startTimer (repaintTimerPeriod);
  1575. }
  1576. #if JUCE_USE_XSHM
  1577. void notifyPaintCompleted() noexcept { --shmPaintsPending; }
  1578. #endif
  1579. private:
  1580. enum { repaintTimerPeriod = 1000 / 100 };
  1581. LinuxComponentPeer& peer;
  1582. Image image;
  1583. uint32 lastTimeImageUsed;
  1584. RectangleList<int> regionsNeedingRepaint;
  1585. #if JUCE_USE_XSHM
  1586. bool useARGBImagesForRendering;
  1587. int shmPaintsPending;
  1588. #endif
  1589. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
  1590. };
  1591. ScopedPointer <LinuxRepaintManager> repainter;
  1592. friend class LinuxRepaintManager;
  1593. Window windowH, parentWindow;
  1594. Rectangle<int> bounds;
  1595. Image taskbarImage;
  1596. bool fullScreen, mapped;
  1597. Visual* visual;
  1598. int depth;
  1599. BorderSize<int> windowBorder;
  1600. bool isAlwaysOnTop;
  1601. enum { KeyPressEventType = 2 };
  1602. struct MotifWmHints
  1603. {
  1604. unsigned long flags;
  1605. unsigned long functions;
  1606. unsigned long decorations;
  1607. long input_mode;
  1608. unsigned long status;
  1609. };
  1610. static void updateKeyStates (const int keycode, const bool press) noexcept
  1611. {
  1612. const int keybyte = keycode >> 3;
  1613. const int keybit = (1 << (keycode & 7));
  1614. if (press)
  1615. Keys::keyStates [keybyte] |= keybit;
  1616. else
  1617. Keys::keyStates [keybyte] &= ~keybit;
  1618. }
  1619. static void updateKeyModifiers (const int status) noexcept
  1620. {
  1621. int keyMods = 0;
  1622. if ((status & ShiftMask) != 0) keyMods |= ModifierKeys::shiftModifier;
  1623. if ((status & ControlMask) != 0) keyMods |= ModifierKeys::ctrlModifier;
  1624. if ((status & Keys::AltMask) != 0) keyMods |= ModifierKeys::altModifier;
  1625. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  1626. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  1627. Keys::capsLock = ((status & LockMask) != 0);
  1628. }
  1629. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) noexcept
  1630. {
  1631. int modifier = 0;
  1632. bool isModifier = true;
  1633. switch (sym)
  1634. {
  1635. case XK_Shift_L:
  1636. case XK_Shift_R: modifier = ModifierKeys::shiftModifier; break;
  1637. case XK_Control_L:
  1638. case XK_Control_R: modifier = ModifierKeys::ctrlModifier; break;
  1639. case XK_Alt_L:
  1640. case XK_Alt_R: modifier = ModifierKeys::altModifier; break;
  1641. case XK_Num_Lock:
  1642. if (press)
  1643. Keys::numLock = ! Keys::numLock;
  1644. break;
  1645. case XK_Caps_Lock:
  1646. if (press)
  1647. Keys::capsLock = ! Keys::capsLock;
  1648. break;
  1649. case XK_Scroll_Lock:
  1650. break;
  1651. default:
  1652. isModifier = false;
  1653. break;
  1654. }
  1655. currentModifiers = press ? currentModifiers.withFlags (modifier)
  1656. : currentModifiers.withoutFlags (modifier);
  1657. return isModifier;
  1658. }
  1659. // Alt and Num lock are not defined by standard X
  1660. // modifier constants: check what they're mapped to
  1661. static void updateModifierMappings() noexcept
  1662. {
  1663. ScopedXLock xlock;
  1664. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  1665. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  1666. Keys::AltMask = 0;
  1667. Keys::NumLockMask = 0;
  1668. if (XModifierKeymap* const mapping = XGetModifierMapping (display))
  1669. {
  1670. for (int i = 0; i < 8; i++)
  1671. {
  1672. if (mapping->modifiermap [i << 1] == altLeftCode)
  1673. Keys::AltMask = 1 << i;
  1674. else if (mapping->modifiermap [i << 1] == numLockCode)
  1675. Keys::NumLockMask = 1 << i;
  1676. }
  1677. XFreeModifiermap (mapping);
  1678. }
  1679. }
  1680. //==============================================================================
  1681. static void xchangeProperty (Window wndH, Atom property, Atom type, int format, const void* data, int numElements)
  1682. {
  1683. XChangeProperty (display, wndH, property, type, format, PropModeReplace, (const unsigned char*) data, numElements);
  1684. }
  1685. void removeWindowDecorations (Window wndH)
  1686. {
  1687. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1688. if (hints != None)
  1689. {
  1690. MotifWmHints motifHints;
  1691. zerostruct (motifHints);
  1692. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  1693. motifHints.decorations = 0;
  1694. ScopedXLock xlock;
  1695. xchangeProperty (wndH, hints, hints, 32, &motifHints, 4);
  1696. }
  1697. hints = Atoms::getIfExists ("_WIN_HINTS");
  1698. if (hints != None)
  1699. {
  1700. long gnomeHints = 0;
  1701. ScopedXLock xlock;
  1702. xchangeProperty (wndH, hints, hints, 32, &gnomeHints, 1);
  1703. }
  1704. hints = Atoms::getIfExists ("KWM_WIN_DECORATION");
  1705. if (hints != None)
  1706. {
  1707. long kwmHints = 2; /*KDE_tinyDecoration*/
  1708. ScopedXLock xlock;
  1709. xchangeProperty (wndH, hints, hints, 32, &kwmHints, 1);
  1710. }
  1711. }
  1712. void addWindowButtons (Window wndH)
  1713. {
  1714. ScopedXLock xlock;
  1715. Atom hints = Atoms::getIfExists ("_MOTIF_WM_HINTS");
  1716. if (hints != None)
  1717. {
  1718. MotifWmHints motifHints;
  1719. zerostruct (motifHints);
  1720. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  1721. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  1722. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  1723. if ((styleFlags & windowHasCloseButton) != 0)
  1724. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  1725. if ((styleFlags & windowHasMinimiseButton) != 0)
  1726. {
  1727. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  1728. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  1729. }
  1730. if ((styleFlags & windowHasMaximiseButton) != 0)
  1731. {
  1732. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  1733. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  1734. }
  1735. if ((styleFlags & windowIsResizable) != 0)
  1736. {
  1737. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  1738. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  1739. }
  1740. xchangeProperty (wndH, hints, hints, 32, &motifHints, 5);
  1741. }
  1742. hints = Atoms::getIfExists ("_NET_WM_ALLOWED_ACTIONS");
  1743. if (hints != None)
  1744. {
  1745. Atom netHints [6];
  1746. int num = 0;
  1747. if ((styleFlags & windowIsResizable) != 0)
  1748. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_RESIZE");
  1749. if ((styleFlags & windowHasMaximiseButton) != 0)
  1750. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_FULLSCREEN");
  1751. if ((styleFlags & windowHasMinimiseButton) != 0)
  1752. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_MINIMIZE");
  1753. if ((styleFlags & windowHasCloseButton) != 0)
  1754. netHints [num++] = Atoms::getIfExists ("_NET_WM_ACTION_CLOSE");
  1755. xchangeProperty (wndH, hints, XA_ATOM, 32, &netHints, num);
  1756. }
  1757. }
  1758. void setWindowType()
  1759. {
  1760. Atom netHints [2];
  1761. if ((styleFlags & windowIsTemporary) != 0
  1762. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  1763. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_COMBO");
  1764. else
  1765. netHints [0] = Atoms::getIfExists ("_NET_WM_WINDOW_TYPE_NORMAL");
  1766. netHints[1] = Atoms::getIfExists ("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE");
  1767. xchangeProperty (windowH, Atoms::get().WindowType, XA_ATOM, 32, &netHints, 2);
  1768. int numHints = 0;
  1769. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  1770. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_SKIP_TASKBAR");
  1771. if (component.isAlwaysOnTop())
  1772. netHints [numHints++] = Atoms::getIfExists ("_NET_WM_STATE_ABOVE");
  1773. if (numHints > 0)
  1774. xchangeProperty (windowH, Atoms::get().WindowState, XA_ATOM, 32, &netHints, numHints);
  1775. }
  1776. void createWindow (Window parentToAddTo)
  1777. {
  1778. ScopedXLock xlock;
  1779. resetDragAndDrop();
  1780. // Get defaults for various properties
  1781. const int screen = DefaultScreen (display);
  1782. Window root = RootWindow (display, screen);
  1783. // Try to obtain a 32-bit visual or fallback to 24 or 16
  1784. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  1785. if (visual == nullptr)
  1786. {
  1787. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  1788. Process::terminate();
  1789. }
  1790. // Create and install a colormap suitable fr our visual
  1791. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  1792. XInstallColormap (display, colormap);
  1793. // Set up the window attributes
  1794. XSetWindowAttributes swa;
  1795. swa.border_pixel = 0;
  1796. swa.background_pixmap = None;
  1797. swa.colormap = colormap;
  1798. swa.override_redirect = (component.isAlwaysOnTop() && (styleFlags & windowIsTemporary) != 0) ? True : False;
  1799. swa.event_mask = getAllEventsMask();
  1800. windowH = XCreateWindow (display, parentToAddTo != 0 ? parentToAddTo : root,
  1801. 0, 0, 1, 1,
  1802. 0, depth, InputOutput, visual,
  1803. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  1804. &swa);
  1805. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  1806. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  1807. GrabModeAsync, GrabModeAsync, None, None);
  1808. // Set the window context to identify the window handle object
  1809. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  1810. {
  1811. // Failed
  1812. jassertfalse;
  1813. Logger::outputDebugString ("Failed to create context information for window.\n");
  1814. XDestroyWindow (display, windowH);
  1815. windowH = 0;
  1816. return;
  1817. }
  1818. // Set window manager hints
  1819. XWMHints* wmHints = XAllocWMHints();
  1820. wmHints->flags = InputHint | StateHint;
  1821. wmHints->input = True; // Locally active input model
  1822. wmHints->initial_state = NormalState;
  1823. XSetWMHints (display, windowH, wmHints);
  1824. XFree (wmHints);
  1825. // Set the window type
  1826. setWindowType();
  1827. // Define decoration
  1828. if ((styleFlags & windowHasTitleBar) == 0)
  1829. removeWindowDecorations (windowH);
  1830. else
  1831. addWindowButtons (windowH);
  1832. setTitle (component.getName());
  1833. const Atoms& atoms = Atoms::get();
  1834. // Associate the PID, allowing to be shut down when something goes wrong
  1835. unsigned long pid = getpid();
  1836. xchangeProperty (windowH, atoms.Pid, XA_CARDINAL, 32, &pid, 1);
  1837. // Set window manager protocols
  1838. xchangeProperty (windowH, atoms.Protocols, XA_ATOM, 32, atoms.ProtocolList, 2);
  1839. // Set drag and drop flags
  1840. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32, atoms.allowedMimeTypes, numElementsInArray (atoms.allowedMimeTypes));
  1841. xchangeProperty (windowH, atoms.XdndActionList, XA_ATOM, 32, atoms.allowedActions, numElementsInArray (atoms.allowedActions));
  1842. xchangeProperty (windowH, atoms.XdndActionDescription, XA_STRING, 8, "", 0);
  1843. xchangeProperty (windowH, atoms.XdndAware, XA_ATOM, 32, &Atoms::DndVersion, 1);
  1844. initialisePointerMap();
  1845. updateModifierMappings();
  1846. }
  1847. void destroyWindow()
  1848. {
  1849. ScopedXLock xlock;
  1850. XPointer handlePointer;
  1851. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  1852. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  1853. XDestroyWindow (display, windowH);
  1854. // Wait for it to complete and then remove any events for this
  1855. // window from the event queue.
  1856. XSync (display, false);
  1857. XEvent event;
  1858. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  1859. {}
  1860. }
  1861. static int getAllEventsMask() noexcept
  1862. {
  1863. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  1864. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  1865. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  1866. }
  1867. template <typename EventType>
  1868. static int64 getEventTime (const EventType& t)
  1869. {
  1870. return getEventTime (t.time);
  1871. }
  1872. static int64 getEventTime (::Time t)
  1873. {
  1874. static int64 eventTimeOffset = 0x12345678;
  1875. const int64 thisMessageTime = t;
  1876. if (eventTimeOffset == 0x12345678)
  1877. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  1878. return eventTimeOffset + thisMessageTime;
  1879. }
  1880. long getUserTime() const
  1881. {
  1882. GetXProperty prop (windowH, Atoms::get().UserTime, 0, 65536, false, XA_CARDINAL);
  1883. return prop.success ? *(long*) prop.data : 0;
  1884. }
  1885. void updateBorderSize()
  1886. {
  1887. if ((styleFlags & windowHasTitleBar) == 0)
  1888. {
  1889. windowBorder = BorderSize<int> (0);
  1890. }
  1891. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  1892. {
  1893. ScopedXLock xlock;
  1894. Atom hints = Atoms::getIfExists ("_NET_FRAME_EXTENTS");
  1895. if (hints != None)
  1896. {
  1897. GetXProperty prop (windowH, hints, 0, 4, false, XA_CARDINAL);
  1898. if (prop.success && prop.actualFormat == 32)
  1899. {
  1900. const unsigned long* const sizes = (const unsigned long*) prop.data;
  1901. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  1902. (int) sizes[3], (int) sizes[1]);
  1903. }
  1904. }
  1905. }
  1906. }
  1907. void updateWindowBounds()
  1908. {
  1909. jassert (windowH != 0);
  1910. if (windowH != 0)
  1911. {
  1912. Window root, child;
  1913. int wx = 0, wy = 0;
  1914. unsigned int ww = 0, wh = 0, bw, depth;
  1915. ScopedXLock xlock;
  1916. if (XGetGeometry (display, (::Drawable) windowH, &root, &wx, &wy, &ww, &wh, &bw, &depth))
  1917. if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  1918. wx = wy = 0;
  1919. bounds.setBounds (wx, wy, ww, wh);
  1920. }
  1921. }
  1922. //==============================================================================
  1923. struct DragState
  1924. {
  1925. DragState() noexcept
  1926. : isText (false), dragging (false), expectingStatus (false),
  1927. canDrop (false), targetWindow (None), xdndVersion (-1)
  1928. {
  1929. }
  1930. bool isText;
  1931. bool dragging; // currently performing outgoing external dnd as Xdnd source, have grabbed mouse
  1932. bool expectingStatus; // XdndPosition sent, waiting for XdndStatus
  1933. bool canDrop; // target window signals it will accept the drop
  1934. Window targetWindow; // potential drop target
  1935. int xdndVersion; // negotiated version with target
  1936. Rectangle<int> silentRect;
  1937. String textOrFiles;
  1938. const Atom* getMimeTypes() const noexcept { return isText ? Atoms::get().externalAllowedTextMimeTypes
  1939. : Atoms::get().externalAllowedFileMimeTypes; }
  1940. int getNumMimeTypes() const noexcept { return isText ? numElementsInArray (Atoms::get().externalAllowedTextMimeTypes)
  1941. : numElementsInArray (Atoms::get().externalAllowedFileMimeTypes); }
  1942. bool matchesTarget (Atom targetType) const
  1943. {
  1944. for (int i = getNumMimeTypes(); --i >= 0;)
  1945. if (getMimeTypes()[i] == targetType)
  1946. return true;
  1947. return false;
  1948. }
  1949. };
  1950. //==============================================================================
  1951. void resetDragAndDrop()
  1952. {
  1953. dragInfo.clear();
  1954. dragInfo.position = Point<int> (-1, -1);
  1955. dragAndDropCurrentMimeType = 0;
  1956. dragAndDropSourceWindow = 0;
  1957. srcMimeTypeAtomList.clear();
  1958. finishAfterDropDataReceived = false;
  1959. }
  1960. void resetExternalDragState()
  1961. {
  1962. dragState = DragState();
  1963. }
  1964. void sendDragAndDropMessage (XClientMessageEvent& msg)
  1965. {
  1966. msg.type = ClientMessage;
  1967. msg.display = display;
  1968. msg.window = dragAndDropSourceWindow;
  1969. msg.format = 32;
  1970. msg.data.l[0] = windowH;
  1971. ScopedXLock xlock;
  1972. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  1973. }
  1974. bool sendExternalDragAndDropMessage (XClientMessageEvent& msg, const Window targetWindow)
  1975. {
  1976. msg.type = ClientMessage;
  1977. msg.display = display;
  1978. msg.window = targetWindow;
  1979. msg.format = 32;
  1980. msg.data.l[0] = windowH;
  1981. ScopedXLock xlock;
  1982. return XSendEvent (display, targetWindow, False, 0, (XEvent*) &msg) != 0;
  1983. }
  1984. void sendExternalDragAndDropDrop (const Window targetWindow)
  1985. {
  1986. XClientMessageEvent msg;
  1987. zerostruct (msg);
  1988. msg.message_type = Atoms::get().XdndDrop;
  1989. msg.data.l[2] = CurrentTime;
  1990. sendExternalDragAndDropMessage (msg, targetWindow);
  1991. }
  1992. void sendExternalDragAndDropEnter (const Window targetWindow)
  1993. {
  1994. XClientMessageEvent msg;
  1995. zerostruct (msg);
  1996. msg.message_type = Atoms::get().XdndEnter;
  1997. const Atom* mimeTypes = dragState.getMimeTypes();
  1998. const int numMimeTypes = dragState.getNumMimeTypes();
  1999. msg.data.l[1] = (dragState.xdndVersion << 24) | (numMimeTypes > 3);
  2000. msg.data.l[2] = numMimeTypes > 0 ? mimeTypes[0] : 0;
  2001. msg.data.l[3] = numMimeTypes > 1 ? mimeTypes[1] : 0;
  2002. msg.data.l[4] = numMimeTypes > 2 ? mimeTypes[2] : 0;
  2003. sendExternalDragAndDropMessage (msg, targetWindow);
  2004. }
  2005. void sendExternalDragAndDropPosition (const Window targetWindow)
  2006. {
  2007. XClientMessageEvent msg;
  2008. zerostruct (msg);
  2009. msg.message_type = Atoms::get().XdndPosition;
  2010. const Point<int> mousePos (Desktop::getInstance().getMousePosition());
  2011. if (dragState.silentRect.contains (mousePos)) // we've been asked to keep silent
  2012. return;
  2013. msg.data.l[1] = 0;
  2014. msg.data.l[2] = (mousePos.x << 16) | mousePos.y;
  2015. msg.data.l[3] = CurrentTime;
  2016. msg.data.l[4] = Atoms::get().XdndActionCopy; // this is all JUCE currently supports
  2017. dragState.expectingStatus = sendExternalDragAndDropMessage (msg, targetWindow);
  2018. }
  2019. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  2020. {
  2021. XClientMessageEvent msg;
  2022. zerostruct (msg);
  2023. msg.message_type = Atoms::get().XdndStatus;
  2024. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  2025. msg.data.l[4] = dropAction;
  2026. sendDragAndDropMessage (msg);
  2027. }
  2028. void sendExternalDragAndDropLeave (const Window targetWindow)
  2029. {
  2030. XClientMessageEvent msg;
  2031. zerostruct (msg);
  2032. msg.message_type = Atoms::get().XdndLeave;
  2033. sendExternalDragAndDropMessage (msg, targetWindow);
  2034. }
  2035. void sendDragAndDropFinish()
  2036. {
  2037. XClientMessageEvent msg;
  2038. zerostruct (msg);
  2039. msg.message_type = Atoms::get().XdndFinished;
  2040. sendDragAndDropMessage (msg);
  2041. }
  2042. void handleExternalSelectionClear()
  2043. {
  2044. if (dragState.dragging)
  2045. externalResetDragAndDrop();
  2046. }
  2047. void handleExternalSelectionRequest (const XEvent& evt)
  2048. {
  2049. Atom targetType = evt.xselectionrequest.target;
  2050. XEvent s;
  2051. s.xselection.type = SelectionNotify;
  2052. s.xselection.requestor = evt.xselectionrequest.requestor;
  2053. s.xselection.selection = evt.xselectionrequest.selection;
  2054. s.xselection.target = targetType;
  2055. s.xselection.property = None;
  2056. s.xselection.time = evt.xselectionrequest.time;
  2057. if (dragState.matchesTarget (targetType))
  2058. {
  2059. s.xselection.property = evt.xselectionrequest.property;
  2060. xchangeProperty (evt.xselectionrequest.requestor,
  2061. evt.xselectionrequest.property,
  2062. targetType, 8,
  2063. dragState.textOrFiles.toRawUTF8(),
  2064. dragState.textOrFiles.getNumBytesAsUTF8());
  2065. }
  2066. XSendEvent (display, evt.xselectionrequest.requestor, True, 0, &s);
  2067. }
  2068. void handleExternalDragAndDropStatus (const XClientMessageEvent& clientMsg)
  2069. {
  2070. if (dragState.expectingStatus)
  2071. {
  2072. dragState.expectingStatus = false;
  2073. dragState.canDrop = false;
  2074. dragState.silentRect = Rectangle<int>();
  2075. if ((clientMsg.data.l[1] & 1) != 0
  2076. && ((Atom) clientMsg.data.l[4] == Atoms::get().XdndActionCopy
  2077. || (Atom) clientMsg.data.l[4] == Atoms::get().XdndActionPrivate))
  2078. {
  2079. if ((clientMsg.data.l[1] & 2) == 0) // target requests silent rectangle
  2080. dragState.silentRect.setBounds (clientMsg.data.l[2] >> 16,
  2081. clientMsg.data.l[2] & 0xffff,
  2082. clientMsg.data.l[3] >> 16,
  2083. clientMsg.data.l[3] & 0xffff);
  2084. dragState.canDrop = true;
  2085. }
  2086. }
  2087. }
  2088. void handleExternalDragButtonReleaseEvent()
  2089. {
  2090. if (dragState.dragging)
  2091. XUngrabPointer (display, CurrentTime);
  2092. if (dragState.canDrop)
  2093. {
  2094. sendExternalDragAndDropDrop (dragState.targetWindow);
  2095. }
  2096. else
  2097. {
  2098. sendExternalDragAndDropLeave (dragState.targetWindow);
  2099. externalResetDragAndDrop();
  2100. }
  2101. }
  2102. void handleExternalDragMotionNotify()
  2103. {
  2104. Window targetWindow = externalFindDragTargetWindow (RootWindow (display, DefaultScreen (display)));
  2105. if (dragState.targetWindow != targetWindow)
  2106. {
  2107. if (dragState.targetWindow != None)
  2108. sendExternalDragAndDropLeave (dragState.targetWindow);
  2109. dragState.canDrop = false;
  2110. dragState.silentRect = Rectangle<int>();
  2111. if (targetWindow == None)
  2112. return;
  2113. GetXProperty prop (targetWindow, Atoms::get().XdndAware,
  2114. 0, 2, false, AnyPropertyType);
  2115. if (prop.success
  2116. && prop.data != None
  2117. && prop.actualFormat == 32
  2118. && prop.numItems == 1)
  2119. {
  2120. dragState.xdndVersion = jmin ((int) prop.data[0], (int) Atoms::DndVersion);
  2121. }
  2122. else
  2123. {
  2124. dragState.xdndVersion = -1;
  2125. return;
  2126. }
  2127. sendExternalDragAndDropEnter (targetWindow);
  2128. dragState.targetWindow = targetWindow;
  2129. }
  2130. if (! dragState.expectingStatus)
  2131. sendExternalDragAndDropPosition (targetWindow);
  2132. }
  2133. void handleDragAndDropPosition (const XClientMessageEvent& clientMsg)
  2134. {
  2135. if (dragAndDropSourceWindow == 0)
  2136. return;
  2137. dragAndDropSourceWindow = clientMsg.data.l[0];
  2138. Point<int> dropPos ((int) clientMsg.data.l[2] >> 16,
  2139. (int) clientMsg.data.l[2] & 0xffff);
  2140. dropPos -= bounds.getPosition();
  2141. const Atoms& atoms = Atoms::get();
  2142. Atom targetAction = atoms.XdndActionCopy;
  2143. for (int i = numElementsInArray (atoms.allowedActions); --i >= 0;)
  2144. {
  2145. if ((Atom) clientMsg.data.l[4] == atoms.allowedActions[i])
  2146. {
  2147. targetAction = atoms.allowedActions[i];
  2148. break;
  2149. }
  2150. }
  2151. sendDragAndDropStatus (true, targetAction);
  2152. if (dragInfo.position != dropPos)
  2153. {
  2154. dragInfo.position = dropPos;
  2155. if (dragInfo.isEmpty())
  2156. updateDraggedFileList (clientMsg);
  2157. if (! dragInfo.isEmpty())
  2158. handleDragMove (dragInfo);
  2159. }
  2160. }
  2161. void handleDragAndDropDrop (const XClientMessageEvent& clientMsg)
  2162. {
  2163. if (dragInfo.isEmpty())
  2164. {
  2165. // no data, transaction finished in handleDragAndDropSelection()
  2166. finishAfterDropDataReceived = true;
  2167. updateDraggedFileList (clientMsg);
  2168. }
  2169. else
  2170. {
  2171. handleDragAndDropDataReceived(); // data was already received
  2172. }
  2173. }
  2174. void handleDragAndDropDataReceived()
  2175. {
  2176. DragInfo dragInfoCopy (dragInfo);
  2177. sendDragAndDropFinish();
  2178. resetDragAndDrop();
  2179. if (! dragInfoCopy.isEmpty())
  2180. handleDragDrop (dragInfoCopy);
  2181. }
  2182. void handleDragAndDropEnter (const XClientMessageEvent& clientMsg)
  2183. {
  2184. dragInfo.clear();
  2185. srcMimeTypeAtomList.clear();
  2186. dragAndDropCurrentMimeType = 0;
  2187. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg.data.l[1] & 0xff000000) >> 24;
  2188. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  2189. {
  2190. dragAndDropSourceWindow = 0;
  2191. return;
  2192. }
  2193. dragAndDropSourceWindow = clientMsg.data.l[0];
  2194. if ((clientMsg.data.l[1] & 1) != 0)
  2195. {
  2196. ScopedXLock xlock;
  2197. GetXProperty prop (dragAndDropSourceWindow, Atoms::get().XdndTypeList, 0, 0x8000000L, false, XA_ATOM);
  2198. if (prop.success
  2199. && prop.actualType == XA_ATOM
  2200. && prop.actualFormat == 32
  2201. && prop.numItems != 0)
  2202. {
  2203. const unsigned long* const types = (const unsigned long*) prop.data;
  2204. for (unsigned long i = 0; i < prop.numItems; ++i)
  2205. if (types[i] != None)
  2206. srcMimeTypeAtomList.add (types[i]);
  2207. }
  2208. }
  2209. if (srcMimeTypeAtomList.size() == 0)
  2210. {
  2211. for (int i = 2; i < 5; ++i)
  2212. if (clientMsg.data.l[i] != None)
  2213. srcMimeTypeAtomList.add (clientMsg.data.l[i]);
  2214. if (srcMimeTypeAtomList.size() == 0)
  2215. {
  2216. dragAndDropSourceWindow = 0;
  2217. return;
  2218. }
  2219. }
  2220. const Atoms& atoms = Atoms::get();
  2221. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  2222. for (int j = 0; j < numElementsInArray (atoms.allowedMimeTypes); ++j)
  2223. if (srcMimeTypeAtomList[i] == atoms.allowedMimeTypes[j])
  2224. dragAndDropCurrentMimeType = atoms.allowedMimeTypes[j];
  2225. handleDragAndDropPosition (clientMsg);
  2226. }
  2227. void handleDragAndDropSelection (const XEvent& evt)
  2228. {
  2229. dragInfo.clear();
  2230. if (evt.xselection.property != None)
  2231. {
  2232. StringArray lines;
  2233. {
  2234. MemoryBlock dropData;
  2235. for (;;)
  2236. {
  2237. GetXProperty prop (evt.xany.window, evt.xselection.property,
  2238. dropData.getSize() / 4, 65536, false, AnyPropertyType);
  2239. if (! prop.success)
  2240. break;
  2241. dropData.append (prop.data, prop.numItems * prop.actualFormat / 8);
  2242. if (prop.bytesLeft <= 0)
  2243. break;
  2244. }
  2245. lines.addLines (dropData.toString());
  2246. }
  2247. if (Atoms::isMimeTypeFile (dragAndDropCurrentMimeType))
  2248. {
  2249. for (int i = 0; i < lines.size(); ++i)
  2250. dragInfo.files.add (URL::removeEscapeChars (lines[i].replace ("file://", String::empty, true)));
  2251. dragInfo.files.trim();
  2252. dragInfo.files.removeEmptyStrings();
  2253. }
  2254. else
  2255. {
  2256. dragInfo.text = lines.joinIntoString ("\n");
  2257. }
  2258. if (finishAfterDropDataReceived)
  2259. handleDragAndDropDataReceived();
  2260. }
  2261. }
  2262. void updateDraggedFileList (const XClientMessageEvent& clientMsg)
  2263. {
  2264. jassert (dragInfo.isEmpty());
  2265. if (dragAndDropSourceWindow != None
  2266. && dragAndDropCurrentMimeType != None)
  2267. {
  2268. ScopedXLock xlock;
  2269. XConvertSelection (display,
  2270. Atoms::get().XdndSelection,
  2271. dragAndDropCurrentMimeType,
  2272. Atoms::getCreating ("JXSelectionWindowProperty"),
  2273. windowH,
  2274. clientMsg.data.l[2]);
  2275. }
  2276. }
  2277. static bool isWindowDnDAware (Window w)
  2278. {
  2279. int numProperties = 0;
  2280. Atom* const atoms = XListProperties (display, w, &numProperties);
  2281. bool dndAwarePropFound = false;
  2282. for (int i = 0; i < numProperties; ++i)
  2283. if (atoms[i] == Atoms::get().XdndAware)
  2284. dndAwarePropFound = true;
  2285. if (atoms != nullptr)
  2286. XFree (atoms);
  2287. return dndAwarePropFound;
  2288. }
  2289. Window externalFindDragTargetWindow (Window targetWindow)
  2290. {
  2291. if (targetWindow == None)
  2292. return None;
  2293. if (isWindowDnDAware (targetWindow))
  2294. return targetWindow;
  2295. Window child, phonyWin;
  2296. int phony;
  2297. unsigned int uphony;
  2298. XQueryPointer (display, targetWindow, &phonyWin, &child,
  2299. &phony, &phony, &phony, &phony, &uphony);
  2300. return externalFindDragTargetWindow (child);
  2301. }
  2302. bool externalDragInit (bool isText, const String& textOrFiles)
  2303. {
  2304. ScopedXLock xlock;
  2305. resetExternalDragState();
  2306. dragState.isText = isText;
  2307. dragState.textOrFiles = textOrFiles;
  2308. dragState.targetWindow = windowH;
  2309. const int pointerGrabMask = Button1MotionMask | ButtonReleaseMask;
  2310. if (XGrabPointer (display, windowH, True, pointerGrabMask,
  2311. GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
  2312. {
  2313. // No other method of changing the pointer seems to work, this call is needed from this very context
  2314. XChangeActivePointerGrab (display, pointerGrabMask, (Cursor) createDraggingHandCursor(), CurrentTime);
  2315. const Atoms& atoms = Atoms::get();
  2316. XSetSelectionOwner (display, atoms.XdndSelection, windowH, CurrentTime);
  2317. // save the available types to XdndTypeList
  2318. xchangeProperty (windowH, atoms.XdndTypeList, XA_ATOM, 32,
  2319. dragState.getMimeTypes(),
  2320. dragState.getNumMimeTypes());
  2321. dragState.dragging = true;
  2322. handleExternalDragMotionNotify();
  2323. return true;
  2324. }
  2325. return false;
  2326. }
  2327. void externalResetDragAndDrop()
  2328. {
  2329. if (dragState.dragging)
  2330. {
  2331. ScopedXLock xlock;
  2332. XUngrabPointer (display, CurrentTime);
  2333. }
  2334. resetExternalDragState();
  2335. }
  2336. DragState dragState;
  2337. DragInfo dragInfo;
  2338. Atom dragAndDropCurrentMimeType;
  2339. Window dragAndDropSourceWindow;
  2340. bool finishAfterDropDataReceived;
  2341. Array <Atom> srcMimeTypeAtomList;
  2342. int pointerMap[5];
  2343. void initialisePointerMap()
  2344. {
  2345. const int numButtons = XGetPointerMapping (display, 0, 0);
  2346. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  2347. if (numButtons == 2)
  2348. {
  2349. pointerMap[0] = Keys::LeftButton;
  2350. pointerMap[1] = Keys::RightButton;
  2351. }
  2352. else if (numButtons >= 3)
  2353. {
  2354. pointerMap[0] = Keys::LeftButton;
  2355. pointerMap[1] = Keys::MiddleButton;
  2356. pointerMap[2] = Keys::RightButton;
  2357. if (numButtons >= 5)
  2358. {
  2359. pointerMap[3] = Keys::WheelUp;
  2360. pointerMap[4] = Keys::WheelDown;
  2361. }
  2362. }
  2363. }
  2364. static Point<int> lastMousePos;
  2365. static void clearLastMousePos() noexcept
  2366. {
  2367. lastMousePos = Point<int> (0x100000, 0x100000);
  2368. }
  2369. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
  2370. };
  2371. ModifierKeys LinuxComponentPeer::currentModifiers;
  2372. bool LinuxComponentPeer::isActiveApplication = false;
  2373. Point<int> LinuxComponentPeer::lastMousePos;
  2374. //==============================================================================
  2375. JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()
  2376. {
  2377. return LinuxComponentPeer::isActiveApplication;
  2378. }
  2379. // N/A on Linux as far as I know.
  2380. JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}
  2381. JUCE_API void JUCE_CALLTYPE Process::hide() {}
  2382. //==============================================================================
  2383. void ModifierKeys::updateCurrentModifiers() noexcept
  2384. {
  2385. currentModifiers = LinuxComponentPeer::currentModifiers;
  2386. }
  2387. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  2388. {
  2389. Window root, child;
  2390. int x, y, winx, winy;
  2391. unsigned int mask;
  2392. int mouseMods = 0;
  2393. ScopedXLock xlock;
  2394. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  2395. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  2396. {
  2397. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  2398. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  2399. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  2400. }
  2401. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  2402. return LinuxComponentPeer::currentModifiers;
  2403. }
  2404. //==============================================================================
  2405. void Desktop::setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /* allowMenusAndBars */)
  2406. {
  2407. if (enableOrDisable)
  2408. kioskModeComponent->setBounds (getDisplays().getMainDisplay().totalArea);
  2409. }
  2410. //==============================================================================
  2411. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  2412. {
  2413. return new LinuxComponentPeer (*this, styleFlags, (Window) nativeWindowToAttachTo);
  2414. }
  2415. //==============================================================================
  2416. static double getDisplayDPI (int index)
  2417. {
  2418. double dpiX = (DisplayWidth (display, index) * 25.4) / DisplayWidthMM (display, index);
  2419. double dpiY = (DisplayHeight (display, index) * 25.4) / DisplayHeightMM (display, index);
  2420. return (dpiX + dpiY) / 2.0;
  2421. }
  2422. void Desktop::Displays::findDisplays (float masterScale)
  2423. {
  2424. if (display == 0)
  2425. return;
  2426. ScopedXLock xlock;
  2427. #if JUCE_USE_XINERAMA
  2428. int major_opcode, first_event, first_error;
  2429. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  2430. {
  2431. typedef Bool (*tXineramaIsActive) (::Display*);
  2432. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (::Display*, int*);
  2433. static tXineramaIsActive xineramaIsActive = nullptr;
  2434. static tXineramaQueryScreens xineramaQueryScreens = nullptr;
  2435. if (xineramaIsActive == nullptr || xineramaQueryScreens == nullptr)
  2436. {
  2437. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  2438. if (h == nullptr)
  2439. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  2440. if (h != nullptr)
  2441. {
  2442. xineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  2443. xineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  2444. }
  2445. }
  2446. if (xineramaIsActive != nullptr
  2447. && xineramaQueryScreens != nullptr
  2448. && xineramaIsActive (display))
  2449. {
  2450. int numMonitors = 0;
  2451. if (XineramaScreenInfo* const screens = xineramaQueryScreens (display, &numMonitors))
  2452. {
  2453. for (int index = 0; index < numMonitors; ++index)
  2454. {
  2455. for (int j = numMonitors; --j >= 0;)
  2456. {
  2457. if (screens[j].screen_number == index)
  2458. {
  2459. Display d;
  2460. d.userArea = d.totalArea = Rectangle<int> (screens[j].x_org,
  2461. screens[j].y_org,
  2462. screens[j].width,
  2463. screens[j].height) * masterScale;
  2464. d.isMain = (index == 0);
  2465. d.scale = masterScale;
  2466. d.dpi = getDisplayDPI (index);
  2467. displays.add (d);
  2468. }
  2469. }
  2470. }
  2471. XFree (screens);
  2472. }
  2473. }
  2474. }
  2475. if (displays.size() == 0)
  2476. #endif
  2477. {
  2478. Atom hints = Atoms::getIfExists ("_NET_WORKAREA");
  2479. if (hints != None)
  2480. {
  2481. const int numMonitors = ScreenCount (display);
  2482. for (int i = 0; i < numMonitors; ++i)
  2483. {
  2484. GetXProperty prop (RootWindow (display, i), hints, 0, 4, false, XA_CARDINAL);
  2485. if (prop.success && prop.actualType == XA_CARDINAL && prop.actualFormat == 32 && prop.numItems == 4)
  2486. {
  2487. const long* const position = (const long*) prop.data;
  2488. Display d;
  2489. d.userArea = d.totalArea = Rectangle<int> (position[0], position[1],
  2490. position[2], position[3]) / masterScale;
  2491. d.isMain = (displays.size() == 0);
  2492. d.scale = masterScale;
  2493. d.dpi = getDisplayDPI (i);
  2494. displays.add (d);
  2495. }
  2496. }
  2497. }
  2498. if (displays.size() == 0)
  2499. {
  2500. Display d;
  2501. d.userArea = d.totalArea = Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  2502. DisplayHeight (display, DefaultScreen (display))) * masterScale;
  2503. d.isMain = true;
  2504. d.scale = masterScale;
  2505. d.dpi = getDisplayDPI (0);
  2506. displays.add (d);
  2507. }
  2508. }
  2509. }
  2510. //==============================================================================
  2511. bool MouseInputSource::SourceList::addSource()
  2512. {
  2513. if (sources.size() == 0)
  2514. {
  2515. addSource (0, true);
  2516. return true;
  2517. }
  2518. return false;
  2519. }
  2520. bool Desktop::canUseSemiTransparentWindows() noexcept
  2521. {
  2522. int matchedDepth = 0;
  2523. const int desiredDepth = 32;
  2524. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  2525. && (matchedDepth == desiredDepth);
  2526. }
  2527. Point<int> MouseInputSource::getCurrentRawMousePosition()
  2528. {
  2529. Window root, child;
  2530. int x, y, winx, winy;
  2531. unsigned int mask;
  2532. ScopedXLock xlock;
  2533. if (XQueryPointer (display,
  2534. RootWindow (display, DefaultScreen (display)),
  2535. &root, &child,
  2536. &x, &y, &winx, &winy, &mask) == False)
  2537. {
  2538. // Pointer not on the default screen
  2539. x = y = -1;
  2540. }
  2541. return Point<int> (x, y);
  2542. }
  2543. void MouseInputSource::setRawMousePosition (Point<int> newPosition)
  2544. {
  2545. ScopedXLock xlock;
  2546. Window root = RootWindow (display, DefaultScreen (display));
  2547. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  2548. }
  2549. double Desktop::getDefaultMasterScale()
  2550. {
  2551. return 1.0;
  2552. }
  2553. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  2554. {
  2555. return upright;
  2556. }
  2557. //==============================================================================
  2558. static bool screenSaverAllowed = true;
  2559. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  2560. {
  2561. if (screenSaverAllowed != isEnabled)
  2562. {
  2563. screenSaverAllowed = isEnabled;
  2564. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  2565. static tXScreenSaverSuspend xScreenSaverSuspend = nullptr;
  2566. if (xScreenSaverSuspend == nullptr)
  2567. if (void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW))
  2568. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  2569. ScopedXLock xlock;
  2570. if (xScreenSaverSuspend != nullptr)
  2571. xScreenSaverSuspend (display, ! isEnabled);
  2572. }
  2573. }
  2574. bool Desktop::isScreenSaverEnabled()
  2575. {
  2576. return screenSaverAllowed;
  2577. }
  2578. //==============================================================================
  2579. void* CustomMouseCursorInfo::create() const
  2580. {
  2581. ScopedXLock xlock;
  2582. const unsigned int imageW = image.getWidth();
  2583. const unsigned int imageH = image.getHeight();
  2584. int hotspotX = hotspot.x;
  2585. int hotspotY = hotspot.y;
  2586. #if JUCE_USE_XCURSOR
  2587. {
  2588. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  2589. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  2590. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  2591. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  2592. static tXcursorSupportsARGB xcursorSupportsARGB = nullptr;
  2593. static tXcursorImageCreate xcursorImageCreate = nullptr;
  2594. static tXcursorImageDestroy xcursorImageDestroy = nullptr;
  2595. static tXcursorImageLoadCursor xcursorImageLoadCursor = nullptr;
  2596. static bool hasBeenLoaded = false;
  2597. if (! hasBeenLoaded)
  2598. {
  2599. hasBeenLoaded = true;
  2600. if (void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW))
  2601. {
  2602. xcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  2603. xcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  2604. xcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  2605. xcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  2606. if (xcursorSupportsARGB == nullptr || xcursorImageCreate == nullptr
  2607. || xcursorImageLoadCursor == nullptr || xcursorImageDestroy == nullptr
  2608. || ! xcursorSupportsARGB (display))
  2609. xcursorSupportsARGB = nullptr;
  2610. }
  2611. }
  2612. if (xcursorSupportsARGB != nullptr)
  2613. {
  2614. if (XcursorImage* xcImage = xcursorImageCreate (imageW, imageH))
  2615. {
  2616. xcImage->xhot = hotspotX;
  2617. xcImage->yhot = hotspotY;
  2618. XcursorPixel* dest = xcImage->pixels;
  2619. for (int y = 0; y < (int) imageH; ++y)
  2620. for (int x = 0; x < (int) imageW; ++x)
  2621. *dest++ = image.getPixelAt (x, y).getARGB();
  2622. void* result = (void*) xcursorImageLoadCursor (display, xcImage);
  2623. xcursorImageDestroy (xcImage);
  2624. if (result != nullptr)
  2625. return result;
  2626. }
  2627. }
  2628. }
  2629. #endif
  2630. Window root = RootWindow (display, DefaultScreen (display));
  2631. unsigned int cursorW, cursorH;
  2632. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  2633. return nullptr;
  2634. Image im (Image::ARGB, cursorW, cursorH, true);
  2635. {
  2636. Graphics g (im);
  2637. if (imageW > cursorW || imageH > cursorH)
  2638. {
  2639. hotspotX = (hotspotX * cursorW) / imageW;
  2640. hotspotY = (hotspotY * cursorH) / imageH;
  2641. g.drawImageWithin (image, 0, 0, imageW, imageH,
  2642. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  2643. false);
  2644. }
  2645. else
  2646. {
  2647. g.drawImageAt (image, 0, 0);
  2648. }
  2649. }
  2650. const int stride = (cursorW + 7) >> 3;
  2651. HeapBlock <char> maskPlane, sourcePlane;
  2652. maskPlane.calloc (stride * cursorH);
  2653. sourcePlane.calloc (stride * cursorH);
  2654. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  2655. for (int y = cursorH; --y >= 0;)
  2656. {
  2657. for (int x = cursorW; --x >= 0;)
  2658. {
  2659. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  2660. const int offset = y * stride + (x >> 3);
  2661. const Colour c (im.getPixelAt (x, y));
  2662. if (c.getAlpha() >= 128) maskPlane[offset] |= mask;
  2663. if (c.getBrightness() >= 0.5f) sourcePlane[offset] |= mask;
  2664. }
  2665. }
  2666. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2667. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  2668. XColor white, black;
  2669. black.red = black.green = black.blue = 0;
  2670. white.red = white.green = white.blue = 0xffff;
  2671. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  2672. XFreePixmap (display, sourcePixmap);
  2673. XFreePixmap (display, maskPixmap);
  2674. return result;
  2675. }
  2676. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  2677. {
  2678. ScopedXLock xlock;
  2679. if (cursorHandle != nullptr)
  2680. XFreeCursor (display, (Cursor) cursorHandle);
  2681. }
  2682. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  2683. {
  2684. unsigned int shape;
  2685. switch (type)
  2686. {
  2687. case NormalCursor:
  2688. case ParentCursor: return None; // Use parent cursor
  2689. case NoCursor: return CustomMouseCursorInfo (Image (Image::ARGB, 16, 16, true), 0, 0).create();
  2690. case WaitCursor: shape = XC_watch; break;
  2691. case IBeamCursor: shape = XC_xterm; break;
  2692. case PointingHandCursor: shape = XC_hand2; break;
  2693. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  2694. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  2695. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  2696. case TopEdgeResizeCursor: shape = XC_top_side; break;
  2697. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  2698. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  2699. case RightEdgeResizeCursor: shape = XC_right_side; break;
  2700. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  2701. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  2702. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  2703. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  2704. case CrosshairCursor: shape = XC_crosshair; break;
  2705. case DraggingHandCursor: return createDraggingHandCursor();
  2706. case CopyingCursor:
  2707. {
  2708. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  2709. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0, 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  2710. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174, 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  2711. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  2712. const int copyCursorSize = 119;
  2713. return CustomMouseCursorInfo (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3).create();
  2714. }
  2715. default:
  2716. jassertfalse;
  2717. return None;
  2718. }
  2719. ScopedXLock xlock;
  2720. return (void*) XCreateFontCursor (display, shape);
  2721. }
  2722. void MouseCursor::showInWindow (ComponentPeer* peer) const
  2723. {
  2724. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer))
  2725. lp->showMouseCursor ((Cursor) getHandle());
  2726. }
  2727. void MouseCursor::showInAllWindows() const
  2728. {
  2729. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  2730. showInWindow (ComponentPeer::getPeer (i));
  2731. }
  2732. //==============================================================================
  2733. Image juce_createIconForFile (const File& /* file */)
  2734. {
  2735. return Image::null;
  2736. }
  2737. //==============================================================================
  2738. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  2739. {
  2740. if (files.size() == 0)
  2741. return false;
  2742. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2743. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2744. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2745. return lp->externalDragFileInit (files, canMoveFiles);
  2746. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2747. jassertfalse;
  2748. return false;
  2749. }
  2750. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  2751. {
  2752. if (text.isEmpty())
  2753. return false;
  2754. if (MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  2755. if (Component* sourceComp = draggingSource->getComponentUnderMouse())
  2756. if (LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (sourceComp->getPeer()))
  2757. return lp->externalDragTextInit (text);
  2758. // This method must be called in response to a component's mouseDown or mouseDrag event!
  2759. jassertfalse;
  2760. return false;
  2761. }
  2762. //==============================================================================
  2763. void LookAndFeel::playAlertSound()
  2764. {
  2765. std::cout << "\a" << std::flush;
  2766. }
  2767. //==============================================================================
  2768. #if JUCE_MODAL_LOOPS_PERMITTED
  2769. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  2770. const String& title, const String& message,
  2771. Component* /* associatedComponent */)
  2772. {
  2773. AlertWindow::showMessageBox (iconType, title, message);
  2774. }
  2775. #endif
  2776. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  2777. const String& title, const String& message,
  2778. Component* associatedComponent,
  2779. ModalComponentManager::Callback* callback)
  2780. {
  2781. AlertWindow::showMessageBoxAsync (iconType, title, message, String::empty, associatedComponent, callback);
  2782. }
  2783. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  2784. const String& title, const String& message,
  2785. Component* associatedComponent,
  2786. ModalComponentManager::Callback* callback)
  2787. {
  2788. return AlertWindow::showOkCancelBox (iconType, title, message, String::empty, String::empty,
  2789. associatedComponent, callback);
  2790. }
  2791. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  2792. const String& title, const String& message,
  2793. Component* associatedComponent,
  2794. ModalComponentManager::Callback* callback)
  2795. {
  2796. return AlertWindow::showYesNoCancelBox (iconType, title, message,
  2797. String::empty, String::empty, String::empty,
  2798. associatedComponent, callback);
  2799. }
  2800. //==============================================================================
  2801. const int KeyPress::spaceKey = XK_space & 0xff;
  2802. const int KeyPress::returnKey = XK_Return & 0xff;
  2803. const int KeyPress::escapeKey = XK_Escape & 0xff;
  2804. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  2805. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  2806. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  2807. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  2808. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  2809. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  2810. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  2811. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  2812. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  2813. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  2814. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  2815. const int KeyPress::tabKey = XK_Tab & 0xff;
  2816. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  2817. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  2818. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  2819. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  2820. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  2821. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  2822. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  2823. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  2824. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  2825. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  2826. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  2827. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  2828. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  2829. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  2830. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  2831. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  2832. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  2833. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  2834. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  2835. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  2836. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  2837. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  2838. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  2839. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  2840. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  2841. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  2842. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  2843. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  2844. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  2845. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  2846. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  2847. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  2848. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  2849. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  2850. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  2851. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  2852. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  2853. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;