1=head1 NAME
2
3Prima::Object - Prima toolkit base classes
4
5=head1 SYNOPSIS
6
7    if ( $obj-> isa('Prima::Component')) {
8
9        # set and get a property
10	my $name = $obj-> name;
11	$obj->name( 'an object' );
12
13	# set a notification callback
14	$obj-> onPostMessage( sub {
15	    shift;
16	    print "hey! I've received this: @_\n";
17	});
18
19	# can set multiple properties. note, that 'name' and 'owner',
20	# replace the old values, while onPostMessage are aggregated.
21	$obj-> set(
22	    name => 'AnObject',
23	    owner => $new_owner,
24	    onPostMessage => sub {
25	       shift;
26	       print "hey! me too!\n";
27	    },
28	);
29
30        # de-reference by name
31	$new_owner-> AnObject-> post_message(1,2);
32    }
33
34=head1 DESCRIPTION
35
36Prima::Object and Prima::Component are the root objects of the Prima toolkit
37hierarchy. All the other objects are derived from the Component class, which in
38turn is the only descendant of Object class. Both of these classes are never
39used for spawning their instances, although this is possible using
40
41   Prima::Component-> new( .. parameters ... );
42
43call. This document describes the basic concepts of the OO programming with
44Prima toolkit. Although Component has wider functionality than Object, all
45examples will be explained on Component, since Object has no descendant classes
46and all the functionality of Object is present in Component.  Some of the
47information here can be found in L<Prima::internals> as well, the difference is
48that L<Prima::internals> considers the coding tasks from a C programmer's view,
49whereas this document is wholly about perl programming.
50
51=head1 Object base features
52
53=head2 Creation
54
55Object creation has fixed syntax:
56
57   $new_object = Class-> new(
58     parameter => value,
59     parameter => value,
60     ...
61   );
62
63Parameters and values form a hash, which is passed to the new() method.
64This hash is applied to a default parameter-value hash ( a I<profile> ),
65specific to every Prima class. The object creation is performed in several
66stages.
67
68=over 4
69
70=item new
71
72new() calls profile_default() method that returns ( as its name states ) the
73default profile, a hash with the appropriate default values assigned to its
74keys.  The Component class defaults are ( see Classes.pm ):
75
76     name        => ref $_[ 0],
77     owner       => $::application,
78     delegations => undef,
79
80While the exact meaning of these parameters is described later, in
81L<"Properties">, the idea is that a newly created object will have 'owner'
82parameter set to '$::application' and 'delegations' to undef etc etc - unless
83these parameters are explicitly passed to new(). Example:
84
85     $a1 = Prima::Component-> new();
86
87$a1's owner will be $::application
88
89     $a2 = Prima::Component-> new( owner => $a1);
90
91$a2's owner will be $a1.
92The actual merging of the default and the parameter hashes
93is performed on the next stage, in profile_check_in() method
94which is called inside profile_add() method.
95
96Note: the older syntax used create() instead of new(), which is still valid but is not preferred
97
98=item profile_check_in
99
100A profile_check_in() method merges the default and the parameter profiles. By
101default all specified parameters have the ultimate precedence over the default
102ones, but in case the specification is incomplete or ambiguous, the
103profile_check_in()'s task is to determine actual parameter values. In case of
104Component, this method maintains a simple automatic naming of the newly created
105objects. If the object name was not specified with new(), it is assigned to
106a concatenated class name with an integer - Component1, Component2 etc.
107
108Another example can be taken from Prima::Widget::profile_check_in().
109Prima::Widget horizontal position can be specified by using basic C<left> and
110C<width> parameters, and as well by auxiliary C<right>, C<size> and C<rect>.
111The default of both C<left> and C<width> is 100. But if only C<right>
112parameter, for example, was passed to new() it is profile_check_in() job to
113determine C<left> value, given that C<width> is still 100.
114
115After profiles gets merged, the resulting hash is passed to the third stage,
116init().
117
118=item init
119
120init() duty is to map the profile content into object, e.g., assign C<name>
121property to C<name> parameter value, and so on - for all relevant parameters.
122After that, it has to return the profile in order the overridden subsequent
123init() methods can perform same actions. This stage along with the previous is
124exemplified in almost all Prima modules.
125
126Note: usually init() attaches the object to its owner in order to keep the
127newly-created object instance from being deleted by garbage-collection
128mechanisms. More on that later ( see L<"Links between objects">).
129
130After init() finishes, new() calls setup() method
131
132=item setup
133
134setup() method is a convenience function, it is used when some post-init
135actions must be taken. It is seldom overloaded, primarily because the
136Component::setup() method calls C<onCreate> notification, which is more
137convenient to overload than setup().
138
139=back
140
141As can be noticed from the code pieces above, a successful new() call
142returns a newly created object. If an error condition occurred, undef is
143returned. It must be noted, that only errors that were generated via die()
144during init() stage result in undef. Other errors raise an exception instead.
145It is not recommended to frame new() calls in an C<eval{}> block, because
146the error conditions can only occur in two situations. The first is a system
147error, either inside perl or Prima guts, and not much can be done here, since
148that error can very probably lead to an unstable program and almost always
149signals an implementation bug. The second reason is a caller's error, when an
150unexistent parameter key or invalid value is passed; such conditions are not
151subject to a runtime error handling as are not the syntax errors.
152
153After new(), the object is subject to the event flow.  As C<onCreate> event
154is the first event the object receives, only after that stage other events can
155be circulated.
156
157=head2 Destruction
158
159Object destruction can be caused by many conditions, but all execution flow is
160finally passed through destroy() method.  destroy(), as well as new()
161performs several finalizing steps:
162
163=over 4
164
165=item cleanup
166
167The first method called inside destroy() is cleanup().  cleanup() is the pair
168to setup(), as destroy() is the pair to new(). cleanup() generates
169C<onDestroy> event, which can be overridden more easily than cleanup() itself.
170
171C<onDestroy> is the last event the object sees. After cleanup() no events are
172allowed to circulate.
173
174=item done
175
176done() method is the pair to init(), and is the place where all object
177resources are freed. Although it is as safe to overload done() as init(), it
178almost never gets overloaded, primarily because overloading C<onDestroy> is
179easier.
180
181=back
182
183The typical conditions that lead to object destructions are
184direct destroy() call, garbage collections mechanisms,
185user-initiated window close ( on C<Prima::Window> only ), and
186exception during init() stage. Thus, one must be careful implementing
187done() which is called after init() throws an exception.
188
189=head2 Methods
190
191The class methods are declared and used with perl OO syntax, which allow both
192method of object referencing:
193
194  $object-> method();
195
196and
197
198  method( $object);
199
200The actual code is a sub, located under the object class package.  The
201overloaded methods that call their ancestor code use
202
203  $object-> SUPER::method();
204
205syntax. Most Prima methods have fixed number of parameters.
206
207=head2 Properties
208
209Properties are methods that combine functionality of two ephemeral "get" and
210"set" methods. The idea behind properties is that many object parameters
211require two independent methods, one that returns some internal state and
212another that changes it.  For example, for managing the object name, set_name()
213and get_name() methods are needed. Indeed, the early Prima implementation dealt
214with large amount of these get's and set's, but later these method pairs were
215deprecated in the favor of properties.  Currently, there is only one method
216name() ( referred as C<::name> later in the documentation ).
217
218The property returns a value if no parameters ( except the object) are passed,
219and changes the internal data to the passed parameters otherwise. Here's
220a sketch code for C<::name> property implementation:
221
222 sub name
223 {
224    return $_[0]-> {name} unless $#_;
225    $_[0]->{name} = $_[1];
226 }
227
228There are many examples of properties throughout the toolkit.  Not all
229properties deal with scalar values, some accept arrays or hashes as well.
230The properties can be set-called not only by name like
231
232  $object-> name( "new name");
233
234but also with set() method. The set() method accepts a hash,
235that is much like to new(), and assigns the values to
236the corresponding properties. For example, the code
237
238  $object-> name( "new name");
239  $object-> owner( $owner);
240
241can be rewritten as
242
243  $object-> set(
244     name  => "new name",
245     owner => $owner
246  );
247
248A minor positive effect of a possible speed-up is gained by eliminating
249C-to-perl and perl-to-C calls, especially if the code called is implemented in
250C. The negative effect of such technique is that the order in which the
251properties are set, is undefined. Therefore, the usage of set() is recommended
252either when the property order is irrelevant, or it is known beforehand that
253such a call speeds up the code, or is an only way to achieve the result. An
254example of the latter case from L<Prima::internals> shows that Prima::Image
255calls
256
257    $image-> type( $a);
258    $image-> palette( $b);
259
260and
261
262    $image-> palette( $b);
263    $image-> type( $a);
264
265produce different results. It is indeed the only solution
266to call for such a change using
267
268    $image-> set(
269       type => $a,
270       palette => $b
271    );
272
273when it is known beforehand that C<Prima::Image::set> is aware of such
274combinations and calls neither C<::type> nor C<::palette> but
275performs another image conversion instead.
276
277Some properties are read-only and some are write-only. Some methods that might
278be declared as properties are not; these are declared as plain methods with
279get_ or set_ name prefix. There is not much certainty about what methods are
280better off being declared as properties and vice versa.
281
282However, if get_ or set_ methods cannot be used in correspondingly write or
283read fashion, the R/O and W/O properties can. They raise an exception on an
284attempt to do so.
285
286=head2 Links between objects
287
288Prima::Component descendants can be used as containers, as objects that are on
289a higher hierarchy level than the others. This scheme is implemented in a
290child-owner relationship.  The 'children' objects have the C<::owner> property
291value assigned to a reference to a 'owner' object, while the 'owner' object
292conducts the list of its children. It is a one-to-many hierarchy scheme, as a
293'child' object can have only one owner, but an 'owner' object can have many
294children. The same object can be an owner and a child at the same time, so the
295owner-child hierarchy can be viewed as a tree-like structure.
296
297Prima::Component::owner property maintains this relation, and is writable - the
298object can change its owner dynamically. There is no corresponding property
299that manages children objects, but is a method get_components(), that returns
300an array of the child references.
301
302The owner-child relationship is used in several ways in the toolkit.  For
303example, the widgets that are children of another widget appear ( usually, but
304not always ) in the geometrical interior of the owner widget.  Some events (
305keyboard events, for example ) are propagated automatically up and/or down the
306object tree. Another important feature is that when an object gets destroyed,
307its children are destroyed first.  In a typical program the whole object tree
308roots in a Prima::Application object instance. When the application finishes,
309this feature helps cleaning up the widgets and quitting gracefully.
310
311Implementation note: name 'owner' was taken instead of initial 'parent',
312because the 'parent' is a fixed term for widget hierarchy relationship
313description. Prima::Widget relationship between owner and child is not the same
314as GUI's parent-to-child.  The parent is the widget for the children widgets
315located in and clipped by its inferior. The owner widget is more than that, its
316children can be located outside its owner boundaries.
317
318The special convenience variety of new(), the insert() method is used
319to explicitly select owner of the newly created object. insert() can
320be considered a 'constructor' in OO-terms. It makes the construct
321
322   $obj = Class-> new( owner => $owner, name => 'name);
323
324more readable by introducing
325
326   $obj = $owner-> insert( 'Class', name => 'name');
327
328scheme. These two code blocks are identical to each other.
329
330There is another type of relation, where objects can hold references to each
331other. Internally this link level is used to keep objects from deletion by
332garbage collection mechanisms.  This relation is many-to-many scheme, where
333every object can have many links to other objects. This functionality is
334managed by attach() and detach() methods.
335
336=head1 Events
337
338Prima::Component descendants employ a well-developed event propagation
339mechanism, which allows handling events using several different schemes.  An
340event is a condition, caused by the system or the user, or an explicit notify()
341call. The formerly described events onCreate and onDestroy are triggered after
342a new object is created or before it gets destroyed. These two events, and the
343described below onPostMessage are present in namespaces of all Prima objects.
344New classes can register their own events and define their execution flow,
345using notification_types() method.  This method returns all available
346information about the events registered in a class.
347
348Prima defines also a non-object event dispatching and filtering mechanism,
349available through L<"event_hook"> static method.
350
351=head2 Propagation
352
353The event propagation mechanism has three layers of user-defined callback
354registration, that are called in different order and contexts when an event is
355triggered. The examples below show the usage of these layers. It is assumed
356that an implicit
357
358  $obj-> notify("PostMessage", $data1, $data2);
359
360call is issued for all these examples.
361
362=over 4
363
364=item Direct methods
365
366As it is usual in OO programming, event callback routines
367are declared as methods. 'Direct methods' employ such a paradigm,
368so if a class method with name C<on_postmessage> is present,
369it will be called as a method ( i.e., in the object context )
370when C<onPostMessage> event is triggered. Example:
371
372 sub on_postmessage
373 {
374    my ( $self, $data1, $data2) = @_;
375    ...
376 }
377
378The callback name is a modified lower-case event name: the name for Create
379event is on_create, PostMessage - on_postmessage etc.  These methods can be
380overloaded in the object's class descendants.  The only note on declaring these
381methods in the first instance is that no C<::SUPER> call is needed, because
382these methods are not defined by default.
383
384Usually the direct methods are used for the internal object book-keeping,
385reacting on the events that are not designed to be passed higher. For example,
386a Prima::Button class catches mouse and keyboard events in such a fashion,
387because usually the only notification that is interesting for the code that
388employs push-buttons is C<Click>.  This scheme is convenient when an event
389handling routine serves the internal, implementation-specific needs.
390
391=item Delegated methods
392
393The delegated methods are used when objects ( mostly widgets ) include other
394dependent objects, and the functionality requires interaction between these.
395The callback functions here are the same methods as direct methods, except that
396they get called in context of two, not one, objects. If, for example, a $obj's
397owner, $owner would be interested in $obj's PostMessage event, it would
398register the notification callback by
399
400   $obj-> delegations([ $owner, 'PostMessage']);
401
402where the actual callback sub will be
403
404 sub Obj_PostMessage
405 {
406    my ( $self, $obj, $data1, $data2) = @_;
407 }
408
409Note that the naming style is different - the callback name is constructed from
410object name ( let assume that $obj's name is 'Obj') and the event name. ( This
411is one of the reasons why Component::profile_check_in() performs automatic
412naming of newly created onbjects). Note also that context objects are $self (
413that equals $owner ) and $obj.
414
415The delegated methods can be used not only for the owner-child relations. Every
416Prima object is free to add a delegation method to every other object. However,
417if the objects are in other than owner-child relation, it is a good practice to
418add Destroy notification to the object which events are of interest, so if it
419gets destroyed, the partner object gets a message about that.
420
421=item Anonymous subroutines
422
423The two previous callback types are more relevant when a separate class is
424developed, but it is not necessary to declare a new class every time the event
425handling is needed.  It is possible to use the third and the most powerful
426event hook method using perl anonymous subroutines ( subs ) for the easy
427customization.
428
429Contrary to the usual OO event implementations, when only one routine per class
430dispatches an event, and calls inherited handlers when it is appropriate, Prima
431event handling mechanism can accept many event handlers for one object ( it is
432greatly facilitated by the fact that perl has I<anonymous subs>, however).
433
434All the callback routines are called when an event is triggered, one by one in
435turn. If the direct and delegated methods can only be multiplexed by the usual
436OO inheritance, the anonymous subs are allowed to be multiple by the design.
437There are three syntaxes for setting such a event hook; the example below
438sets a hook on $obj using each syntax for a different situation:
439
440- during new():
441
442   $obj = Class-> new(
443    ...
444    onPostMessage => sub {
445       my ( $self, $data1, $data2) = @_;
446    },
447    ...
448    );
449
450- after new using set()
451
452   $obj-> set( onPostMessage => sub {
453       my ( $self, $data1, $data2) = @_;
454   });
455
456- after new using event name:
457
458   $obj-> onPostMessage( sub {
459       my ( $self, $data1, $data2) = @_;
460   });
461
462As was noted in L<Prima>, the events can be addressed as properties, with the
463exception that they are not substitutive but additive.  The additivity is that
464when the latter type of syntax is used, the subs already registered do not get
465overwritten or discarded but stack in queue. Thus,
466
467   $obj-> onPostMessage( sub { print "1" });
468   $obj-> onPostMessage( sub { print "2" });
469   $obj-> notify( "PostMessage", 0, 0);
470
471code block would print
472
473   21
474
475as the execution result.
476
477This, it is a distinctive feature of a toolkit is that two objects of same class may
478have different set of event handlers.
479
480=back
481
482=head2 Flow
483
484When there is more than one handler of a particular event type present on an
485object, a question is risen about what are callbacks call priorities and when
486does the event processing stop. One of ways to regulate the event flow is based
487on prototyping events, by using notification_types() event type description.
488This function returns a hash, where keys are the event names and the values are
489the constants that describe the event flow. The constant can be a bitwise OR
490combination of several basic flow constants, that control the three aspects of
491the event flow.
492
493=over 4
494
495=item Order
496
497If both anonymous subs and direct/delegated methods are present, it must be
498decided which callback class must be called first.  Both 'orders' are useful:
499for example, if it is designed that a class's default action is to be
500overridden, it is better to call the custom actions first. If, on the contrary,
501the class action is primary, and the others are supplementary, the reverse
502order is preferred. One of two C<nt::PrivateFirst> and C<nt::CustomFirst>
503constants defines the order.
504
505=item Direction
506
507Almost the same as order, but for finer granulation of event flow, the
508direction constants C<nt::FluxNormal> and C<nt::FluxReverse> are used. The
509'normal flux' defines FIFO ( first in first out ) direction. That means, that
510the sooner the callback is registered, the greater priority it would possess
511during the execution.  The code block shown above
512
513   $obj-> onPostMessage( sub { print "1" });
514   $obj-> onPostMessage( sub { print "2" });
515   $obj-> notify( "PostMessage", 0, 0);
516
517results in C<21>, not C<12> because PostMessage event type is prototyped
518C<nt::FluxReverse>.
519
520=item Execution control
521
522It was stated above that the events are additive, - the callback storage is
523never discarded  when 'set'-syntax is used.  However, the event can be told to
524behave like a substitutive property, e.g. to call one and only one callback.
525This functionality is governed by C<nt::Single> bit in execution control
526constant set, which consists of the following constants:
527
528  nt::Single
529  nt::Multiple
530  nt::Event
531
532These constants are mutually exclusive, and may not appear together in an event
533type declaration.  A C<nt::Single>-prototyped notification calls only the first
534( or the last - depending on order and direction bits ) callback. The usage of
535this constant is somewhat limited.
536
537In contrary of C<nt::Single>, the C<nt::Multiple> constant sets the execution
538control to call all the available callbacks, with respect to direction and
539order bits.
540
541The third constant, C<nt::Event>, is the  impact as C<nt::Multiple>, except
542that the event flow can be stopped at any time by calling clear_event() method.
543
544=back
545
546Although there are 12 possible event type combinations, a half of them are not
547viable. Another half were assigned to unique more-less intelligible names:
548
549  nt::Default       ( PrivateFirst | Multiple | FluxReverse)
550  nt::Property      ( PrivateFirst | Single   | FluxNormal )
551  nt::Request       ( PrivateFirst | Event    | FluxNormal )
552  nt::Notification  ( CustomFirst  | Multiple | FluxReverse )
553  nt::Action        ( CustomFirst  | Single   | FluxReverse )
554  nt::Command       ( CustomFirst  | Event    | FluxReverse )
555
556=head2 Success state
557
558Events do not return values, although the event generator, the notify() method
559does - it returns either 1 or 0, which is the value of event success state.
560The 0 and 1 results in general do not mean either success or failure, they
561simply reflect the fact whether clear_event() method was called during the
562processing - 1 if it was not, 0 otherwise. The state is kept during the whole
563processing stage, and can be accessed from Component::eventFlag property. Since
564it is allowed to call notify() inside event callbacks, the object maintains a
565stack for those states.  Component::eventFlags always works with the topmost
566one, and fails if is called from outside the event processing stage. Actually,
567clear_event() is an alias for ::eventFlag(0) call. The state stack is operated
568by push_event() and pop_event() methods.
569
570Implementation note: a call of clear_event() inside a C<nt::Event>-prototyped
571event call does not automatically stops the execution. The execution stops if
572the state value equals to 0 after the callback is finished.  A ::eventFlag(1)
573call thus cancels the effect of clear_event().
574
575A particular coding style is used when the event is C<nt::Single>-prototyped
576and is called many times in a row, so overheads of calling notify() become a
577burden. Although notify() logic is somewhat complicated, it is rather simple
578with C<nt::Single> case. The helper function get_notify_sub() returns the context
579of callback to-be-called, so it can be used to emulate notify() behavior.
580Example:
581
582  for ( ... ) {
583     $result = $obj-> notify( "Measure", @parms);
584  }
585
586can be expressed in more cumbersome, but efficient code if
587C<nt::Single>-prototyped event is used:
588
589   my ( $notifier, @notifyParms) = $obj-> get_notify_sub( "Measure" );
590   $obj-> push_event;
591   for ( ... ) {
592       $notifier-> ( @notifyParms, @parms);
593       # $result = $obj-> eventFlag; # this is optional
594   }
595   $result = $obj-> pop_event;
596
597=head1 API
598
599=head2 Prima::Object methods
600
601=over 4
602
603=item alive
604
605Returns the object 'vitality' state - true if the object is alive and usable,
606false otherwise.  This method can be used as a general checkout if the scalar
607passed is a Prima object, and if it is usable.  The true return value can be 1
608for normal and operational object state, and 2 if the object is alive but in
609its init() stage. Example:
610
611  print $obj-> name if Prima::Object::alive( $obj);
612
613=item cleanup
614
615Called right after destroy() started. Used to initiate C<cmDestroy>
616event. Is never called directly.
617
618=item create CLASS, %PARAMETERS
619
620Same as L<new>.
621
622=item destroy
623
624Initiates the object destruction. Perform in turn cleanup() and done() calls.
625destroy() can be called several times and is the only Prima re-entrant
626function, therefore may not be overloaded.
627
628=item done
629
630Called by destroy() after cleanup() is finished. Used to free the object
631resources, as a finalization stage.  During done() no events are allowed to
632circulate, and alive() returns 0. The object is not usable after done()
633finishes. Is never called directly.
634
635Note: the eventual child objects are destroyed inside done() call.
636
637=item get @PARAMETERS
638
639Returns hash where keys are @PARAMETERS and values are
640the corresponding object properties.
641
642=item init %PARAMETERS
643
644The most important stage of object creation process.  %PARAMETERS is the
645modified hash that was passed to new().  The modification consists of
646merging with the result of profile_default() class method inside
647profile_check_in() method. init() is responsible for applying the relevant data
648into PARAMETERS to the object properties. Is never called directly.
649
650=item insert CLASS, %PARAMETERS
651
652A convenience wrapper for new(), that explicitly sets
653the owner property for a newly created object.
654
655   $obj = $owner-> insert( 'Class', name => 'name');
656
657is adequate to
658
659   $obj = Class-> new( owner => $owner, name => 'name);
660
661code. insert() has another syntax that allows simultaneous
662creation of several objects:
663
664   @objects = $owner-> insert(
665     [ 'Class', %parameters],
666     [ 'Class', %parameters],
667     ...
668   );
669
670With such syntax, all newly created objects would have $owner
671set to their 'owner' properties.
672
673=item new CLASS, %PARAMETERS
674
675Creates a new object instance of a given CLASS
676and sets its properties corresponding to the passed parameter hash. Examples:
677
678   $obj = Class-> new( PARAMETERS);
679   $obj = Prima::Object::new( "class" , PARAMETERS);
680
681Is never called in an object context.
682
683Alias: create()
684
685
686=item profile_add PROFILE
687
688The first stage of object creation process.  PROFILE is a reference to a
689PARAMETERS hash, passed to new().  It is merged with profile_default() after
690passing both to profile_check_in(). The merge result is stored back in PROFILE.
691Is never called directly.
692
693=item profile_check_in CUSTOM_PROFILE, DEFAULT_PROFILE
694
695The second stage of object creation process.  Resolves eventual ambiguities in
696CUSTOM_PROFILE, which is the reference to PARAMETERS passed to new(), by
697comparing to and using default values from DEFAULT_PROFILE, which is the result
698of profile_default() method. Is never called directly.
699
700=item profile_default
701
702Returns hash of the appropriate default values for all properties of a class.
703In object creation process serves as a provider of fall-back values, and is
704called implicitly. This method can be used directly, contrary to the other
705creation process-related functions.
706
707Can be called in a context of class.
708
709=item raise_ro TEXT
710
711Throws an exception with text TEXT when a read-only property is called in
712a set- context.
713
714=item raise_wo TEXT
715
716Throws an exception with text TEXT when a write-only property is called in
717a get- context.
718
719=item set %PARAMETERS
720
721The default behavior is an equivalent to
722
723  sub set
724  {
725     my $obj = shift;
726     my %PARAMETERS = @_;
727     $obj-> $_( $PARAMETERS{$_}) for keys %PARAMETERS;
728  }
729
730code. Assigns object properties correspondingly to PARAMETERS hash.  Many
731Prima::Component descendants overload set() to make it more efficient for
732particular parameter key patterns.
733
734As the code above, raises an exception if the key in PARAMETERS has no
735correspondent object property.
736
737=item setup
738
739The last stage of object creation process.  Called after init() finishes. Used
740to initiate C<cmCreate> event. Is never called directly.
741
742=back
743
744=head2 Prima::Component methods
745
746=over 4
747
748=item add_notification NAME, SUB, REFERER = undef, INDEX = -1
749
750Adds SUB to the list of notification of event NAME.  REFERER is the object
751reference, which is used to create a context to SUB and is passed as a
752parameter to it when called.  If REFERER is undef ( or not specified ), the
753same object is assumed. REFERER also gets implicitly attached to the object, -
754the implementation frees the link between objects when one of these gets
755destroyed.
756
757INDEX is a desired insert position in the notification list.  By default it is
758-1, what means 'in the start'. If the notification type contains nt::FluxNormal
759bit set, the newly inserted SUB will be called first. If it has
760nt::FluxReverse, it is called last, correspondingly.
761
762Returns positive integer value on success, 0 on failure.  This value can be
763later used to refer to the SUB in remove_notification().
764
765See also: C<remove_notification>, C<get_notification>.
766
767=item attach OBJECT
768
769Inserts OBJECT to the attached objects list and increases OBJECT's reference
770count. The list can not hold more than one reference to the same object. The
771warning is issued on such an attempt.
772
773See also: C<detach>.
774
775=item bring NAME
776
777Looks for a immediate child object that has name equals to NAME.  Returns its
778reference on success, undef otherwise. It is a convenience method, that makes
779possible the usage of the following constructs:
780
781   $obj-> name( "Obj");
782   $obj-> owner( $owner);
783   ...
784   $owner-> Obj-> destroy;
785
786See also: C<find_component>
787
788=item can_event
789
790Returns true if the object event circulation is allowed.  In general, the same
791as C<alive() == 1>, except that can_event() fails if an invalid object
792reference is passed.
793
794=item clear_event
795
796Clears the event state, that is set to 1 when the event processing begins.
797Signals the event execution stop for nt::Event-prototyped events.
798
799See also: L<"Events">, C<push_event>, C<pop_event>, C<::eventFlag>, C<notify>.
800
801=item detach OBJECT, KILL
802
803Removes OBJECT from the attached objects list and decreases OBJECT's reference
804count. If KILL is true, destroys OBJECT.
805
806See also: C<attach>
807
808=item event_error
809
810Issues a system-dependent warning sound signal.
811
812=item event_hook [ SUB ]
813
814Installs a SUB to receive all events on all Prima objects.  SUB receives same
815parameters passed to L<notify>, and must return an integer, either 1 or 0, to
816pass or block the event respectively.
817
818If no SUB is set, returns currently installed event hook pointer.  If SUB is
819set, replaces the old hook sub with SUB. If SUB is C<'undef'>, event filtering
820is not used.
821
822Since the C<'event_hook'> mechanism allows only one hook routine to be
823installed at a time, direct usage of the method is discouraged.  Instead, use
824L<Prima::EventHook> for multiplexing of the hook access.
825
826The method is static, and can be called either with or without class or
827object as a first parameter.
828
829=item find_component NAME
830
831Performs a depth-first search on children tree hierarchy, matching the object
832that has name equal to NAME.  Returns its reference on success, undef
833otherwise.
834
835See also: C<bring>
836
837=item get_components
838
839Returns array of the child objects.
840
841See: C<new>, L<"Links between objects">.
842
843=item get_handle
844
845Returns a system-dependent handle for the object.  For example, Prima::Widget
846return its system WINDOW/HWND handles, Prima::DeviceBitmap - its system
847PIXMAP/HBITMAP handles, etc.
848
849Can be used to pass the handle value outside the program, for an eventual
850interprocess communication scheme.
851
852=item get_notification NAME, @INDEX_LIST
853
854For each index in INDEX_LIST return three scalars, bound at the index position
855in the NAME event notification list.  These three scalars are REFERER, SUB and
856ID. REFERER and SUB are those passed to C<add_notification>, and ID is its
857result.
858
859See also: C<remove_notification>, C<add_notification>.
860
861=item get_notify_sub NAME
862
863A convenience method for nt::Single-prototyped events.  Returns code reference
864and context for the first notification sub for event NAME.
865
866See L<"Success state"> for example.
867
868=item notification_types
869
870Returns a hash, where the keys are the event names and the values are the
871C<nt::> constants that describe the event flow.
872
873Can be called in a context of class.
874
875See L<"Events"> and L<"Flow"> for details.
876
877=item notify NAME, @PARAMETERS
878
879Calls the subroutines bound to the event NAME with parameters @PARAMETERS in
880context of the object.  The calling order is described by C<nt::> constants,
881contained in the notification_types() result hash.
882
883notify() accepts variable number of parameters, and while it is possible, it is
884not recommended to call notify() with the exceeding number of parameters; the
885call with the deficient number of parameters results in an exception.
886
887Example:
888
889   $obj-> notify( "PostMessage", 0, 1);
890
891See L<"Events"> and L<"Flow"> for details.
892
893=item pop_event
894
895Closes event processing stage brackets.
896
897See C<push_event>, L<"Events">
898
899=item post_message SCALAR1, SCALAR2
900
901Calls C<PostMessage> event with parameters SCALAR1 and SCALAR2 once during idle
902event loop. Returns immediately.  Does not guarantee that C<PostMessage> will
903be called, however.
904
905See also L<Prima::Utils/post>
906
907=item push_event
908
909Opens event processing stage brackets.
910
911See C<pop_event>, L<"Events">
912
913=item remove_notification ID
914
915Removes a notification subroutine that was registered before with
916C<add_notification>, where ID was its result. After successful removal, the
917eventual context object gets implicitly detached from the storage object.
918
919See also: C<add_notification>, C<get_notification>.
920
921=item set_notification NAME, SUB
922
923Adds SUB to the event NAME notification list. Almost never used directly, but
924is a key point in enabling the following notification add syntax
925
926   $obj-> onPostMessage( sub { ... });
927
928or
929
930   $obj-> set( onPostMessage => sub { ... });
931
932that are shortcuts for
933
934   $obj-> add_notification( "PostMessage", sub { ... });
935
936
937=item unlink_notifier REFERER
938
939Removes all notification subs from all event lists bound to REFERER object.
940
941=back
942
943=head2 Prima::Component properties
944
945=over 4
946
947=item eventFlag STATE
948
949Provides access to the last event processing state in the object event state
950stack.
951
952See also: L<"Success state">, C<clear_event>, L<"Events">.
953
954=item delegations [ <REFERER>, NAME, <NAME>, < <REFERER>, NAME, ... > ]
955
956Accepts an anonymous array in I<set-> context, which consists of a list of event NAMEs,
957that a REFERER object ( the caller object by default ) is interested in.
958Registers notification entries for routines if subs with naming scheme
959REFERER_NAME are present on REFERER name space.  The example code
960
961   $obj-> name("Obj");
962   $obj-> delegations([ $owner, 'PostMessage']);
963
964registers Obj_PostMessage callback if it is present in $owner namespace.
965
966In I<get-> context returns an array reference that reflects the object's delegated
967events list content.
968
969See also: L<"Delegated methods">.
970
971=item name NAME
972
973Maintains object name. NAME can be an arbitrary string, however it is
974recommended against usage of special characters and spaces in NAME, to
975facilitate the indirect object access coding style:
976
977   $obj-> name( "Obj");
978   $obj-> owner( $owner);
979   ...
980   $owner-> Obj-> destroy;
981
982and to prevent system-dependent issues. If the system provides capabilities
983that allow to predefine some object parameters by its name ( or class), then it
984is impossible to know beforehand the system naming restrictions.  For example,
985in X window system the following resource string would make all Prima toolkit
986buttons green:
987
988  Prima*Button*backColor: green
989
990In this case, using special characters such as C<:> or C<*> in the name of an object
991would make the X resource unusable.
992
993=item owner OBJECT
994
995Selects an owner of the object, which may be any Prima::Component descendant.
996Setting an owner to a object does not alter its reference count. Some classes
997allow OBJECT to be undef, while some do not. All widget objects can not exist
998without a valid owner; Prima::Application on the contrary can only exist with
999owner set to undef. Prima::Image objects are indifferent to the value of the
1000owner property.
1001
1002Changing owner dynamically is allowed, but it is a main source of
1003implementation bugs, since the whole hierarchy tree is needed to be recreated.
1004Although this effect is not visible in perl, the results are deeply
1005system-dependent, and the code that changes owner property should be thoroughly
1006tested.
1007
1008Changes to C<owner> result in up to three notifications: C<ChangeOwner>, which
1009is called to the object itself, C<ChildLeave>, which notifies the previous
1010owner that the object is about to leave, and C<ChildEnter>, telling the new
1011owner about the new child.
1012
1013=back
1014
1015=head2 Prima::Component events
1016
1017=over 4
1018
1019=item ChangeOwner OLD_OWNER
1020
1021Called at runtime when the object changes its owner.
1022
1023=item ChildEnter CHILD
1024
1025Triggered when a child object is attached, either as
1026a new instance or as a result of runtime owner change.
1027
1028=item ChildLeave CHILD
1029
1030Triggered when a child object is detached, either because
1031it is getting destroyed or as a result of runtime owner change.
1032
1033=item Create
1034
1035The first event an event sees. Called automatically after init() is finished.
1036Is never called directly.
1037
1038=item Destroy
1039
1040The last event an event sees. Called automatically before done() is started.
1041Is never called directly.
1042
1043=item PostMessage SCALAR1, SCALAR2
1044
1045Called after post_message() call is issued, not inside post_message() but at
1046the next idle event loop.  SCALAR1 and SCALAR2 are the data passed to
1047post_message().
1048
1049=item SysHandle
1050
1051Sometimes Prima needs to implicitly re-create the system handle of a component.
1052The re-creation is not seen on the toolkit level, except for some repaints when
1053widgets on screen are affected, but under the hood, when it happens, Prima
1054creates a whole new system resource. This happens when the underlying system
1055either doesn't have API to change a certain property during the runtime, or
1056when such a re-creation happens on one of component's parent, leading to a
1057downward cascade of children re-creation. Also, it may happen when the user
1058changes some system settings resolution, so that some resources have to be changed
1059accordingly.
1060
1061This event will be only needed when the system handle (that can be acquired by
1062C<get_handle> ) is used further, or in case when Prima doesn't restore some
1063properties bound to the system handle.
1064
1065=back
1066
1067=head1 AUTHOR
1068
1069Dmitry Karasik, E<lt>dmitry@karasik.eu.orgE<gt>.
1070
1071=head1 SEE ALSO
1072
1073L<Prima>, L<Prima::internals>, L<Prima::EventHook>.
1074