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

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