xref: /haiku/docs/user/book.dox (revision 1fe24d0cd0b547a771c00f6fca8f50ba6ca2fb2c)
1/*!
2	\mainpage Welcome to the Haiku Book
3
4	Below you will find documentation on the Application Programming
5	Interface (API) of the Haiku operating system. This API describes
6	the internals of the operating system allowing developers to write
7	native C++ applications and device drivers. See the
8	<a href="http://api.haiku-os.org">online version</a> for the most
9	updated version of this document. If you would like to help contribute
10	contact the <a href="http://www.freelists.org/list/haiku-doc">documentation
11	mailing list</a>. For guidelines on how to help document the API see
12	the \link apidoc Documenting the API\endlink page. A list of
13	contributors can be found \ref credits page. Documenting the API is
14	an ongoing process so contributions are greatly appreciated.
15
16	The Haiku API is based on the BeOS R5 API but changes and additions have
17	been included where appropriate. Important compatibility differences are
18	detailed on the \ref compatibility page. New classes and methods
19	and incompatible API changes to the BeOS R5 API are noted in the
20	appropriate sections.
21
22	A complete reference to the BeOS R5 API is available on the web in
23	<a href="http://haiku-os.org/legacy-docs/bebook/">The Be Book</a>.
24	The Be Book is used with permission from
25	<a href="http://www.access-company.com/">Access Co.</a>, the current
26	owners of Be's intellectual property.
27
28	\section kits Kits and Servers
29
30	The API is split into several kits and servers each detailing a different
31	aspect of the operating system.
32		- The \ref app is the starting point for developing applications
33			and includes classes for messaging and for interacting with
34			the rest of the system.
35		- The \ref interface is used to create responsive and attractive
36			graphical user interfaces building on the messaging facilities
37			provided by the Application Kit.
38			- The \link layout_intro Layout API \endlink is a new addition
39				to the Interface Kit in Haiku which provides resources to
40				layout your application flexibly and easily.
41		- The \ref locale includes classes to localize your application to
42			different languages, timezones, number formatting conventions and
43			much more.
44		- The \ref media provides a unified and consistent interface for media
45			streams and applications to intercommunicate.
46		- The \ref midi2 describes an interface to generating, processing,
47			and playing music in MIDI format. For reference documentation on the
48			\ref midi1 is also included.
49		- The \ref storage is a collection of classes that deal with storing and
50			retrieving information from disk.
51		- The \ref support contains support classes to use in your application
52			including resources for thread safety, IO, and serialization.
53
54	\section special_topics Special Topics
55
56	- \ref drivers
57	- \ref keyboard
58*/
59
60///// Define main kits /////
61
62/*!
63	\defgroup app Application Kit
64	\brief The Application Kit is the starting point for writing native Haiku
65		GUI applications.
66
67	The application kit is exactly what its name suggests &mdash; it is the
68	basis of Haiku applications. You should first read through this document
69	and the references here before moving on to the other parts of the API.
70
71	The Application Kit classes can be divided into two groups: the messaging
72	classes and the system interaction classes. The larger of the two groups is
73	the messaging classes. Since the Haiku API relies on pervasive
74	multithreading messaging is an essential topic for any application. Have a
75	look at the \link app_messaging Introduction to Messaging \endlink for more
76	information.
77
78	The following messaging classes which allow you to easily and securely
79	communicate between threads.
80		- BHandler
81		- BInvoker
82		- BLooper
83		- BMessage
84		- BMessageFilter
85		- BMessageQueue
86		- BMessageRunner
87		- BMessenger
88
89	The second group is the system interaction classes. These classes
90	provide hooks for your application to interact with the rest of the system.
91	The most important class in this group is BApplication. Below is a list of
92	all system interaction classes:
93		- BApplication
94		- BClipboard
95		- BCursor
96		- BPropertyInfo
97		- BRoster
98
99
100	\defgroup interface Interface Kit
101	\brief API for displaying a graphical user interface.
102
103	The Interface Kit holds all the classes you'll need to develop a GUI.
104	Building on the messaging facilities provided by the Application Kit,
105	the Interface Kit can be used to create a responsive and attractive
106	graphical user interface.
107
108 	The most important class in the Interface Kit is the BView class, which
109	handles drawing and user interaction. Pointer and keyboard events are
110	processed in this class.
111
112	Another important class is the BWindow class, which holds BViews and makes
113	them visible to the user. The BWindow class also handles BView focusing
114	and BMessage dispatching, among other things.
115
116	A new addition Haiku has added over the BeOS API is the Layout API, which
117	is based around the BLayoutItem and BLayout classes. These classes will
118	take care of making sure all your GUI widgets end up where you want them,
119	with enough space to be useful. You can start learning the Layout API
120	by reading the \link layout_intro introduction \endlink.
121
122
123	\defgroup locale Locale Kit
124	\brief Collection of classes for localizing applications.
125
126	The Locale Kit provides a set of tools for internationalizing,
127	localizing and translating your software. This includes not only
128	replacing string with their translations at runtime, but also more
129	complex tasks such as formatting numbers, dates, and times in a way
130	that match the locale preferences of the user.
131
132	The main way to access locale data is through the be_locale_roster.
133	This is a global instance of the BLocaleRoster class, storing the data
134	for localizing an application according to the user's preferred settings.
135	The locale roster also acts as a factory to instantiate most of the other
136	classes. However, there are some cases where you will need to instantiate
137	another class by yourself, to use it with custom settings. For example, you
138	may need to format a date with a fixed format in english for including in an
139	e-mail header, as it is the only format accepted there.
140
141	Unlike the other kits in Haiku, the Locale kit does not live in libbe.
142	When building a localized application, you have to link it to
143	liblocale.so. If you want to use the catalog macros, you also have to
144	link each of your images (that is, applications, libraries and add-ons)
145	to liblocalestub.a.
146
147	\defgroup media Media Kit
148	\brief Collection of classes that deal with audio and video.
149
150
151	\defgroup midi1 The old MIDI Kit (libmidi.so)
152	\brief The old MIDI kit.
153
154
155	\defgroup midi2 MIDI 2 Kit
156	\brief The Midi Kit is the API that implements support for generating,
157		processing, and playing music in MIDI format.
158
159	<A HREF="http://www.midi.org/">MIDI</A>, which  stands for 'Musical
160	Instrument Digital Interface', is a well-established  standard for
161	representing and communicating musical data. This document serves as
162	an overview. If you would like to see all the components, please look
163	at \link midi2 the list with classes \endlink.
164
165	\section midi2twokits A Tale of Two MIDI Kits
166
167	BeOS comes with two different, but compatible Midi Kits. This
168	documentation focuses on the "new" Midi Kit, or midi2 as we like to
169	call it, that was  introduced with BeOS R5. The old kit, which we'll
170	refer to as midi1, is more complete than the new kit, but less powerful.
171
172	Both kits let you create so-called MIDI endpoints, but the endpoints
173	from midi1 cannot be shared between different applications. The midi2
174	kit solves that  problem, but unlike midi1 it does not include a General
175	MIDI softsynth, nor does it have a facility for reading and playing
176	Standard MIDI Files. Don't worry: both kits are compatible and you can
177	mix-and-match them in your applications.
178
179	The main differences between the two kits:
180		- Instead of one BMidi object that both produces and consumes events,
181			we have BMidiProducer and BMidiConsumer.
182		- Applications are capable of sharing MIDI producers and consumers
183			with other applications via the centralized Midi Roster.
184		- Physical MIDI ports are now sharable without apps "stealing" events
185			from each other.
186		- Applications can now send/receive raw MIDI byte streams (useful if
187			an application has its own MIDI parser/engine).
188		- Channels are numbered 0&ndash;15, not 1&ndash;16
189		- Timing is now specified in microseconds rather than milliseconds.
190
191	\section midi2concepts Midi Kit Concepts
192
193	A brief overview of the elements that comprise the Midi Kit:
194		- \b Endpoints. This is what the Midi Kit is all about: sending MIDI
195			messages between endpoints. An endpoint is like a MIDI In or MIDI
196			Out socket on your equipment; it either receives information or it
197			sends information. Endpoints that send MIDI events are called
198			\b producers; the endpoints that receive those events are called
199			\b consumers. An endpoint that is created by your own application
200			is called \b local; endpoints from other applications are
201			\b remote. You can access remote endpoints using \b proxies.
202		- \b Filters. A filter is an object that has a consumer and a producer
203			endpoint. It reads incoming events from its consumer, performs some
204			operation, and tells its producer to send out the results. In its
205			current form, the Midi  Kit doesn't provide any special facilities
206			for writing filters.
207		- \b Midi \b Roster. The roster is the list of all published producers
208			and consumers. By publishing an endpoint, you allow other
209			applications to talk to it. You are not required to publish your
210			endpoints, in which case only your own application can use them.
211		- \b Midi \b Server. The Midi Server does the behind-the-scenes work.
212			It manages the roster, it connects endpoints, it makes sure that
213			endpoints can communicate, and so on. The Midi Server is started
214			automatically when BeOS boots, and you never have to deal with it
215			directly. Just remember that it runs the show.
216		- \b libmidi. The BMidi* classes live inside two shared libraries:
217			libmidi.so and libmidi2.so. If you write an application that uses
218			old Midi Kit, you must link it to libmidi.so. Applications that use
219			the new Midi Kit must link to libmidi2.so. If you want to
220			mix-and-match both kits, you should also link to both libraries.
221
222	Here is a pretty picture:
223
224	\image html midi2concepts.png
225
226	\section midi2mediakit Midi Kit != Media Kit
227
228	Be chose not to integrate the Midi Kit into the Media Kit as another media
229	type, mainly because MIDI doesn't require any of the format negotiation that
230	other media types need. Although the two kits look similar -- both have a
231	"roster" for finding or registering "consumers" and "producers" -- there are
232	some very important differences.
233
234	The first and most important point to note is that BMidiConsumer and
235	BMidiProducer in the Midi Kit are \b NOT directly analogous to
236	BBufferConsumer and  BBufferProducer in the Media Kit! In the Media Kit,
237	consumers and producers are the data consuming and producing properties
238	of a media node. A filter in the Media Kit, therefore, inherits from both
239	BBufferConsumer and BBufferProducer, and implements their virtual member
240	functions to do its work.
241
242	In the Midi Kit, consumers and producers act as endpoints of MIDI data
243	connections, much as media_source and media_destination do in the Media Kit.
244	Thus, a MIDI filter does not derive from BMidiConsumer and BMidiProducer;
245	instead, it contains BMidiConsumer and BMidiProducer objects for each of its
246	distinct endpoints that connect to other MIDI objects. The Midi Kit does not
247	allow the use of multiple virtual inheritance, so you can't create an object
248	that's both a BMidiConsumer and a BMidiProducer.
249
250	This also contrasts with the old Midi Kit's conception of a BMidi object,
251	which stood for an object that both received and sent MIDI data. In the new
252	Midi Kit, the endpoints of MIDI connections are all that matters. What lies
253	between the endpoints, i.e. how a MIDI filter is actually structured, is
254	entirely at your discretion.
255
256	Also, rather than use token structs like media_node to make connections
257	via the MediaRoster, the new kit makes the connections directly via the
258	BMidiProducer object.
259
260	\section midi2remotelocal Remote vs. Local Objects
261
262	The Midi Kit makes a distinction between remote and local MIDI objects.
263	You can  only create local MIDI endpoints, which derive from either
264	BMidiLocalConsumer or BMidiLocalProducer. Remote endpoints are endpoints
265	that live in other applications, and you access them through BMidiRoster.
266
267	BMidiRoster only gives you access to BMidiEndpoints, BMidiConsumers, and
268	BMidiProducers. When you want to talk to remote MIDI objects, you do so
269	through the proxy objects that BMidiRoster provides. Unlike
270	BMidiLocalConsumer and BMidiLocalProducer, these classes do not provide a
271	lot of functions. That is intentional. In order to hide the details of
272	communication with MIDI endpoints in other applications, the Midi Kit must
273	hide the details of how a particular endpoint is implemented.
274
275	So what can you do with remote objects? Only what BMidiConsumer,
276	BMidiProducer, and BMidiEndpoint will let you do. You can connect
277	objects, get the properties of these objects -- and that's about it.
278
279	\section midi2lifespan Creating and Destroying Objects
280
281	The constructors and destructors of most midi2 classes are private,
282	which means that you cannot directly create them using the C++
283	<CODE>new</CODE> operator, on the  stack, or as globals. Nor can you
284	<CODE>delete</CODE> them. Instead, these objects are obtained through
285	BMidiRoster. The only two exceptions to this rule are BMidiLocalConsumer
286	and BMidiLocalProducer. These two objects may be directly created and
287	subclassed by developers.
288
289	\section midi2refcount Reference Counting
290
291	Each MIDI endpoint has a reference count associated with it, so that
292	the Midi Roster can do proper bookkeeping. When you construct a
293	BMidiLocalProducer or  BMidiLocalConsumer endpoint, it starts with a
294	reference count of 1. In addition, BMidiRoster increments the reference
295	count of any object it hands to you as a result of
296	\link BMidiRoster::NextEndpoint() NextEndpoint() \endlink or
297	\link BMidiRoster::FindEndpoint() FindEndpoint() \endlink.
298	Once the count hits  0, the endpoint will be deleted.
299
300	This means that, to delete an endpoint, you don't call the
301	<CODE>delete</CODE>  operator directly; instead, you call
302	\link BMidiEndpoint::Release() Release() \endlink.
303	To balance this call, there's also an
304	\link BMidiEndpoint::Acquire() Acquire() \endlink, in case you have two
305	disparate parts of your application working with the endpoint, and you
306	don't want to have to keep track of who needs to Release() the endpoint.
307
308	When you're done with any endpoint object, you must Release() it.
309	This is true  for both local and remote objects. Repeat after me:
310	Release() when you're done.
311
312	\section midi2events MIDI Events
313
314	To make some actual music, you need to
315	\link BMidiProducer::Connect() Connect() \endlink your consumers to
316	your producers. Then you tell the producer to "spray" MIDI events to all
317	the connected consumers. The consumers are notified of these incoming
318	events through a set of hook functions.
319
320	The Midi Kit already provides a set of commonly used spray functions,
321	such as  \link BMidiLocalProducer::SprayNoteOn() SprayNoteOn() \endlink,
322	\link BMidiLocalProducer::SprayControlChange() SprayControlChange()
323	\endlink, and so on. These correspond one-to-one with the message types
324	from the MIDI spec. You don't need to be a MIDI expert to use the kit, but
325	of course some knowledge of the protocol helps. If you are really hardcore,
326	you can also use the
327	\link BMidiLocalProducer::SprayData() SprayData() \endlink to send raw MIDI
328	events to the consumers.
329
330	At the consumer side, a dedicated thread invokes a hook function for every
331	incoming MIDI event. For every spray function, there is a corresponding hook
332	function, e.g. \link BMidiLocalConsumer::NoteOn() NoteOn() \endlink and
333	\link  BMidiLocalConsumer::ControlChange() ControlChange() \endlink.
334	The hardcore MIDI fanatics among you will be pleased to know that you can
335	also tap into the \link BMidiLocalConsumer::Data() Data() \endlink hook and
336	get your hands dirty with the raw MIDI data.
337
338	\section midi2time Time
339
340	The spray and hook functions accept a bigtime_t parameter named "time". This
341	indicates when the MIDI event should be performed. The time is given in
342	microseconds since the computer booted. To get the current tick measurement,
343	you call the system_time() function from the Kernel Kit.
344
345	If you override a hook function in one of your consumer objects, it should
346	look  at the time argument, wait until the designated time, and then perform
347	its action. The preferred method is to use the Kernel Kit's
348	<CODE>snooze_until()</CODE> function, which sends the consumer thread to
349	sleep  until the requested time has come. (Or, if the time has already
350	passed, returns immediately.)
351
352	Like this:
353
354	\code
355void MyConsumer::NoteOn(
356    uchar channel, uchar note, uchar velocity, bigtime_t time)
357{
358    snooze_until(time, B_SYSTEM_TIMEBASE);
359    ...do your thing...
360}
361	\endcode
362
363	If you want your producers to run in real time, i.e. they produce MIDI data
364	that needs to be performed immediately, you should pass time 0 to the spray
365	functions (which also happens to be the default value). Since time 0 has
366	already passed, <CODE>snooze_until()</CODE> returns immediately, and the
367	consumer will process the events as soon as they are received.
368
369	To schedule MIDI events for a performance time that lies somewhere in the
370	future, the producer must take into account the consumer's latency.
371	Producers  should attempt to get notes to the consumer by or before
372	<I>(scheduled_performance_time - latency)</I>. The time argument is still
373	the scheduled performance time, so if your consumer has latency, it should
374	snooze like this before it starts to perform the events:
375
376	\code
377snooze_until(time - Latency(), B_SYSTEM_TIMEBASE);
378	\endcode
379
380	Note that a typical producer sends out its events as soon as it can;
381	unlike a consumer, it does not have to snooze.
382
383	\section midi2ports Other Timing Issues
384
385	Each consumer object uses a Kernel Kit port to receive MIDI events from
386	connected producers. The queue for this port is only 1 message deep.
387	This means that if the consumer thread is asleep in a
388	<CODE>snooze_until()</CODE>, it will not read its port. Consequently,
389	any producer that tries to write a new event to this port will block until
390	the consumer thread is ready to receive a new message. This is intentional,
391	because it prevents producers from generating and queueing up thousands of
392	events.
393
394	This mechanism, while simple, puts on the producer the responsibility
395	for sorting the events in time. Suppose your producer sends three Note
396	On events, the first on t + 0, the second on t + 4, and the third on t + 2.
397	This last event won't be received until after t + 4, so it will be two ticks
398	too late. If this sort of thing can happen with your producer, you should
399	somehow sort the events before you spray them. Of course, if you have two or
400	more producers connected to the same consumer, it is nearly impossible to
401	sort this all out (pardon the pun). So it is not wise to send the same kinds
402	of events from more than one producer to one consumer at the same time.
403
404	The article Introduction to MIDI, Part 2 in <A
405	HREF="http://open-beos.sourceforge.net/nsl.php?mode=display&id=36">OpenBeOS
406	Newsletter 36</A> describes this problem in more detail, and provides a
407	solution. Go read it now!
408
409	\section midi2filters Writing a Filter
410
411	A typical filter contains a consumer and a producer endpoint. It receives
412	events from the consumer, processes them, and sends them out again using the
413	producer. The consumer endpoint is a subclass of BMidiLocalConsumer, whereas
414	the producer is simply a BMidiLocalProducer, not a subclass. This is a
415	common  configuration, because consumers work by overriding the event hooks
416	to do work  when MIDI data arrives. Producers work by sending an event when
417	you call their  member functions. You should hardly ever need to derive from
418	BMidiLocalProducer (unless you need to know when the producer gets connected
419	or disconnected, perhaps), but you'll always have to override one or more of
420	BMidiLocalConsumer's member functions to do something useful with incoming
421	data.
422
423	Filters should ignore the time argument from the spray and hook functions,
424	and  simply pass it on unchanged. Objects that only filter data should
425	process the  event as quickly as possible and be done with it. Do not
426	<CODE>snooze_until()</CODE> in the consumer endpoint of a filter!
427
428	\section midi2apidiffs API Differences
429
430	As far as the end user is concerned, the Haiku Midi Kit is mostly the same
431	as the BeOS R5 kits, although there are a few small differences in the API
432	(mostly bug fixes):
433		- BMidiEndpoint::IsPersistent() always returns false.
434		- The B_MIDI_CHANGE_LATENCY notification is now properly sent. The Be
435			kit  incorrectly set be:op to B_MIDI_CHANGED_NAME, even though the
436			rest of the  message was properly structured.
437		- If creating a local endpoint fails, you can still Release() the object
438		  without crashing into the debugger.
439
440	\section midi2seealso See also
441
442	More about the Midi Kit:
443		- \ref Midi2Defs.h
444		- Be Newsletter Volume 3, Issue 47 - Motor Mix sample code
445		- Be Newsletter Volume 4, Issue 3 - Overview of the new kit
446		- <A HREF="http://haiku-os.org/documents/dev/introduction_to_midi_part_1">Newsletter
447		  33</A>, Introduction to MIDI, Part 1
448		- <A HREF="http://haiku-os.org/documents/dev/introduction_to_midi_part_2">Newsletter
449		  36</A>, Introduction to MIDI, Part 2
450		- Sample code and other goodies at the
451		  <A HREF="http://haiku-os.org/about/teams/midi_kit">Haiku Midi Kit team page</A>
452
453	Information about MIDI in general:
454		- <A HREF="http://www.midi.org">MIDI Manufacturers Association</A>
455		- <A HREF="http://www.borg.com/~jglatt/tutr/miditutr.htm">MIDI Tutorials</A>
456		- <A HREF="http://www.borg.com/~jglatt/tech/midispec.htm">MIDI Specification</A>
457		- <A HREF="http://www.borg.com/~jglatt/tech/midifile.htm">Standard MIDI File Format</A>
458		- <A HREF="http://www.io.com/~jimm/midi_ref.html">Jim Menard's MIDI Reference</A>
459
460
461	\defgroup libmidi2 (libmidi2.so)
462
463
464	\defgroup storage Storage Kit
465	\brief Collection of classes that deal with storing and retrieving
466		information from disk.
467
468
469	\defgroup support Support Kit
470	\brief Collection of utility classes that are used throughout the API.
471
472	The Support Kit provides a handy set of classes that you can use in your
473	applications. These classes provide:
474		- \b Thread \b Safety. Haiku can execute multiple threads of an
475			application in parallel, letting certain parts of an application
476			continue when one part is stalled, as well as letting an application
477			process multiple pieces of data at the same time on multicore or
478			multiprocessor systems. However, there are times when multiple
479			threads desire to work on the same piece of data at the same time,
480			potentially causing a conflict where variables or pointers are
481			changed by one thread causing another to execute incorrectly. To
482			prevent this, Haiku implements a \"locking\" mechanism, allowing one
483			thread to \"lock out\" other threads from executing code that might
484			modify the same data.
485		  - \b Archiving \b and \b IO. These classes allow a programmer to
486			convert objects into a form that can more easily be transferred to
487			other applications or stored to disk, as well as performing basic
488			input and output operations.
489		  - \b Memory \b Allocation. This class allows a programmer to hand off
490			some of the duties of memory accounting and management.
491		  - \b Common \b Datatypes. To avoid unnecessary duplication of code
492			and to make life easier for programmers, Haiku includes classes that
493			handle management of ordered lists and strings.
494
495	There are also a number of utility functions to time actions, play system
496	alert sounds, compare strings, and atomically manipulate integers. Have a
497	look at the overview, or go straight to the complete
498	\link support list of components \endlink of this kit.
499
500	\section Overview
501		- Thread Safety:
502			- BLocker provides a semaphore-like locking mechanism allowing for
503				recursive locks.
504			- BAutolock provides a simple method of automatically removing a
505				lock when a function ends.
506			- \ref TLS.h "Thread Local Storage" allows a global variable\'s
507				content to be sensitive to thread context.
508		- Archiving and IO:
509			- BArchivable provides an interface for \"archiving\" objects so
510				that they may be sent to other applications where an identical
511				copy will be recreated.
512			- BArchiver simplifies archiving of BArchivable hierarchies.
513			- BUnarchiver simplifies unarchiving hierarchies that have been
514				archived using BArchiver.
515			- BFlattenable provides an interface for \"flattening\" objects so
516				that they may be easily stored to disk.
517		- BDataIO provides an interface for generalized read/write streams.
518			- BPositionIO extends BDataIO to allow seeking within the data.
519			- BBufferIO creates a buffer and attaches it to a BPositionIO
520				stream, allowing for reduced load on the underlying stream.
521			- BMemoryIO allows operation on an already-existing buffer.
522			- BMallocIO creates and allows operation on a buffer.
523		- Memory Allocation:
524			- BBlockCache allows an application to allocate a \"pool\" of
525				memory blocks that the application can fetch and dispose of as
526				it pleases, letting the application make only a few large memory
527				allocations, instead of many small expensive allocations.
528		- Common Datatypes:
529			- BList allows simple ordered lists and provides common access,
530				modification, and comparison functions.
531			- BString allows strings and provides common access, modification,
532				and comparison functions.
533		- BStopWatch allows an application to measure the time an action takes.
534			- \ref support_globals "Global functions"
535			- \ref TypeConstants.h "Common types and constants"
536			- Error codes for all kits
537
538
539	\defgroup libbe (libbe.so)
540
541
542	\defgroup libroot (libroot.so)
543*/
544
545///// Subgroups /////
546
547/*!
548	\defgroup support_globals Global functions in the support kit
549	\ingroup support
550
551	\defgroup layout Layout classes in the Interface Kit
552	\ingroup interface
553*/
554
555
556///// Special Topics /////
557
558\defgroup drivers Device Drivers
559\defgroup keyboard Keyboard