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

juce_Component.cpp 98KB

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