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

juce_Component.cpp 97KB

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