juce_Component.cpp 96 KB

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