juce_linux_Windowing.cpp 124 KB

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