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

juce_linux_Windowing.cpp 123KB

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