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 99KB

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