1
0
Fork 0
mirror of https://github.com/juce-framework/JUCE.git synced 2026-01-13 00:04:19 +00:00

Added Animated App template and examples

This commit is contained in:
Felix Faire 2014-10-29 15:55:23 +00:00
parent fefcf7aca6
commit ff6520a89a
1141 changed files with 438491 additions and 94 deletions

View file

@ -0,0 +1,91 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
class ActionBroadcaster::ActionMessage : public MessageManager::MessageBase
{
public:
ActionMessage (const ActionBroadcaster* ab,
const String& messageText, ActionListener* l) noexcept
: broadcaster (const_cast<ActionBroadcaster*> (ab)),
message (messageText),
listener (l)
{}
void messageCallback() override
{
if (const ActionBroadcaster* const b = broadcaster)
if (b->actionListeners.contains (listener))
listener->actionListenerCallback (message);
}
private:
WeakReference<ActionBroadcaster> broadcaster;
const String message;
ActionListener* const listener;
JUCE_DECLARE_NON_COPYABLE (ActionMessage)
};
//==============================================================================
ActionBroadcaster::ActionBroadcaster()
{
// are you trying to create this object before or after juce has been intialised??
jassert (MessageManager::getInstanceWithoutCreating() != nullptr);
}
ActionBroadcaster::~ActionBroadcaster()
{
// all event-based objects must be deleted BEFORE juce is shut down!
jassert (MessageManager::getInstanceWithoutCreating() != nullptr);
masterReference.clear();
}
void ActionBroadcaster::addActionListener (ActionListener* const listener)
{
const ScopedLock sl (actionListenerLock);
if (listener != nullptr)
actionListeners.add (listener);
}
void ActionBroadcaster::removeActionListener (ActionListener* const listener)
{
const ScopedLock sl (actionListenerLock);
actionListeners.removeValue (listener);
}
void ActionBroadcaster::removeAllActionListeners()
{
const ScopedLock sl (actionListenerLock);
actionListeners.clear();
}
void ActionBroadcaster::sendActionMessage (const String& message) const
{
const ScopedLock sl (actionListenerLock);
for (int i = actionListeners.size(); --i >= 0;)
(new ActionMessage (this, message, actionListeners.getUnchecked(i)))->post();
}

View file

@ -0,0 +1,83 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_ACTIONBROADCASTER_H_INCLUDED
#define JUCE_ACTIONBROADCASTER_H_INCLUDED
//==============================================================================
/** Manages a list of ActionListeners, and can send them messages.
To quickly add methods to your class that can add/remove action
listeners and broadcast to them, you can derive from this.
@see ActionListener, ChangeListener
*/
class JUCE_API ActionBroadcaster
{
public:
//==============================================================================
/** Creates an ActionBroadcaster. */
ActionBroadcaster();
/** Destructor. */
virtual ~ActionBroadcaster();
//==============================================================================
/** Adds a listener to the list.
Trying to add a listener that's already on the list will have no effect.
*/
void addActionListener (ActionListener* listener);
/** Removes a listener from the list.
If the listener isn't on the list, this won't have any effect.
*/
void removeActionListener (ActionListener* listener);
/** Removes all listeners from the list. */
void removeAllActionListeners();
//==============================================================================
/** Broadcasts a message to all the registered listeners.
@see ActionListener::actionListenerCallback
*/
void sendActionMessage (const String& message) const;
private:
//==============================================================================
friend class WeakReference<ActionBroadcaster>;
WeakReference<ActionBroadcaster>::Master masterReference;
class ActionMessage;
friend class ActionMessage;
SortedSet<ActionListener*> actionListeners;
CriticalSection actionListenerLock;
JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster)
};
#endif // JUCE_ACTIONBROADCASTER_H_INCLUDED

View file

@ -0,0 +1,50 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_ACTIONLISTENER_H_INCLUDED
#define JUCE_ACTIONLISTENER_H_INCLUDED
//==============================================================================
/**
Interface class for delivery of events that are sent by an ActionBroadcaster.
@see ActionBroadcaster, ChangeListener
*/
class JUCE_API ActionListener
{
public:
/** Destructor. */
virtual ~ActionListener() {}
/** Overridden by your subclass to receive the callback.
@param message the string that was specified when the event was triggered
by a call to ActionBroadcaster::sendActionMessage()
*/
virtual void actionListenerCallback (const String& message) = 0;
};
#endif // JUCE_ACTIONLISTENER_H_INCLUDED

View file

@ -0,0 +1,86 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
class AsyncUpdater::AsyncUpdaterMessage : public CallbackMessage
{
public:
AsyncUpdaterMessage (AsyncUpdater& au) : owner (au) {}
void messageCallback() override
{
if (shouldDeliver.compareAndSetBool (0, 1))
owner.handleAsyncUpdate();
}
Atomic<int> shouldDeliver;
private:
AsyncUpdater& owner;
JUCE_DECLARE_NON_COPYABLE (AsyncUpdaterMessage)
};
//==============================================================================
AsyncUpdater::AsyncUpdater()
{
activeMessage = new AsyncUpdaterMessage (*this);
}
AsyncUpdater::~AsyncUpdater()
{
// You're deleting this object with a background thread while there's an update
// pending on the main event thread - that's pretty dodgy threading, as the callback could
// happen after this destructor has finished. You should either use a MessageManagerLock while
// deleting this object, or find some other way to avoid such a race condition.
jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
activeMessage->shouldDeliver.set (0);
}
void AsyncUpdater::triggerAsyncUpdate()
{
if (activeMessage->shouldDeliver.compareAndSetBool (1, 0))
if (! activeMessage->post())
cancelPendingUpdate(); // if the message queue fails, this avoids getting
// trapped waiting for the message to arrive
}
void AsyncUpdater::cancelPendingUpdate() noexcept
{
activeMessage->shouldDeliver.set (0);
}
void AsyncUpdater::handleUpdateNowIfNeeded()
{
// This can only be called by the event thread.
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
if (activeMessage->shouldDeliver.exchange (0) != 0)
handleAsyncUpdate();
}
bool AsyncUpdater::isUpdatePending() const noexcept
{
return activeMessage->shouldDeliver.value != 0;
}

View file

@ -0,0 +1,109 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_ASYNCUPDATER_H_INCLUDED
#define JUCE_ASYNCUPDATER_H_INCLUDED
//==============================================================================
/**
Has a callback method that is triggered asynchronously.
This object allows an asynchronous callback function to be triggered, for
tasks such as coalescing multiple updates into a single callback later on.
Basically, one or more calls to the triggerAsyncUpdate() will result in the
message thread calling handleAsyncUpdate() as soon as it can.
*/
class JUCE_API AsyncUpdater
{
public:
//==============================================================================
/** Creates an AsyncUpdater object. */
AsyncUpdater();
/** Destructor.
If there are any pending callbacks when the object is deleted, these are lost.
*/
virtual ~AsyncUpdater();
//==============================================================================
/** Causes the callback to be triggered at a later time.
This method returns immediately, having made sure that a callback
to the handleAsyncUpdate() method will occur as soon as possible.
If an update callback is already pending but hasn't happened yet, calls
to this method will be ignored.
It's thread-safe to call this method from any number of threads without
needing to worry about locking.
*/
void triggerAsyncUpdate();
/** This will stop any pending updates from happening.
If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
callback happens, this will cancel the handleAsyncUpdate() callback.
Note that this method simply cancels the next callback - if a callback is already
in progress on a different thread, this won't block until the callback finishes, so
there's no guarantee that the callback isn't still running when the method returns.
*/
void cancelPendingUpdate() noexcept;
/** If an update has been triggered and is pending, this will invoke it
synchronously.
Use this as a kind of "flush" operation - if an update is pending, the
handleAsyncUpdate() method will be called immediately; if no update is
pending, then nothing will be done.
Because this may invoke the callback, this method must only be called on
the main event thread.
*/
void handleUpdateNowIfNeeded();
/** Returns true if there's an update callback in the pipeline. */
bool isUpdatePending() const noexcept;
//==============================================================================
/** Called back to do whatever your class needs to do.
This method is called by the message thread at the next convenient time
after the triggerAsyncUpdate() method has been called.
*/
virtual void handleAsyncUpdate() = 0;
private:
//==============================================================================
class AsyncUpdaterMessage;
friend class ReferenceCountedObjectPtr<AsyncUpdaterMessage>;
ReferenceCountedObjectPtr<AsyncUpdaterMessage> activeMessage;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater)
};
#endif // JUCE_ASYNCUPDATER_H_INCLUDED

View file

@ -0,0 +1,96 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
ChangeBroadcaster::ChangeBroadcaster() noexcept
{
callback.owner = this;
}
ChangeBroadcaster::~ChangeBroadcaster()
{
}
void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
{
// Listeners can only be safely added when the event thread is locked
// You can use a MessageManagerLock if you need to call this from another thread.
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
changeListeners.add (listener);
}
void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
{
// Listeners can only be safely added when the event thread is locked
// You can use a MessageManagerLock if you need to call this from another thread.
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
changeListeners.remove (listener);
}
void ChangeBroadcaster::removeAllChangeListeners()
{
// Listeners can only be safely added when the event thread is locked
// You can use a MessageManagerLock if you need to call this from another thread.
jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
changeListeners.clear();
}
void ChangeBroadcaster::sendChangeMessage()
{
if (changeListeners.size() > 0)
callback.triggerAsyncUpdate();
}
void ChangeBroadcaster::sendSynchronousChangeMessage()
{
// This can only be called by the event thread.
jassert (MessageManager::getInstance()->isThisTheMessageThread());
callback.cancelPendingUpdate();
callListeners();
}
void ChangeBroadcaster::dispatchPendingMessages()
{
callback.handleUpdateNowIfNeeded();
}
void ChangeBroadcaster::callListeners()
{
changeListeners.call (&ChangeListener::changeListenerCallback, this);
}
//==============================================================================
ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
: owner (nullptr)
{
}
void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
{
jassert (owner != nullptr);
owner->callListeners();
}

View file

@ -0,0 +1,105 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_CHANGEBROADCASTER_H_INCLUDED
#define JUCE_CHANGEBROADCASTER_H_INCLUDED
//==============================================================================
/**
Holds a list of ChangeListeners, and sends messages to them when instructed.
@see ChangeListener
*/
class JUCE_API ChangeBroadcaster
{
public:
//==============================================================================
/** Creates an ChangeBroadcaster. */
ChangeBroadcaster() noexcept;
/** Destructor. */
virtual ~ChangeBroadcaster();
//==============================================================================
/** Registers a listener to receive change callbacks from this broadcaster.
Trying to add a listener that's already on the list will have no effect.
*/
void addChangeListener (ChangeListener* listener);
/** Unregisters a listener from the list.
If the listener isn't on the list, this won't have any effect.
*/
void removeChangeListener (ChangeListener* listener);
/** Removes all listeners from the list. */
void removeAllChangeListeners();
//==============================================================================
/** Causes an asynchronous change message to be sent to all the registered listeners.
The message will be delivered asynchronously by the main message thread, so this
method will return immediately. To call the listeners synchronously use
sendSynchronousChangeMessage().
*/
void sendChangeMessage();
/** Sends a synchronous change message to all the registered listeners.
This will immediately call all the listeners that are registered. For thread-safety
reasons, you must only call this method on the main message thread.
@see dispatchPendingMessages
*/
void sendSynchronousChangeMessage();
/** If a change message has been sent but not yet dispatched, this will call
sendSynchronousChangeMessage() to make the callback immediately.
For thread-safety reasons, you must only call this method on the main message thread.
*/
void dispatchPendingMessages();
private:
//==============================================================================
class ChangeBroadcasterCallback : public AsyncUpdater
{
public:
ChangeBroadcasterCallback();
void handleAsyncUpdate() override;
ChangeBroadcaster* owner;
};
friend class ChangeBroadcasterCallback;
ChangeBroadcasterCallback callback;
ListenerList <ChangeListener> changeListeners;
void callListeners();
JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster)
};
#endif // JUCE_CHANGEBROADCASTER_H_INCLUDED

View file

@ -0,0 +1,64 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_CHANGELISTENER_H_INCLUDED
#define JUCE_CHANGELISTENER_H_INCLUDED
class ChangeBroadcaster;
//==============================================================================
/**
Receives change event callbacks that are sent out by a ChangeBroadcaster.
A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
ChangeListener is used to receive these callbacks.
Note that the major difference between an ActionListener and a ChangeListener
is that for a ChangeListener, multiple changes will be coalesced into fewer
callbacks, but ActionListeners perform one callback for every event posted.
@see ChangeBroadcaster, ActionListener
*/
class JUCE_API ChangeListener
{
public:
/** Destructor. */
virtual ~ChangeListener() {}
/** Your subclass should implement this method to receive the callback.
@param source the ChangeBroadcaster that triggered the callback.
*/
virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
//==============================================================================
#if JUCE_CATCH_DEPRECATED_CODE_MISUSE
// This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
private: virtual int changeListenerCallback (void*) { return 0; }
#endif
};
#endif // JUCE_CHANGELISTENER_H_INCLUDED

View file

@ -0,0 +1,359 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_LISTENERLIST_H_INCLUDED
#define JUCE_LISTENERLIST_H_INCLUDED
//==============================================================================
/**
Holds a set of objects and can invoke a member function callback on each object
in the set with a single call.
Use a ListenerList to manage a set of objects which need a callback, and you
can invoke a member function by simply calling call() or callChecked().
E.g.
@code
class MyListenerType
{
public:
void myCallbackMethod (int foo, bool bar);
};
ListenerList <MyListenerType> listeners;
listeners.add (someCallbackObjects...);
// This will invoke myCallbackMethod (1234, true) on each of the objects
// in the list...
listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
@endcode
If you add or remove listeners from the list during one of the callbacks - i.e. while
it's in the middle of iterating the listeners, then it's guaranteed that no listeners
will be mistakenly called after they've been removed, but it may mean that some of the
listeners could be called more than once, or not at all, depending on the list's order.
Sometimes, there's a chance that invoking one of the callbacks might result in the
list itself being deleted while it's still iterating - to survive this situation, you can
use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
the list will check this after each callback to determine whether it should abort the
operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
which can be used to check when a Component has been deleted. See also
ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
*/
template <class ListenerClass,
class ArrayType = Array<ListenerClass*> >
class ListenerList
{
// Horrible macros required to support VC7..
#ifndef DOXYGEN
#if JUCE_VC8_OR_EARLIER
#define LL_TEMPLATE(a) typename P##a, typename Q##a
#define LL_PARAM(a) Q##a& param##a
#else
#define LL_TEMPLATE(a) typename P##a
#define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
#endif
#endif
public:
//==============================================================================
/** Creates an empty list. */
ListenerList()
{
}
/** Destructor. */
~ListenerList()
{
}
//==============================================================================
/** Adds a listener to the list.
A listener can only be added once, so if the listener is already in the list,
this method has no effect.
@see remove
*/
void add (ListenerClass* const listenerToAdd)
{
// Listeners can't be null pointers!
jassert (listenerToAdd != nullptr);
if (listenerToAdd != nullptr)
listeners.addIfNotAlreadyThere (listenerToAdd);
}
/** Removes a listener from the list.
If the listener wasn't in the list, this has no effect.
*/
void remove (ListenerClass* const listenerToRemove)
{
// Listeners can't be null pointers!
jassert (listenerToRemove != nullptr);
listeners.removeFirstMatchingValue (listenerToRemove);
}
/** Returns the number of registered listeners. */
int size() const noexcept
{
return listeners.size();
}
/** Returns true if any listeners are registered. */
bool isEmpty() const noexcept
{
return listeners.size() == 0;
}
/** Clears the list. */
void clear()
{
listeners.clear();
}
/** Returns true if the specified listener has been added to the list. */
bool contains (ListenerClass* const listener) const noexcept
{
return listeners.contains (listener);
}
//==============================================================================
/** Calls a member function on each listener in the list, with no parameters. */
void call (void (ListenerClass::*callbackFunction) ())
{
callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
}
/** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) ())
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) ();
}
//==============================================================================
/** Calls a member function on each listener in the list, with 1 parameter. */
template <LL_TEMPLATE(1)>
void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1);
}
/** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1),
LL_PARAM(1))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1);
}
//==============================================================================
/** Calls a member function on each listener in the list, with 2 parameters. */
template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
void call (void (ListenerClass::*callbackFunction) (P1, P2),
LL_PARAM(1), LL_PARAM(2))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1, param2);
}
/** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1, P2),
LL_PARAM(1), LL_PARAM(2))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1, param2);
}
//==============================================================================
/** Calls a member function on each listener in the list, with 3 parameters. */
template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1, param2, param3);
}
/** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1, P2, P3),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1, param2, param3);
}
//==============================================================================
/** Calls a member function on each listener in the list, with 4 parameters. */
template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
}
/** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
}
//==============================================================================
/** Calls a member function on each listener in the list, with 5 parameters. */
template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
}
/** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
}
//==============================================================================
/** Calls a member function on each listener in the list, with 5 parameters. */
template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5), LL_TEMPLATE(6)>
void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5, P6),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5), LL_PARAM(6))
{
for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5, param6);
}
/** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
See the class description for info about writing a bail-out checker. */
template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5), LL_TEMPLATE(6)>
void callChecked (const BailOutCheckerType& bailOutChecker,
void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5, P6),
LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5), LL_PARAM(6))
{
for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
(iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5, param6);
}
//==============================================================================
/** A dummy bail-out checker that always returns false.
See the ListenerList notes for more info about bail-out checkers.
*/
class DummyBailOutChecker
{
public:
inline bool shouldBailOut() const noexcept { return false; }
};
//==============================================================================
/** Iterates the listeners in a ListenerList. */
template <class BailOutCheckerType, class ListType>
class Iterator
{
public:
//==============================================================================
Iterator (const ListType& listToIterate) noexcept
: list (listToIterate), index (listToIterate.size())
{}
~Iterator() noexcept {}
//==============================================================================
bool next() noexcept
{
if (index <= 0)
return false;
const int listSize = list.size();
if (--index < listSize)
return true;
index = listSize - 1;
return index >= 0;
}
bool next (const BailOutCheckerType& bailOutChecker) noexcept
{
return (! bailOutChecker.shouldBailOut()) && next();
}
typename ListType::ListenerType* getListener() const noexcept
{
return list.getListeners().getUnchecked (index);
}
//==============================================================================
private:
const ListType& list;
int index;
JUCE_DECLARE_NON_COPYABLE (Iterator)
};
typedef ListenerList<ListenerClass, ArrayType> ThisType;
typedef ListenerClass ListenerType;
const ArrayType& getListeners() const noexcept { return listeners; }
private:
//==============================================================================
ArrayType listeners;
JUCE_DECLARE_NON_COPYABLE (ListenerList)
#undef LL_TEMPLATE
#undef LL_PARAM
};
#endif // JUCE_LISTENERLIST_H_INCLUDED

View file

@ -0,0 +1,264 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
enum { magicMastSlaveConnectionHeader = 0x712baf04 };
static const char* startMessage = "__ipc_st";
static const char* killMessage = "__ipc_k_";
static const char* pingMessage = "__ipc_p_";
enum { specialMessageSize = 8, defaultTimeoutMs = 8000 };
static String getCommandLinePrefix (const String& commandLineUniqueID)
{
return "--" + commandLineUniqueID + ":";
}
//==============================================================================
// This thread sends and receives ping messages every second, so that it
// can find out if the other process has stopped running.
struct ChildProcessPingThread : public Thread,
private AsyncUpdater
{
ChildProcessPingThread (int timeout) : Thread ("IPC ping"), timeoutMs (timeout)
{
pingReceived();
}
static bool isPingMessage (const MemoryBlock& m) noexcept
{
return memcmp (m.getData(), pingMessage, specialMessageSize) == 0;
}
void pingReceived() noexcept { countdown = timeoutMs / 1000 + 1; }
void triggerConnectionLostMessage() { triggerAsyncUpdate(); }
virtual bool sendPingMessage (const MemoryBlock&) = 0;
virtual void pingFailed() = 0;
int timeoutMs;
private:
Atomic<int> countdown;
void handleAsyncUpdate() override { pingFailed(); }
void run() override
{
while (! threadShouldExit())
{
if (--countdown <= 0 || ! sendPingMessage (MemoryBlock (pingMessage, specialMessageSize)))
{
triggerConnectionLostMessage();
break;
}
wait (1000);
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessPingThread)
};
//==============================================================================
struct ChildProcessMaster::Connection : public InterprocessConnection,
private ChildProcessPingThread
{
Connection (ChildProcessMaster& m, const String& pipeName, int timeout)
: InterprocessConnection (false, magicMastSlaveConnectionHeader),
ChildProcessPingThread (timeout),
owner (m)
{
if (createPipe (pipeName, timeoutMs))
startThread (4);
}
~Connection()
{
stopThread (10000);
}
private:
void connectionMade() override {}
void connectionLost() override { owner.handleConnectionLost(); }
bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToSlave (m); }
void pingFailed() override { connectionLost(); }
void messageReceived (const MemoryBlock& m) override
{
pingReceived();
if (m.getSize() != specialMessageSize || ! isPingMessage (m))
owner.handleMessageFromSlave (m);
}
ChildProcessMaster& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
};
//==============================================================================
ChildProcessMaster::ChildProcessMaster() {}
ChildProcessMaster::~ChildProcessMaster()
{
if (connection != nullptr)
{
sendMessageToSlave (MemoryBlock (killMessage, specialMessageSize));
connection->disconnect();
connection = nullptr;
}
}
void ChildProcessMaster::handleConnectionLost() {}
bool ChildProcessMaster::sendMessageToSlave (const MemoryBlock& mb)
{
if (connection != nullptr)
return connection->sendMessage (mb);
jassertfalse; // this can only be used when the connection is active!
return false;
}
bool ChildProcessMaster::launchSlaveProcess (const File& executable, const String& commandLineUniqueID, int timeoutMs)
{
connection = nullptr;
jassert (childProcess.kill());
const String pipeName ("p" + String::toHexString (Random().nextInt64()));
StringArray args;
args.add (executable.getFullPathName());
args.add (getCommandLinePrefix (commandLineUniqueID) + pipeName);
if (childProcess.start (args))
{
connection = new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs);
if (connection->isConnected())
{
sendMessageToSlave (MemoryBlock (startMessage, specialMessageSize));
return true;
}
connection = nullptr;
}
return false;
}
//==============================================================================
struct ChildProcessSlave::Connection : public InterprocessConnection,
private ChildProcessPingThread
{
Connection (ChildProcessSlave& p, const String& pipeName, int timeout)
: InterprocessConnection (false, magicMastSlaveConnectionHeader),
ChildProcessPingThread (timeout),
owner (p)
{
connectToPipe (pipeName, timeoutMs);
startThread (4);
}
~Connection()
{
stopThread (10000);
}
private:
ChildProcessSlave& owner;
void connectionMade() override {}
void connectionLost() override { owner.handleConnectionLost(); }
bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToMaster (m); }
void pingFailed() override { connectionLost(); }
void messageReceived (const MemoryBlock& m) override
{
pingReceived();
if (m.getSize() == specialMessageSize)
{
if (isPingMessage (m))
return;
if (memcmp (m.getData(), killMessage, specialMessageSize) == 0)
{
triggerConnectionLostMessage();
return;
}
if (memcmp (m.getData(), startMessage, specialMessageSize) == 0)
{
owner.handleConnectionMade();
return;
}
}
owner.handleMessageFromMaster (m);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
};
//==============================================================================
ChildProcessSlave::ChildProcessSlave() {}
ChildProcessSlave::~ChildProcessSlave() {}
void ChildProcessSlave::handleConnectionMade() {}
void ChildProcessSlave::handleConnectionLost() {}
bool ChildProcessSlave::sendMessageToMaster (const MemoryBlock& mb)
{
if (connection != nullptr)
return connection->sendMessage (mb);
jassertfalse; // this can only be used when the connection is active!
return false;
}
bool ChildProcessSlave::initialiseFromCommandLine (const String& commandLine,
const String& commandLineUniqueID,
int timeoutMs)
{
String prefix (getCommandLinePrefix (commandLineUniqueID));
if (commandLine.trim().startsWith (prefix))
{
String pipeName (commandLine.fromFirstOccurrenceOf (prefix, false, false)
.upToFirstOccurrenceOf (" ", false, false).trim());
if (pipeName.isNotEmpty())
{
connection = new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs);
if (! connection->isConnected())
connection = nullptr;
}
}
return connection != nullptr;
}

View file

@ -0,0 +1,191 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_CONNECTEDCHILDPROCESS_H_INCLUDED
#define JUCE_CONNECTEDCHILDPROCESS_H_INCLUDED
//==============================================================================
/**
Acts as the slave end of a master/slave pair of connected processes.
The ChildProcessSlave and ChildProcessMaster classes make it easy for an app
to spawn a child process, and to manage a 2-way messaging connection to control it.
To use the system, you need to create subclasses of both ChildProcessSlave and
ChildProcessMaster. To instantiate the ChildProcessSlave object, you must
add some code to your main() or JUCEApplication::initialise() function that
calls the initialiseFromCommandLine() method to check the app's command-line
parameters to see whether it's being launched as a child process. If this returns
true then the slave process can be allowed to run, and its handleMessageFromMaster()
method will be called whenever a message arrives.
The juce demo app has a good example of this class in action.
@see ChildProcessMaster, InterprocessConnection, ChildProcess
*/
class JUCE_API ChildProcessSlave
{
public:
/** Creates a non-connected slave process.
Use initialiseFromCommandLine to connect to a master process.
*/
ChildProcessSlave();
/** Destructor. */
virtual ~ChildProcessSlave();
/** This checks some command-line parameters to see whether they were generated by
ChildProcessMaster::launchSlaveProcess(), and if so, connects to that master process.
In an exe that can be used as a child process, you should add some code to your
main() or JUCEApplication::initialise() that calls this method.
The commandLineUniqueID should be a short alphanumeric identifier (no spaces!)
that matches the string passed to ChildProcessMaster::launchSlaveProcess().
The timeoutMs parameter lets you specify how long the child process is allowed
to run without receiving a ping from the master before the master is considered to
have died, and handleConnectionLost() will be called. Passing <= 0 for this timeout
makes it use a default value.
Returns true if the command-line matches and the connection is made successfully.
*/
bool initialiseFromCommandLine (const String& commandLine,
const String& commandLineUniqueID,
int timeoutMs = 0);
//==============================================================================
/** This will be called to deliver messages from the master process.
The call will probably be made on a background thread, so be careful with your
thread-safety! You may want to respond by sending back a message with
sendMessageToMaster()
*/
virtual void handleMessageFromMaster (const MemoryBlock&) = 0;
/** This will be called when the master process finishes connecting to this slave.
The call will probably be made on a background thread, so be careful with your thread-safety!
*/
virtual void handleConnectionMade();
/** This will be called when the connection to the master process is lost.
The call may be made from any thread (including the message thread).
Typically, if your process only exists to act as a slave, you should probably exit
when this happens.
*/
virtual void handleConnectionLost();
/** Tries to send a message to the master process.
This returns true if the message was sent, but doesn't check that it actually gets
delivered at the other end. If successful, the data will emerge in a call to your
ChildProcessMaster::handleMessageFromSlave().
*/
bool sendMessageToMaster (const MemoryBlock&);
private:
struct Connection;
friend struct Connection;
friend struct ContainerDeletePolicy<Connection>;
ScopedPointer<Connection> connection;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessSlave)
};
//==============================================================================
/**
Acts as the master in a master/slave pair of connected processes.
The ChildProcessSlave and ChildProcessMaster classes make it easy for an app
to spawn a child process, and to manage a 2-way messaging connection to control it.
To use the system, you need to create subclasses of both ChildProcessSlave and
ChildProcessMaster. When you want your master process to launch the slave, you
just call launchSlaveProcess(), and it'll attempt to launch the executable that
you specify (which may be the same exe), and assuming it has been set-up to
correctly parse the command-line parameters (see ChildProcessSlave) then a
two-way connection will be created.
The juce demo app has a good example of this class in action.
@see ChildProcessSlave, InterprocessConnection, ChildProcess
*/
class JUCE_API ChildProcessMaster
{
public:
/** Creates an uninitialised master process object.
Use launchSlaveProcess to launch and connect to a child process.
*/
ChildProcessMaster();
/** Destructor. */
virtual ~ChildProcessMaster();
/** Attempts to launch and connect to a slave process.
This will start the given executable, passing it a special command-line
parameter based around the commandLineUniqueID string, which must be a
short alphanumeric string (no spaces!) that identifies your app. The exe
that gets launched must respond by calling ChildProcessSlave::initialiseFromCommandLine()
in its startup code, and must use a matching ID to commandLineUniqueID.
The timeoutMs parameter lets you specify how long the child process is allowed
to go without sending a ping before it is considered to have died and
handleConnectionLost() will be called. Passing <= 0 for this timeout makes
it use a default value.
If this all works, the method returns true, and you can begin sending and
receiving messages with the slave process.
*/
bool launchSlaveProcess (const File& executableToLaunch,
const String& commandLineUniqueID,
int timeoutMs = 0);
/** This will be called to deliver a message from the slave process.
The call will probably be made on a background thread, so be careful with your thread-safety!
*/
virtual void handleMessageFromSlave (const MemoryBlock&) = 0;
/** This will be called when the slave process dies or is somehow disconnected.
The call will probably be made on a background thread, so be careful with your thread-safety!
*/
virtual void handleConnectionLost();
/** Attempts to send a message to the slave process.
This returns true if the message was dispatched, but doesn't check that it actually
gets delivered at the other end. If successful, the data will emerge in a call to
your ChildProcessSlave::handleMessageFromMaster().
*/
bool sendMessageToSlave (const MemoryBlock&);
private:
ChildProcess childProcess;
struct Connection;
friend struct Connection;
friend struct ContainerDeletePolicy<Connection>;
ScopedPointer<Connection> connection;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessMaster)
};
#endif // JUCE_CONNECTEDCHILDPROCESS_H_INCLUDED

View file

@ -0,0 +1,365 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
struct InterprocessConnection::ConnectionThread : public Thread
{
ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
void run() override { owner.runThread(); }
private:
InterprocessConnection& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
};
//==============================================================================
InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
const uint32 magicMessageHeaderNumber)
: callbackConnectionState (false),
useMessageThread (callbacksOnMessageThread),
magicMessageHeader (magicMessageHeaderNumber),
pipeReceiveMessageTimeout (-1)
{
thread = new ConnectionThread (*this);
}
InterprocessConnection::~InterprocessConnection()
{
callbackConnectionState = false;
disconnect();
masterReference.clear();
thread = nullptr;
}
//==============================================================================
bool InterprocessConnection::connectToSocket (const String& hostName,
const int portNumber,
const int timeOutMillisecs)
{
disconnect();
const ScopedLock sl (pipeAndSocketLock);
socket = new StreamingSocket();
if (socket->connect (hostName, portNumber, timeOutMillisecs))
{
connectionMadeInt();
thread->startThread();
return true;
}
socket = nullptr;
return false;
}
bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
{
disconnect();
ScopedPointer<NamedPipe> newPipe (new NamedPipe());
if (newPipe->openExisting (pipeName))
{
const ScopedLock sl (pipeAndSocketLock);
pipeReceiveMessageTimeout = timeoutMs;
initialiseWithPipe (newPipe.release());
return true;
}
return false;
}
bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs)
{
disconnect();
ScopedPointer<NamedPipe> newPipe (new NamedPipe());
if (newPipe->createNewPipe (pipeName))
{
const ScopedLock sl (pipeAndSocketLock);
pipeReceiveMessageTimeout = timeoutMs;
initialiseWithPipe (newPipe.release());
return true;
}
return false;
}
void InterprocessConnection::disconnect()
{
thread->signalThreadShouldExit();
{
const ScopedLock sl (pipeAndSocketLock);
if (socket != nullptr) socket->close();
if (pipe != nullptr) pipe->close();
}
thread->stopThread (4000);
deletePipeAndSocket();
connectionLostInt();
}
void InterprocessConnection::deletePipeAndSocket()
{
const ScopedLock sl (pipeAndSocketLock);
socket = nullptr;
pipe = nullptr;
}
bool InterprocessConnection::isConnected() const
{
const ScopedLock sl (pipeAndSocketLock);
return ((socket != nullptr && socket->isConnected())
|| (pipe != nullptr && pipe->isOpen()))
&& thread->isThreadRunning();
}
String InterprocessConnection::getConnectedHostName() const
{
{
const ScopedLock sl (pipeAndSocketLock);
if (pipe == nullptr && socket == nullptr)
return String();
if (socket != nullptr && ! socket->isLocal())
return socket->getHostName();
}
return IPAddress::local().toString();
}
//==============================================================================
bool InterprocessConnection::sendMessage (const MemoryBlock& message)
{
uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
}
int InterprocessConnection::writeData (void* data, int dataSize)
{
const ScopedLock sl (pipeAndSocketLock);
if (socket != nullptr)
return socket->write (data, dataSize);
if (pipe != nullptr)
return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
return 0;
}
//==============================================================================
void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
{
jassert (socket == nullptr && pipe == nullptr);
socket = newSocket;
connectionMadeInt();
thread->startThread();
}
void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
{
jassert (socket == nullptr && pipe == nullptr);
pipe = newPipe;
connectionMadeInt();
thread->startThread();
}
//==============================================================================
struct ConnectionStateMessage : public MessageManager::MessageBase
{
ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
: owner (ipc), connectionMade (connected)
{}
void messageCallback() override
{
if (InterprocessConnection* const ipc = owner)
{
if (connectionMade)
ipc->connectionMade();
else
ipc->connectionLost();
}
}
WeakReference<InterprocessConnection> owner;
bool connectionMade;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
};
void InterprocessConnection::connectionMadeInt()
{
if (! callbackConnectionState)
{
callbackConnectionState = true;
if (useMessageThread)
(new ConnectionStateMessage (this, true))->post();
else
connectionMade();
}
}
void InterprocessConnection::connectionLostInt()
{
if (callbackConnectionState)
{
callbackConnectionState = false;
if (useMessageThread)
(new ConnectionStateMessage (this, false))->post();
else
connectionLost();
}
}
struct DataDeliveryMessage : public Message
{
DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
: owner (ipc), data (d)
{}
void messageCallback() override
{
if (InterprocessConnection* const ipc = owner)
ipc->messageReceived (data);
}
WeakReference<InterprocessConnection> owner;
MemoryBlock data;
};
void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
{
jassert (callbackConnectionState);
if (useMessageThread)
(new DataDeliveryMessage (this, data))->post();
else
messageReceived (data);
}
//==============================================================================
bool InterprocessConnection::readNextMessageInt()
{
uint32 messageHeader[2];
const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
: pipe ->read (messageHeader, sizeof (messageHeader), -1);
if (bytes == sizeof (messageHeader)
&& ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
{
int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
if (bytesInMessage > 0)
{
MemoryBlock messageData ((size_t) bytesInMessage, true);
int bytesRead = 0;
while (bytesInMessage > 0)
{
if (thread->threadShouldExit())
return false;
const int numThisTime = jmin (bytesInMessage, 65536);
void* const data = addBytesToPointer (messageData.getData(), bytesRead);
const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
: pipe ->read (data, numThisTime, -1);
if (bytesIn <= 0)
break;
bytesRead += bytesIn;
bytesInMessage -= bytesIn;
}
if (bytesRead >= 0)
deliverDataInt (messageData);
}
}
else if (bytes < 0)
{
if (socket != nullptr)
deletePipeAndSocket();
connectionLostInt();
return false;
}
return true;
}
void InterprocessConnection::runThread()
{
while (! thread->threadShouldExit())
{
if (socket != nullptr)
{
const int ready = socket->waitUntilReady (true, 0);
if (ready < 0)
{
deletePipeAndSocket();
connectionLostInt();
break;
}
if (ready == 0)
{
thread->wait (1);
continue;
}
}
else if (pipe != nullptr)
{
if (! pipe->isOpen())
{
deletePipeAndSocket();
connectionLostInt();
break;
}
}
else
{
break;
}
if (thread->threadShouldExit() || ! readNextMessageInt())
break;
}
}

View file

@ -0,0 +1,209 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_INTERPROCESSCONNECTION_H_INCLUDED
#define JUCE_INTERPROCESSCONNECTION_H_INCLUDED
class InterprocessConnectionServer;
class MemoryBlock;
//==============================================================================
/**
Manages a simple two-way messaging connection to another process, using either
a socket or a named pipe as the transport medium.
To connect to a waiting socket or an open pipe, use the connectToSocket() or
connectToPipe() methods. If this succeeds, messages can be sent to the other end,
and incoming messages will result in a callback via the messageReceived()
method.
To open a pipe and wait for another client to connect to it, use the createPipe()
method.
To act as a socket server and create connections for one or more client, see the
InterprocessConnectionServer class.
@see InterprocessConnectionServer, Socket, NamedPipe
*/
class JUCE_API InterprocessConnection
{
public:
//==============================================================================
/** Creates a connection.
Connections are created manually, connecting them with the connectToSocket()
or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
when a client wants to connect.
@param callbacksOnMessageThread if true, callbacks to the connectionMade(),
connectionLost() and messageReceived() methods will
always be made using the message thread; if false,
these will be called immediately on the connection's
own thread.
@param magicMessageHeaderNumber a magic number to use in the header to check the
validity of the data blocks being sent and received. This
can be any number, but the sender and receiver must obviously
use matching values or they won't recognise each other.
*/
InterprocessConnection (bool callbacksOnMessageThread = true,
uint32 magicMessageHeaderNumber = 0xf2b49e2c);
/** Destructor. */
virtual ~InterprocessConnection();
//==============================================================================
/** Tries to connect this object to a socket.
For this to work, the machine on the other end needs to have a InterprocessConnectionServer
object waiting to receive client connections on this port number.
@param hostName the host computer, either a network address or name
@param portNumber the socket port number to try to connect to
@param timeOutMillisecs how long to keep trying before giving up
@returns true if the connection is established successfully
@see Socket
*/
bool connectToSocket (const String& hostName,
int portNumber,
int timeOutMillisecs);
/** Tries to connect the object to an existing named pipe.
For this to work, another process on the same computer must already have opened
an InterprocessConnection object and used createPipe() to create a pipe for this
to connect to.
@param pipeName the name to use for the pipe - this should be unique to your app
@param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
to the pipe, or -1 for an infinite timeout.
@returns true if it connects successfully.
@see createPipe, NamedPipe
*/
bool connectToPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs);
/** Tries to create a new pipe for other processes to connect to.
This creates a pipe with the given name, so that other processes can use
connectToPipe() to connect to the other end.
@param pipeName the name to use for the pipe - this should be unique to your app
@param pipeReceiveMessageTimeoutMs a timeout length to be used when reading or writing
to the pipe, or -1 for an infinite timeout.
@returns true if the pipe was created, or false if it fails (e.g. if another process is
already using using the pipe).
*/
bool createPipe (const String& pipeName, int pipeReceiveMessageTimeoutMs);
/** Disconnects and closes any currently-open sockets or pipes. */
void disconnect();
/** True if a socket or pipe is currently active. */
bool isConnected() const;
/** Returns the socket that this connection is using (or nullptr if it uses a pipe). */
StreamingSocket* getSocket() const noexcept { return socket; }
/** Returns the pipe that this connection is using (or nullptr if it uses a socket). */
NamedPipe* getPipe() const noexcept { return pipe; }
/** Returns the name of the machine at the other end of this connection.
This may return an empty string if the name is unknown.
*/
String getConnectedHostName() const;
//==============================================================================
/** Tries to send a message to the other end of this connection.
This will fail if it's not connected, or if there's some kind of write error. If
it succeeds, the connection object at the other end will receive the message by
a callback to its messageReceived() method.
@see messageReceived
*/
bool sendMessage (const MemoryBlock& message);
//==============================================================================
/** Called when the connection is first connected.
If the connection was created with the callbacksOnMessageThread flag set, then
this will be called on the message thread; otherwise it will be called on a server
thread.
*/
virtual void connectionMade() = 0;
/** Called when the connection is broken.
If the connection was created with the callbacksOnMessageThread flag set, then
this will be called on the message thread; otherwise it will be called on a server
thread.
*/
virtual void connectionLost() = 0;
/** Called when a message arrives.
When the object at the other end of this connection sends us a message with sendMessage(),
this callback is used to deliver it to us.
If the connection was created with the callbacksOnMessageThread flag set, then
this will be called on the message thread; otherwise it will be called on a server
thread.
@see sendMessage
*/
virtual void messageReceived (const MemoryBlock& message) = 0;
private:
//==============================================================================
WeakReference<InterprocessConnection>::Master masterReference;
friend class WeakReference<InterprocessConnection>;
CriticalSection pipeAndSocketLock;
ScopedPointer <StreamingSocket> socket;
ScopedPointer <NamedPipe> pipe;
bool callbackConnectionState;
const bool useMessageThread;
const uint32 magicMessageHeader;
int pipeReceiveMessageTimeout;
friend class InterprocessConnectionServer;
void initialiseWithSocket (StreamingSocket*);
void initialiseWithPipe (NamedPipe*);
void deletePipeAndSocket();
void connectionMadeInt();
void connectionLostInt();
void deliverDataInt (const MemoryBlock&);
bool readNextMessageInt();
struct ConnectionThread;
friend struct ConnectionThread;
friend struct ContainerDeletePolicy<ConnectionThread>;
ScopedPointer<ConnectionThread> thread;
void runThread();
int writeData (void*, int);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection)
};
#endif // JUCE_INTERPROCESSCONNECTION_H_INCLUDED

View file

@ -0,0 +1,73 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
InterprocessConnectionServer::InterprocessConnectionServer()
: Thread ("Juce IPC server")
{
}
InterprocessConnectionServer::~InterprocessConnectionServer()
{
stop();
}
//==============================================================================
bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
{
stop();
socket = new StreamingSocket();
if (socket->createListener (portNumber))
{
startThread();
return true;
}
socket = nullptr;
return false;
}
void InterprocessConnectionServer::stop()
{
signalThreadShouldExit();
if (socket != nullptr)
socket->close();
stopThread (4000);
socket = nullptr;
}
void InterprocessConnectionServer::run()
{
while ((! threadShouldExit()) && socket != nullptr)
{
ScopedPointer<StreamingSocket> clientSocket (socket->waitForNextConnection());
if (clientSocket != nullptr)
if (InterprocessConnection* newConnection = createConnectionObject())
newConnection->initialiseWithSocket (clientSocket.release());
}
}

View file

@ -0,0 +1,93 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_INTERPROCESSCONNECTIONSERVER_H_INCLUDED
#define JUCE_INTERPROCESSCONNECTIONSERVER_H_INCLUDED
//==============================================================================
/**
An object that waits for client sockets to connect to a port on this host, and
creates InterprocessConnection objects for each one.
To use this, create a class derived from it which implements the createConnectionObject()
method, so that it creates suitable connection objects for each client that tries
to connect.
@see InterprocessConnection
*/
class JUCE_API InterprocessConnectionServer : private Thread
{
public:
//==============================================================================
/** Creates an uninitialised server object.
*/
InterprocessConnectionServer();
/** Destructor. */
~InterprocessConnectionServer();
//==============================================================================
/** Starts an internal thread which listens on the given port number.
While this is running, in another process tries to connect with the
InterprocessConnection::connectToSocket() method, this object will call
createConnectionObject() to create a connection to that client.
Use stop() to stop the thread running.
@see createConnectionObject, stop
*/
bool beginWaitingForSocket (int portNumber);
/** Terminates the listener thread, if it's active.
@see beginWaitingForSocket
*/
void stop();
protected:
/** Creates a suitable connection object for a client process that wants to
connect to this one.
This will be called by the listener thread when a client process tries
to connect, and must return a new InterprocessConnection object that will
then run as this end of the connection.
@see InterprocessConnection
*/
virtual InterprocessConnection* createConnectionObject() = 0;
private:
//==============================================================================
ScopedPointer <StreamingSocket> socket;
void run() override;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer)
};
#endif // JUCE_INTERPROCESSCONNECTIONSERVER_H_INCLUDED

View file

@ -0,0 +1,103 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#if defined (JUCE_EVENTS_H_INCLUDED) && ! JUCE_AMALGAMATED_INCLUDE
/* When you add this cpp file to your project, you mustn't include it in a file where you've
already included any other headers - just put it inside a file on its own, possibly with your config
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
header files that the compiler may be using.
*/
#error "Incorrect use of JUCE cpp file"
#endif
// Your project must contain an AppConfig.h file with your project-specific settings in it,
// and your header search path must make it accessible to the module's files.
#include "AppConfig.h"
#include "../juce_core/native/juce_BasicNativeHeaders.h"
#include "juce_events.h"
#if JUCE_CATCH_UNHANDLED_EXCEPTIONS && JUCE_MODULE_AVAILABLE_juce_gui_basics
#include "../juce_gui_basics/juce_gui_basics.h"
#endif
//==============================================================================
#if JUCE_MAC
#import <IOKit/IOKitLib.h>
#import <IOKit/IOCFPlugIn.h>
#import <IOKit/hid/IOHIDLib.h>
#import <IOKit/hid/IOHIDKeys.h>
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif JUCE_LINUX
#include <X11/Xlib.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#undef KeyPress
#include <unistd.h>
#endif
//==============================================================================
namespace juce
{
#include "messages/juce_ApplicationBase.cpp"
#include "messages/juce_DeletedAtShutdown.cpp"
#include "messages/juce_MessageListener.cpp"
#include "messages/juce_MessageManager.cpp"
#include "broadcasters/juce_ActionBroadcaster.cpp"
#include "broadcasters/juce_AsyncUpdater.cpp"
#include "broadcasters/juce_ChangeBroadcaster.cpp"
#include "timers/juce_MultiTimer.cpp"
#include "timers/juce_Timer.cpp"
#include "interprocess/juce_InterprocessConnection.cpp"
#include "interprocess/juce_InterprocessConnectionServer.cpp"
#include "interprocess/juce_ConnectedChildProcess.cpp"
//==============================================================================
#if JUCE_MAC
#include "../juce_core/native/juce_osx_ObjCHelpers.h"
#include "native/juce_osx_MessageQueue.h"
#include "native/juce_mac_MessageManager.mm"
#elif JUCE_IOS
#include "../juce_core/native/juce_osx_ObjCHelpers.h"
#include "native/juce_osx_MessageQueue.h"
#include "native/juce_ios_MessageManager.mm"
#elif JUCE_WINDOWS
#include "native/juce_win32_HiddenMessageWindow.h"
#include "native/juce_win32_Messaging.cpp"
#elif JUCE_LINUX
#include "native/juce_ScopedXLock.h"
#include "native/juce_linux_Messaging.cpp"
#elif JUCE_ANDROID
#include "../juce_core/native/juce_android_JNIHelpers.h"
#include "native/juce_android_Messaging.cpp"
#endif
}

View file

@ -0,0 +1,58 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_EVENTS_H_INCLUDED
#define JUCE_EVENTS_H_INCLUDED
//=============================================================================
#include "../juce_core/juce_core.h"
namespace juce
{
#include "messages/juce_MessageManager.h"
#include "messages/juce_Message.h"
#include "messages/juce_MessageListener.h"
#include "messages/juce_CallbackMessage.h"
#include "messages/juce_DeletedAtShutdown.h"
#include "messages/juce_NotificationType.h"
#include "messages/juce_ApplicationBase.h"
#include "messages/juce_Initialisation.h"
#include "messages/juce_MountedVolumeListChangeDetector.h"
#include "broadcasters/juce_ListenerList.h"
#include "broadcasters/juce_ActionBroadcaster.h"
#include "broadcasters/juce_ActionListener.h"
#include "broadcasters/juce_AsyncUpdater.h"
#include "broadcasters/juce_ChangeListener.h"
#include "broadcasters/juce_ChangeBroadcaster.h"
#include "timers/juce_Timer.h"
#include "timers/juce_MultiTimer.h"
#include "interprocess/juce_InterprocessConnection.h"
#include "interprocess/juce_InterprocessConnectionServer.h"
#include "interprocess/juce_ConnectedChildProcess.h"
#include "native/juce_ScopedXLock.h"
}
#endif // JUCE_EVENTS_H_INCLUDED

View file

@ -0,0 +1,25 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#include "juce_events.cpp"

View file

@ -0,0 +1,23 @@
{
"id": "juce_events",
"name": "JUCE message and event handling classes",
"version": "3.0.8",
"description": "Classes for running an application's main event loop and sending/receiving messages, timers, etc.",
"website": "http://www.juce.com/juce",
"license": "GPL/Commercial",
"dependencies": [ { "id": "juce_core", "version": "matching" } ],
"include": "juce_events.h",
"compile": [ { "file": "juce_events.cpp", "target": "! xcode" },
{ "file": "juce_events.mm", "target": "xcode" } ],
"browse": [ "messages/*",
"timers/*",
"broadcasters/*",
"interprocess/*",
"native/*" ],
"LinuxLibs": "X11"
}

View file

@ -0,0 +1,294 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
JUCEApplicationBase::CreateInstanceFunction JUCEApplicationBase::createInstance = 0;
JUCEApplicationBase* JUCEApplicationBase::appInstance = nullptr;
JUCEApplicationBase::JUCEApplicationBase()
: appReturnValue (0),
stillInitialising (true)
{
jassert (isStandaloneApp() && appInstance == nullptr);
appInstance = this;
}
JUCEApplicationBase::~JUCEApplicationBase()
{
jassert (appInstance == this);
appInstance = nullptr;
}
void JUCEApplicationBase::setApplicationReturnValue (const int newReturnValue) noexcept
{
appReturnValue = newReturnValue;
}
// This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
void JUCEApplicationBase::appWillTerminateByForce()
{
JUCE_AUTORELEASEPOOL
{
{
const ScopedPointer<JUCEApplicationBase> app (appInstance);
if (app != nullptr)
app->shutdownApp();
}
DeletedAtShutdown::deleteAll();
MessageManager::deleteInstance();
}
}
void JUCEApplicationBase::quit()
{
MessageManager::getInstance()->stopDispatchLoop();
}
void JUCEApplicationBase::sendUnhandledException (const std::exception* const e,
const char* const sourceFile,
const int lineNumber)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
app->unhandledException (e, sourceFile, lineNumber);
}
//==============================================================================
#if ! (JUCE_IOS || JUCE_ANDROID)
#define JUCE_HANDLE_MULTIPLE_INSTANCES 1
#endif
#if JUCE_HANDLE_MULTIPLE_INSTANCES
struct JUCEApplicationBase::MultipleInstanceHandler : public ActionListener
{
public:
MultipleInstanceHandler (const String& appName)
: appLock ("juceAppLock_" + appName)
{
}
bool sendCommandLineToPreexistingInstance()
{
if (appLock.enter (0))
return false;
JUCEApplicationBase* const app = JUCEApplicationBase::getInstance();
jassert (app != nullptr);
MessageManager::broadcastMessage (app->getApplicationName()
+ "/" + app->getCommandLineParameters());
return true;
}
void actionListenerCallback (const String& message) override
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
{
const String appName (app->getApplicationName());
if (message.startsWith (appName + "/"))
app->anotherInstanceStarted (message.substring (appName.length() + 1));
}
}
private:
InterProcessLock appLock;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultipleInstanceHandler)
};
bool JUCEApplicationBase::sendCommandLineToPreexistingInstance()
{
jassert (multipleInstanceHandler == nullptr); // this must only be called once!
multipleInstanceHandler = new MultipleInstanceHandler (getApplicationName());
return multipleInstanceHandler->sendCommandLineToPreexistingInstance();
}
#else
struct JUCEApplicationBase::MultipleInstanceHandler {};
#endif
//==============================================================================
#if JUCE_ANDROID
StringArray JUCEApplicationBase::getCommandLineParameterArray() { return StringArray(); }
String JUCEApplicationBase::getCommandLineParameters() { return String(); }
#else
#if JUCE_WINDOWS && ! defined (_CONSOLE)
String JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameters()
{
return CharacterFunctions::findEndOfToken (CharPointer_UTF16 (GetCommandLineW()),
CharPointer_UTF16 (L" "),
CharPointer_UTF16 (L"\"")).findEndOfWhitespace();
}
StringArray JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameterArray()
{
StringArray s;
int argc = 0;
if (LPWSTR* const argv = CommandLineToArgvW (GetCommandLineW(), &argc))
{
s = StringArray (argv + 1, argc - 1);
LocalFree (argv);
}
return s;
}
#else
#if JUCE_IOS
extern int juce_iOSMain (int argc, const char* argv[]);
#endif
#if JUCE_MAC
extern void initialiseNSApplication();
#endif
#if JUCE_WINDOWS
const char* const* juce_argv = nullptr;
int juce_argc = 0;
#else
extern const char* const* juce_argv; // declared in juce_core
extern int juce_argc;
#endif
String JUCEApplicationBase::getCommandLineParameters()
{
String argString;
for (int i = 1; i < juce_argc; ++i)
{
String arg (juce_argv[i]);
if (arg.containsChar (' ') && ! arg.isQuotedString())
arg = arg.quoted ('"');
argString << arg << ' ';
}
return argString.trim();
}
StringArray JUCEApplicationBase::getCommandLineParameterArray()
{
return StringArray (juce_argv + 1, juce_argc - 1);
}
int JUCEApplicationBase::main (int argc, const char* argv[])
{
JUCE_AUTORELEASEPOOL
{
juce_argc = argc;
juce_argv = argv;
#if JUCE_MAC
initialiseNSApplication();
#endif
#if JUCE_IOS
return juce_iOSMain (argc, argv);
#else
return JUCEApplicationBase::main();
#endif
}
}
#endif
//==============================================================================
int JUCEApplicationBase::main()
{
ScopedJuceInitialiser_GUI libraryInitialiser;
jassert (createInstance != nullptr);
const ScopedPointer<JUCEApplicationBase> app (createInstance());
jassert (app != nullptr);
if (! app->initialiseApp())
return app->getApplicationReturnValue();
JUCE_TRY
{
// loop until a quit message is received..
MessageManager::getInstance()->runDispatchLoop();
}
JUCE_CATCH_EXCEPTION
return app->shutdownApp();
}
#endif
//==============================================================================
bool JUCEApplicationBase::initialiseApp()
{
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if ((! moreThanOneInstanceAllowed()) && sendCommandLineToPreexistingInstance())
{
DBG ("Another instance is running - quitting...");
return false;
}
#endif
// let the app do its setting-up..
initialise (getCommandLineParameters());
stillInitialising = false;
if (MessageManager::getInstance()->hasStopMessageBeenSent())
return false;
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if (multipleInstanceHandler != nullptr)
MessageManager::getInstance()->registerBroadcastListener (multipleInstanceHandler);
#endif
return true;
}
int JUCEApplicationBase::shutdownApp()
{
jassert (JUCEApplicationBase::getInstance() == this);
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if (multipleInstanceHandler != nullptr)
MessageManager::getInstance()->deregisterBroadcastListener (multipleInstanceHandler);
#endif
JUCE_TRY
{
// give the app a chance to clean up..
shutdown();
}
JUCE_CATCH_EXCEPTION
multipleInstanceHandler = nullptr;
return getApplicationReturnValue();
}

View file

@ -0,0 +1,283 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_APPLICATIONBASE_H_INCLUDED
#define JUCE_APPLICATIONBASE_H_INCLUDED
//==============================================================================
/**
Abstract base class for application classes.
Note that in the juce_gui_basics module, there's a utility class JUCEApplication
which derives from JUCEApplicationBase, and takes care of a few chores. Most
of the time you'll want to derive your class from JUCEApplication rather than
using JUCEApplicationBase directly, but if you're not using the juce_gui_basics
module then you might need to go straight to this base class.
Any application that wants to run an event loop must declare a subclass of
JUCEApplicationBase, and implement its various pure virtual methods.
It then needs to use the START_JUCE_APPLICATION macro somewhere in a CPP file
to declare an instance of this class and generate suitable platform-specific
boilerplate code to launch the app.
e.g. @code
class MyJUCEApp : public JUCEApplication
{
public:
MyJUCEApp() {}
~MyJUCEApp() {}
void initialise (const String& commandLine) override
{
myMainWindow = new MyApplicationWindow();
myMainWindow->setBounds (100, 100, 400, 500);
myMainWindow->setVisible (true);
}
void shutdown() override
{
myMainWindow = nullptr;
}
const String getApplicationName() override
{
return "Super JUCE-o-matic";
}
const String getApplicationVersion() override
{
return "1.0";
}
private:
ScopedPointer<MyApplicationWindow> myMainWindow;
};
// this generates boilerplate code to launch our app class:
START_JUCE_APPLICATION (MyJUCEApp)
@endcode
@see JUCEApplication, START_JUCE_APPLICATION
*/
class JUCE_API JUCEApplicationBase
{
protected:
//==============================================================================
JUCEApplicationBase();
public:
/** Destructor. */
virtual ~JUCEApplicationBase();
//==============================================================================
/** Returns the global instance of the application object that's running. */
static JUCEApplicationBase* getInstance() noexcept { return appInstance; }
//==============================================================================
/** Returns the application's name. */
virtual const String getApplicationName() = 0;
/** Returns the application's version number. */
virtual const String getApplicationVersion() = 0;
/** Checks whether multiple instances of the app are allowed.
If you application class returns true for this, more than one instance is
permitted to run (except on the Mac where this isn't possible).
If it's false, the second instance won't start, but it you will still get a
callback to anotherInstanceStarted() to tell you about this - which
gives you a chance to react to what the user was trying to do.
*/
virtual bool moreThanOneInstanceAllowed() = 0;
/** Called when the application starts.
This will be called once to let the application do whatever initialisation
it needs, create its windows, etc.
After the method returns, the normal event-dispatch loop will be run,
until the quit() method is called, at which point the shutdown()
method will be called to let the application clear up anything it needs
to delete.
If during the initialise() method, the application decides not to start-up
after all, it can just call the quit() method and the event loop won't be run.
@param commandLineParameters the line passed in does not include the name of
the executable, just the parameter list. To get the
parameters as an array, you can call
JUCEApplication::getCommandLineParameters()
@see shutdown, quit
*/
virtual void initialise (const String& commandLineParameters) = 0;
/* Called to allow the application to clear up before exiting.
After JUCEApplication::quit() has been called, the event-dispatch loop will
terminate, and this method will get called to allow the app to sort itself
out.
Be careful that nothing happens in this method that might rely on messages
being sent, or any kind of window activity, because the message loop is no
longer running at this point.
@see DeletedAtShutdown
*/
virtual void shutdown() = 0;
/** Indicates that the user has tried to start up another instance of the app.
This will get called even if moreThanOneInstanceAllowed() is false.
*/
virtual void anotherInstanceStarted (const String& commandLine) = 0;
/** Called when the operating system is trying to close the application.
The default implementation of this method is to call quit(), but it may
be overloaded to ignore the request or do some other special behaviour
instead. For example, you might want to offer the user the chance to save
their changes before quitting, and give them the chance to cancel.
If you want to send a quit signal to your app, this is the correct method
to call, because it means that requests that come from the system get handled
in the same way as those from your own application code. So e.g. you'd
call this method from a "quit" item on a menu bar.
*/
virtual void systemRequestedQuit() = 0;
/** This method is called when the application is being put into background mode
by the operating system.
*/
virtual void suspended() = 0;
/** This method is called when the application is being woken from background mode
by the operating system.
*/
virtual void resumed() = 0;
/** If any unhandled exceptions make it through to the message dispatch loop, this
callback will be triggered, in case you want to log them or do some other
type of error-handling.
If the type of exception is derived from the std::exception class, the pointer
passed-in will be valid. If the exception is of unknown type, this pointer
will be null.
*/
virtual void unhandledException (const std::exception*,
const String& sourceFilename,
int lineNumber) = 0;
//==============================================================================
/** Signals that the main message loop should stop and the application should terminate.
This isn't synchronous, it just posts a quit message to the main queue, and
when this message arrives, the message loop will stop, the shutdown() method
will be called, and the app will exit.
Note that this will cause an unconditional quit to happen, so if you need an
extra level before this, e.g. to give the user the chance to save their work
and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
method - see that method's help for more info.
@see MessageManager
*/
static void quit();
//==============================================================================
/** Returns the application's command line parameters as a set of strings.
@see getCommandLineParameters
*/
static StringArray JUCE_CALLTYPE getCommandLineParameterArray();
/** Returns the application's command line parameters as a single string.
@see getCommandLineParameterArray
*/
static String JUCE_CALLTYPE getCommandLineParameters();
//==============================================================================
/** Sets the value that should be returned as the application's exit code when the
app quits.
This is the value that's returned by the main() function. Normally you'd leave this
as 0 unless you want to indicate an error code.
@see getApplicationReturnValue
*/
void setApplicationReturnValue (int newReturnValue) noexcept;
/** Returns the value that has been set as the application's exit code.
@see setApplicationReturnValue
*/
int getApplicationReturnValue() const noexcept { return appReturnValue; }
//==============================================================================
/** Returns true if this executable is running as an app (as opposed to being a plugin
or other kind of shared library. */
static bool isStandaloneApp() noexcept { return createInstance != nullptr; }
/** Returns true if the application hasn't yet completed its initialise() method
and entered the main event loop.
This is handy for things like splash screens to know when the app's up-and-running
properly.
*/
bool isInitialising() const noexcept { return stillInitialising; }
//==============================================================================
#ifndef DOXYGEN
// The following methods are for internal use only...
static int main();
static int main (int argc, const char* argv[]);
static void appWillTerminateByForce();
typedef JUCEApplicationBase* (*CreateInstanceFunction)();
static CreateInstanceFunction createInstance;
virtual bool initialiseApp();
static void JUCE_CALLTYPE sendUnhandledException (const std::exception*, const char* sourceFile, int lineNumber);
bool sendCommandLineToPreexistingInstance();
#endif
private:
//==============================================================================
static JUCEApplicationBase* appInstance;
int appReturnValue;
bool stillInitialising;
struct MultipleInstanceHandler;
friend struct MultipleInstanceHandler;
friend struct ContainerDeletePolicy<MultipleInstanceHandler>;
ScopedPointer<MultipleInstanceHandler> multipleInstanceHandler;
int shutdownApp();
JUCE_DECLARE_NON_COPYABLE (JUCEApplicationBase)
};
#endif // JUCE_APPLICATIONBASE_H_INCLUDED

View file

@ -0,0 +1,73 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_CALLBACKMESSAGE_H_INCLUDED
#define JUCE_CALLBACKMESSAGE_H_INCLUDED
//==============================================================================
/**
A message that invokes a callback method when it gets delivered.
You can use this class to fire off actions that you want to be performed later
on the message thread.
To use it, create a subclass of CallbackMessage which implements the messageCallback()
method, then call post() to dispatch it. The event thread will then invoke your
messageCallback() method later on, and will automatically delete the message object
afterwards.
Always create a new instance of a CallbackMessage on the heap, as it will be
deleted automatically after the message has been delivered.
@see MessageManager, MessageListener, ActionListener, ChangeListener
*/
class JUCE_API CallbackMessage : public MessageManager::MessageBase
{
public:
//==============================================================================
CallbackMessage() noexcept {}
/** Destructor. */
~CallbackMessage() {}
//==============================================================================
/** Called when the message is delivered.
You should implement this method and make it do whatever action you want
to perform.
Note that like all other messages, this object will be deleted immediately
after this method has been invoked.
*/
virtual void messageCallback() = 0;
private:
// Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
// messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
JUCE_DECLARE_NON_COPYABLE (CallbackMessage)
};
#endif // JUCE_CALLBACKMESSAGE_H_INCLUDED

View file

@ -0,0 +1,79 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
static SpinLock deletedAtShutdownLock;
DeletedAtShutdown::DeletedAtShutdown()
{
const SpinLock::ScopedLockType sl (deletedAtShutdownLock);
getObjects().add (this);
}
DeletedAtShutdown::~DeletedAtShutdown()
{
const SpinLock::ScopedLockType sl (deletedAtShutdownLock);
getObjects().removeFirstMatchingValue (this);
}
void DeletedAtShutdown::deleteAll()
{
// make a local copy of the array, so it can't get into a loop if something
// creates another DeletedAtShutdown object during its destructor.
Array <DeletedAtShutdown*> localCopy;
{
const SpinLock::ScopedLockType sl (deletedAtShutdownLock);
localCopy = getObjects();
}
for (int i = localCopy.size(); --i >= 0;)
{
JUCE_TRY
{
DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
// double-check that it's not already been deleted during another object's destructor.
{
const SpinLock::ScopedLockType sl (deletedAtShutdownLock);
if (! getObjects().contains (deletee))
deletee = nullptr;
}
delete deletee;
}
JUCE_CATCH_EXCEPTION
}
// if no objects got re-created during shutdown, this should have been emptied by their
// destructors
jassert (getObjects().size() == 0);
getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
}
Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
{
static Array <DeletedAtShutdown*> objects;
return objects;
}

View file

@ -0,0 +1,68 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_DELETEDATSHUTDOWN_H_INCLUDED
#define JUCE_DELETEDATSHUTDOWN_H_INCLUDED
//==============================================================================
/**
Classes derived from this will be automatically deleted when the application exits.
After JUCEApplicationBase::shutdown() has been called, any objects derived from
DeletedAtShutdown which are still in existence will be deleted in the reverse
order to that in which they were created.
So if you've got a singleton and don't want to have to explicitly delete it, just
inherit from this and it'll be taken care of.
*/
class JUCE_API DeletedAtShutdown
{
protected:
/** Creates a DeletedAtShutdown object. */
DeletedAtShutdown();
/** Destructor.
It's ok to delete these objects explicitly - it's only the ones left
dangling at the end that will be deleted automatically.
*/
virtual ~DeletedAtShutdown();
public:
/** Deletes all extant objects.
This shouldn't be used by applications, as it's called automatically
in the shutdown code of the JUCEApplicationBase class.
*/
static void deleteAll();
private:
static Array <DeletedAtShutdown*>& getObjects();
JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown)
};
#endif // JUCE_DELETEDATSHUTDOWN_H_INCLUDED

View file

@ -0,0 +1,112 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_INITIALISATION_H_INCLUDED
#define JUCE_INITIALISATION_H_INCLUDED
//==============================================================================
/** Initialises Juce's GUI classes.
If you're embedding Juce into an application that uses its own event-loop rather
than using the START_JUCE_APPLICATION macro, call this function before making any
Juce calls, to make sure things are initialised correctly.
Note that if you're creating a Juce DLL for Windows, you may also need to call the
Process::setCurrentModuleInstanceHandle() method.
@see shutdownJuce_GUI()
*/
JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
/** Clears up any static data being used by Juce's GUI classes.
If you're embedding Juce into an application that uses its own event-loop rather
than using the START_JUCE_APPLICATION macro, call this function in your shutdown
code to clean up any juce objects that might be lying around.
@see initialiseJuce_GUI()
*/
JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
//==============================================================================
/** A utility object that helps you initialise and shutdown Juce correctly
using an RAII pattern.
When the first instance of this class is created, it calls initialiseJuce_GUI(),
and when the last instance is deleted, it calls shutdownJuce_GUI(), so that you
can easily be sure that as long as at least one instance of the class exists, the
library will be initialised.
This class is particularly handy to use at the beginning of a console app's
main() function, because it'll take care of shutting down whenever you return
from the main() call.
Be careful with your threading though - to be safe, you should always make sure
that these objects are created and deleted on the message thread.
*/
class JUCE_API ScopedJuceInitialiser_GUI
{
public:
/** The constructor simply calls initialiseJuce_GUI(). */
ScopedJuceInitialiser_GUI();
/** The destructor simply calls shutdownJuce_GUI(). */
~ScopedJuceInitialiser_GUI();
};
//==============================================================================
/**
To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
AppSubClass is the name of a class derived from JUCEApplication or JUCEApplicationBase.
See the JUCEApplication and JUCEApplicationBase class documentation for more details.
*/
#ifdef DOXYGEN
#define START_JUCE_APPLICATION(AppClass)
#elif JUCE_ANDROID
#define START_JUCE_APPLICATION(AppClass) \
juce::JUCEApplicationBase* juce_CreateApplication() { return new AppClass(); }
#else
#if JUCE_WINDOWS && ! defined (_CONSOLE)
#define JUCE_MAIN_FUNCTION int __stdcall WinMain (struct HINSTANCE__*, struct HINSTANCE__*, char*, int)
#define JUCE_MAIN_FUNCTION_ARGS
#else
#define JUCE_MAIN_FUNCTION int main (int argc, char* argv[])
#define JUCE_MAIN_FUNCTION_ARGS argc, (const char**) argv
#endif
#define START_JUCE_APPLICATION(AppClass) \
static juce::JUCEApplicationBase* juce_CreateApplication() { return new AppClass(); } \
extern "C" JUCE_MAIN_FUNCTION \
{ \
juce::JUCEApplicationBase::createInstance = &juce_CreateApplication; \
return juce::JUCEApplicationBase::main (JUCE_MAIN_FUNCTION_ARGS); \
}
#endif
#endif // JUCE_INITIALISATION_H_INCLUDED

View file

@ -0,0 +1,65 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_MESSAGE_H_INCLUDED
#define JUCE_MESSAGE_H_INCLUDED
class MessageListener;
//==============================================================================
/** The base class for objects that can be sent to a MessageListener.
If you want to send a message that carries some kind of custom data, just
create a subclass of Message with some appropriate member variables to hold
your data.
Always create a new instance of a Message object on the heap, as it will be
deleted automatically after the message has been delivered.
@see MessageListener, MessageManager, ActionListener, ChangeListener
*/
class JUCE_API Message : public MessageManager::MessageBase
{
public:
//==============================================================================
/** Creates an uninitialised message. */
Message() noexcept;
~Message();
typedef ReferenceCountedObjectPtr<Message> Ptr;
//==============================================================================
private:
friend class MessageListener;
WeakReference<MessageListener> recipient;
void messageCallback() override;
// Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
// messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
JUCE_DECLARE_NON_COPYABLE (Message)
};
#endif // JUCE_MESSAGE_H_INCLUDED

View file

@ -0,0 +1,49 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
Message::Message() noexcept {}
Message::~Message() {}
void Message::messageCallback()
{
if (MessageListener* const r = recipient)
r->handleMessage (*this);
}
MessageListener::MessageListener() noexcept
{
// Are you trying to create a messagelistener before or after juce has been intialised??
jassert (MessageManager::getInstanceWithoutCreating() != nullptr);
}
MessageListener::~MessageListener()
{
masterReference.clear();
}
void MessageListener::postMessage (Message* const message) const
{
message->recipient = const_cast <MessageListener*> (this);
message->post();
}

View file

@ -0,0 +1,72 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_MESSAGELISTENER_H_INCLUDED
#define JUCE_MESSAGELISTENER_H_INCLUDED
//==============================================================================
/**
MessageListener subclasses can post and receive Message objects.
@see Message, MessageManager, ActionListener, ChangeListener
*/
class JUCE_API MessageListener
{
public:
//==============================================================================
MessageListener() noexcept;
/** Destructor. */
virtual ~MessageListener();
//==============================================================================
/** This is the callback method that receives incoming messages.
This is called by the MessageManager from its dispatch loop.
@see postMessage
*/
virtual void handleMessage (const Message& message) = 0;
//==============================================================================
/** Sends a message to the message queue, for asynchronous delivery to this listener
later on.
This method can be called safely by any thread.
@param message the message object to send - this will be deleted
automatically by the message queue, so make sure it's
allocated on the heap, not the stack!
@see handleMessage
*/
void postMessage (Message* message) const;
private:
WeakReference<MessageListener>::Master masterReference;
friend class WeakReference<MessageListener>;
};
#endif // JUCE_MESSAGELISTENER_H_INCLUDED

View file

@ -0,0 +1,375 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
MessageManager::MessageManager() noexcept
: quitMessagePosted (false),
quitMessageReceived (false),
messageThreadId (Thread::getCurrentThreadId()),
threadWithLock (0)
{
if (JUCEApplicationBase::isStandaloneApp())
Thread::setCurrentThreadName ("Juce Message Thread");
}
MessageManager::~MessageManager() noexcept
{
broadcaster = nullptr;
doPlatformSpecificShutdown();
jassert (instance == this);
instance = nullptr; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
}
MessageManager* MessageManager::instance = nullptr;
MessageManager* MessageManager::getInstance()
{
if (instance == nullptr)
{
instance = new MessageManager();
doPlatformSpecificInitialisation();
}
return instance;
}
MessageManager* MessageManager::getInstanceWithoutCreating() noexcept
{
return instance;
}
void MessageManager::deleteInstance()
{
deleteAndZero (instance);
}
//==============================================================================
bool MessageManager::MessageBase::post()
{
MessageManager* const mm = MessageManager::instance;
if (mm == nullptr || mm->quitMessagePosted || ! postMessageToSystemQueue (this))
{
Ptr deleter (this); // (this will delete messages that were just created with a 0 ref count)
return false;
}
return true;
}
//==============================================================================
#if JUCE_MODAL_LOOPS_PERMITTED && ! (JUCE_MAC || JUCE_IOS)
void MessageManager::runDispatchLoop()
{
runDispatchLoopUntil (-1);
}
bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
{
jassert (isThisTheMessageThread()); // must only be called by the message thread
const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
while (! quitMessageReceived)
{
JUCE_TRY
{
if (! dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
Thread::sleep (1);
}
JUCE_CATCH_EXCEPTION
if (millisecondsToRunFor >= 0 && Time::currentTimeMillis() >= endTime)
break;
}
return ! quitMessageReceived;
}
class MessageManager::QuitMessage : public MessageManager::MessageBase
{
public:
QuitMessage() {}
void messageCallback() override
{
if (MessageManager* const mm = MessageManager::instance)
mm->quitMessageReceived = true;
}
JUCE_DECLARE_NON_COPYABLE (QuitMessage)
};
void MessageManager::stopDispatchLoop()
{
(new QuitMessage())->post();
quitMessagePosted = true;
}
#endif
//==============================================================================
#if JUCE_COMPILER_SUPPORTS_LAMBDAS
struct AsyncFunction : private MessageManager::MessageBase
{
AsyncFunction (std::function<void(void)> f) : fn (f) { post(); }
private:
std::function<void(void)> fn;
void messageCallback() override { fn(); }
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncFunction)
};
void MessageManager::callAsync (std::function<void(void)> f)
{
new AsyncFunction (f);
}
#endif
//==============================================================================
class AsyncFunctionCallback : public MessageManager::MessageBase
{
public:
AsyncFunctionCallback (MessageCallbackFunction* const f, void* const param)
: result (nullptr), func (f), parameter (param)
{}
void messageCallback() override
{
result = (*func) (parameter);
finished.signal();
}
WaitableEvent finished;
void* volatile result;
private:
MessageCallbackFunction* const func;
void* const parameter;
JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCallback)
};
void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* const func, void* const parameter)
{
if (isThisTheMessageThread())
return func (parameter);
// If this thread has the message manager locked, then this will deadlock!
jassert (! currentThreadHasLockedMessageManager());
const ReferenceCountedObjectPtr<AsyncFunctionCallback> message (new AsyncFunctionCallback (func, parameter));
if (message->post())
{
message->finished.wait();
return message->result;
}
jassertfalse; // the OS message queue failed to send the message!
return nullptr;
}
//==============================================================================
void MessageManager::deliverBroadcastMessage (const String& value)
{
if (broadcaster != nullptr)
broadcaster->sendActionMessage (value);
}
void MessageManager::registerBroadcastListener (ActionListener* const listener)
{
if (broadcaster == nullptr)
broadcaster = new ActionBroadcaster();
broadcaster->addActionListener (listener);
}
void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
{
if (broadcaster != nullptr)
broadcaster->removeActionListener (listener);
}
//==============================================================================
bool MessageManager::isThisTheMessageThread() const noexcept
{
return Thread::getCurrentThreadId() == messageThreadId;
}
void MessageManager::setCurrentThreadAsMessageThread()
{
const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
if (messageThreadId != thisThread)
{
messageThreadId = thisThread;
// This is needed on windows to make sure the message window is created by this thread
doPlatformSpecificShutdown();
doPlatformSpecificInitialisation();
}
}
bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
{
const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
return thisThread == messageThreadId || thisThread == threadWithLock;
}
//==============================================================================
//==============================================================================
/* The only safe way to lock the message thread while another thread does
some work is by posting a special message, whose purpose is to tie up the event
loop until the other thread has finished its business.
Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
get locked before making an event callback, because if the same OS lock gets indirectly
accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
in Cocoa).
*/
class MessageManagerLock::BlockingMessage : public MessageManager::MessageBase
{
public:
BlockingMessage() noexcept {}
void messageCallback() override
{
lockedEvent.signal();
releaseEvent.wait();
}
WaitableEvent lockedEvent, releaseEvent;
JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
};
//==============================================================================
MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
: blockingMessage(), locked (attemptLock (threadToCheck, nullptr))
{
}
MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
: blockingMessage(), locked (attemptLock (nullptr, jobToCheckForExitSignal))
{
}
bool MessageManagerLock::attemptLock (Thread* const threadToCheck, ThreadPoolJob* const job)
{
MessageManager* const mm = MessageManager::instance;
if (mm == nullptr)
return false;
if (mm->currentThreadHasLockedMessageManager())
return true;
if (threadToCheck == nullptr && job == nullptr)
{
mm->lockingLock.enter();
}
else
{
while (! mm->lockingLock.tryEnter())
{
if ((threadToCheck != nullptr && threadToCheck->threadShouldExit())
|| (job != nullptr && job->shouldExit()))
return false;
Thread::yield();
}
}
blockingMessage = new BlockingMessage();
if (! blockingMessage->post())
{
blockingMessage = nullptr;
return false;
}
while (! blockingMessage->lockedEvent.wait (20))
{
if ((threadToCheck != nullptr && threadToCheck->threadShouldExit())
|| (job != nullptr && job->shouldExit()))
{
blockingMessage->releaseEvent.signal();
blockingMessage = nullptr;
mm->lockingLock.exit();
return false;
}
}
jassert (mm->threadWithLock == 0);
mm->threadWithLock = Thread::getCurrentThreadId();
return true;
}
MessageManagerLock::~MessageManagerLock() noexcept
{
if (blockingMessage != nullptr)
{
MessageManager* const mm = MessageManager::instance;
jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
blockingMessage->releaseEvent.signal();
blockingMessage = nullptr;
if (mm != nullptr)
{
mm->threadWithLock = 0;
mm->lockingLock.exit();
}
}
}
//==============================================================================
JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
{
JUCE_AUTORELEASEPOOL
{
MessageManager::getInstance();
}
}
JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
{
JUCE_AUTORELEASEPOOL
{
DeletedAtShutdown::deleteAll();
MessageManager::deleteInstance();
}
}
static int numScopedInitInstances = 0;
ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }

View file

@ -0,0 +1,335 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_MESSAGEMANAGER_H_INCLUDED
#define JUCE_MESSAGEMANAGER_H_INCLUDED
class MessageManagerLock;
class ThreadPoolJob;
class ActionListener;
class ActionBroadcaster;
//==============================================================================
/** See MessageManager::callFunctionOnMessageThread() for use of this function type
*/
typedef void* (MessageCallbackFunction) (void* userData);
//==============================================================================
/**
This class is in charge of the application's event-dispatch loop.
@see Message, CallbackMessage, MessageManagerLock, JUCEApplication, JUCEApplicationBase
*/
class JUCE_API MessageManager
{
public:
//==============================================================================
/** Returns the global instance of the MessageManager. */
static MessageManager* getInstance();
/** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
static MessageManager* getInstanceWithoutCreating() noexcept;
/** Deletes the global MessageManager instance.
Does nothing if no instance had been created.
*/
static void deleteInstance();
//==============================================================================
/** Runs the event dispatch loop until a stop message is posted.
This method is only intended to be run by the application's startup routine,
as it blocks, and will only return after the stopDispatchLoop() method has been used.
@see stopDispatchLoop
*/
void runDispatchLoop();
/** Sends a signal that the dispatch loop should terminate.
After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
will be interrupted and will return.
@see runDispatchLoop
*/
void stopDispatchLoop();
/** Returns true if the stopDispatchLoop() method has been called.
*/
bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
#if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
/** Synchronously dispatches messages until a given time has elapsed.
Returns false if a quit message has been posted by a call to stopDispatchLoop(),
otherwise returns true.
*/
bool runDispatchLoopUntil (int millisecondsToRunFor);
#endif
//==============================================================================
#if JUCE_COMPILER_SUPPORTS_LAMBDAS
/** Asynchronously invokes a function or C++11 lambda on the message thread.
Internally this uses the CallbackMessage class to invoke the callback.
*/
static void callAsync (std::function<void(void)>);
#endif
/** Calls a function using the message-thread.
This can be used by any thread to cause this function to be called-back
by the message thread. If it's the message-thread that's calling this method,
then the function will just be called; if another thread is calling, a message
will be posted to the queue, and this method will block until that message
is delivered, the function is called, and the result is returned.
Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
thread has a critical section locked, which an unrelated message callback then tries to lock
before the message thread gets round to processing this callback.
@param callback the function to call - its signature must be @code
void* myCallbackFunction (void*) @endcode
@param userData a user-defined pointer that will be passed to the function that gets called
@returns the value that the callback function returns.
@see MessageManagerLock
*/
void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
/** Returns true if the caller-thread is the message thread. */
bool isThisTheMessageThread() const noexcept;
/** Called to tell the manager that the current thread is the one that's running the dispatch loop.
(Best to ignore this method unless you really know what you're doing..)
@see getCurrentMessageThread
*/
void setCurrentThreadAsMessageThread();
/** Returns the ID of the current message thread, as set by setCurrentThreadAsMessageThread().
(Best to ignore this method unless you really know what you're doing..)
@see setCurrentThreadAsMessageThread
*/
Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
/** Returns true if the caller thread has currently got the message manager locked.
see the MessageManagerLock class for more info about this.
This will be true if the caller is the message thread, because that automatically
gains a lock while a message is being dispatched.
*/
bool currentThreadHasLockedMessageManager() const noexcept;
//==============================================================================
/** Sends a message to all other JUCE applications that are running.
@param messageText the string that will be passed to the actionListenerCallback()
method of the broadcast listeners in the other app.
@see registerBroadcastListener, ActionListener
*/
static void broadcastMessage (const String& messageText);
/** Registers a listener to get told about broadcast messages.
The actionListenerCallback() callback's string parameter
is the message passed into broadcastMessage().
@see broadcastMessage
*/
void registerBroadcastListener (ActionListener* listener);
/** Deregisters a broadcast listener. */
void deregisterBroadcastListener (ActionListener* listener);
//==============================================================================
/** Internal class used as the base class for all message objects.
You shouldn't need to use this directly - see the CallbackMessage or Message
classes instead.
*/
class JUCE_API MessageBase : public ReferenceCountedObject
{
public:
MessageBase() noexcept {}
virtual ~MessageBase() {}
virtual void messageCallback() = 0;
bool post();
typedef ReferenceCountedObjectPtr<MessageBase> Ptr;
JUCE_DECLARE_NON_COPYABLE (MessageBase)
};
//==============================================================================
#ifndef DOXYGEN
// Internal methods - do not use!
void deliverBroadcastMessage (const String&);
~MessageManager() noexcept;
#endif
private:
//==============================================================================
MessageManager() noexcept;
static MessageManager* instance;
friend class MessageBase;
class QuitMessage;
friend class QuitMessage;
friend class MessageManagerLock;
ScopedPointer <ActionBroadcaster> broadcaster;
bool quitMessagePosted, quitMessageReceived;
Thread::ThreadID messageThreadId;
Thread::ThreadID volatile threadWithLock;
CriticalSection lockingLock;
static bool postMessageToSystemQueue (MessageBase*);
static void* exitModalLoopCallback (void*);
static void doPlatformSpecificInitialisation();
static void doPlatformSpecificShutdown();
static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
};
//==============================================================================
/** Used to make sure that the calling thread has exclusive access to the message loop.
Because it's not thread-safe to call any of the Component or other UI classes
from threads other than the message thread, one of these objects can be used to
lock the message loop and allow this to be done. The message thread will be
suspended for the lifetime of the MessageManagerLock object, so create one on
the stack like this: @code
void MyThread::run()
{
someData = 1234;
const MessageManagerLock mmLock;
// the event loop will now be locked so it's safe to make a few calls..
myComponent->setBounds (newBounds);
myComponent->repaint();
// ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
}
@endcode
Obviously be careful not to create one of these and leave it lying around, or
your app will grind to a halt!
Another caveat is that using this in conjunction with other CriticalSections
can create lots of interesting ways of producing a deadlock! In particular, if
your message thread calls stopThread() for a thread that uses these locks,
you'll get an (occasional) deadlock..
@see MessageManager, MessageManager::currentThreadHasLockedMessageManager
*/
class JUCE_API MessageManagerLock
{
public:
//==============================================================================
/** Tries to acquire a lock on the message manager.
The constructor attempts to gain a lock on the message loop, and the lock will be
kept for the lifetime of this object.
Optionally, you can pass a thread object here, and while waiting to obtain the lock,
this method will keep checking whether the thread has been given the
Thread::signalThreadShouldExit() signal. If this happens, then it will return
without gaining the lock. If you pass a thread, you must check whether the lock was
successful by calling lockWasGained(). If this is false, your thread is being told to
die, so you should take evasive action.
If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
careful when doing this, because it's very easy to deadlock if your message thread
attempts to call stopThread() on a thread just as that thread attempts to get the
message lock.
If the calling thread already has the lock, nothing will be done, so it's safe and
quick to use these locks recursively.
E.g.
@code
void run()
{
...
while (! threadShouldExit())
{
MessageManagerLock mml (Thread::getCurrentThread());
if (! mml.lockWasGained())
return; // another thread is trying to kill us!
..do some locked stuff here..
}
..and now the MM is now unlocked..
}
@endcode
*/
MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
//==============================================================================
/** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
instead of a thread.
See the MessageManagerLock (Thread*) constructor for details on how this works.
*/
MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
//==============================================================================
/** Releases the current thread's lock on the message manager.
Make sure this object is created and deleted by the same thread,
otherwise there are no guarantees what will happen!
*/
~MessageManagerLock() noexcept;
//==============================================================================
/** Returns true if the lock was successfully acquired.
(See the constructor that takes a Thread for more info).
*/
bool lockWasGained() const noexcept { return locked; }
private:
class BlockingMessage;
friend class ReferenceCountedObjectPtr<BlockingMessage>;
ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
bool locked;
bool attemptLock (Thread*, ThreadPoolJob*);
JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
};
#endif // JUCE_MESSAGEMANAGER_H_INCLUDED

View file

@ -0,0 +1,59 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_MOUNTEDVOLUMELISTCHANGEDETECTOR_H_INCLUDED
#define JUCE_MOUNTEDVOLUMELISTCHANGEDETECTOR_H_INCLUDED
#if JUCE_MAC || JUCE_WINDOWS || defined (DOXYGEN)
//==============================================================================
/**
An instance of this class will provide callbacks when drives are
mounted or unmounted on the system.
Just inherit from this class and implement the pure virtual method
to get the callbacks, there's no need to do anything else.
@see File::findFileSystemRoots()
*/
class JUCE_API MountedVolumeListChangeDetector
{
public:
MountedVolumeListChangeDetector();
virtual ~MountedVolumeListChangeDetector();
/** This method is called when a volume is mounted or unmounted. */
virtual void mountedVolumeListChanged() = 0;
private:
JUCE_PUBLIC_IN_DLL_BUILD (struct Pimpl)
friend struct ContainerDeletePolicy<Pimpl>;
ScopedPointer<Pimpl> pimpl;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MountedVolumeListChangeDetector)
};
#endif
#endif // JUCE_MOUNTEDVOLUMELISTCHANGEDETECTOR_H_INCLUDED

View file

@ -0,0 +1,42 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_NOTIFICATIONTYPE_H_INCLUDED
#define JUCE_NOTIFICATIONTYPE_H_INCLUDED
//==============================================================================
/**
These enums are used in various classes to indicate whether a notification
event should be sent out.
*/
enum NotificationType
{
dontSendNotification = 0, /**< No notification message should be sent. */
sendNotification = 1, /**< Requests a notification message, either synchronous or not. */
sendNotificationSync, /**< Requests a synchronous notification. */
sendNotificationAsync, /**< Requests an asynchronous notification. */
};
#endif // JUCE_NOTIFICATIONTYPE_H_INCLUDED

View file

@ -0,0 +1,50 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_SCOPEDXLOCK_H_INCLUDED
#define JUCE_SCOPEDXLOCK_H_INCLUDED
//==============================================================================
#if JUCE_LINUX || DOXYGEN
/** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
using RAII (Only available in Linux!).
*/
class ScopedXLock
{
public:
/** Creating a ScopedXLock object locks the X display.
This uses XLockDisplay() to grab the display that Juce is using.
*/
ScopedXLock();
/** Deleting a ScopedXLock object unlocks the X display.
This calls XUnlockDisplay() to release the lock.
*/
~ScopedXLock();
};
#endif
#endif // JUCE_SCOPEDXLOCK_H_INCLUDED

View file

@ -0,0 +1,79 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
void MessageManager::doPlatformSpecificInitialisation() {}
void MessageManager::doPlatformSpecificShutdown() {}
//==============================================================================
bool MessageManager::dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
{
Logger::outputDebugString ("*** Modal loops are not possible in Android!! Exiting...");
exit (1);
return true;
}
//==============================================================================
bool MessageManager::postMessageToSystemQueue (MessageManager::MessageBase* const message)
{
message->incReferenceCount();
android.activity.callVoidMethod (JuceAppActivity.postMessage, (jlong) (pointer_sized_uint) message);
return true;
}
JUCE_JNI_CALLBACK (JUCE_ANDROID_ACTIVITY_CLASSNAME, deliverMessage, void, (jobject activity, jlong value))
{
JUCE_TRY
{
MessageManager::MessageBase* const message = (MessageManager::MessageBase*) (pointer_sized_uint) value;
message->messageCallback();
message->decReferenceCount();
}
JUCE_CATCH_EXCEPTION
}
//==============================================================================
void MessageManager::broadcastMessage (const String&)
{
}
void MessageManager::runDispatchLoop()
{
}
void MessageManager::stopDispatchLoop()
{
struct QuitCallback : public CallbackMessage
{
QuitCallback() {}
void messageCallback() override
{
android.activity.callVoidMethod (JuceAppActivity.finish);
}
};
(new QuitCallback())->post();
quitMessagePosted = true;
}

View file

@ -0,0 +1,88 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
void MessageManager::runDispatchLoop()
{
jassert (isThisTheMessageThread()); // must only be called by the message thread
runDispatchLoopUntil (-1);
}
void MessageManager::stopDispatchLoop()
{
[[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
exit (0); // iOS apps get no mercy..
}
bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
{
JUCE_AUTORELEASEPOOL
{
jassert (isThisTheMessageThread()); // must only be called by the message thread
uint32 startTime = Time::getMillisecondCounter();
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
while (! quitMessagePosted)
{
JUCE_AUTORELEASEPOOL
{
[[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
beforeDate: endDate];
if (millisecondsToRunFor >= 0
&& Time::getMillisecondCounter() >= startTime + (uint32) millisecondsToRunFor)
break;
}
}
return ! quitMessagePosted;
}
}
//==============================================================================
static ScopedPointer<MessageQueue> messageQueue;
void MessageManager::doPlatformSpecificInitialisation()
{
if (messageQueue == nullptr)
messageQueue = new MessageQueue();
}
void MessageManager::doPlatformSpecificShutdown()
{
messageQueue = nullptr;
}
bool MessageManager::postMessageToSystemQueue (MessageManager::MessageBase* const message)
{
if (messageQueue != nullptr)
messageQueue->post (message);
return true;
}
void MessageManager::broadcastMessage (const String&)
{
// N/A on current iOS
}

View file

@ -0,0 +1,398 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
#define JUCE_DEBUG_XERRORS 1
#endif
Display* display = nullptr;
Window juce_messageWindowHandle = None;
XContext windowHandleXContext; // This is referenced from Windowing.cpp
typedef bool (*WindowMessageReceiveCallback) (XEvent&);
WindowMessageReceiveCallback dispatchWindowMessage = nullptr;
typedef void (*SelectionRequestCallback) (XSelectionRequestEvent&);
SelectionRequestCallback handleSelectionRequest = nullptr;
//==============================================================================
ScopedXLock::ScopedXLock() { XLockDisplay (display); }
ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
//==============================================================================
class InternalMessageQueue
{
public:
InternalMessageQueue()
: bytesInSocket (0),
totalEventCount (0)
{
int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
(void) ret; jassert (ret == 0);
}
~InternalMessageQueue()
{
close (fd[0]);
close (fd[1]);
clearSingletonInstance();
}
//==============================================================================
void postMessage (MessageManager::MessageBase* const msg)
{
const int maxBytesInSocketQueue = 128;
ScopedLock sl (lock);
queue.add (msg);
if (bytesInSocket < maxBytesInSocketQueue)
{
++bytesInSocket;
ScopedUnlock ul (lock);
const unsigned char x = 0xff;
size_t bytesWritten = write (fd[0], &x, 1);
(void) bytesWritten;
}
}
bool isEmpty() const
{
ScopedLock sl (lock);
return queue.size() == 0;
}
bool dispatchNextEvent()
{
// This alternates between giving priority to XEvents or internal messages,
// to keep everything running smoothly..
if ((++totalEventCount & 1) != 0)
return dispatchNextXEvent() || dispatchNextInternalMessage();
return dispatchNextInternalMessage() || dispatchNextXEvent();
}
// Wait for an event (either XEvent, or an internal Message)
bool sleepUntilEvent (const int timeoutMs)
{
if (! isEmpty())
return true;
if (display != 0)
{
ScopedXLock xlock;
if (XPending (display))
return true;
}
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeoutMs * 1000;
int fd0 = getWaitHandle();
int fdmax = fd0;
fd_set readset;
FD_ZERO (&readset);
FD_SET (fd0, &readset);
if (display != 0)
{
ScopedXLock xlock;
int fd1 = XConnectionNumber (display);
FD_SET (fd1, &readset);
fdmax = jmax (fd0, fd1);
}
const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
return (ret > 0); // ret <= 0 if error or timeout
}
//==============================================================================
juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
private:
CriticalSection lock;
ReferenceCountedArray <MessageManager::MessageBase> queue;
int fd[2];
int bytesInSocket;
int totalEventCount;
int getWaitHandle() const noexcept { return fd[1]; }
static bool setNonBlocking (int handle)
{
int socketFlags = fcntl (handle, F_GETFL, 0);
if (socketFlags == -1)
return false;
socketFlags |= O_NONBLOCK;
return fcntl (handle, F_SETFL, socketFlags) == 0;
}
static bool dispatchNextXEvent()
{
if (display == 0)
return false;
XEvent evt;
{
ScopedXLock xlock;
if (! XPending (display))
return false;
XNextEvent (display, &evt);
}
if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle
&& handleSelectionRequest != nullptr)
handleSelectionRequest (evt.xselectionrequest);
else if (evt.xany.window != juce_messageWindowHandle && dispatchWindowMessage != nullptr)
dispatchWindowMessage (evt);
return true;
}
MessageManager::MessageBase::Ptr popNextMessage()
{
const ScopedLock sl (lock);
if (bytesInSocket > 0)
{
--bytesInSocket;
const ScopedUnlock ul (lock);
unsigned char x;
size_t numBytes = read (fd[1], &x, 1);
(void) numBytes;
}
return queue.removeAndReturn (0);
}
bool dispatchNextInternalMessage()
{
if (const MessageManager::MessageBase::Ptr msg = popNextMessage())
{
JUCE_TRY
{
msg->messageCallback();
return true;
}
JUCE_CATCH_EXCEPTION
}
return false;
}
};
juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
//==============================================================================
namespace LinuxErrorHandling
{
static bool errorOccurred = false;
static bool keyboardBreakOccurred = false;
static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
//==============================================================================
// Usually happens when client-server connection is broken
int ioErrorHandler (Display*)
{
DBG ("ERROR: connection to X server broken.. terminating.");
if (JUCEApplicationBase::isStandaloneApp())
MessageManager::getInstance()->stopDispatchLoop();
errorOccurred = true;
return 0;
}
int errorHandler (Display* display, XErrorEvent* event)
{
#if JUCE_DEBUG_XERRORS
char errorStr[64] = { 0 };
char requestStr[64] = { 0 };
XGetErrorText (display, event->error_code, errorStr, 64);
XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toUTF8(), "Unknown", requestStr, 64);
DBG ("ERROR: X returned " << errorStr << " for operation " << requestStr);
#endif
return 0;
}
void installXErrorHandlers()
{
oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
oldErrorHandler = XSetErrorHandler (errorHandler);
}
void removeXErrorHandlers()
{
if (JUCEApplicationBase::isStandaloneApp())
{
XSetIOErrorHandler (oldIOErrorHandler);
oldIOErrorHandler = 0;
XSetErrorHandler (oldErrorHandler);
oldErrorHandler = 0;
}
}
//==============================================================================
void keyboardBreakSignalHandler (int sig)
{
if (sig == SIGINT)
keyboardBreakOccurred = true;
}
void installKeyboardBreakHandler()
{
struct sigaction saction;
sigset_t maskSet;
sigemptyset (&maskSet);
saction.sa_handler = keyboardBreakSignalHandler;
saction.sa_mask = maskSet;
saction.sa_flags = 0;
sigaction (SIGINT, &saction, 0);
}
}
//==============================================================================
void MessageManager::doPlatformSpecificInitialisation()
{
if (JUCEApplicationBase::isStandaloneApp())
{
// Initialise xlib for multiple thread support
static bool initThreadCalled = false;
if (! initThreadCalled)
{
if (! XInitThreads())
{
// This is fatal! Print error and closedown
Logger::outputDebugString ("Failed to initialise xlib thread support.");
Process::terminate();
return;
}
initThreadCalled = true;
}
LinuxErrorHandling::installXErrorHandlers();
LinuxErrorHandling::installKeyboardBreakHandler();
}
// Create the internal message queue
InternalMessageQueue::getInstance();
// Try to connect to a display
String displayName (getenv ("DISPLAY"));
if (displayName.isEmpty())
displayName = ":0.0";
display = XOpenDisplay (displayName.toUTF8());
if (display != 0) // This is not fatal! we can run headless.
{
// Create a context to store user data associated with Windows we create
windowHandleXContext = XUniqueContext();
// We're only interested in client messages for this window, which are always sent
XSetWindowAttributes swa;
swa.event_mask = NoEventMask;
// Create our message window (this will never be mapped)
const int screen = DefaultScreen (display);
juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
0, 0, 1, 1, 0, 0, InputOnly,
DefaultVisual (display, screen),
CWEventMask, &swa);
}
}
void MessageManager::doPlatformSpecificShutdown()
{
InternalMessageQueue::deleteInstance();
if (display != 0 && ! LinuxErrorHandling::errorOccurred)
{
XDestroyWindow (display, juce_messageWindowHandle);
XCloseDisplay (display);
juce_messageWindowHandle = 0;
display = nullptr;
LinuxErrorHandling::removeXErrorHandlers();
}
}
bool MessageManager::postMessageToSystemQueue (MessageManager::MessageBase* const message)
{
if (LinuxErrorHandling::errorOccurred)
return false;
InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
return true;
}
void MessageManager::broadcastMessage (const String& /* value */)
{
/* TODO */
}
// this function expects that it will NEVER be called simultaneously for two concurrent threads
bool MessageManager::dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
{
while (! LinuxErrorHandling::errorOccurred)
{
if (LinuxErrorHandling::keyboardBreakOccurred)
{
LinuxErrorHandling::errorOccurred = true;
if (JUCEApplicationBase::isStandaloneApp())
Process::terminate();
break;
}
InternalMessageQueue* const queue = InternalMessageQueue::getInstanceWithoutCreating();
jassert (queue != nullptr);
if (queue->dispatchNextEvent())
return true;
if (returnIfNoPendingMessages)
break;
queue->sleepUntilEvent (2000);
}
return false;
}

View file

@ -0,0 +1,418 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
typedef void (*AppFocusChangeCallback)();
AppFocusChangeCallback appFocusChangeCallback = nullptr;
typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
CheckEventBlockedByModalComps isEventBlockedByModalComps = nullptr;
typedef void (*MenuTrackingChangedCallback)(bool);
MenuTrackingChangedCallback menuTrackingChangedCallback = nullptr;
//==============================================================================
struct AppDelegate
{
public:
AppDelegate()
{
static AppDelegateClass cls;
delegate = [cls.createInstance() init];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver: delegate selector: @selector (mainMenuTrackingBegan:)
name: NSMenuDidBeginTrackingNotification object: nil];
[center addObserver: delegate selector: @selector (mainMenuTrackingEnded:)
name: NSMenuDidEndTrackingNotification object: nil];
if (JUCEApplicationBase::isStandaloneApp())
{
[NSApp setDelegate: delegate];
[[NSDistributedNotificationCenter defaultCenter] addObserver: delegate
selector: @selector (broadcastMessageCallback:)
name: getBroacastEventName()
object: nil];
}
else
{
[center addObserver: delegate selector: @selector (applicationDidResignActive:)
name: NSApplicationDidResignActiveNotification object: NSApp];
[center addObserver: delegate selector: @selector (applicationDidBecomeActive:)
name: NSApplicationDidBecomeActiveNotification object: NSApp];
[center addObserver: delegate selector: @selector (applicationWillUnhide:)
name: NSApplicationWillUnhideNotification object: NSApp];
}
}
~AppDelegate()
{
[[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: delegate];
[[NSNotificationCenter defaultCenter] removeObserver: delegate];
if (JUCEApplicationBase::isStandaloneApp())
{
[NSApp setDelegate: nil];
[[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate
name: getBroacastEventName()
object: nil];
}
[delegate release];
}
static NSString* getBroacastEventName()
{
return juceStringToNS ("juce_" + String::toHexString (File::getSpecialLocation (File::currentExecutableFile).hashCode64()));
}
MessageQueue messageQueue;
id delegate;
private:
//==============================================================================
struct AppDelegateClass : public ObjCClass <NSObject>
{
AppDelegateClass() : ObjCClass <NSObject> ("JUCEAppDelegate_")
{
addMethod (@selector (applicationShouldTerminate:), applicationShouldTerminate, "I@:@");
addMethod (@selector (applicationWillTerminate:), applicationWillTerminate, "v@:@");
addMethod (@selector (application:openFile:), application_openFile, "c@:@@");
addMethod (@selector (application:openFiles:), application_openFiles, "v@:@@");
addMethod (@selector (applicationDidBecomeActive:), applicationDidBecomeActive, "v@:@");
addMethod (@selector (applicationDidResignActive:), applicationDidResignActive, "v@:@");
addMethod (@selector (applicationWillUnhide:), applicationWillUnhide, "v@:@");
addMethod (@selector (broadcastMessageCallback:), broadcastMessageCallback, "v@:@");
addMethod (@selector (mainMenuTrackingBegan:), mainMenuTrackingBegan, "v@:@");
addMethod (@selector (mainMenuTrackingEnded:), mainMenuTrackingEnded, "v@:@");
addMethod (@selector (dummyMethod), dummyMethod, "v@:");
registerClass();
}
private:
static NSApplicationTerminateReply applicationShouldTerminate (id /*self*/, SEL, NSApplication*)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
{
app->systemRequestedQuit();
if (! MessageManager::getInstance()->hasStopMessageBeenSent())
return NSTerminateCancel;
}
return NSTerminateNow;
}
static void applicationWillTerminate (id /*self*/, SEL, NSNotification*)
{
JUCEApplicationBase::appWillTerminateByForce();
}
static BOOL application_openFile (id /*self*/, SEL, NSApplication*, NSString* filename)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
{
app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
return YES;
}
return NO;
}
static void application_openFiles (id /*self*/, SEL, NSApplication*, NSArray* filenames)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
{
StringArray files;
for (NSString* f in filenames)
files.add (quotedIfContainsSpaces (f));
if (files.size() > 0)
app->anotherInstanceStarted (files.joinIntoString (" "));
}
}
static void applicationDidBecomeActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
static void applicationDidResignActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
static void applicationWillUnhide (id /*self*/, SEL, NSNotification*) { focusChanged(); }
static void broadcastMessageCallback (id /*self*/, SEL, NSNotification* n)
{
NSDictionary* dict = (NSDictionary*) [n userInfo];
const String messageString (nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]));
MessageManager::getInstance()->deliverBroadcastMessage (messageString);
}
static void mainMenuTrackingBegan (id /*self*/, SEL, NSNotification*)
{
if (menuTrackingChangedCallback != nullptr)
(*menuTrackingChangedCallback) (true);
}
static void mainMenuTrackingEnded (id /*self*/, SEL, NSNotification*)
{
if (menuTrackingChangedCallback != nullptr)
(*menuTrackingChangedCallback) (false);
}
static void dummyMethod (id /*self*/, SEL) {} // (used as a way of running a dummy thread)
private:
static void focusChanged()
{
if (appFocusChangeCallback != nullptr)
(*appFocusChangeCallback)();
}
static String quotedIfContainsSpaces (NSString* file)
{
String s (nsStringToJuce (file));
if (s.containsChar (' '))
s = s.quoted ('"');
return s;
}
};
};
//==============================================================================
void MessageManager::runDispatchLoop()
{
if (! quitMessagePosted) // check that the quit message wasn't already posted..
{
JUCE_AUTORELEASEPOOL
{
// must only be called by the message thread!
jassert (isThisTheMessageThread());
#if JUCE_PROJUCER_LIVE_BUILD
runDispatchLoopUntil (std::numeric_limits<int>::max());
#else
#if JUCE_CATCH_UNHANDLED_EXCEPTIONS
@try
{
[NSApp run];
}
@catch (NSException* e)
{
// An AppKit exception will kill the app, but at least this provides a chance to log it.,
std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
}
@finally
{
}
#else
[NSApp run];
#endif
#endif
}
}
}
static void shutdownNSApp()
{
[NSApp stop: nil];
[NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
[NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
}
void MessageManager::stopDispatchLoop()
{
quitMessagePosted = true;
#if ! JUCE_PROJUCER_LIVE_BUILD
if (isThisTheMessageThread())
{
shutdownNSApp();
}
else
{
struct QuitCallback : public CallbackMessage
{
QuitCallback() {}
void messageCallback() override { shutdownNSApp(); }
};
(new QuitCallback())->post();
}
#endif
}
#if JUCE_MODAL_LOOPS_PERMITTED
bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
{
jassert (millisecondsToRunFor >= 0);
jassert (isThisTheMessageThread()); // must only be called by the message thread
uint32 endTime = Time::getMillisecondCounter() + (uint32) millisecondsToRunFor;
while (! quitMessagePosted)
{
JUCE_AUTORELEASEPOOL
{
CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (e != nil && (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e)))
[NSApp sendEvent: e];
if (Time::getMillisecondCounter() >= endTime)
break;
}
}
return ! quitMessagePosted;
}
#endif
//==============================================================================
void initialiseNSApplication();
void initialiseNSApplication()
{
JUCE_AUTORELEASEPOOL
{
[NSApplication sharedApplication];
}
}
static AppDelegate* appDelegate = nullptr;
void MessageManager::doPlatformSpecificInitialisation()
{
if (appDelegate == nil)
appDelegate = new AppDelegate();
#if ! (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
// This launches a dummy thread, which forces Cocoa to initialise NSThreads correctly (needed prior to 10.5)
if (! [NSThread isMultiThreaded])
[NSThread detachNewThreadSelector: @selector (dummyMethod)
toTarget: appDelegate->delegate
withObject: nil];
#endif
}
void MessageManager::doPlatformSpecificShutdown()
{
delete appDelegate;
appDelegate = nullptr;
}
bool MessageManager::postMessageToSystemQueue (MessageBase* message)
{
jassert (appDelegate != nil);
appDelegate->messageQueue.post (message);
return true;
}
void MessageManager::broadcastMessage (const String& message)
{
NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
forKey: nsStringLiteral ("message")];
[[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroacastEventName()
object: nil
userInfo: info];
}
// Special function used by some plugin classes to re-post carbon events
void repostCurrentNSEvent();
void repostCurrentNSEvent()
{
struct EventReposter : public CallbackMessage
{
EventReposter() : e ([[NSApp currentEvent] retain]) {}
~EventReposter() { [e release]; }
void messageCallback() override
{
[NSApp postEvent: e atStart: YES];
}
NSEvent* e;
};
(new EventReposter())->post();
}
//==============================================================================
#if JUCE_MAC
struct MountedVolumeListChangeDetector::Pimpl
{
Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
{
static ObserverClass cls;
delegate = [cls.createInstance() init];
ObserverClass::setOwner (delegate, this);
NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
[nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
[nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
}
~Pimpl()
{
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
[delegate release];
}
private:
MountedVolumeListChangeDetector& owner;
id delegate;
struct ObserverClass : public ObjCClass<NSObject>
{
ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
{
addIvar<Pimpl*> ("owner");
addMethod (@selector (changed:), changed, "v@:@");
addProtocol (@protocol (NSTextInput));
registerClass();
}
static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
static void changed (id self, SEL, NSNotification*)
{
getOwner (self)->owner.mountedVolumeListChanged();
}
};
};
MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl = new Pimpl (*this); }
MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
#endif

View file

@ -0,0 +1,103 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_OSX_MESSAGEQUEUE_H_INCLUDED
#define JUCE_OSX_MESSAGEQUEUE_H_INCLUDED
//==============================================================================
/* An internal message pump class used in OSX and iOS. */
class MessageQueue
{
public:
MessageQueue()
{
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
runLoop = CFRunLoopGetMain();
#else
runLoop = CFRunLoopGetCurrent();
#endif
CFRunLoopSourceContext sourceContext;
zerostruct (sourceContext); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct)
sourceContext.info = this;
sourceContext.perform = runLoopSourceCallback;
runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
}
~MessageQueue()
{
CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
CFRunLoopSourceInvalidate (runLoopSource);
CFRelease (runLoopSource);
}
void post (MessageManager::MessageBase* const message)
{
messages.add (message);
CFRunLoopSourceSignal (runLoopSource);
CFRunLoopWakeUp (runLoop);
}
private:
ReferenceCountedArray <MessageManager::MessageBase, CriticalSection> messages;
CFRunLoopRef runLoop;
CFRunLoopSourceRef runLoopSource;
bool deliverNextMessage()
{
const MessageManager::MessageBase::Ptr nextMessage (messages.removeAndReturn (0));
if (nextMessage == nullptr)
return false;
JUCE_AUTORELEASEPOOL
{
JUCE_TRY
{
nextMessage->messageCallback();
}
JUCE_CATCH_EXCEPTION
}
return true;
}
void runLoopCallback()
{
for (int i = 4; --i >= 0;)
if (! deliverNextMessage())
return;
CFRunLoopSourceSignal (runLoopSource);
CFRunLoopWakeUp (runLoop);
}
static void runLoopSourceCallback (void* info)
{
static_cast <MessageQueue*> (info)->runLoopCallback();
}
};
#endif // JUCE_OSX_MESSAGEQUEUE_H_INCLUDED

View file

@ -0,0 +1,137 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_WIN32_HIDDENMESSAGEWINDOW_H_INCLUDED
#define JUCE_WIN32_HIDDENMESSAGEWINDOW_H_INCLUDED
//==============================================================================
class HiddenMessageWindow
{
public:
HiddenMessageWindow (const TCHAR* const messageWindowName, WNDPROC wndProc)
{
String className ("JUCE_");
className << String::toHexString (Time::getHighResolutionTicks());
HMODULE moduleHandle = (HMODULE) Process::getCurrentModuleInstanceHandle();
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof (wc);
wc.lpfnWndProc = wndProc;
wc.cbWndExtra = 4;
wc.hInstance = moduleHandle;
wc.lpszClassName = className.toWideCharPointer();
atom = RegisterClassEx (&wc);
jassert (atom != 0);
hwnd = CreateWindow (getClassNameFromAtom(), messageWindowName,
0, 0, 0, 0, 0, 0, 0, moduleHandle, 0);
jassert (hwnd != 0);
}
~HiddenMessageWindow()
{
DestroyWindow (hwnd);
UnregisterClass (getClassNameFromAtom(), 0);
}
inline HWND getHWND() const noexcept { return hwnd; }
private:
ATOM atom;
HWND hwnd;
LPCTSTR getClassNameFromAtom() noexcept { return (LPCTSTR) MAKELONG (atom, 0); }
};
//==============================================================================
class JuceWindowIdentifier
{
public:
static bool isJUCEWindow (HWND hwnd) noexcept
{
return GetWindowLongPtr (hwnd, GWLP_USERDATA) == getImprobableWindowNumber();
}
static void setAsJUCEWindow (HWND hwnd, bool isJuceWindow) noexcept
{
SetWindowLongPtr (hwnd, GWLP_USERDATA, isJuceWindow ? getImprobableWindowNumber() : 0);
}
private:
static LONG_PTR getImprobableWindowNumber() noexcept
{
static LONG_PTR number = (LONG_PTR) Random::getSystemRandom().nextInt64();
return number;
}
};
//==============================================================================
class DeviceChangeDetector : private Timer
{
public:
DeviceChangeDetector (const wchar_t* const name)
: messageWindow (name, (WNDPROC) deviceChangeEventCallback)
{
SetWindowLongPtr (messageWindow.getHWND(), GWLP_USERDATA, (LONG_PTR) this);
}
virtual ~DeviceChangeDetector() {}
virtual void systemDeviceChanged() = 0;
void triggerAsyncDeviceChangeCallback()
{
// We'll pause before sending a message, because on device removal, the OS hasn't always updated
// its device lists correctly at this point. This also helps avoid repeated callbacks.
startTimer (500);
}
private:
HiddenMessageWindow messageWindow;
static LRESULT CALLBACK deviceChangeEventCallback (HWND h, const UINT message,
const WPARAM wParam, const LPARAM lParam)
{
if (message == WM_DEVICECHANGE
&& (wParam == 0x8000 /*DBT_DEVICEARRIVAL*/
|| wParam == 0x8004 /*DBT_DEVICEREMOVECOMPLETE*/
|| wParam == 0x0007 /*DBT_DEVNODES_CHANGED*/))
{
((DeviceChangeDetector*) GetWindowLongPtr (h, GWLP_USERDATA))
->triggerAsyncDeviceChangeCallback();
}
return DefWindowProc (h, message, wParam, lParam);
}
void timerCallback() override
{
stopTimer();
systemDeviceChanged();
}
};
#endif // JUCE_WIN32_HIDDENMESSAGEWINDOW_H_INCLUDED

View file

@ -0,0 +1,217 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
extern HWND juce_messageWindowHandle;
typedef bool (*CheckEventBlockedByModalComps) (const MSG&);
CheckEventBlockedByModalComps isEventBlockedByModalComps = nullptr;
//==============================================================================
namespace WindowsMessageHelpers
{
const unsigned int specialId = WM_APP + 0x4400;
const unsigned int broadcastId = WM_APP + 0x4403;
const TCHAR messageWindowName[] = _T("JUCEWindow");
ScopedPointer<HiddenMessageWindow> messageWindow;
void dispatchMessageFromLParam (LPARAM lParam)
{
MessageManager::MessageBase* const message = reinterpret_cast <MessageManager::MessageBase*> (lParam);
JUCE_TRY
{
message->messageCallback();
}
JUCE_CATCH_EXCEPTION
message->decReferenceCount();
}
//==============================================================================
LRESULT CALLBACK messageWndProc (HWND h, const UINT message, const WPARAM wParam, const LPARAM lParam) noexcept
{
if (h == juce_messageWindowHandle)
{
if (message == specialId)
{
// (These are trapped early in our dispatch loop, but must also be checked
// here in case some 3rd-party code is running the dispatch loop).
dispatchMessageFromLParam (lParam);
return 0;
}
else if (message == broadcastId)
{
const ScopedPointer<String> messageString ((String*) lParam);
MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
return 0;
}
else if (message == WM_COPYDATA)
{
const COPYDATASTRUCT* const data = reinterpret_cast <const COPYDATASTRUCT*> (lParam);
if (data->dwData == broadcastId)
{
const String messageString (CharPointer_UTF32 ((const CharPointer_UTF32::CharType*) data->lpData),
data->cbData / sizeof (CharPointer_UTF32::CharType));
PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
return 0;
}
}
}
return DefWindowProc (h, message, wParam, lParam);
}
BOOL CALLBACK broadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
{
if (hwnd != juce_messageWindowHandle)
reinterpret_cast <Array<HWND>*> (lParam)->add (hwnd);
return TRUE;
}
}
//==============================================================================
bool MessageManager::dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
{
using namespace WindowsMessageHelpers;
MSG m;
if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, PM_NOREMOVE))
return false;
if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
{
if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
{
dispatchMessageFromLParam (m.lParam);
}
else if (m.message == WM_QUIT)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
app->systemRequestedQuit();
}
else if (isEventBlockedByModalComps == nullptr || ! isEventBlockedByModalComps (m))
{
if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
&& ! JuceWindowIdentifier::isJUCEWindow (m.hwnd))
{
// if it's someone else's window being clicked on, and the focus is
// currently on a juce window, pass the kb focus over..
HWND currentFocus = GetFocus();
if (currentFocus == 0 || JuceWindowIdentifier::isJUCEWindow (currentFocus))
SetFocus (m.hwnd);
}
TranslateMessage (&m);
DispatchMessage (&m);
}
}
return true;
}
bool MessageManager::postMessageToSystemQueue (MessageManager::MessageBase* const message)
{
message->incReferenceCount();
return PostMessage (juce_messageWindowHandle, WindowsMessageHelpers::specialId, 0, (LPARAM) message) != 0;
}
void MessageManager::broadcastMessage (const String& value)
{
Array<HWND> windows;
EnumWindows (&WindowsMessageHelpers::broadcastEnumWindowProc, (LPARAM) &windows);
const String localCopy (value);
COPYDATASTRUCT data;
data.dwData = WindowsMessageHelpers::broadcastId;
data.cbData = (localCopy.length() + 1) * sizeof (CharPointer_UTF32::CharType);
data.lpData = (void*) localCopy.toUTF32().getAddress();
for (int i = windows.size(); --i >= 0;)
{
HWND hwnd = windows.getUnchecked(i);
TCHAR windowName [64]; // no need to read longer strings than this
GetWindowText (hwnd, windowName, 64);
windowName [63] = 0;
if (String (windowName) == WindowsMessageHelpers::messageWindowName)
{
DWORD_PTR result;
SendMessageTimeout (hwnd, WM_COPYDATA,
(WPARAM) juce_messageWindowHandle,
(LPARAM) &data,
SMTO_BLOCK | SMTO_ABORTIFHUNG, 8000, &result);
}
}
}
//==============================================================================
void MessageManager::doPlatformSpecificInitialisation()
{
OleInitialize (0);
using namespace WindowsMessageHelpers;
messageWindow = new HiddenMessageWindow (messageWindowName, (WNDPROC) messageWndProc);
juce_messageWindowHandle = messageWindow->getHWND();
}
void MessageManager::doPlatformSpecificShutdown()
{
WindowsMessageHelpers::messageWindow = nullptr;
OleUninitialize();
}
//==============================================================================
struct MountedVolumeListChangeDetector::Pimpl : private DeviceChangeDetector
{
Pimpl (MountedVolumeListChangeDetector& d) : DeviceChangeDetector (L"MountedVolumeList"), owner (d)
{
File::findFileSystemRoots (lastVolumeList);
}
void systemDeviceChanged() override
{
Array<File> newList;
File::findFileSystemRoots (newList);
if (lastVolumeList != newList)
{
lastVolumeList = newList;
owner.mountedVolumeListChanged();
}
}
MountedVolumeListChangeDetector& owner;
Array<File> lastVolumeList;
};
MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl = new Pimpl (*this); }
MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}

View file

@ -0,0 +1,105 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
struct MultiTimerCallback : public Timer
{
MultiTimerCallback (const int tid, MultiTimer& mt) noexcept
: owner (mt), timerID (tid)
{
}
void timerCallback() override
{
owner.timerCallback (timerID);
}
MultiTimer& owner;
const int timerID;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiTimerCallback)
};
//==============================================================================
MultiTimer::MultiTimer() noexcept {}
MultiTimer::MultiTimer (const MultiTimer&) noexcept {}
MultiTimer::~MultiTimer()
{
const SpinLock::ScopedLockType sl (timerListLock);
timers.clear();
}
//==============================================================================
Timer* MultiTimer::getCallback (int timerID) const noexcept
{
for (int i = timers.size(); --i >= 0;)
{
MultiTimerCallback* const t = static_cast<MultiTimerCallback*> (timers.getUnchecked(i));
if (t->timerID == timerID)
return t;
}
return nullptr;
}
void MultiTimer::startTimer (const int timerID, const int intervalInMilliseconds) noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
Timer* timer = getCallback (timerID);
if (timer == nullptr)
timers.add (timer = new MultiTimerCallback (timerID, *this));
timer->startTimer (intervalInMilliseconds);
}
void MultiTimer::stopTimer (const int timerID) noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
t->stopTimer();
}
bool MultiTimer::isTimerRunning (const int timerID) const noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
return t->isTimerRunning();
return false;
}
int MultiTimer::getTimerInterval (const int timerID) const noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
return t->getTimerInterval();
return 0;
}

View file

@ -0,0 +1,126 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_MULTITIMER_H_INCLUDED
#define JUCE_MULTITIMER_H_INCLUDED
//==============================================================================
/**
A type of timer class that can run multiple timers with different frequencies,
all of which share a single callback.
This class is very similar to the Timer class, but allows you run multiple
separate timers, where each one has a unique ID number. The methods in this
class are exactly equivalent to those in Timer, but with the addition of
this ID number.
To use it, you need to create a subclass of MultiTimer, implementing the
timerCallback() method. Then you can start timers with startTimer(), and
each time the callback is triggered, it passes in the ID of the timer that
caused it.
@see Timer
*/
class JUCE_API MultiTimer
{
protected:
//==============================================================================
/** Creates a MultiTimer.
When created, no timers are running, so use startTimer() to start things off.
*/
MultiTimer() noexcept;
/** Creates a copy of another timer.
Note that this timer will not contain any running timers, even if the one you're
copying from was running.
*/
MultiTimer (const MultiTimer&) noexcept;
public:
//==============================================================================
/** Destructor. */
virtual ~MultiTimer();
//==============================================================================
/** The user-defined callback routine that actually gets called by each of the
timers that are running.
It's perfectly ok to call startTimer() or stopTimer() from within this
callback to change the subsequent intervals.
*/
virtual void timerCallback (int timerID) = 0;
//==============================================================================
/** Starts a timer and sets the length of interval required.
If the timer is already started, this will reset it, so the
time between calling this method and the next timer callback
will not be less than the interval length passed in.
@param timerID a unique Id number that identifies the timer to
start. This is the id that will be passed back
to the timerCallback() method when this timer is
triggered
@param intervalInMilliseconds the interval to use (any values less than 1 will be
rounded up to 1)
*/
void startTimer (int timerID, int intervalInMilliseconds) noexcept;
/** Stops a timer.
If a timer has been started with the given ID number, it will be cancelled.
No more callbacks will be made for the specified timer after this method returns.
If this is called from a different thread, any callbacks that may
be currently executing may be allowed to finish before the method
returns.
*/
void stopTimer (int timerID) noexcept;
//==============================================================================
/** Checks whether a timer has been started for a specified ID.
@returns true if a timer with the given ID is running.
*/
bool isTimerRunning (int timerID) const noexcept;
/** Returns the interval for a specified timer ID.
@returns the timer's interval in milliseconds if it's running, or 0 if no
timer was running for the ID number specified.
*/
int getTimerInterval (int timerID) const noexcept;
//==============================================================================
private:
SpinLock timerListLock;
OwnedArray<Timer> timers;
Timer* getCallback (int) const noexcept;
MultiTimer& operator= (const MultiTimer&);
};
#endif // JUCE_MULTITIMER_H_INCLUDED

View file

@ -0,0 +1,350 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
class Timer::TimerThread : private Thread,
private DeletedAtShutdown,
private AsyncUpdater
{
public:
typedef CriticalSection LockType; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
TimerThread()
: Thread ("Juce Timer"),
firstTimer (nullptr),
callbackNeeded (0)
{
triggerAsyncUpdate();
}
~TimerThread() noexcept
{
stopThread (4000);
jassert (instance == this || instance == nullptr);
if (instance == this)
instance = nullptr;
}
void run() override
{
uint32 lastTime = Time::getMillisecondCounter();
MessageManager::MessageBase::Ptr messageToSend (new CallTimersMessage());
while (! threadShouldExit())
{
const uint32 now = Time::getMillisecondCounter();
if (now == lastTime)
{
wait (1);
continue;
}
const int elapsed = (int) (now >= lastTime ? (now - lastTime)
: (std::numeric_limits<uint32>::max() - (lastTime - now)));
lastTime = now;
const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
if (timeUntilFirstTimer <= 0)
{
/* If we managed to set the atomic boolean to true then send a message, this is needed
as a memory barrier so the message won't be sent before callbackNeeded is set to true,
but if it fails it means the message-thread changed the value from under us so at least
some processing is happenening and we can just loop around and try again
*/
if (callbackNeeded.compareAndSetBool (1, 0))
{
messageToSend->post();
/* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
when the app has a modal loop), so this is how long to wait before assuming the
message has been lost and trying again.
*/
const uint32 messageDeliveryTimeout = now + 300;
while (callbackNeeded.get() != 0)
{
wait (4);
if (threadShouldExit())
return;
if (Time::getMillisecondCounter() > messageDeliveryTimeout)
{
messageToSend->post();
break;
}
}
}
}
else
{
// don't wait for too long because running this loop also helps keep the
// Time::getApproximateMillisecondTimer value stay up-to-date
wait (jlimit (1, 50, timeUntilFirstTimer));
}
}
}
void callTimers()
{
const LockType::ScopedLockType sl (lock);
while (firstTimer != nullptr && firstTimer->countdownMs <= 0)
{
Timer* const t = firstTimer;
t->countdownMs = t->periodMs;
removeTimer (t);
addTimer (t);
const LockType::ScopedUnlockType ul (lock);
JUCE_TRY
{
t->timerCallback();
}
JUCE_CATCH_EXCEPTION
}
/* This is needed as a memory barrier to make sure all processing of current timers is done
before the boolean is set. This set should never fail since if it was false in the first place,
we wouldn't get a message (so it can't be changed from false to true from under us), and if we
get a message then the value is true and the other thread can only set it to true again and
we will get another callback to set it to false.
*/
callbackNeeded.set (0);
}
void callTimersSynchronously()
{
if (! isThreadRunning())
{
// (This is relied on by some plugins in cases where the MM has
// had to restart and the async callback never started)
cancelPendingUpdate();
triggerAsyncUpdate();
}
callTimers();
}
static inline void add (Timer* const tim) noexcept
{
if (instance == nullptr)
instance = new TimerThread();
instance->addTimer (tim);
}
static inline void remove (Timer* const tim) noexcept
{
if (instance != nullptr)
instance->removeTimer (tim);
}
static inline void resetCounter (Timer* const tim, const int newCounter) noexcept
{
if (instance != nullptr)
{
tim->countdownMs = newCounter;
tim->periodMs = newCounter;
if ((tim->next != nullptr && tim->next->countdownMs < tim->countdownMs)
|| (tim->previous != nullptr && tim->previous->countdownMs > tim->countdownMs))
{
instance->removeTimer (tim);
instance->addTimer (tim);
}
}
}
static TimerThread* instance;
static LockType lock;
private:
Timer* volatile firstTimer;
Atomic <int> callbackNeeded;
struct CallTimersMessage : public MessageManager::MessageBase
{
CallTimersMessage() {}
void messageCallback() override
{
if (instance != nullptr)
instance->callTimers();
}
};
//==============================================================================
void addTimer (Timer* const t) noexcept
{
#if JUCE_DEBUG
// trying to add a timer that's already here - shouldn't get to this point,
// so if you get this assertion, let me know!
jassert (! timerExists (t));
#endif
Timer* i = firstTimer;
if (i == nullptr || i->countdownMs > t->countdownMs)
{
t->next = firstTimer;
firstTimer = t;
}
else
{
while (i->next != nullptr && i->next->countdownMs <= t->countdownMs)
i = i->next;
jassert (i != nullptr);
t->next = i->next;
t->previous = i;
i->next = t;
}
if (t->next != nullptr)
t->next->previous = t;
jassert ((t->next == nullptr || t->next->countdownMs >= t->countdownMs)
&& (t->previous == nullptr || t->previous->countdownMs <= t->countdownMs));
notify();
}
void removeTimer (Timer* const t) noexcept
{
#if JUCE_DEBUG
// trying to remove a timer that's not here - shouldn't get to this point,
// so if you get this assertion, let me know!
jassert (timerExists (t));
#endif
if (t->previous != nullptr)
{
jassert (firstTimer != t);
t->previous->next = t->next;
}
else
{
jassert (firstTimer == t);
firstTimer = t->next;
}
if (t->next != nullptr)
t->next->previous = t->previous;
t->next = nullptr;
t->previous = nullptr;
}
int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
{
const LockType::ScopedLockType sl (lock);
for (Timer* t = firstTimer; t != nullptr; t = t->next)
t->countdownMs -= numMillisecsElapsed;
return firstTimer != nullptr ? firstTimer->countdownMs : 1000;
}
void handleAsyncUpdate() override
{
startThread (7);
}
#if JUCE_DEBUG
bool timerExists (Timer* const t) const noexcept
{
for (Timer* tt = firstTimer; tt != nullptr; tt = tt->next)
if (tt == t)
return true;
return false;
}
#endif
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
};
Timer::TimerThread* Timer::TimerThread::instance = nullptr;
Timer::TimerThread::LockType Timer::TimerThread::lock;
//==============================================================================
Timer::Timer() noexcept
: countdownMs (0),
periodMs (0),
previous (nullptr),
next (nullptr)
{
}
Timer::Timer (const Timer&) noexcept
: countdownMs (0),
periodMs (0),
previous (nullptr),
next (nullptr)
{
}
Timer::~Timer()
{
stopTimer();
}
void Timer::startTimer (const int interval) noexcept
{
const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
if (periodMs == 0)
{
countdownMs = interval;
periodMs = jmax (1, interval);
TimerThread::add (this);
}
else
{
TimerThread::resetCounter (this, interval);
}
}
void Timer::stopTimer() noexcept
{
const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
if (periodMs > 0)
{
TimerThread::remove (this);
periodMs = 0;
}
}
void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
{
if (TimerThread::instance != nullptr)
TimerThread::instance->callTimersSynchronously();
}

View file

@ -0,0 +1,134 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_TIMER_H_INCLUDED
#define JUCE_TIMER_H_INCLUDED
//==============================================================================
/**
Makes repeated callbacks to a virtual method at a specified time interval.
A Timer's timerCallback() method will be repeatedly called at a given
interval. When you create a Timer object, it will do nothing until the
startTimer() method is called, which will cause the message thread to
start making callbacks at the specified interval, until stopTimer() is called
or the object is deleted.
The time interval isn't guaranteed to be precise to any more than maybe
10-20ms, and the intervals may end up being much longer than requested if the
system is busy. Because the callbacks are made by the main message thread,
anything that blocks the message queue for a period of time will also prevent
any timers from running until it can carry on.
If you need to have a single callback that is shared by multiple timers with
different frequencies, then the MultiTimer class allows you to do that - its
structure is very similar to the Timer class, but contains multiple timers
internally, each one identified by an ID number.
@see HighResolutionTimer, MultiTimer
*/
class JUCE_API Timer
{
protected:
//==============================================================================
/** Creates a Timer.
When created, the timer is stopped, so use startTimer() to get it going.
*/
Timer() noexcept;
/** Creates a copy of another timer.
Note that this timer won't be started, even if the one you're copying
is running.
*/
Timer (const Timer& other) noexcept;
public:
//==============================================================================
/** Destructor. */
virtual ~Timer();
//==============================================================================
/** The user-defined callback routine that actually gets called periodically.
It's perfectly ok to call startTimer() or stopTimer() from within this
callback to change the subsequent intervals.
*/
virtual void timerCallback() = 0;
//==============================================================================
/** Starts the timer and sets the length of interval required.
If the timer is already started, this will reset it, so the
time between calling this method and the next timer callback
will not be less than the interval length passed in.
@param intervalInMilliseconds the interval to use (any values less than 1 will be
rounded up to 1)
*/
void startTimer (int intervalInMilliseconds) noexcept;
/** Stops the timer.
No more callbacks will be made after this method returns.
If this is called from a different thread, any callbacks that may
be currently executing may be allowed to finish before the method
returns.
*/
void stopTimer() noexcept;
//==============================================================================
/** Checks if the timer has been started.
@returns true if the timer is running.
*/
bool isTimerRunning() const noexcept { return periodMs > 0; }
/** Returns the timer's interval.
@returns the timer's interval in milliseconds if it's running, or 0 if it's not.
*/
int getTimerInterval() const noexcept { return periodMs; }
//==============================================================================
/** For internal use only: invokes any timers that need callbacks.
Don't call this unless you really know what you're doing!
*/
static void JUCE_CALLTYPE callPendingTimersSynchronously();
private:
class TimerThread;
friend class TimerThread;
int countdownMs, periodMs;
Timer* previous;
Timer* next;
Timer& operator= (const Timer&);
};
#endif // JUCE_TIMER_H_INCLUDED