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_Component.cpp 97KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. Component* Component::currentlyFocusedComponent = nullptr;
  22. //==============================================================================
  23. class Component::MouseListenerList
  24. {
  25. public:
  26. MouseListenerList() noexcept {}
  27. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  28. {
  29. if (! listeners.contains (newListener))
  30. {
  31. if (wantsEventsForAllNestedChildComponents)
  32. {
  33. listeners.insert (0, newListener);
  34. ++numDeepMouseListeners;
  35. }
  36. else
  37. {
  38. listeners.add (newListener);
  39. }
  40. }
  41. }
  42. void removeListener (MouseListener* const listenerToRemove)
  43. {
  44. auto index = listeners.indexOf (listenerToRemove);
  45. if (index >= 0)
  46. {
  47. if (index < numDeepMouseListeners)
  48. --numDeepMouseListeners;
  49. listeners.remove (index);
  50. }
  51. }
  52. static void sendMouseEvent (Component& comp, Component::BailOutChecker& checker,
  53. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  54. {
  55. if (checker.shouldBailOut())
  56. return;
  57. if (auto* list = comp.mouseListeners.get())
  58. {
  59. for (int i = list->listeners.size(); --i >= 0;)
  60. {
  61. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  62. if (checker.shouldBailOut())
  63. return;
  64. i = jmin (i, list->listeners.size());
  65. }
  66. }
  67. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  68. {
  69. if (auto* list = p->mouseListeners.get())
  70. {
  71. if (list->numDeepMouseListeners > 0)
  72. {
  73. BailOutChecker2 checker2 (checker, p);
  74. for (int i = list->numDeepMouseListeners; --i >= 0;)
  75. {
  76. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  77. if (checker2.shouldBailOut())
  78. return;
  79. i = jmin (i, list->numDeepMouseListeners);
  80. }
  81. }
  82. }
  83. }
  84. }
  85. static void sendWheelEvent (Component& comp, Component::BailOutChecker& checker,
  86. const MouseEvent& e, const MouseWheelDetails& wheel)
  87. {
  88. if (auto* list = comp.mouseListeners.get())
  89. {
  90. for (int i = list->listeners.size(); --i >= 0;)
  91. {
  92. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  93. if (checker.shouldBailOut())
  94. return;
  95. i = jmin (i, list->listeners.size());
  96. }
  97. }
  98. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  99. {
  100. if (auto* list = p->mouseListeners.get())
  101. {
  102. if (list->numDeepMouseListeners > 0)
  103. {
  104. BailOutChecker2 checker2 (checker, p);
  105. for (int i = list->numDeepMouseListeners; --i >= 0;)
  106. {
  107. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  108. if (checker2.shouldBailOut())
  109. return;
  110. i = jmin (i, list->numDeepMouseListeners);
  111. }
  112. }
  113. }
  114. }
  115. }
  116. private:
  117. Array<MouseListener*> listeners;
  118. int numDeepMouseListeners = 0;
  119. struct BailOutChecker2
  120. {
  121. BailOutChecker2 (Component::BailOutChecker& boc, Component* const comp)
  122. : checker (boc), safePointer (comp)
  123. {
  124. }
  125. bool shouldBailOut() const noexcept
  126. {
  127. return checker.shouldBailOut() || safePointer == nullptr;
  128. }
  129. private:
  130. Component::BailOutChecker& checker;
  131. const WeakReference<Component> safePointer;
  132. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2)
  133. };
  134. JUCE_DECLARE_NON_COPYABLE (MouseListenerList)
  135. };
  136. //==============================================================================
  137. struct FocusRestorer
  138. {
  139. FocusRestorer() : lastFocus (Component::getCurrentlyFocusedComponent()) {}
  140. ~FocusRestorer()
  141. {
  142. if (lastFocus != nullptr
  143. && lastFocus->isShowing()
  144. && ! lastFocus->isCurrentlyBlockedByAnotherModalComponent())
  145. lastFocus->grabKeyboardFocus();
  146. }
  147. WeakReference<Component> lastFocus;
  148. JUCE_DECLARE_NON_COPYABLE (FocusRestorer)
  149. };
  150. //==============================================================================
  151. struct ScalingHelpers
  152. {
  153. template <typename PointOrRect>
  154. static PointOrRect unscaledScreenPosToScaled (float scale, PointOrRect pos) noexcept
  155. {
  156. return scale != 1.0f ? pos / scale : pos;
  157. }
  158. template <typename PointOrRect>
  159. static PointOrRect scaledScreenPosToUnscaled (float scale, PointOrRect pos) noexcept
  160. {
  161. return scale != 1.0f ? pos * scale : pos;
  162. }
  163. // For these, we need to avoid getSmallestIntegerContainer being used, which causes
  164. // judder when moving windows
  165. static Rectangle<int> unscaledScreenPosToScaled (float scale, Rectangle<int> pos) noexcept
  166. {
  167. return scale != 1.0f ? Rectangle<int> (roundToInt (pos.getX() / scale),
  168. roundToInt (pos.getY() / scale),
  169. roundToInt (pos.getWidth() / scale),
  170. roundToInt (pos.getHeight() / scale)) : pos;
  171. }
  172. static Rectangle<int> scaledScreenPosToUnscaled (float scale, Rectangle<int> pos) noexcept
  173. {
  174. return scale != 1.0f ? Rectangle<int> (roundToInt (pos.getX() * scale),
  175. roundToInt (pos.getY() * scale),
  176. roundToInt (pos.getWidth() * scale),
  177. roundToInt (pos.getHeight() * scale)) : pos;
  178. }
  179. template <typename PointOrRect>
  180. static PointOrRect unscaledScreenPosToScaled (PointOrRect pos) noexcept
  181. {
  182. return unscaledScreenPosToScaled (Desktop::getInstance().getGlobalScaleFactor(), pos);
  183. }
  184. template <typename PointOrRect>
  185. static PointOrRect scaledScreenPosToUnscaled (PointOrRect pos) noexcept
  186. {
  187. return scaledScreenPosToUnscaled (Desktop::getInstance().getGlobalScaleFactor(), pos);
  188. }
  189. template <typename PointOrRect>
  190. static PointOrRect unscaledScreenPosToScaled (const Component& comp, PointOrRect pos) noexcept
  191. {
  192. return unscaledScreenPosToScaled (comp.getDesktopScaleFactor(), pos);
  193. }
  194. template <typename PointOrRect>
  195. static PointOrRect scaledScreenPosToUnscaled (const Component& comp, PointOrRect pos) noexcept
  196. {
  197. return scaledScreenPosToUnscaled (comp.getDesktopScaleFactor(), pos);
  198. }
  199. static Point<int> addPosition (Point<int> p, const Component& c) noexcept { return p + c.getPosition(); }
  200. static Rectangle<int> addPosition (Rectangle<int> p, const Component& c) noexcept { return p + c.getPosition(); }
  201. static Point<float> addPosition (Point<float> p, const Component& c) noexcept { return p + c.getPosition().toFloat(); }
  202. static Rectangle<float> addPosition (Rectangle<float> p, const Component& c) noexcept { return p + c.getPosition().toFloat(); }
  203. static Point<int> subtractPosition (Point<int> p, const Component& c) noexcept { return p - c.getPosition(); }
  204. static Rectangle<int> subtractPosition (Rectangle<int> p, const Component& c) noexcept { return p - c.getPosition(); }
  205. static Point<float> subtractPosition (Point<float> p, const Component& c) noexcept { return p - c.getPosition().toFloat(); }
  206. static Rectangle<float> subtractPosition (Rectangle<float> p, const Component& c) noexcept { return p - c.getPosition().toFloat(); }
  207. };
  208. //==============================================================================
  209. struct Component::ComponentHelpers
  210. {
  211. #if JUCE_MODAL_LOOPS_PERMITTED
  212. static void* runModalLoopCallback (void* userData)
  213. {
  214. return (void*) (pointer_sized_int) static_cast<Component*> (userData)->runModalLoop();
  215. }
  216. #endif
  217. static Identifier getColourPropertyId (int colourId)
  218. {
  219. char reversedHex[32];
  220. char* t = reversedHex;
  221. for (unsigned int v = (unsigned int) colourId;;)
  222. {
  223. *t++ = "0123456789abcdef" [(int) (v & 15)];
  224. v >>= 4;
  225. if (v == 0)
  226. break;
  227. }
  228. char destBuffer[32];
  229. char* dest = destBuffer;
  230. memcpy (dest, "jcclr_", 6);
  231. dest += 6;
  232. while (t > reversedHex)
  233. *dest++ = *--t;
  234. *dest++ = 0;
  235. return destBuffer;
  236. }
  237. //==============================================================================
  238. static inline bool hitTest (Component& comp, Point<int> localPoint)
  239. {
  240. return isPositiveAndBelow (localPoint.x, comp.getWidth())
  241. && isPositiveAndBelow (localPoint.y, comp.getHeight())
  242. && comp.hitTest (localPoint.x, localPoint.y);
  243. }
  244. // converts an unscaled position within a peer to the local position within that peer's component
  245. template <typename PointOrRect>
  246. static PointOrRect rawPeerPositionToLocal (const Component& comp, PointOrRect pos) noexcept
  247. {
  248. if (comp.isTransformed())
  249. pos = pos.transformedBy (comp.getTransform().inverted());
  250. return ScalingHelpers::unscaledScreenPosToScaled (comp, pos);
  251. }
  252. // converts a position within a peer's component to the unscaled position within the peer
  253. template <typename PointOrRect>
  254. static PointOrRect localPositionToRawPeerPos (const Component& comp, PointOrRect pos) noexcept
  255. {
  256. if (comp.isTransformed())
  257. pos = pos.transformedBy (comp.getTransform());
  258. return ScalingHelpers::scaledScreenPosToUnscaled (comp, pos);
  259. }
  260. template <typename PointOrRect>
  261. static PointOrRect convertFromParentSpace (const Component& comp, PointOrRect pointInParentSpace)
  262. {
  263. if (comp.affineTransform != nullptr)
  264. pointInParentSpace = pointInParentSpace.transformedBy (comp.affineTransform->inverted());
  265. if (comp.isOnDesktop())
  266. {
  267. if (auto* peer = comp.getPeer())
  268. pointInParentSpace = ScalingHelpers::unscaledScreenPosToScaled
  269. (comp, peer->globalToLocal (ScalingHelpers::scaledScreenPosToUnscaled (pointInParentSpace)));
  270. else
  271. jassertfalse;
  272. }
  273. else
  274. {
  275. pointInParentSpace = ScalingHelpers::subtractPosition (pointInParentSpace, comp);
  276. }
  277. return pointInParentSpace;
  278. }
  279. template <typename PointOrRect>
  280. static PointOrRect convertToParentSpace (const Component& comp, PointOrRect pointInLocalSpace)
  281. {
  282. if (comp.isOnDesktop())
  283. {
  284. if (auto* peer = comp.getPeer())
  285. pointInLocalSpace = ScalingHelpers::unscaledScreenPosToScaled
  286. (peer->localToGlobal (ScalingHelpers::scaledScreenPosToUnscaled (comp, pointInLocalSpace)));
  287. else
  288. jassertfalse;
  289. }
  290. else
  291. {
  292. pointInLocalSpace = ScalingHelpers::addPosition (pointInLocalSpace, comp);
  293. }
  294. if (comp.affineTransform != nullptr)
  295. pointInLocalSpace = pointInLocalSpace.transformedBy (*comp.affineTransform);
  296. return pointInLocalSpace;
  297. }
  298. template <typename PointOrRect>
  299. static PointOrRect convertFromDistantParentSpace (const Component* parent, const Component& target, const PointOrRect& coordInParent)
  300. {
  301. auto* directParent = target.getParentComponent();
  302. jassert (directParent != nullptr);
  303. if (directParent == parent)
  304. return convertFromParentSpace (target, coordInParent);
  305. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  306. }
  307. template <typename PointOrRect>
  308. static PointOrRect convertCoordinate (const Component* target, const Component* source, PointOrRect p)
  309. {
  310. while (source != nullptr)
  311. {
  312. if (source == target)
  313. return p;
  314. if (source->isParentOf (target))
  315. return convertFromDistantParentSpace (source, *target, p);
  316. p = convertToParentSpace (*source, p);
  317. source = source->getParentComponent();
  318. }
  319. jassert (source == nullptr);
  320. if (target == nullptr)
  321. return p;
  322. auto* topLevelComp = target->getTopLevelComponent();
  323. p = convertFromParentSpace (*topLevelComp, p);
  324. if (topLevelComp == target)
  325. return p;
  326. return convertFromDistantParentSpace (topLevelComp, *target, p);
  327. }
  328. static bool clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int> clipRect, Point<int> delta)
  329. {
  330. bool wasClipped = false;
  331. for (int i = comp.childComponentList.size(); --i >= 0;)
  332. {
  333. auto& child = *comp.childComponentList.getUnchecked(i);
  334. if (child.isVisible() && ! child.isTransformed())
  335. {
  336. auto newClip = clipRect.getIntersection (child.boundsRelativeToParent);
  337. if (! newClip.isEmpty())
  338. {
  339. if (child.isOpaque() && child.componentTransparency == 0)
  340. {
  341. g.excludeClipRegion (newClip + delta);
  342. wasClipped = true;
  343. }
  344. else
  345. {
  346. auto childPos = child.getPosition();
  347. if (clipObscuredRegions (child, g, newClip - childPos, childPos + delta))
  348. wasClipped = true;
  349. }
  350. }
  351. }
  352. }
  353. return wasClipped;
  354. }
  355. static Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  356. {
  357. if (auto* p = comp.getParentComponent())
  358. return p->getLocalBounds();
  359. return Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  360. }
  361. static void releaseAllCachedImageResources (Component& c)
  362. {
  363. if (auto* cached = c.getCachedComponentImage())
  364. cached->releaseResources();
  365. for (auto* child : c.childComponentList)
  366. releaseAllCachedImageResources (*child);
  367. }
  368. };
  369. //==============================================================================
  370. Component::Component() noexcept
  371. : componentFlags (0)
  372. {
  373. }
  374. Component::Component (const String& name) noexcept
  375. : componentName (name), componentFlags (0)
  376. {
  377. }
  378. Component::~Component()
  379. {
  380. static_assert (sizeof (flags) <= sizeof (componentFlags), "componentFlags has too many bits!");
  381. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  382. masterReference.clear();
  383. while (childComponentList.size() > 0)
  384. removeChildComponent (childComponentList.size() - 1, false, true);
  385. if (parentComponent != nullptr)
  386. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  387. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  388. giveAwayFocus (currentlyFocusedComponent != this);
  389. if (flags.hasHeavyweightPeerFlag)
  390. removeFromDesktop();
  391. // Something has added some children to this component during its destructor! Not a smart idea!
  392. jassert (childComponentList.size() == 0);
  393. }
  394. //==============================================================================
  395. void Component::setName (const String& name)
  396. {
  397. // if component methods are being called from threads other than the message
  398. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  399. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  400. if (componentName != name)
  401. {
  402. componentName = name;
  403. if (flags.hasHeavyweightPeerFlag)
  404. if (auto* peer = getPeer())
  405. peer->setTitle (name);
  406. BailOutChecker checker (this);
  407. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  408. }
  409. }
  410. void Component::setComponentID (const String& newID)
  411. {
  412. componentID = newID;
  413. }
  414. void Component::setVisible (bool shouldBeVisible)
  415. {
  416. if (flags.visibleFlag != shouldBeVisible)
  417. {
  418. // if component methods are being called from threads other than the message
  419. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  420. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  421. const WeakReference<Component> safePointer (this);
  422. flags.visibleFlag = shouldBeVisible;
  423. if (shouldBeVisible)
  424. repaint();
  425. else
  426. repaintParent();
  427. sendFakeMouseMove();
  428. if (! shouldBeVisible)
  429. {
  430. ComponentHelpers::releaseAllCachedImageResources (*this);
  431. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  432. {
  433. if (parentComponent != nullptr)
  434. parentComponent->grabKeyboardFocus();
  435. else
  436. giveAwayFocus (true);
  437. }
  438. }
  439. if (safePointer != nullptr)
  440. {
  441. sendVisibilityChangeMessage();
  442. if (safePointer != nullptr && flags.hasHeavyweightPeerFlag)
  443. {
  444. if (auto* peer = getPeer())
  445. {
  446. peer->setVisible (shouldBeVisible);
  447. internalHierarchyChanged();
  448. }
  449. }
  450. }
  451. }
  452. }
  453. void Component::visibilityChanged() {}
  454. void Component::sendVisibilityChangeMessage()
  455. {
  456. BailOutChecker checker (this);
  457. visibilityChanged();
  458. if (! checker.shouldBailOut())
  459. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  460. }
  461. bool Component::isShowing() const
  462. {
  463. if (! flags.visibleFlag)
  464. return false;
  465. if (parentComponent != nullptr)
  466. return parentComponent->isShowing();
  467. if (auto* peer = getPeer())
  468. return ! peer->isMinimised();
  469. return false;
  470. }
  471. //==============================================================================
  472. void* Component::getWindowHandle() const
  473. {
  474. if (auto* peer = getPeer())
  475. return peer->getNativeHandle();
  476. return nullptr;
  477. }
  478. //==============================================================================
  479. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  480. {
  481. // if component methods are being called from threads other than the message
  482. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  483. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  484. if (isOpaque())
  485. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  486. else
  487. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  488. // don't use getPeer(), so that we only get the peer that's specifically
  489. // for this comp, and not for one of its parents.
  490. auto* peer = ComponentPeer::getPeerFor (this);
  491. if (peer == nullptr || styleWanted != peer->getStyleFlags())
  492. {
  493. const WeakReference<Component> safePointer (this);
  494. #if JUCE_LINUX
  495. // it's wise to give the component a non-zero size before
  496. // putting it on the desktop, as X windows get confused by this, and
  497. // a (1, 1) minimum size is enforced here.
  498. setSize (jmax (1, getWidth()),
  499. jmax (1, getHeight()));
  500. #endif
  501. auto topLeft = getScreenPosition();
  502. bool wasFullscreen = false;
  503. bool wasMinimised = false;
  504. ComponentBoundsConstrainer* currentConstrainer = nullptr;
  505. Rectangle<int> oldNonFullScreenBounds;
  506. int oldRenderingEngine = -1;
  507. if (peer != nullptr)
  508. {
  509. ScopedPointer<ComponentPeer> oldPeerToDelete (peer);
  510. wasFullscreen = peer->isFullScreen();
  511. wasMinimised = peer->isMinimised();
  512. currentConstrainer = peer->getConstrainer();
  513. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  514. oldRenderingEngine = peer->getCurrentRenderingEngine();
  515. flags.hasHeavyweightPeerFlag = false;
  516. Desktop::getInstance().removeDesktopComponent (this);
  517. internalHierarchyChanged(); // give comps a chance to react to the peer change before the old peer is deleted.
  518. if (safePointer == nullptr)
  519. return;
  520. setTopLeftPosition (topLeft);
  521. }
  522. if (parentComponent != nullptr)
  523. parentComponent->removeChildComponent (this);
  524. if (safePointer != nullptr)
  525. {
  526. flags.hasHeavyweightPeerFlag = true;
  527. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  528. Desktop::getInstance().addDesktopComponent (this);
  529. boundsRelativeToParent.setPosition (topLeft);
  530. peer->updateBounds();
  531. if (oldRenderingEngine >= 0)
  532. peer->setCurrentRenderingEngine (oldRenderingEngine);
  533. peer->setVisible (isVisible());
  534. peer = ComponentPeer::getPeerFor (this);
  535. if (peer == nullptr)
  536. return;
  537. if (wasFullscreen)
  538. {
  539. peer->setFullScreen (true);
  540. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  541. }
  542. if (wasMinimised)
  543. peer->setMinimised (true);
  544. #if JUCE_WINDOWS
  545. if (isAlwaysOnTop())
  546. peer->setAlwaysOnTop (true);
  547. #endif
  548. peer->setConstrainer (currentConstrainer);
  549. repaint();
  550. internalHierarchyChanged();
  551. }
  552. }
  553. }
  554. void Component::removeFromDesktop()
  555. {
  556. // if component methods are being called from threads other than the message
  557. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  558. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  559. if (flags.hasHeavyweightPeerFlag)
  560. {
  561. auto* peer = ComponentPeer::getPeerFor (this);
  562. jassert (peer != nullptr);
  563. flags.hasHeavyweightPeerFlag = false;
  564. delete peer;
  565. Desktop::getInstance().removeDesktopComponent (this);
  566. }
  567. }
  568. bool Component::isOnDesktop() const noexcept
  569. {
  570. return flags.hasHeavyweightPeerFlag;
  571. }
  572. ComponentPeer* Component::getPeer() const
  573. {
  574. if (flags.hasHeavyweightPeerFlag)
  575. return ComponentPeer::getPeerFor (this);
  576. if (parentComponent == nullptr)
  577. return nullptr;
  578. return parentComponent->getPeer();
  579. }
  580. void Component::userTriedToCloseWindow()
  581. {
  582. /* This means that the user's trying to get rid of your window with the 'close window' system
  583. menu option (on windows) or possibly the task manager - you should really handle this
  584. and delete or hide your component in an appropriate way.
  585. If you want to ignore the event and don't want to trigger this assertion, just override
  586. this method and do nothing.
  587. */
  588. jassertfalse;
  589. }
  590. void Component::minimisationStateChanged (bool) {}
  591. float Component::getDesktopScaleFactor() const { return Desktop::getInstance().getGlobalScaleFactor(); }
  592. //==============================================================================
  593. void Component::setOpaque (const bool shouldBeOpaque)
  594. {
  595. if (shouldBeOpaque != flags.opaqueFlag)
  596. {
  597. flags.opaqueFlag = shouldBeOpaque;
  598. if (flags.hasHeavyweightPeerFlag)
  599. if (auto* peer = ComponentPeer::getPeerFor (this))
  600. addToDesktop (peer->getStyleFlags()); // recreates the heavyweight window
  601. repaint();
  602. }
  603. }
  604. bool Component::isOpaque() const noexcept
  605. {
  606. return flags.opaqueFlag;
  607. }
  608. //==============================================================================
  609. class StandardCachedComponentImage : public CachedComponentImage
  610. {
  611. public:
  612. StandardCachedComponentImage (Component& c) noexcept : owner (c), scale (1.0f) {}
  613. void paint (Graphics& g) override
  614. {
  615. scale = g.getInternalContext().getPhysicalPixelScaleFactor();
  616. auto compBounds = owner.getLocalBounds();
  617. auto imageBounds = compBounds * scale;
  618. if (image.isNull() || image.getBounds() != imageBounds)
  619. {
  620. image = Image (owner.isOpaque() ? Image::RGB
  621. : Image::ARGB,
  622. jmax (1, imageBounds.getWidth()),
  623. jmax (1, imageBounds.getHeight()),
  624. ! owner.isOpaque());
  625. validArea.clear();
  626. }
  627. if (! validArea.containsRectangle (compBounds))
  628. {
  629. Graphics imG (image);
  630. auto& lg = imG.getInternalContext();
  631. lg.addTransform (AffineTransform::scale (scale));
  632. for (auto& i : validArea)
  633. lg.excludeClipRectangle (i);
  634. if (! owner.isOpaque())
  635. {
  636. lg.setFill (Colours::transparentBlack);
  637. lg.fillRect (compBounds, true);
  638. lg.setFill (Colours::black);
  639. }
  640. owner.paintEntireComponent (imG, true);
  641. }
  642. validArea = compBounds;
  643. g.setColour (Colours::black.withAlpha (owner.getAlpha()));
  644. g.drawImageTransformed (image, AffineTransform::scale (compBounds.getWidth() / (float) imageBounds.getWidth(),
  645. compBounds.getHeight() / (float) imageBounds.getHeight()), false);
  646. }
  647. bool invalidateAll() override { validArea.clear(); return true; }
  648. bool invalidate (const Rectangle<int>& area) override { validArea.subtract (area); return true; }
  649. void releaseResources() override { image = Image(); }
  650. private:
  651. Image image;
  652. RectangleList<int> validArea;
  653. Component& owner;
  654. float scale;
  655. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StandardCachedComponentImage)
  656. };
  657. void Component::setCachedComponentImage (CachedComponentImage* newCachedImage)
  658. {
  659. if (cachedImage != newCachedImage)
  660. {
  661. cachedImage = newCachedImage;
  662. repaint();
  663. }
  664. }
  665. void Component::setBufferedToImage (const bool shouldBeBuffered)
  666. {
  667. // This assertion means that this component is already using a custom CachedComponentImage,
  668. // so by calling setBufferedToImage, you'll be deleting the custom one - this is almost certainly
  669. // not what you wanted to happen... If you really do know what you're doing here, and want to
  670. // avoid this assertion, just call setCachedComponentImage (nullptr) before setBufferedToImage().
  671. jassert (cachedImage == nullptr || dynamic_cast<StandardCachedComponentImage*> (cachedImage.get()) != nullptr);
  672. if (shouldBeBuffered)
  673. {
  674. if (cachedImage == nullptr)
  675. cachedImage = new StandardCachedComponentImage (*this);
  676. }
  677. else
  678. {
  679. cachedImage = nullptr;
  680. }
  681. }
  682. //==============================================================================
  683. void Component::reorderChildInternal (const int sourceIndex, const int destIndex)
  684. {
  685. if (sourceIndex != destIndex)
  686. {
  687. auto* c = childComponentList.getUnchecked (sourceIndex);
  688. jassert (c != nullptr);
  689. c->repaintParent();
  690. childComponentList.move (sourceIndex, destIndex);
  691. sendFakeMouseMove();
  692. internalChildrenChanged();
  693. }
  694. }
  695. void Component::toFront (const bool setAsForeground)
  696. {
  697. // if component methods are being called from threads other than the message
  698. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  699. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  700. if (flags.hasHeavyweightPeerFlag)
  701. {
  702. if (auto* peer = getPeer())
  703. {
  704. peer->toFront (setAsForeground);
  705. if (setAsForeground && ! hasKeyboardFocus (true))
  706. grabKeyboardFocus();
  707. }
  708. }
  709. else if (parentComponent != nullptr)
  710. {
  711. auto& childList = parentComponent->childComponentList;
  712. if (childList.getLast() != this)
  713. {
  714. auto index = childList.indexOf (this);
  715. if (index >= 0)
  716. {
  717. int insertIndex = -1;
  718. if (! flags.alwaysOnTopFlag)
  719. {
  720. insertIndex = childList.size() - 1;
  721. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  722. --insertIndex;
  723. }
  724. parentComponent->reorderChildInternal (index, insertIndex);
  725. }
  726. }
  727. if (setAsForeground)
  728. {
  729. internalBroughtToFront();
  730. if (isShowing())
  731. grabKeyboardFocus();
  732. }
  733. }
  734. }
  735. void Component::toBehind (Component* const other)
  736. {
  737. if (other != nullptr && other != this)
  738. {
  739. // the two components must belong to the same parent..
  740. jassert (parentComponent == other->parentComponent);
  741. if (parentComponent != nullptr)
  742. {
  743. auto& childList = parentComponent->childComponentList;
  744. auto index = childList.indexOf (this);
  745. if (index >= 0 && childList [index + 1] != other)
  746. {
  747. int otherIndex = childList.indexOf (other);
  748. if (otherIndex >= 0)
  749. {
  750. if (index < otherIndex)
  751. --otherIndex;
  752. parentComponent->reorderChildInternal (index, otherIndex);
  753. }
  754. }
  755. }
  756. else if (isOnDesktop())
  757. {
  758. jassert (other->isOnDesktop());
  759. if (other->isOnDesktop())
  760. {
  761. auto* us = getPeer();
  762. auto* them = other->getPeer();
  763. jassert (us != nullptr && them != nullptr);
  764. if (us != nullptr && them != nullptr)
  765. us->toBehind (them);
  766. }
  767. }
  768. }
  769. }
  770. void Component::toBack()
  771. {
  772. if (isOnDesktop())
  773. {
  774. jassertfalse; //xxx need to add this to native window
  775. }
  776. else if (parentComponent != nullptr)
  777. {
  778. auto& childList = parentComponent->childComponentList;
  779. if (childList.getFirst() != this)
  780. {
  781. auto index = childList.indexOf (this);
  782. if (index > 0)
  783. {
  784. int insertIndex = 0;
  785. if (flags.alwaysOnTopFlag)
  786. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  787. ++insertIndex;
  788. parentComponent->reorderChildInternal (index, insertIndex);
  789. }
  790. }
  791. }
  792. }
  793. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  794. {
  795. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  796. {
  797. BailOutChecker checker (this);
  798. flags.alwaysOnTopFlag = shouldStayOnTop;
  799. if (isOnDesktop())
  800. {
  801. if (auto* peer = getPeer())
  802. {
  803. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  804. {
  805. // some kinds of peer can't change their always-on-top status, so
  806. // for these, we'll need to create a new window
  807. auto oldFlags = peer->getStyleFlags();
  808. removeFromDesktop();
  809. addToDesktop (oldFlags);
  810. }
  811. }
  812. }
  813. if (shouldStayOnTop && ! checker.shouldBailOut())
  814. toFront (false);
  815. if (! checker.shouldBailOut())
  816. internalHierarchyChanged();
  817. }
  818. }
  819. bool Component::isAlwaysOnTop() const noexcept
  820. {
  821. return flags.alwaysOnTopFlag;
  822. }
  823. //==============================================================================
  824. int Component::proportionOfWidth (const float proportion) const noexcept { return roundToInt (proportion * boundsRelativeToParent.getWidth()); }
  825. int Component::proportionOfHeight (const float proportion) const noexcept { return roundToInt (proportion * boundsRelativeToParent.getHeight()); }
  826. int Component::getParentWidth() const noexcept
  827. {
  828. return parentComponent != nullptr ? parentComponent->getWidth()
  829. : getParentMonitorArea().getWidth();
  830. }
  831. int Component::getParentHeight() const noexcept
  832. {
  833. return parentComponent != nullptr ? parentComponent->getHeight()
  834. : getParentMonitorArea().getHeight();
  835. }
  836. int Component::getScreenX() const { return getScreenPosition().x; }
  837. int Component::getScreenY() const { return getScreenPosition().y; }
  838. Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  839. Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  840. Rectangle<int> Component::getParentMonitorArea() const
  841. {
  842. return Desktop::getInstance().getDisplays().getDisplayContaining (getScreenBounds().getCentre()).userArea;
  843. }
  844. Point<int> Component::getLocalPoint (const Component* source, Point<int> point) const
  845. {
  846. return ComponentHelpers::convertCoordinate (this, source, point);
  847. }
  848. Point<float> Component::getLocalPoint (const Component* source, Point<float> point) const
  849. {
  850. return ComponentHelpers::convertCoordinate (this, source, point);
  851. }
  852. Rectangle<int> Component::getLocalArea (const Component* source, Rectangle<int> area) const
  853. {
  854. return ComponentHelpers::convertCoordinate (this, source, area);
  855. }
  856. Point<int> Component::localPointToGlobal (Point<int> point) const
  857. {
  858. return ComponentHelpers::convertCoordinate (nullptr, this, point);
  859. }
  860. Point<float> Component::localPointToGlobal (Point<float> point) const
  861. {
  862. return ComponentHelpers::convertCoordinate (nullptr, this, point);
  863. }
  864. Rectangle<int> Component::localAreaToGlobal (Rectangle<int> area) const
  865. {
  866. return ComponentHelpers::convertCoordinate (nullptr, this, area);
  867. }
  868. // Deprecated methods...
  869. Point<int> Component::relativePositionToGlobal (Point<int> relativePosition) const
  870. {
  871. return localPointToGlobal (relativePosition);
  872. }
  873. Point<int> Component::globalPositionToRelative (Point<int> screenPosition) const
  874. {
  875. return getLocalPoint (nullptr, screenPosition);
  876. }
  877. Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, Point<int> positionRelativeToThis) const
  878. {
  879. return targetComponent == nullptr ? localPointToGlobal (positionRelativeToThis)
  880. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  881. }
  882. //==============================================================================
  883. void Component::setBounds (const int x, const int y, int w, int h)
  884. {
  885. // if component methods are being called from threads other than the message
  886. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  887. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  888. if (w < 0) w = 0;
  889. if (h < 0) h = 0;
  890. const bool wasResized = (getWidth() != w || getHeight() != h);
  891. const bool wasMoved = (getX() != x || getY() != y);
  892. #if JUCE_DEBUG
  893. // It's a very bad idea to try to resize a window during its paint() method!
  894. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  895. #endif
  896. if (wasMoved || wasResized)
  897. {
  898. const bool showing = isShowing();
  899. if (showing)
  900. {
  901. // send a fake mouse move to trigger enter/exit messages if needed..
  902. sendFakeMouseMove();
  903. if (! flags.hasHeavyweightPeerFlag)
  904. repaintParent();
  905. }
  906. boundsRelativeToParent.setBounds (x, y, w, h);
  907. if (showing)
  908. {
  909. if (wasResized)
  910. repaint();
  911. else if (! flags.hasHeavyweightPeerFlag)
  912. repaintParent();
  913. }
  914. else if (cachedImage != nullptr)
  915. {
  916. cachedImage->invalidateAll();
  917. }
  918. flags.isMoveCallbackPending = wasMoved;
  919. flags.isResizeCallbackPending = wasResized;
  920. if (flags.hasHeavyweightPeerFlag)
  921. if (auto* peer = getPeer())
  922. peer->updateBounds();
  923. sendMovedResizedMessagesIfPending();
  924. }
  925. }
  926. void Component::sendMovedResizedMessagesIfPending()
  927. {
  928. const bool wasMoved = flags.isMoveCallbackPending;
  929. const bool wasResized = flags.isResizeCallbackPending;
  930. if (wasMoved || wasResized)
  931. {
  932. flags.isMoveCallbackPending = false;
  933. flags.isResizeCallbackPending = false;
  934. sendMovedResizedMessages (wasMoved, wasResized);
  935. }
  936. }
  937. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  938. {
  939. BailOutChecker checker (this);
  940. if (wasMoved)
  941. {
  942. moved();
  943. if (checker.shouldBailOut())
  944. return;
  945. }
  946. if (wasResized)
  947. {
  948. resized();
  949. if (checker.shouldBailOut())
  950. return;
  951. for (int i = childComponentList.size(); --i >= 0;)
  952. {
  953. childComponentList.getUnchecked(i)->parentSizeChanged();
  954. if (checker.shouldBailOut())
  955. return;
  956. i = jmin (i, childComponentList.size());
  957. }
  958. }
  959. if (parentComponent != nullptr)
  960. parentComponent->childBoundsChanged (this);
  961. if (! checker.shouldBailOut())
  962. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  963. *this, wasMoved, wasResized);
  964. }
  965. void Component::setSize (int w, int h)
  966. {
  967. setBounds (getX(), getY(), w, h);
  968. }
  969. void Component::setTopLeftPosition (int x, int y)
  970. {
  971. setBounds (x, y, getWidth(), getHeight());
  972. }
  973. void Component::setTopLeftPosition (Point<int> pos)
  974. {
  975. setBounds (pos.x, pos.y, getWidth(), getHeight());
  976. }
  977. void Component::setTopRightPosition (const int x, const int y)
  978. {
  979. setTopLeftPosition (x - getWidth(), y);
  980. }
  981. void Component::setBounds (Rectangle<int> r)
  982. {
  983. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  984. }
  985. void Component::setBounds (const RelativeRectangle& newBounds)
  986. {
  987. newBounds.applyToComponent (*this);
  988. }
  989. void Component::setBounds (const String& newBoundsExpression)
  990. {
  991. RelativeRectangle (newBoundsExpression).applyToComponent (*this);
  992. }
  993. void Component::setBoundsRelative (const float x, const float y,
  994. const float w, const float h)
  995. {
  996. auto pw = getParentWidth();
  997. auto ph = getParentHeight();
  998. setBounds (roundToInt (x * pw),
  999. roundToInt (y * ph),
  1000. roundToInt (w * pw),
  1001. roundToInt (h * ph));
  1002. }
  1003. void Component::setCentrePosition (Point<int> p) { setBounds (getBounds().withCentre (p)); }
  1004. void Component::setCentrePosition (int x, int y) { setCentrePosition ({x, y}); }
  1005. void Component::setCentreRelative (float x, float y)
  1006. {
  1007. setCentrePosition (roundToInt (getParentWidth() * x),
  1008. roundToInt (getParentHeight() * y));
  1009. }
  1010. void Component::centreWithSize (const int width, const int height)
  1011. {
  1012. auto parentArea = ComponentHelpers::getParentOrMainMonitorBounds (*this);
  1013. setBounds (parentArea.getCentreX() - width / 2,
  1014. parentArea.getCentreY() - height / 2,
  1015. width, height);
  1016. }
  1017. void Component::setBoundsInset (BorderSize<int> borders)
  1018. {
  1019. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  1020. }
  1021. void Component::setBoundsToFit (int x, int y, int width, int height,
  1022. Justification justification,
  1023. const bool onlyReduceInSize)
  1024. {
  1025. // it's no good calling this method unless both the component and
  1026. // target rectangle have a finite size.
  1027. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  1028. if (getWidth() > 0 && getHeight() > 0
  1029. && width > 0 && height > 0)
  1030. {
  1031. int newW, newH;
  1032. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  1033. {
  1034. newW = getWidth();
  1035. newH = getHeight();
  1036. }
  1037. else
  1038. {
  1039. const double imageRatio = getHeight() / (double) getWidth();
  1040. const double targetRatio = height / (double) width;
  1041. if (imageRatio <= targetRatio)
  1042. {
  1043. newW = width;
  1044. newH = jmin (height, roundToInt (newW * imageRatio));
  1045. }
  1046. else
  1047. {
  1048. newH = height;
  1049. newW = jmin (width, roundToInt (newH / imageRatio));
  1050. }
  1051. }
  1052. if (newW > 0 && newH > 0)
  1053. setBounds (justification.appliedToRectangle (Rectangle<int> (newW, newH),
  1054. Rectangle<int> (x, y, width, height)));
  1055. }
  1056. }
  1057. //==============================================================================
  1058. void Component::setTransform (const AffineTransform& newTransform)
  1059. {
  1060. // If you pass in a transform with no inverse, the component will have no dimensions,
  1061. // and there will be all sorts of maths errors when converting coordinates.
  1062. jassert (! newTransform.isSingularity());
  1063. if (newTransform.isIdentity())
  1064. {
  1065. if (affineTransform != nullptr)
  1066. {
  1067. repaint();
  1068. affineTransform = nullptr;
  1069. repaint();
  1070. sendMovedResizedMessages (false, false);
  1071. }
  1072. }
  1073. else if (affineTransform == nullptr)
  1074. {
  1075. repaint();
  1076. affineTransform = new AffineTransform (newTransform);
  1077. repaint();
  1078. sendMovedResizedMessages (false, false);
  1079. }
  1080. else if (*affineTransform != newTransform)
  1081. {
  1082. repaint();
  1083. *affineTransform = newTransform;
  1084. repaint();
  1085. sendMovedResizedMessages (false, false);
  1086. }
  1087. }
  1088. bool Component::isTransformed() const noexcept
  1089. {
  1090. return affineTransform != nullptr;
  1091. }
  1092. AffineTransform Component::getTransform() const
  1093. {
  1094. return affineTransform != nullptr ? *affineTransform : AffineTransform();
  1095. }
  1096. //==============================================================================
  1097. bool Component::hitTest (int x, int y)
  1098. {
  1099. if (! flags.ignoresMouseClicksFlag)
  1100. return true;
  1101. if (flags.allowChildMouseClicksFlag)
  1102. {
  1103. for (int i = childComponentList.size(); --i >= 0;)
  1104. {
  1105. auto& child = *childComponentList.getUnchecked (i);
  1106. if (child.isVisible()
  1107. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  1108. return true;
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. void Component::setInterceptsMouseClicks (const bool allowClicks,
  1114. const bool allowClicksOnChildComponents) noexcept
  1115. {
  1116. flags.ignoresMouseClicksFlag = ! allowClicks;
  1117. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  1118. }
  1119. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  1120. bool& allowsClicksOnChildComponents) const noexcept
  1121. {
  1122. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  1123. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  1124. }
  1125. bool Component::contains (Point<int> point)
  1126. {
  1127. if (ComponentHelpers::hitTest (*this, point))
  1128. {
  1129. if (parentComponent != nullptr)
  1130. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  1131. if (flags.hasHeavyweightPeerFlag)
  1132. if (auto* peer = getPeer())
  1133. return peer->contains (ComponentHelpers::localPositionToRawPeerPos (*this, point), true);
  1134. }
  1135. return false;
  1136. }
  1137. bool Component::reallyContains (Point<int> point, const bool returnTrueIfWithinAChild)
  1138. {
  1139. if (! contains (point))
  1140. return false;
  1141. auto* top = getTopLevelComponent();
  1142. auto* compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  1143. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  1144. }
  1145. Component* Component::getComponentAt (Point<int> position)
  1146. {
  1147. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  1148. {
  1149. for (int i = childComponentList.size(); --i >= 0;)
  1150. {
  1151. auto* child = childComponentList.getUnchecked(i);
  1152. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  1153. if (child != nullptr)
  1154. return child;
  1155. }
  1156. return this;
  1157. }
  1158. return nullptr;
  1159. }
  1160. Component* Component::getComponentAt (const int x, const int y)
  1161. {
  1162. return getComponentAt ({ x, y });
  1163. }
  1164. //==============================================================================
  1165. void Component::addChildComponent (Component& child, int zOrder)
  1166. {
  1167. // if component methods are being called from threads other than the message
  1168. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1169. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1170. if (child.parentComponent != this)
  1171. {
  1172. if (child.parentComponent != nullptr)
  1173. child.parentComponent->removeChildComponent (&child);
  1174. else
  1175. child.removeFromDesktop();
  1176. child.parentComponent = this;
  1177. if (child.isVisible())
  1178. child.repaintParent();
  1179. if (! child.isAlwaysOnTop())
  1180. {
  1181. if (zOrder < 0 || zOrder > childComponentList.size())
  1182. zOrder = childComponentList.size();
  1183. while (zOrder > 0)
  1184. {
  1185. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  1186. break;
  1187. --zOrder;
  1188. }
  1189. }
  1190. childComponentList.insert (zOrder, &child);
  1191. child.internalHierarchyChanged();
  1192. internalChildrenChanged();
  1193. }
  1194. }
  1195. void Component::addAndMakeVisible (Component& child, int zOrder)
  1196. {
  1197. child.setVisible (true);
  1198. addChildComponent (child, zOrder);
  1199. }
  1200. void Component::addChildComponent (Component* const child, int zOrder)
  1201. {
  1202. if (child != nullptr)
  1203. addChildComponent (*child, zOrder);
  1204. }
  1205. void Component::addAndMakeVisible (Component* const child, int zOrder)
  1206. {
  1207. if (child != nullptr)
  1208. addAndMakeVisible (*child, zOrder);
  1209. }
  1210. void Component::addChildAndSetID (Component* const child, const String& childID)
  1211. {
  1212. if (child != nullptr)
  1213. {
  1214. child->setComponentID (childID);
  1215. addAndMakeVisible (child);
  1216. }
  1217. }
  1218. void Component::removeChildComponent (Component* const child)
  1219. {
  1220. removeChildComponent (childComponentList.indexOf (child), true, true);
  1221. }
  1222. Component* Component::removeChildComponent (const int index)
  1223. {
  1224. return removeChildComponent (index, true, true);
  1225. }
  1226. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1227. {
  1228. // if component methods are being called from threads other than the message
  1229. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1230. ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1231. auto* child = childComponentList [index];
  1232. if (child != nullptr)
  1233. {
  1234. sendParentEvents = sendParentEvents && child->isShowing();
  1235. if (sendParentEvents)
  1236. {
  1237. sendFakeMouseMove();
  1238. if (child->isVisible())
  1239. child->repaintParent();
  1240. }
  1241. childComponentList.remove (index);
  1242. child->parentComponent = nullptr;
  1243. ComponentHelpers::releaseAllCachedImageResources (*child);
  1244. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1245. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1246. {
  1247. if (sendParentEvents)
  1248. {
  1249. const WeakReference<Component> thisPointer (this);
  1250. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1251. if (thisPointer == nullptr)
  1252. return child;
  1253. grabKeyboardFocus();
  1254. }
  1255. else
  1256. {
  1257. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1258. }
  1259. }
  1260. if (sendChildEvents)
  1261. child->internalHierarchyChanged();
  1262. if (sendParentEvents)
  1263. internalChildrenChanged();
  1264. }
  1265. return child;
  1266. }
  1267. //==============================================================================
  1268. void Component::removeAllChildren()
  1269. {
  1270. while (childComponentList.size() > 0)
  1271. removeChildComponent (childComponentList.size() - 1);
  1272. }
  1273. void Component::deleteAllChildren()
  1274. {
  1275. while (childComponentList.size() > 0)
  1276. delete (removeChildComponent (childComponentList.size() - 1));
  1277. }
  1278. int Component::getNumChildComponents() const noexcept
  1279. {
  1280. return childComponentList.size();
  1281. }
  1282. Component* Component::getChildComponent (const int index) const noexcept
  1283. {
  1284. return childComponentList[index];
  1285. }
  1286. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1287. {
  1288. return childComponentList.indexOf (const_cast<Component*> (child));
  1289. }
  1290. Component* Component::findChildWithID (StringRef targetID) const noexcept
  1291. {
  1292. for (auto* c : childComponentList)
  1293. if (c->componentID == targetID)
  1294. return c;
  1295. return nullptr;
  1296. }
  1297. Component* Component::getTopLevelComponent() const noexcept
  1298. {
  1299. const Component* comp = this;
  1300. while (comp->parentComponent != nullptr)
  1301. comp = comp->parentComponent;
  1302. return const_cast<Component*> (comp);
  1303. }
  1304. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1305. {
  1306. while (possibleChild != nullptr)
  1307. {
  1308. possibleChild = possibleChild->parentComponent;
  1309. if (possibleChild == this)
  1310. return true;
  1311. }
  1312. return false;
  1313. }
  1314. //==============================================================================
  1315. void Component::parentHierarchyChanged() {}
  1316. void Component::childrenChanged() {}
  1317. void Component::internalChildrenChanged()
  1318. {
  1319. if (componentListeners.isEmpty())
  1320. {
  1321. childrenChanged();
  1322. }
  1323. else
  1324. {
  1325. BailOutChecker checker (this);
  1326. childrenChanged();
  1327. if (! checker.shouldBailOut())
  1328. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1329. }
  1330. }
  1331. void Component::internalHierarchyChanged()
  1332. {
  1333. BailOutChecker checker (this);
  1334. parentHierarchyChanged();
  1335. if (checker.shouldBailOut())
  1336. return;
  1337. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1338. if (checker.shouldBailOut())
  1339. return;
  1340. for (int i = childComponentList.size(); --i >= 0;)
  1341. {
  1342. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1343. if (checker.shouldBailOut())
  1344. {
  1345. // you really shouldn't delete the parent component during a callback telling you
  1346. // that it's changed..
  1347. jassertfalse;
  1348. return;
  1349. }
  1350. i = jmin (i, childComponentList.size());
  1351. }
  1352. }
  1353. //==============================================================================
  1354. #if JUCE_MODAL_LOOPS_PERMITTED
  1355. int Component::runModalLoop()
  1356. {
  1357. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1358. {
  1359. // use a callback so this can be called from non-gui threads
  1360. return (int) (pointer_sized_int) MessageManager::getInstance()
  1361. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1362. }
  1363. if (! isCurrentlyModal (false))
  1364. enterModalState (true);
  1365. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1366. }
  1367. #endif
  1368. //==============================================================================
  1369. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1370. ModalComponentManager::Callback* callback,
  1371. const bool deleteWhenDismissed)
  1372. {
  1373. // if component methods are being called from threads other than the message
  1374. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1375. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1376. if (! isCurrentlyModal (false))
  1377. {
  1378. auto& mcm = *ModalComponentManager::getInstance();
  1379. mcm.startModal (this, deleteWhenDismissed);
  1380. mcm.attachCallback (this, callback);
  1381. setVisible (true);
  1382. if (shouldTakeKeyboardFocus)
  1383. grabKeyboardFocus();
  1384. }
  1385. else
  1386. {
  1387. // Probably a bad idea to try to make a component modal twice!
  1388. jassertfalse;
  1389. }
  1390. }
  1391. void Component::exitModalState (const int returnValue)
  1392. {
  1393. if (isCurrentlyModal (false))
  1394. {
  1395. if (MessageManager::getInstance()->isThisTheMessageThread())
  1396. {
  1397. auto& mcm = *ModalComponentManager::getInstance();
  1398. mcm.endModal (this, returnValue);
  1399. mcm.bringModalComponentsToFront();
  1400. // If any of the mouse sources are over another Component when we exit the modal state then send a mouse enter event
  1401. for (auto& ms : Desktop::getInstance().getMouseSources())
  1402. if (auto* c = ms.getComponentUnderMouse())
  1403. c->internalMouseEnter (ms, ms.getScreenPosition(), Time::getCurrentTime());
  1404. }
  1405. else
  1406. {
  1407. WeakReference<Component> target (this);
  1408. MessageManager::callAsync ([=]()
  1409. {
  1410. if (auto* c = target.get())
  1411. c->exitModalState (returnValue);
  1412. });
  1413. }
  1414. }
  1415. }
  1416. bool Component::isCurrentlyModal (bool onlyConsiderForemostModalComponent) const noexcept
  1417. {
  1418. const int n = onlyConsiderForemostModalComponent ? 1 : getNumCurrentlyModalComponents();
  1419. for (int i = 0; i < n; ++i)
  1420. if (getCurrentlyModalComponent(i) == this)
  1421. return true;
  1422. return false;
  1423. }
  1424. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1425. {
  1426. auto* mc = getCurrentlyModalComponent();
  1427. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1428. || mc->canModalEventBeSentToComponent (this));
  1429. }
  1430. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1431. {
  1432. return ModalComponentManager::getInstance()->getNumModalComponents();
  1433. }
  1434. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1435. {
  1436. return ModalComponentManager::getInstance()->getModalComponent (index);
  1437. }
  1438. //==============================================================================
  1439. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1440. {
  1441. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1442. }
  1443. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1444. {
  1445. return flags.bringToFrontOnClickFlag;
  1446. }
  1447. //==============================================================================
  1448. void Component::setMouseCursor (const MouseCursor& newCursor)
  1449. {
  1450. if (cursor != newCursor)
  1451. {
  1452. cursor = newCursor;
  1453. if (flags.visibleFlag)
  1454. updateMouseCursor();
  1455. }
  1456. }
  1457. MouseCursor Component::getMouseCursor()
  1458. {
  1459. return cursor;
  1460. }
  1461. void Component::updateMouseCursor() const
  1462. {
  1463. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1464. }
  1465. //==============================================================================
  1466. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1467. {
  1468. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1469. }
  1470. //==============================================================================
  1471. float Component::getAlpha() const noexcept
  1472. {
  1473. return (255 - componentTransparency) / 255.0f;
  1474. }
  1475. void Component::setAlpha (const float newAlpha)
  1476. {
  1477. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1478. if (componentTransparency != newIntAlpha)
  1479. {
  1480. componentTransparency = newIntAlpha;
  1481. alphaChanged();
  1482. }
  1483. }
  1484. void Component::alphaChanged()
  1485. {
  1486. if (flags.hasHeavyweightPeerFlag)
  1487. {
  1488. if (auto* peer = getPeer())
  1489. peer->setAlpha (getAlpha());
  1490. }
  1491. else
  1492. {
  1493. repaint();
  1494. }
  1495. }
  1496. //==============================================================================
  1497. void Component::repaint()
  1498. {
  1499. internalRepaintUnchecked (getLocalBounds(), true);
  1500. }
  1501. void Component::repaint (const int x, const int y, const int w, const int h)
  1502. {
  1503. internalRepaint ({ x, y, w, h });
  1504. }
  1505. void Component::repaint (Rectangle<int> area)
  1506. {
  1507. internalRepaint (area);
  1508. }
  1509. void Component::repaintParent()
  1510. {
  1511. if (parentComponent != nullptr)
  1512. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1513. }
  1514. void Component::internalRepaint (Rectangle<int> area)
  1515. {
  1516. area = area.getIntersection (getLocalBounds());
  1517. if (! area.isEmpty())
  1518. internalRepaintUnchecked (area, false);
  1519. }
  1520. void Component::internalRepaintUnchecked (Rectangle<int> area, const bool isEntireComponent)
  1521. {
  1522. if (flags.visibleFlag)
  1523. {
  1524. if (cachedImage != nullptr)
  1525. if (! (isEntireComponent ? cachedImage->invalidateAll()
  1526. : cachedImage->invalidate (area)))
  1527. return;
  1528. if (flags.hasHeavyweightPeerFlag)
  1529. {
  1530. // if component methods are being called from threads other than the message
  1531. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1532. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1533. if (auto* peer = getPeer())
  1534. {
  1535. // Tweak the scaling so that the component's integer size exactly aligns with the peer's scaled size
  1536. auto peerBounds = peer->getBounds();
  1537. auto scaled = area * Point<float> (peerBounds.getWidth() / (float) getWidth(),
  1538. peerBounds.getHeight() / (float) getHeight());
  1539. peer->repaint (affineTransform != nullptr ? scaled.transformedBy (*affineTransform) : scaled);
  1540. }
  1541. }
  1542. else
  1543. {
  1544. if (parentComponent != nullptr)
  1545. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1546. }
  1547. }
  1548. }
  1549. //==============================================================================
  1550. void Component::paint (Graphics&)
  1551. {
  1552. // if your component is marked as opaque, you must implement a paint
  1553. // method and ensure that its entire area is completely painted.
  1554. jassert (getBounds().isEmpty() || ! isOpaque());
  1555. }
  1556. void Component::paintOverChildren (Graphics&)
  1557. {
  1558. // all painting is done in the subclasses
  1559. }
  1560. //==============================================================================
  1561. void Component::paintWithinParentContext (Graphics& g)
  1562. {
  1563. g.setOrigin (getPosition());
  1564. if (cachedImage != nullptr)
  1565. cachedImage->paint (g);
  1566. else
  1567. paintEntireComponent (g, false);
  1568. }
  1569. void Component::paintComponentAndChildren (Graphics& g)
  1570. {
  1571. auto clipBounds = g.getClipBounds();
  1572. if (flags.dontClipGraphicsFlag)
  1573. {
  1574. paint (g);
  1575. }
  1576. else
  1577. {
  1578. g.saveState();
  1579. if (! (ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, {}) && g.isClipEmpty()))
  1580. paint (g);
  1581. g.restoreState();
  1582. }
  1583. for (int i = 0; i < childComponentList.size(); ++i)
  1584. {
  1585. auto& child = *childComponentList.getUnchecked (i);
  1586. if (child.isVisible())
  1587. {
  1588. if (child.affineTransform != nullptr)
  1589. {
  1590. g.saveState();
  1591. g.addTransform (*child.affineTransform);
  1592. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1593. child.paintWithinParentContext (g);
  1594. g.restoreState();
  1595. }
  1596. else if (clipBounds.intersects (child.getBounds()))
  1597. {
  1598. g.saveState();
  1599. if (child.flags.dontClipGraphicsFlag)
  1600. {
  1601. child.paintWithinParentContext (g);
  1602. }
  1603. else if (g.reduceClipRegion (child.getBounds()))
  1604. {
  1605. bool nothingClipped = true;
  1606. for (int j = i + 1; j < childComponentList.size(); ++j)
  1607. {
  1608. auto& sibling = *childComponentList.getUnchecked (j);
  1609. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1610. {
  1611. nothingClipped = false;
  1612. g.excludeClipRegion (sibling.getBounds());
  1613. }
  1614. }
  1615. if (nothingClipped || ! g.isClipEmpty())
  1616. child.paintWithinParentContext (g);
  1617. }
  1618. g.restoreState();
  1619. }
  1620. }
  1621. }
  1622. g.saveState();
  1623. paintOverChildren (g);
  1624. g.restoreState();
  1625. }
  1626. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1627. {
  1628. // If sizing a top-level-window and the OS paint message is delivered synchronously
  1629. // before resized() is called, then we'll invoke the callback here, to make sure
  1630. // the components inside have had a chance to sort their sizes out..
  1631. #if JUCE_DEBUG
  1632. if (! flags.isInsidePaintCall) // (avoids an assertion in plugins hosted in WaveLab)
  1633. #endif
  1634. sendMovedResizedMessagesIfPending();
  1635. #if JUCE_DEBUG
  1636. flags.isInsidePaintCall = true;
  1637. #endif
  1638. if (effect != nullptr)
  1639. {
  1640. auto scale = g.getInternalContext().getPhysicalPixelScaleFactor();
  1641. auto scaledBounds = getLocalBounds() * scale;
  1642. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1643. scaledBounds.getWidth(), scaledBounds.getHeight(), ! flags.opaqueFlag);
  1644. {
  1645. Graphics g2 (effectImage);
  1646. g2.addTransform (AffineTransform::scale (scaledBounds.getWidth() / (float) getWidth(),
  1647. scaledBounds.getHeight() / (float) getHeight()));
  1648. paintComponentAndChildren (g2);
  1649. }
  1650. g.saveState();
  1651. g.addTransform (AffineTransform::scale (1.0f / scale));
  1652. effect->applyEffect (effectImage, g, scale, ignoreAlphaLevel ? 1.0f : getAlpha());
  1653. g.restoreState();
  1654. }
  1655. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1656. {
  1657. if (componentTransparency < 255)
  1658. {
  1659. g.beginTransparencyLayer (getAlpha());
  1660. paintComponentAndChildren (g);
  1661. g.endTransparencyLayer();
  1662. }
  1663. }
  1664. else
  1665. {
  1666. paintComponentAndChildren (g);
  1667. }
  1668. #if JUCE_DEBUG
  1669. flags.isInsidePaintCall = false;
  1670. #endif
  1671. }
  1672. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1673. {
  1674. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1675. }
  1676. //==============================================================================
  1677. Image Component::createComponentSnapshot (Rectangle<int> areaToGrab,
  1678. bool clipImageToComponentBounds, float scaleFactor)
  1679. {
  1680. auto r = areaToGrab;
  1681. if (clipImageToComponentBounds)
  1682. r = r.getIntersection (getLocalBounds());
  1683. if (r.isEmpty())
  1684. return Image();
  1685. const int w = roundToInt (scaleFactor * r.getWidth());
  1686. const int h = roundToInt (scaleFactor * r.getHeight());
  1687. Image image (flags.opaqueFlag ? Image::RGB : Image::ARGB, w, h, true);
  1688. Graphics g (image);
  1689. if (w != getWidth() || h != getHeight())
  1690. g.addTransform (AffineTransform::scale (w / (float) r.getWidth(),
  1691. h / (float) r.getHeight()));
  1692. g.setOrigin (-r.getPosition());
  1693. paintEntireComponent (g, true);
  1694. return image;
  1695. }
  1696. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1697. {
  1698. if (effect != newEffect)
  1699. {
  1700. effect = newEffect;
  1701. repaint();
  1702. }
  1703. }
  1704. //==============================================================================
  1705. LookAndFeel& Component::getLookAndFeel() const noexcept
  1706. {
  1707. for (auto* c = this; c != nullptr; c = c->parentComponent)
  1708. if (c->lookAndFeel != nullptr)
  1709. return *(c->lookAndFeel);
  1710. return LookAndFeel::getDefaultLookAndFeel();
  1711. }
  1712. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1713. {
  1714. if (lookAndFeel != newLookAndFeel)
  1715. {
  1716. lookAndFeel = newLookAndFeel;
  1717. sendLookAndFeelChange();
  1718. }
  1719. }
  1720. void Component::lookAndFeelChanged() {}
  1721. void Component::colourChanged() {}
  1722. void Component::sendLookAndFeelChange()
  1723. {
  1724. const WeakReference<Component> safePointer (this);
  1725. repaint();
  1726. lookAndFeelChanged();
  1727. if (safePointer != nullptr)
  1728. {
  1729. colourChanged();
  1730. if (safePointer != nullptr)
  1731. {
  1732. for (int i = childComponentList.size(); --i >= 0;)
  1733. {
  1734. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1735. if (safePointer == nullptr)
  1736. return;
  1737. i = jmin (i, childComponentList.size());
  1738. }
  1739. }
  1740. }
  1741. }
  1742. Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1743. {
  1744. if (auto* v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId)))
  1745. return Colour ((uint32) static_cast<int> (*v));
  1746. if (inheritFromParent && parentComponent != nullptr
  1747. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1748. return parentComponent->findColour (colourId, true);
  1749. return getLookAndFeel().findColour (colourId);
  1750. }
  1751. bool Component::isColourSpecified (const int colourId) const
  1752. {
  1753. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1754. }
  1755. void Component::removeColour (const int colourId)
  1756. {
  1757. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1758. colourChanged();
  1759. }
  1760. void Component::setColour (const int colourId, Colour colour)
  1761. {
  1762. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1763. colourChanged();
  1764. }
  1765. void Component::copyAllExplicitColoursTo (Component& target) const
  1766. {
  1767. bool changed = false;
  1768. for (int i = properties.size(); --i >= 0;)
  1769. {
  1770. auto name = properties.getName(i);
  1771. if (name.toString().startsWith ("jcclr_"))
  1772. if (target.properties.set (name, properties [name]))
  1773. changed = true;
  1774. }
  1775. if (changed)
  1776. target.colourChanged();
  1777. }
  1778. //==============================================================================
  1779. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1780. {
  1781. return nullptr;
  1782. }
  1783. //==============================================================================
  1784. Component::Positioner::Positioner (Component& c) noexcept
  1785. : component (c)
  1786. {
  1787. }
  1788. Component::Positioner* Component::getPositioner() const noexcept
  1789. {
  1790. return positioner;
  1791. }
  1792. void Component::setPositioner (Positioner* newPositioner)
  1793. {
  1794. // You can only assign a positioner to the component that it was created for!
  1795. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1796. positioner = newPositioner;
  1797. }
  1798. //==============================================================================
  1799. Rectangle<int> Component::getLocalBounds() const noexcept
  1800. {
  1801. return boundsRelativeToParent.withZeroOrigin();
  1802. }
  1803. Rectangle<int> Component::getBoundsInParent() const noexcept
  1804. {
  1805. return affineTransform == nullptr ? boundsRelativeToParent
  1806. : boundsRelativeToParent.transformedBy (*affineTransform);
  1807. }
  1808. //==============================================================================
  1809. void Component::mouseEnter (const MouseEvent&) {}
  1810. void Component::mouseExit (const MouseEvent&) {}
  1811. void Component::mouseDown (const MouseEvent&) {}
  1812. void Component::mouseUp (const MouseEvent&) {}
  1813. void Component::mouseDrag (const MouseEvent&) {}
  1814. void Component::mouseMove (const MouseEvent&) {}
  1815. void Component::mouseDoubleClick (const MouseEvent&) {}
  1816. void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1817. {
  1818. // the base class just passes this event up to its parent..
  1819. if (parentComponent != nullptr)
  1820. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent), wheel);
  1821. }
  1822. void Component::mouseMagnify (const MouseEvent& e, float magnifyAmount)
  1823. {
  1824. // the base class just passes this event up to its parent..
  1825. if (parentComponent != nullptr)
  1826. parentComponent->mouseMagnify (e.getEventRelativeTo (parentComponent), magnifyAmount);
  1827. }
  1828. //==============================================================================
  1829. void Component::resized() {}
  1830. void Component::moved() {}
  1831. void Component::childBoundsChanged (Component*) {}
  1832. void Component::parentSizeChanged() {}
  1833. void Component::addComponentListener (ComponentListener* const newListener)
  1834. {
  1835. // if component methods are being called from threads other than the message
  1836. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1837. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
  1838. if (getParentComponent() != nullptr)
  1839. ASSERT_MESSAGE_MANAGER_IS_LOCKED;
  1840. #endif
  1841. componentListeners.add (newListener);
  1842. }
  1843. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1844. {
  1845. componentListeners.remove (listenerToRemove);
  1846. }
  1847. //==============================================================================
  1848. void Component::inputAttemptWhenModal()
  1849. {
  1850. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1851. getLookAndFeel().playAlertSound();
  1852. }
  1853. bool Component::canModalEventBeSentToComponent (const Component*)
  1854. {
  1855. return false;
  1856. }
  1857. void Component::internalModalInputAttempt()
  1858. {
  1859. if (auto* current = getCurrentlyModalComponent())
  1860. current->inputAttemptWhenModal();
  1861. }
  1862. //==============================================================================
  1863. void Component::postCommandMessage (const int commandID)
  1864. {
  1865. WeakReference<Component> target (this);
  1866. MessageManager::callAsync ([=]()
  1867. {
  1868. if (auto* c = target.get())
  1869. c->handleCommandMessage (commandID);
  1870. });
  1871. }
  1872. void Component::handleCommandMessage (int)
  1873. {
  1874. // used by subclasses
  1875. }
  1876. //==============================================================================
  1877. void Component::addMouseListener (MouseListener* const newListener,
  1878. const bool wantsEventsForAllNestedChildComponents)
  1879. {
  1880. // if component methods are being called from threads other than the message
  1881. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1882. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1883. // If you register a component as a mouselistener for itself, it'll receive all the events
  1884. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1885. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1886. if (mouseListeners == nullptr)
  1887. mouseListeners = new MouseListenerList();
  1888. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1889. }
  1890. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1891. {
  1892. // if component methods are being called from threads other than the message
  1893. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1894. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  1895. if (mouseListeners != nullptr)
  1896. mouseListeners->removeListener (listenerToRemove);
  1897. }
  1898. //==============================================================================
  1899. void Component::internalMouseEnter (MouseInputSource source, Point<float> relativePos, Time time)
  1900. {
  1901. if (isCurrentlyBlockedByAnotherModalComponent())
  1902. {
  1903. // if something else is modal, always just show a normal mouse cursor
  1904. source.showMouseCursor (MouseCursor::NormalCursor);
  1905. return;
  1906. }
  1907. if (flags.repaintOnMouseActivityFlag)
  1908. repaint();
  1909. BailOutChecker checker (this);
  1910. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  1911. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  1912. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  1913. this, this, time, relativePos, time, 0, false);
  1914. mouseEnter (me);
  1915. if (checker.shouldBailOut())
  1916. return;
  1917. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1918. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1919. }
  1920. void Component::internalMouseExit (MouseInputSource source, Point<float> relativePos, Time time)
  1921. {
  1922. if (isCurrentlyBlockedByAnotherModalComponent())
  1923. {
  1924. // if something else is modal, always just show a normal mouse cursor
  1925. source.showMouseCursor (MouseCursor::NormalCursor);
  1926. return;
  1927. }
  1928. if (flags.repaintOnMouseActivityFlag)
  1929. repaint();
  1930. BailOutChecker checker (this);
  1931. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  1932. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  1933. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  1934. this, this, time, relativePos, time, 0, false);
  1935. mouseExit (me);
  1936. if (checker.shouldBailOut())
  1937. return;
  1938. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1939. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1940. }
  1941. void Component::internalMouseDown (MouseInputSource source, Point<float> relativePos, Time time,
  1942. float pressure, float orientation, float rotation, float tiltX, float tiltY)
  1943. {
  1944. auto& desktop = Desktop::getInstance();
  1945. BailOutChecker checker (this);
  1946. if (isCurrentlyBlockedByAnotherModalComponent())
  1947. {
  1948. flags.mouseDownWasBlocked = true;
  1949. internalModalInputAttempt();
  1950. if (checker.shouldBailOut())
  1951. return;
  1952. // If processing the input attempt has exited the modal loop, we'll allow the event
  1953. // to be delivered..
  1954. if (isCurrentlyBlockedByAnotherModalComponent())
  1955. {
  1956. // allow blocked mouse-events to go to global listeners..
  1957. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), pressure,
  1958. orientation, rotation, tiltX, tiltY, this, this, time, relativePos,
  1959. time, source.getNumberOfMultipleClicks(), false);
  1960. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1961. return;
  1962. }
  1963. }
  1964. flags.mouseDownWasBlocked = false;
  1965. for (auto* c = this; c != nullptr; c = c->parentComponent)
  1966. {
  1967. if (c->isBroughtToFrontOnMouseClick())
  1968. {
  1969. c->toFront (true);
  1970. if (checker.shouldBailOut())
  1971. return;
  1972. }
  1973. }
  1974. if (! flags.dontFocusOnMouseClickFlag)
  1975. {
  1976. grabFocusInternal (focusChangedByMouseClick, true);
  1977. if (checker.shouldBailOut())
  1978. return;
  1979. }
  1980. if (flags.repaintOnMouseActivityFlag)
  1981. repaint();
  1982. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), pressure,
  1983. orientation, rotation, tiltX, tiltY, this, this, time, relativePos,
  1984. time, source.getNumberOfMultipleClicks(), false);
  1985. mouseDown (me);
  1986. if (checker.shouldBailOut())
  1987. return;
  1988. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1989. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  1990. }
  1991. void Component::internalMouseUp (MouseInputSource source, Point<float> relativePos, Time time,
  1992. const ModifierKeys oldModifiers, float pressure, float orientation, float rotation, float tiltX, float tiltY)
  1993. {
  1994. if (flags.mouseDownWasBlocked && isCurrentlyBlockedByAnotherModalComponent())
  1995. return;
  1996. BailOutChecker checker (this);
  1997. if (flags.repaintOnMouseActivityFlag)
  1998. repaint();
  1999. const MouseEvent me (source, relativePos, oldModifiers, pressure, orientation,
  2000. rotation, tiltX, tiltY, this, this, time,
  2001. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  2002. source.getLastMouseDownTime(),
  2003. source.getNumberOfMultipleClicks(),
  2004. source.hasMouseMovedSignificantlySincePressed());
  2005. mouseUp (me);
  2006. if (checker.shouldBailOut())
  2007. return;
  2008. auto& desktop = Desktop::getInstance();
  2009. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseUp, me);
  2010. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  2011. if (checker.shouldBailOut())
  2012. return;
  2013. // check for double-click
  2014. if (me.getNumberOfClicks() >= 2)
  2015. {
  2016. mouseDoubleClick (me);
  2017. if (checker.shouldBailOut())
  2018. return;
  2019. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  2020. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  2021. }
  2022. }
  2023. void Component::internalMouseDrag (MouseInputSource source, Point<float> relativePos, Time time,
  2024. float pressure, float orientation, float rotation, float tiltX, float tiltY)
  2025. {
  2026. if (! isCurrentlyBlockedByAnotherModalComponent())
  2027. {
  2028. BailOutChecker checker (this);
  2029. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  2030. pressure, orientation, rotation, tiltX, tiltY, this, this, time,
  2031. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  2032. source.getLastMouseDownTime(),
  2033. source.getNumberOfMultipleClicks(),
  2034. source.hasMouseMovedSignificantlySincePressed());
  2035. mouseDrag (me);
  2036. if (checker.shouldBailOut())
  2037. return;
  2038. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseDrag, me);
  2039. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  2040. }
  2041. }
  2042. void Component::internalMouseMove (MouseInputSource source, Point<float> relativePos, Time time)
  2043. {
  2044. auto& desktop = Desktop::getInstance();
  2045. if (isCurrentlyBlockedByAnotherModalComponent())
  2046. {
  2047. // allow blocked mouse-events to go to global listeners..
  2048. desktop.sendMouseMove();
  2049. }
  2050. else
  2051. {
  2052. BailOutChecker checker (this);
  2053. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2054. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2055. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2056. this, this, time, relativePos, time, 0, false);
  2057. mouseMove (me);
  2058. if (checker.shouldBailOut())
  2059. return;
  2060. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseMove, me);
  2061. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  2062. }
  2063. }
  2064. void Component::internalMouseWheel (MouseInputSource source, Point<float> relativePos,
  2065. Time time, const MouseWheelDetails& wheel)
  2066. {
  2067. auto& desktop = Desktop::getInstance();
  2068. BailOutChecker checker (this);
  2069. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2070. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2071. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2072. this, this, time, relativePos, time, 0, false);
  2073. if (isCurrentlyBlockedByAnotherModalComponent())
  2074. {
  2075. // allow blocked mouse-events to go to global listeners..
  2076. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  2077. }
  2078. else
  2079. {
  2080. mouseWheelMove (me, wheel);
  2081. if (checker.shouldBailOut())
  2082. return;
  2083. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  2084. if (! checker.shouldBailOut())
  2085. MouseListenerList::sendWheelEvent (*this, checker, me, wheel);
  2086. }
  2087. }
  2088. void Component::internalMagnifyGesture (MouseInputSource source, Point<float> relativePos,
  2089. Time time, float amount)
  2090. {
  2091. if (! isCurrentlyBlockedByAnotherModalComponent())
  2092. {
  2093. const MouseEvent me (source, relativePos, source.getCurrentModifiers(), MouseInputSource::invalidPressure,
  2094. MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  2095. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  2096. this, this, time, relativePos, time, 0, false);
  2097. mouseMagnify (me, amount);
  2098. }
  2099. }
  2100. void Component::sendFakeMouseMove() const
  2101. {
  2102. MouseInputSource mainMouse = Desktop::getInstance().getMainMouseSource();
  2103. if (! mainMouse.isDragging())
  2104. mainMouse.triggerFakeMove();
  2105. }
  2106. void JUCE_CALLTYPE Component::beginDragAutoRepeat (const int interval)
  2107. {
  2108. Desktop::getInstance().beginDragAutoRepeat (interval);
  2109. }
  2110. //==============================================================================
  2111. void Component::broughtToFront()
  2112. {
  2113. }
  2114. void Component::internalBroughtToFront()
  2115. {
  2116. if (flags.hasHeavyweightPeerFlag)
  2117. Desktop::getInstance().componentBroughtToFront (this);
  2118. BailOutChecker checker (this);
  2119. broughtToFront();
  2120. if (checker.shouldBailOut())
  2121. return;
  2122. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  2123. if (checker.shouldBailOut())
  2124. return;
  2125. // When brought to the front and there's a modal component blocking this one,
  2126. // we need to bring the modal one to the front instead..
  2127. if (auto* cm = getCurrentlyModalComponent())
  2128. if (cm->getTopLevelComponent() != getTopLevelComponent())
  2129. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2130. // non-front components can't get focus when another modal comp is
  2131. // active, and therefore can't receive mouse-clicks
  2132. }
  2133. //==============================================================================
  2134. void Component::focusGained (FocusChangeType) {}
  2135. void Component::focusLost (FocusChangeType) {}
  2136. void Component::focusOfChildComponentChanged (FocusChangeType) {}
  2137. void Component::internalFocusGain (const FocusChangeType cause)
  2138. {
  2139. internalFocusGain (cause, WeakReference<Component> (this));
  2140. }
  2141. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  2142. {
  2143. focusGained (cause);
  2144. if (safePointer != nullptr)
  2145. internalChildFocusChange (cause, safePointer);
  2146. }
  2147. void Component::internalFocusLoss (const FocusChangeType cause)
  2148. {
  2149. const WeakReference<Component> safePointer (this);
  2150. focusLost (cause);
  2151. if (safePointer != nullptr)
  2152. internalChildFocusChange (cause, safePointer);
  2153. }
  2154. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  2155. {
  2156. const bool childIsNowFocused = hasKeyboardFocus (true);
  2157. if (flags.childCompFocusedFlag != childIsNowFocused)
  2158. {
  2159. flags.childCompFocusedFlag = childIsNowFocused;
  2160. focusOfChildComponentChanged (cause);
  2161. if (safePointer == nullptr)
  2162. return;
  2163. }
  2164. if (parentComponent != nullptr)
  2165. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  2166. }
  2167. void Component::setWantsKeyboardFocus (const bool wantsFocus) noexcept
  2168. {
  2169. flags.wantsFocusFlag = wantsFocus;
  2170. }
  2171. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  2172. {
  2173. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  2174. }
  2175. bool Component::getMouseClickGrabsKeyboardFocus() const noexcept
  2176. {
  2177. return ! flags.dontFocusOnMouseClickFlag;
  2178. }
  2179. bool Component::getWantsKeyboardFocus() const noexcept
  2180. {
  2181. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  2182. }
  2183. void Component::setFocusContainer (const bool shouldBeFocusContainer) noexcept
  2184. {
  2185. flags.isFocusContainerFlag = shouldBeFocusContainer;
  2186. }
  2187. bool Component::isFocusContainer() const noexcept
  2188. {
  2189. return flags.isFocusContainerFlag;
  2190. }
  2191. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  2192. int Component::getExplicitFocusOrder() const
  2193. {
  2194. return properties [juce_explicitFocusOrderId];
  2195. }
  2196. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  2197. {
  2198. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  2199. }
  2200. KeyboardFocusTraverser* Component::createFocusTraverser()
  2201. {
  2202. if (flags.isFocusContainerFlag || parentComponent == nullptr)
  2203. return new KeyboardFocusTraverser();
  2204. return parentComponent->createFocusTraverser();
  2205. }
  2206. void Component::takeKeyboardFocus (const FocusChangeType cause)
  2207. {
  2208. // give the focus to this component
  2209. if (currentlyFocusedComponent != this)
  2210. {
  2211. // get the focus onto our desktop window
  2212. if (auto* peer = getPeer())
  2213. {
  2214. const WeakReference<Component> safePointer (this);
  2215. peer->grabFocus();
  2216. if (peer->isFocused() && currentlyFocusedComponent != this)
  2217. {
  2218. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  2219. currentlyFocusedComponent = this;
  2220. Desktop::getInstance().triggerFocusCallback();
  2221. // call this after setting currentlyFocusedComponent so that the one that's
  2222. // losing it has a chance to see where focus is going
  2223. if (componentLosingFocus != nullptr)
  2224. componentLosingFocus->internalFocusLoss (cause);
  2225. if (currentlyFocusedComponent == this)
  2226. internalFocusGain (cause, safePointer);
  2227. }
  2228. }
  2229. }
  2230. }
  2231. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  2232. {
  2233. if (isShowing())
  2234. {
  2235. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == nullptr))
  2236. {
  2237. takeKeyboardFocus (cause);
  2238. }
  2239. else
  2240. {
  2241. if (isParentOf (currentlyFocusedComponent)
  2242. && currentlyFocusedComponent->isShowing())
  2243. {
  2244. // do nothing if the focused component is actually a child of ours..
  2245. }
  2246. else
  2247. {
  2248. // find the default child component..
  2249. ScopedPointer<KeyboardFocusTraverser> traverser (createFocusTraverser());
  2250. if (traverser != nullptr)
  2251. {
  2252. auto* defaultComp = traverser->getDefaultComponent (this);
  2253. traverser = nullptr;
  2254. if (defaultComp != nullptr)
  2255. {
  2256. defaultComp->grabFocusInternal (cause, false);
  2257. return;
  2258. }
  2259. }
  2260. if (canTryParent && parentComponent != nullptr)
  2261. {
  2262. // if no children want it and we're allowed to try our parent comp,
  2263. // then pass up to parent, which will try our siblings.
  2264. parentComponent->grabFocusInternal (cause, true);
  2265. }
  2266. }
  2267. }
  2268. }
  2269. }
  2270. void Component::grabKeyboardFocus()
  2271. {
  2272. // if component methods are being called from threads other than the message
  2273. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2274. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  2275. grabFocusInternal (focusChangedDirectly, true);
  2276. // A component can only be focused when it's actually on the screen!
  2277. // If this fails then you're probably trying to grab the focus before you've
  2278. // added the component to a parent or made it visible. Or maybe one of its parent
  2279. // components isn't yet visible.
  2280. jassert (isShowing() || isOnDesktop());
  2281. }
  2282. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  2283. {
  2284. // if component methods are being called from threads other than the message
  2285. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2286. ASSERT_MESSAGE_MANAGER_IS_LOCKED
  2287. if (parentComponent != nullptr)
  2288. {
  2289. if (ScopedPointer<KeyboardFocusTraverser> traverser = createFocusTraverser())
  2290. {
  2291. auto* nextComp = moveToNext ? traverser->getNextComponent (this)
  2292. : traverser->getPreviousComponent (this);
  2293. traverser = nullptr;
  2294. if (nextComp != nullptr)
  2295. {
  2296. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2297. {
  2298. const WeakReference<Component> nextCompPointer (nextComp);
  2299. internalModalInputAttempt();
  2300. if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2301. return;
  2302. }
  2303. nextComp->grabFocusInternal (focusChangedByTabKey, true);
  2304. return;
  2305. }
  2306. }
  2307. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  2308. }
  2309. }
  2310. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  2311. {
  2312. return (currentlyFocusedComponent == this)
  2313. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  2314. }
  2315. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept
  2316. {
  2317. return currentlyFocusedComponent;
  2318. }
  2319. void JUCE_CALLTYPE Component::unfocusAllComponents()
  2320. {
  2321. if (auto* c = getCurrentlyFocusedComponent())
  2322. c->giveAwayFocus (true);
  2323. }
  2324. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  2325. {
  2326. auto* componentLosingFocus = currentlyFocusedComponent;
  2327. currentlyFocusedComponent = nullptr;
  2328. if (sendFocusLossEvent && componentLosingFocus != nullptr)
  2329. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  2330. Desktop::getInstance().triggerFocusCallback();
  2331. }
  2332. //==============================================================================
  2333. bool Component::isEnabled() const noexcept
  2334. {
  2335. return (! flags.isDisabledFlag)
  2336. && (parentComponent == nullptr || parentComponent->isEnabled());
  2337. }
  2338. void Component::setEnabled (const bool shouldBeEnabled)
  2339. {
  2340. if (flags.isDisabledFlag == shouldBeEnabled)
  2341. {
  2342. flags.isDisabledFlag = ! shouldBeEnabled;
  2343. // if any parent components are disabled, setting our flag won't make a difference,
  2344. // so no need to send a change message
  2345. if (parentComponent == nullptr || parentComponent->isEnabled())
  2346. sendEnablementChangeMessage();
  2347. }
  2348. }
  2349. void Component::enablementChanged() {}
  2350. void Component::sendEnablementChangeMessage()
  2351. {
  2352. const WeakReference<Component> safePointer (this);
  2353. enablementChanged();
  2354. if (safePointer == nullptr)
  2355. return;
  2356. for (int i = getNumChildComponents(); --i >= 0;)
  2357. {
  2358. if (auto* c = getChildComponent (i))
  2359. {
  2360. c->sendEnablementChangeMessage();
  2361. if (safePointer == nullptr)
  2362. return;
  2363. }
  2364. }
  2365. }
  2366. //==============================================================================
  2367. bool Component::isMouseOver (const bool includeChildren) const
  2368. {
  2369. for (auto& ms : Desktop::getInstance().getMouseSources())
  2370. {
  2371. auto* c = ms.getComponentUnderMouse();
  2372. if ((c == this || (includeChildren && isParentOf (c)))
  2373. && c->reallyContains (c->getLocalPoint (nullptr, ms.getScreenPosition()).roundToInt(), false)
  2374. && ((! ms.isTouch()) || ms.isDragging()))
  2375. return true;
  2376. }
  2377. return false;
  2378. }
  2379. bool Component::isMouseButtonDown() const
  2380. {
  2381. for (auto& ms : Desktop::getInstance().getMouseSources())
  2382. if (ms.isDragging() && ms.getComponentUnderMouse() == this)
  2383. return true;
  2384. return false;
  2385. }
  2386. bool Component::isMouseOverOrDragging (const bool includeChildren) const
  2387. {
  2388. for (auto& ms : Desktop::getInstance().getMouseSources())
  2389. {
  2390. auto* c = ms.getComponentUnderMouse();
  2391. if ((c == this || (includeChildren && isParentOf (c)))
  2392. && ((! ms.isTouch()) || ms.isDragging()))
  2393. return true;
  2394. }
  2395. return false;
  2396. }
  2397. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept
  2398. {
  2399. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  2400. }
  2401. Point<int> Component::getMouseXYRelative() const
  2402. {
  2403. return getLocalPoint (nullptr, Desktop::getMousePosition());
  2404. }
  2405. //==============================================================================
  2406. void Component::addKeyListener (KeyListener* const newListener)
  2407. {
  2408. if (keyListeners == nullptr)
  2409. keyListeners = new Array<KeyListener*>();
  2410. keyListeners->addIfNotAlreadyThere (newListener);
  2411. }
  2412. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  2413. {
  2414. if (keyListeners != nullptr)
  2415. keyListeners->removeFirstMatchingValue (listenerToRemove);
  2416. }
  2417. bool Component::keyPressed (const KeyPress&) { return false; }
  2418. bool Component::keyStateChanged (const bool /*isKeyDown*/) { return false; }
  2419. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  2420. {
  2421. if (parentComponent != nullptr)
  2422. parentComponent->modifierKeysChanged (modifiers);
  2423. }
  2424. void Component::internalModifierKeysChanged()
  2425. {
  2426. sendFakeMouseMove();
  2427. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  2428. }
  2429. //==============================================================================
  2430. Component::BailOutChecker::BailOutChecker (Component* const component)
  2431. : safePointer (component)
  2432. {
  2433. jassert (component != nullptr);
  2434. }
  2435. bool Component::BailOutChecker::shouldBailOut() const noexcept
  2436. {
  2437. return safePointer == nullptr;
  2438. }
  2439. } // namespace juce