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

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