2 * Copyright 2008-2014 Haiku, Inc. All rights reserved.
3 * Distributed under the terms of the MIT License.
6 * Niels Sascha Reedijk, niels.reedijk@gmail.com
7 * John Scipione, jscipione@gmail.com
10 * headers/os/app/Looper.h hrev47355
11 * src/kits/app/Looper.cpp hrev47355
19 \brief Provides the BLooper class.
24 \def B_LOOPER_PORT_DEFAULT_CAPACITY
25 \brief The default size of the port of a BLooper.
35 \brief Receive and process messages in a separate thread.
37 When an object of this class is created, the message loop can be started
38 with Run(). This spawns the thread that receives messages and processes
39 messages. Messages are actually passed on to \link BHandler handlers \endlink
40 that are associated with this looper. By default there is always one
41 handler available: the looper itself. To 'quit' a looper, you should pass
42 a \c B_QUIT_REQUESTED message using one of the message post functions. When
43 a looper receives such a request, it will \b delete itself. As such, looper
44 should <em>always be created on the heap</em> (with \c new), and never on
47 Posting messages can be done using the various PostMessage() methods.
48 Whenever a message is posted, it will be added through to the message
49 queue. It is possible to apply filters (see AddCommonFilter()) to filter
50 out any messages that correspond with certain criteria. The method will
51 copy the contents of the message and this copy is processed, so make sure
52 you delete the original messages in case you create them on the heap.
53 The handler for the message is chosen using the following criteria:
55 -# If PostMessage() or the BMessenger is set to a specific handler, and
56 this handler is associated with this looper, than the message is
57 processed by that handler.
58 -# Else, the preferred handler is used. You can set this using
59 SetPreferredHandler().
60 -# If there is no preferred handler, then the looper itself will process
63 Because a looper usually is used in multiple threads, you should make sure
64 you Lock() and Unlock() it during most operations. Locking calls can be
65 recursive (so multiple locks can come from a single thread), but make sure
66 you pair every Lock() with an Unlock() call. Failing to do so will
67 inevitably cause a deadlock.
69 Because a looper provides a separate thread, and the inherited handler is
70 usually a default handler, you will most often use this class by
71 subclassing it. For example, you are likely to subclass BWindow (which is
72 derived from BLooper) to customize your window and handle the messages
73 sent to that window. You can override Run() in case you want to perform
74 additional tasks before (or right after) starting the message loop. You can
75 override QuitRequested() if you want to decline quitting in certain
76 circumstances. You can override Quit() in case you want to perform
77 additional procedures during closing time. You can also override
78 DispatchMessage() if you want to do something with all incoming messages
79 before they are dispatched to a handler.
81 BLooper is one of the major base classes of the Haiku application
82 programmers interface. Closely related classes are BMessage, BHandler and
83 BMessenger. It is used in the interface kit, for example by the BWindow
84 class, which makes sure every window runs it its own thread.
86 BLooper is a part of the chain in the eloquent messaging structure. For a
87 proper understanding of all its facets, have a look at the \ref app_messaging
95 \fn BLooper::BLooper(const char* name, int32 priority, int32 portCapacity)
96 \brief Construct a new BLooper with a \a priority and an \a capacity.
98 The new looper is, by default, not running yet. If you have set up
99 everything properly, you may call Run().
101 \attention Remember that loopers should be created on the heap, because
102 they will \c delete themselves in the Quit() method.
104 \param name The name of the looper.
105 \param priority The priority of the message thread of this looper. The
106 default priority should be good enough for most tasks. Also, some
107 derived versions of BLooper will use a specialized priority. So it
108 is advised to leave this setting at the default, unless you know
109 why you would like another setting.
110 \param portCapacity Loopers use ports to send and receive messages (see
111 the kernel kit). Ports have a maximum capacity; if there are so many
112 messages queued that the port is full, all other incoming messages
113 are dropped. There are situations where the size of the port should
114 be different from the default. This might be when your looper
115 receives a lot of messages, or if the message handling thread runs
116 at a lower priority than normal, which would decrease the processing
117 speed. Finding a suitable value for these custom scenarios would be
127 \fn BLooper::~BLooper()
128 \brief Destruct the looper.
130 You will never delete a looper yourself. You should pass a
131 \c B_QUIT_REQUESTED message, or if you are destroying the looper from
132 inside its own message handling thread, you should call Quit().
140 ///// Archiving /////
152 \fn BLooper::BLooper(BMessage* data)
153 \brief Construct a looper from an archived message.
155 The \a data message has to be constructed by a BLooper::Archive() call.
156 Note that the data that is restored, is merely the port capacity and the
157 name of the looper/handler. Other data, such as filters, is not archived by
158 the default archiver.
160 \warning This constructor does no type check whatsoever. Since you can pass
161 any BMessage, you should - if you are not sure about the exact
162 type - use the Instantiate() method, which does check the type.
172 \fn BArchivable* BLooper::Instantiate(BMessage* data)
173 \brief Static method to instantiate a looper from an archived message.
175 \return A pointer to the instantiated looper, or \c NULL if the \a data
176 is not a valid archived BLooper object.
178 \see BLooper(BMessage* data)
185 \fn status_t BLooper::Archive(BMessage* data, bool deep) const
186 \brief Archive a looper to a message
188 Currently, only the name and the port capacity are archived. Any other
189 data, such as the filters, is not stored.
191 \param data The message to archive the object in.
192 \param deep This parameter is ignored, as BLooper does not have children.
194 \retval B_OK Archiving succeeded.
195 \retval B_BAD_VALUE The \a data parameter is not a valid message.
197 \see BLooper::Instantiate(BMessage* data)
207 \name Message Mechanics
215 \fn status_t BLooper::PostMessage(uint32 command)
216 \brief Post a message with the \a command as \c what identifier to this
219 Posting a message puts it in the message queue. The message passes through
220 the default handler chain.
222 \param command The \c what identifier of the message that needs to be sent.
224 \return A status code.
225 \retval B_OK The operation succeeded, and the message is sent to the port.
226 \retval B_ERROR There was a general operation error.
227 \retval B_BAD_VALUE This looper is not yet running and therefore cannot
230 \see PostMessage(BMessage *) if you want to send a message with data
232 \see PostMessage(uint32, BHandler *, BHandler *) if you want to send a
233 message to a specific handler, and request a reply.
234 \see PostMessage(BMessage *, BHandler *, BHandler *) for the same thing,
235 but with a complete message.
242 \fn status_t BLooper::PostMessage(BMessage* message)
243 \brief Post a \a message to this looper.
245 Posting a message puts it in the message queue. The message passes through
246 the default handler chain.
248 The \a message is copied, and as such, you should make sure you will not
249 leak it. The best way to send messages is like this:
252 message.what = B_DO_SOMETHING;
253 message.AddString("some_data", "This is data")
255 aLooper->PostMessage(&message);
258 \param message The message you would like to pass to this method.
260 \return A status code.
261 \retval B_OK The operation succeeded, and the message is sent to the port.
262 \retval B_ERROR There was a general operation error.
263 \retval B_BAD_VALUE This looper is not yet running and therefore cannot
266 \see PostMessage(uint32) if you want to send a message without data
268 \see PostMessage(uint32, BHandler *, BHandler *) if you want to send a
269 message to a specific handler, and request a reply.
270 \see PostMessage(BMessage *, BHandler *, BHandler *) for the same thing,
271 but with a complete message.
278 \fn status_t BLooper::PostMessage(uint32 command, BHandler* handler,
280 \brief Send a message with the \a command as \c what identifier to the
281 \a handler associated with this looper, and (optionally) request a
284 The target \a handler should be associated with this looper. This method
285 bypasses the default message queue.
287 \param command The value you want as the message's \c what identifier.
288 \param handler The handler you would like to pass this message to.
289 \param replyTo If you would like to request a reply, pass the handler to
290 which this reply should be directed to. If you pass \c NULL, you
291 will not receive a reply.
293 \return A status code.
294 \retval B_OK The operation succeeded, and the message is sent to the port.
295 \retval B_ERROR There was a general operation error.
296 \retval B_BAD_VALUE This looper is not yet running and therefore cannot
298 \retval B_MISMATCHED_VALUES The \a handler is not associated with this
301 \see PostMessage(uint32) if you want to send a message without data
303 \see PostMessage(BMessage *) if you want to send a message with data
305 \see PostMessage(BMessage *, BHandler *, BHandler *) if you want to send a
306 message to a specific handler, and request a reply.
313 \fn status_t BLooper::PostMessage(BMessage* message, BHandler* handler,
315 \brief Send a \a message to the \a handler associated with this looper,
316 and (optionally) request a reply.
318 The target \a handler should be associated with this looper. This method
319 bypasses the default message queue.
321 The \a message is copied, and as such, you should make sure you will not
322 leak it. The best way to send messages is like this:
325 message.what = B_DO_SOMETHING;
326 message.AddString("some_data", "This is data")
328 aLooper->PostMessage(&message, aHandler);
331 \param message The message you want to pass.
332 \param handler The handler you would like to pass this message to.
333 \param replyTo If you would like to request a reply, pass the handler to
334 which this reply should be directed to. If you pass \c NULL, you
335 will not receive a reply.
337 \return A status code.
338 \retval B_OK The operation succeeded, and the message is sent to the port.
339 \retval B_ERROR There was a general operation error.
340 \retval B_BAD_VALUE This looper is not yet running and therefore cannot
342 \retval B_MISMATCHED_VALUES The \a handler is not associated with this
345 \see PostMessage(uint32) if you want to send a message without data
347 \see PostMessage(BMessage *) if you want to send a message with data
349 \see PostMessage(uint32, BHandler *, BHandler *) if you want to send a
350 message without data to a specific handler, and request a reply.
360 \name Message Processing
368 \fn void BLooper::DispatchMessage(BMessage *message, BHandler *handler)
369 \brief Dispatch a message to a handler. Override if there are messages that
370 you want to catch before they are sent to the handlers.
372 This method is called by the message looping thread to dispatch a message
373 to \a handler. If you implement the BLooper class and your looper receives
374 messages that absolutely have to be processed by the looper instead of any
375 of the handlers, override this method. For example, the default
376 implementation catches B_QUIT_REQUESTED messages before they are sent to
377 the handlers, so that the looper will quit at those messages.
379 You are discouraged from using this method to filter out any messages you
380 do not want to process. For this, there is a more generic method using
381 the BMessageFilter class. If you want to skip messages with certain
382 patterns, have a look at the AddCommonFilter() and SetCommonFilterList()
385 If you do override this method, please remember to call the
386 DispatchMessage() method of the parent class.
393 \fn void BLooper::MessageReceived(BMessage* message)
394 \brief Process a message received by the internal handler of this looper.
396 Reimplemented from BHandler::MessageReceived();
403 \fn BMessage* BLooper::CurrentMessage() const
404 \brief Retrieve the current message.
406 \attention Only call this method from within the thread that processes the
407 messages. It contains a pointer to the message that is currently
408 being handled. Due to the multithreaded nature of the operating
409 system, this method will not safely let you read the message
410 that is being processed by this handler from outside the context
411 of the processing. If you do want to use a message outside of
412 the processing thread, have a look at DetachCurrentMessage() to
413 safely retrieve a message.
415 \return A pointer to the message that is currently being processed. Note
416 that calling it from outside the thread that processes the message,
417 could give you a \c NULL pointer or an invalid pointer.
424 \fn BMessage* BLooper::DetachCurrentMessage()
425 \brief Get ownership of the message currently being processed.
427 Retrieve the current message and gain ownership of it. This means that the
428 message will not be deleted as soon as the looper is done processing it.
429 You can then use it for different purposes.
431 \attention Only call this method from within the thread that processes the
432 messages. Due to the multithreaded nature of the operating
433 system, calling it from another thread is very likely to give
434 you an invalid or a \c NULL pointer.
441 \fn BMessageQueue* BLooper::MessageQueue() const
442 \brief Get a pointer to the internal message queue of this looper.
444 You can use this pointer to manipulate the message queue. Note that the
445 message that is being processed is already detached from this queue.
447 \return A pointer to the internal message queue.
454 \fn bool BLooper::IsMessageWaiting() const
455 \brief Check if there is a message waiting.
457 \return \c true if there are still messages to be processed,
458 \c false if there is no message waiting.
466 \name Handler Management
474 \fn void BLooper::AddHandler(BHandler* handler)
475 \brief Associate a \a handler to this looper.
477 The \a handler will be associated to this looper. By default, the handler
478 in this looper will be chained to the supplied \a handler.
480 \param handler The handler to associate with this looper. If the handler
481 is already associated to another looper, the operation will fail
482 silently. Check beforehand if you cannot be sure that the
483 \a handler is unassociated.
492 \fn bool BLooper::RemoveHandler(BHandler* handler)
493 \brief Disassociate a \a handler from this looper.
495 If the handler is disassociated, it can be reassociated to another looper.
497 \return \c true if the \a handler has been removed from this looper,
498 \c false The \a handler was invalid or the handler was not
499 associated to this looper.
508 \fn int32 BLooper::CountHandlers() const
509 \brief Get the number of handlers associated with this looper.
519 \fn BHandler* BLooper::HandlerAt(int32 index) const
520 \brief Get the handler at an \a index of the list of associated handlers.
522 \return A pointer to the handler at that \a index, or \c NULL if the
523 \a index is out of range.
533 \fn int32 BLooper::IndexOf(BHandler* handler) const
534 \brief Get the index of the \a handler that is in the associated handler
537 \return The index of the handler in the list if the \a handler is in the
538 list, else this method will return -1.
545 \fn BHandler* BLooper::PreferredHandler() const
546 \brief Get the preferred handler.
548 \return A pointer to the preferred handler, or \c NULL if none is set.
550 \see SetPreferredHandler()
557 \fn void BLooper::SetPreferredHandler(BHandler* handler)
558 \brief Set a preferred handler.
560 If messages are posted to this looper using one of the PostMessage()
561 methods without a specific BHandler argument, the messages will be handled
562 by the looper itself (since a looper is a subclass of BHandler, this is
563 perfectly possible). If you want to override that behavior, you should set
564 a preferred handler. This handler will be called if incoming messages do
565 not ask to be directly passed on to a specific handler.
567 \param handler The preferred handler you want undesignated messages to be
568 handled by. If you want to unset the preferred handler, pass
569 \c NULL. If the supplied \a handler is not associated with this
570 looper, this call will fail silently and the current preferred
571 handler will be unset.
573 \see PreferredHandler()
591 \fn thread_id BLooper::Run()
592 \brief Start the event loop.
594 After the looper has been constructed, it needs to be started using this
595 method. A thread will be spawned, which will receive messages.
597 Make sure the looper is not yet running before you call this method.
599 \return A (positive) thread id if spawning the thread succeeded, or an
607 \fn void BLooper::Quit()
608 \brief Hook method that is called after a \c B_QUIT_REQUESTED message.
610 If you want to quit and delete the looper, you should post a
611 \c B_QUIT_REQUESTED message. This will first call the hook method
612 QuitRequested(), which can be overridden in child classes in case there
613 are conditions that would prevent the looper to be quit. If you really
614 know what you are doing, and you definitely want to quit this looper,
615 you may call this method, but only after performing a Lock() operation.
617 Override this method if your subclass needs to perform specific clean-up
618 tasks. Remember to call the base class implementation when you're done.
620 \attention You will not have to delete the looper object, if a looper quits
621 it will delete itself.
628 \fn bool BLooper::QuitRequested()
629 \brief Hook method that is called during a \c B_QUIT_REQUESTED message.
631 This hook function is called by the looper thread when a
632 \c B_QUIT_REQUESTED is received. The default implementation always accepts
633 the message, but if your subclass needs a special condition to be met
634 before actually accepting a quit message, you can test for that condition
635 in this hook method. A good example is a window (which is a derivative of
636 BLooper), which contains a modified document. The condition may be that a
637 modal dialog requesting a path of action is closed.
639 \return \c true if the looper can be quit and destroyed,
640 \c false if this method does not accept the quit message
641 and continue processing messages.
648 \fn bool BLooper::Lock()
649 \brief Lock the looper.
651 For most operations involving the internal data of the looper, you need to
652 hold the lock. Each looper implements a global lock, which you can use to
653 perform operations on internal data in a thread-safe manner.
655 Do not forget to pair each Lock() request with an Unlock() request. Lock()
656 requests can be stacked, which means that recursively locking a looper from
657 a thread that actually holds the lock, will not cause a deadlock. See
658 BLocker for more information on locking internals.
660 \return \c true if the locking request succeeded,
661 \c false if the locking request could not be completed. There are a
662 variety of reasons for this to happen, for example when the
666 \see LockWithTimeout()
674 \fn void BLooper::Unlock()
675 \brief Unlock a locked looper.
677 Use this method paired with Lock() calls, to release a lock. Make sure that
678 this method is only called on a locked looper.
681 \see LockWithTimeout()
689 \fn bool BLooper::IsLocked() const
690 \brief Check if a looper is locked.
692 \return \c true if the looper is locked,
693 \c false if the looper is not locked, or the looper has been
698 \see LockWithTimeout()
705 \fn status_t BLooper::LockWithTimeout(bigtime_t timeout)
706 \brief Lock a looper with a \a timeout.
708 This method locks the looper like Lock(), but if the locking request does
709 not succeed within the provided \a timeout, the method will return.
711 \param timeout The maximum time to wait for the lock request to succeed.
713 \return A status code.
714 \retval B_OK The lock is acquired.
715 \retval B_BAD_VALUE The looper has been destroyed.
716 \retval "other errors" There was an error acquiring the lock.
727 \fn thread_id BLooper::Thread() const
728 \brief Return the thread id of the internal message looper thread.
730 If the looper is not yet running, this method will return 0.
739 \fn team_id BLooper::Team() const
740 \brief Return the team id in which this looper exists.
747 \fn BLooper* BLooper::LooperForThread(thread_id thread)
748 \brief Static method to retrieve a BLooper for a specified \a thread.
760 These methods may aid you in debugging problems when they occur, but do not
761 use these in actual production code. These methods are unreliable because
762 they are not thread-safe, and as such are only useful in specific debugging
763 situations. Handle with care.
771 \fn thread_id BLooper::LockingThread() const
772 \brief Return the thread id of the thread that currently holds the lock.
779 \fn int32 BLooper::CountLocks() const
780 \brief Return the number of recursive locks that are currently being held
788 \fn int32 BLooper::CountLockRequests() const
789 \brief Return the number of pending locks.
796 \fn sem_id BLooper::Sem() const
797 \brief Return the id of the semaphore that is used to lock this looper.
815 \fn BHandler* BLooper::ResolveSpecifier(BMessage* message, int32 index,
816 BMessage* specifier, int32 what, const char* property)
817 \brief Determine the proper handler for a scripting message.
819 \copydetails BHandler::ResolveSpecifier()
824 \fn status_t BLooper::GetSupportedSuites(BMessage* data)
825 \brief Reports the suites of messages and specifiers that derived classes
828 \copydetails BHandler::GetSupportedSuites()
836 \name Looper Message Filters
838 Note that filters added with these methods will be applied to all
839 associated handlers. Have a look at the filtering methods of the BHandler
840 class to see how filters can be applied to the inherited handler of this
849 \fn void BLooper::AddCommonFilter(BMessageFilter* filter)
850 \brief Add a common filter to the list of filters that are applied to all
853 Filters can only be applied once, so they cannot be shared between loopers,
854 a handler and a looper or between two handlers.
856 The \a filter is not copied; rather a pointer is stored. Keep the \a filter
857 alive as long as it is used by a looper.
859 \see RemoveCommonFilter()
860 \see SetCommonFilterList()
861 \see CommonFilterList()
868 \fn bool BLooper::RemoveCommonFilter(BMessageFilter* filter)
869 \brief Remove a \a filter from the common message filter list.
871 Note that this will not free the memory used by the \a filter, so you
872 should dispose of it yourself.
874 \see AddCommonFilter()
875 \see SetCommonFilterList()
876 \see CommonFilterList()
883 \fn void BLooper::SetCommonFilterList(BList* filters)
884 \brief Set a new list of \a filters that need to be applied to all
887 You are responsible for validating that all the items in the list of
888 \a filters are actual filters. The old list is discarded; all the filters
891 Note that filters can only be applied to one looper or handler. If any
892 of the filters is already associated with another one, this call will fail.
894 \see AddCommonFilter()
895 \see RemoveCommonFilter()
896 \see CommonFilterList()
903 \fn BList* BLooper::CommonFilterList() const
904 \brief Return a list of filters applied to all incoming messages.
906 \return A pointer to the internal filter list, or \c NULL if such a list
907 has not yet been created. Please note that you should use the
908 internal list management functions to manipulate the internal
909 filter list, in order to maintain internal consistency.
911 \see AddCommonFilter()
912 \see RemoveCommonFilter()
913 \see SetCommonFilterList()
923 \fn status_t BLooper::Perform(perform_code d, void* arg)
924 \brief Internal method.
931 \fn BMessage* BLooper::MessageFromPort(bigtime_t timeout)
932 \brief Hook method to retrieve a message from the looper's port.
934 The default implementation is called by the internal message looping thread
935 and retrieves the next message from the port that belongs to this looper.
937 If you use a looper in a context where it might receive messages from other
938 sources, you can override this method in order to insert these methods into
939 the message processing. Note that any messages that are returned by this
940 method will be deleted by this looper, so make sure you have ownership of
941 the message. If you override this method, remember to call the base
942 implementation every now and then, in order to retrieve the messages
943 arriving at the default port.