Plug more leaks (in the test, not the core)
[gnash.git] / libcore / MovieClip.h
blob9bb0357515ce2578325bbb806ae23fbc5525eba4
1 // MovieClip.h: Stateful live Sprite instance, for Gnash.
2 //
3 // Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software
4 // Foundation, Inc
5 //
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 // Stateful live Sprite instance
22 #ifndef GNASH_MOVIECLIP_H
23 #define GNASH_MOVIECLIP_H
25 #ifdef HAVE_CONFIG_H
26 #include "gnashconfig.h"
27 #endif
29 #include <vector>
30 #include <list>
31 #include <map>
32 #include <string>
33 #include <boost/ptr_container/ptr_list.hpp>
34 #include <boost/intrusive_ptr.hpp>
36 #include "ControlTag.h"
37 #include "movie_definition.h" // for inlines
38 #include "DisplayList.h" // DisplayList
39 #include "DisplayObjectContainer.h"
40 #include "as_environment.h" // for composition
41 #include "DynamicShape.h" // for composition
42 #include "snappingrange.h"
43 #include "dsodefs.h" // for DSOEXPORT
45 // Forward declarations
46 namespace gnash {
47 class Movie;
48 class swf_event;
49 class drag_state;
50 class LoadVariablesThread;
51 class GradientRecord;
52 class TextField;
53 class BitmapData_as;
54 class CachedBitmap;
55 namespace SWF {
56 class PlaceObject2Tag;
60 namespace gnash {
62 /// A MovieClip is a container for DisplayObjects.
64 /// TODO: This class should inherit from Sprite
66 /// In AS3 is it distinguished from a Sprite by having a timeline, i.e.
67 /// more than one frame. In AS2, there is no Sprite class.
69 /// There are basically two types of MovieClip: dynamic and non-dynamic.
70 /// Dynamic clips are created using createEmptyMovieClip() or
71 /// duplicateMovieClip(). Non-dynamic MovieClips are parsed from a SWF file.
72 /// The isDynamic() member function is the only way to tell the difference
73 /// (see following paragraph).
75 /// The presence of a definition (the _def member) reveals whether the
76 /// MovieClip was constructed with an immutable definition or not. MovieClips
77 /// created using createEmptyMovieClip() have no definition. MovieClips
78 /// constructed using duplicateMovieClip() have the same definition as the
79 /// duplicated clip. They are "dynamic", but may have a definition!
81 /// A MovieClip always has an _swf member. This is the top-level SWF
82 /// (Movie) containing either the definition or the code from
83 /// which the MovieClip was created. The _url member and SWF version are
84 /// dependent on the _swf. Exports are also sought in this Movie.
85 class MovieClip : public DisplayObjectContainer
87 public:
89 typedef std::vector<TextField*> TextFields;
91 /// A container for textfields, indexed by their variable name
92 typedef std::map<ObjectURI, TextFields, ObjectURI::LessThan>
93 TextFieldIndex;
95 typedef std::map<std::string, std::string> MovieVariables;
97 typedef std::list<const action_buffer*> ActionList;
99 typedef movie_definition::PlayList PlayList;
101 enum PlayState
103 PLAYSTATE_PLAY,
104 PLAYSTATE_STOP
107 /// Construct a MovieClip instance
109 /// @param def
110 /// Pointer to the movie_definition this object is an
111 /// instance of (may be a top-level movie or a sprite).
112 /// This may be 0 if there is no immutable definition.
114 /// @param root
115 /// The "relative" _swf of this sprite, which is the
116 /// instance of top-level sprite defined by the same
117 /// SWF that also contained *this* sprite definition.
118 /// Note that this can be *different* from the top-level
119 /// movie accessible through the VM, in case this sprite
120 /// was defined in an externally loaded movie.
122 /// @param parent
123 /// Parent of the created instance in the display list.
124 /// May be 0 for top-level movies (_level#).
125 MovieClip(as_object* object, const movie_definition* def,
126 Movie* root, DisplayObject* parent);
128 virtual ~MovieClip();
130 // Return the originating SWF
131 virtual Movie* get_root() const;
133 virtual bool trackAsMenu();
135 /// Return the _root ActionScript property of this sprite.
137 /// Relative or absolute is determined by the _lockroot property,
138 /// see getLockRoot and setLockRoot. May return this.
139 virtual MovieClip* getAsRoot();
141 /// Get the composite bounds of all component drawing elements
142 virtual SWFRect getBounds() const;
144 // See dox in DisplayObject.h
145 virtual bool pointInShape(boost::int32_t x, boost::int32_t y) const;
147 // See dox in DisplayObject.h
148 virtual bool pointInVisibleShape(boost::int32_t x, boost::int32_t y) const;
150 /// return true if the given point is located in a(this) hitable sprite.
152 /// all sprites except mouse-insensitive dynamic masks are hitable.
153 /// _visible property is ignored for hitable DisplayObjects.
154 virtual bool pointInHitableShape(boost::int32_t x, boost::int32_t y) const;
156 /// Return 0-based index to current frame
157 size_t get_current_frame() const
159 return _currentFrame;
162 size_t get_frame_count() const
164 return _def ? _def->get_frame_count() : 1;
167 /// Return number of completely loaded frames of this sprite/movie
169 /// Note: the number is also the last frame accessible (frames
170 /// numberes are 1-based)
172 size_t get_loaded_frames() const
174 return _def ? _def->get_loading_frame() : 1;
177 /// Return total number of bytes in the movie
178 /// (not sprite!)
179 size_t get_bytes_total() const
181 return isDynamic() ? 0 : _def->get_bytes_total();
184 /// Return number of loaded bytes in the movie
185 /// (not sprite!)
186 size_t get_bytes_loaded() const
188 return isDynamic() ? 0 : _def->get_bytes_loaded();
191 const SWFRect& get_frame_size() const
193 static const SWFRect r;
194 return _def ? _def->get_frame_size() : r;
197 /// Stop or play the sprite.
199 /// If stopped, any stream sound associated with this sprite
200 /// will also be stopped.
202 DSOEXPORT void setPlayState(PlayState s);
204 PlayState getPlayState() const { return _playState; }
206 // delegates to movie_root (possibly wrong)
207 void set_background_color(const rgba& color);
209 /// Return true if we have any mouse event handlers.
211 /// NOTE: this function currently does not consider
212 /// general mouse event handlers MOUSE_MOVE, MOUSE
213 virtual bool mouseEnabled() const;
215 /// \brief
216 /// Return the topmost entity that the given point
217 /// covers that can receive mouse events. NULL if
218 /// none. Coords are in parent's frame.
219 virtual InteractiveObject* topmostMouseEntity(boost::int32_t x,
220 boost::int32_t y);
222 // see dox in DisplayObject.h
223 const DisplayObject* findDropTarget(boost::int32_t x, boost::int32_t y,
224 DisplayObject* dragging) const;
226 void setDropTarget(const std::string& tgt) {
227 _droptarget = tgt;
230 const std::string& getDropTarget() const {
231 return _droptarget;
234 /// Advance to the next frame of the MovieClip.
236 /// Actions will be executed or pushed to the queue as necessary.
237 virtual void advance();
239 /// Set the sprite state at the specified frame number.
241 /// 0-based frame numbers!!
242 ///(in contrast to ActionScript and Flash MX)
244 DSOEXPORT void goto_frame(size_t target_frame_number);
246 /// Parse frame spec and return a 0-based frame number.
248 /// If frame spec cannot be converted to !NAN and !Infinity number
249 /// it will be converted to a string and considered a
250 /// frame label (returns false if referring to an
251 /// unknwown label).
253 /// @param frame_spec
254 /// The frame specification.
256 /// @param frameno
257 /// The evaluated frame number (0-based)
259 /// @return
260 /// True if the frame_spec could be resolved to a frame number.
261 /// False if the frame_spec was invalid.
262 bool get_frame_number(const as_value& frame_spec, size_t& frameno) const;
264 /// Look up the labeled frame, and jump to it.
265 bool goto_labeled_frame(const std::string& label);
267 /// Render this MovieClip.
268 virtual void display(Renderer& renderer, const Transform& xform);
270 /// Draw this MovieClip
272 /// This is effectively the same as display(), but uses only the passed
273 /// transform.
274 void draw(Renderer& renderer, const Transform& xform);
276 void omit_display();
278 /// Swap depth of the given DisplayObjects in the DisplayList
280 /// See DisplayList::swapDepths for more info
281 void swapDepths(DisplayObject* ch1, int newdepth)
283 _displayList.swapDepths(ch1, newdepth);
286 /// Return the DisplayObject at given depth in our DisplayList.
288 /// @return NULL if the specified depth is available (no chars there)
289 DisplayObject* getDisplayObjectAtDepth(int depth);
291 /// Attach a DisplayObject at the specified depth.
292 DisplayObject* addDisplayListObject(DisplayObject* obj, int depth);
294 /// Place a DisplayObject or mask to the DisplayList.
296 /// This method instantiates the given DisplayObject definition
297 /// and places it on the stage at the given depth.
299 /// If the specified depth is already occupied, it results a no-ops.
300 /// Otherwise, a new DisplayObject will be created and onload handler
301 /// will be triggerred.
303 /// @param tag
304 /// A swf defined placement tag (PlaceObject, or PlaceObject2,
305 /// or PlaceObject3).
306 /// No ownership transfer, the tag is still owned by the
307 /// movie_definition class.
309 /// @param dlist
310 /// The display list to add the DisplayObject to.
312 /// @return
313 /// A pointer to the DisplayObject being added or NULL
314 DisplayObject* add_display_object(const SWF::PlaceObject2Tag* tag,
315 DisplayList& dlist);
317 /// Proxy of DisplayList::moveDisplayObject()
318 void move_display_object(const SWF::PlaceObject2Tag* tag,
319 DisplayList& dlist);
321 /// Proxy of DisplayList::replaceDisplayObject()
322 void replace_display_object(const SWF::PlaceObject2Tag* tag,
323 DisplayList& dlist);
325 /// Proxy of DisplayList::removeDisplayObject()
326 void remove_display_object(const SWF::PlaceObject2Tag* tag,
327 DisplayList& dlist);
329 /// \brief
330 /// Remove the object at the specified depth.
332 /// NOTE:
333 /// (1)the id parameter is currently unused, but
334 /// required to avoid breaking of inheritance from movie.h.
335 /// (2)the id might be used for specifying a DisplayObject
336 /// in the depth(think about multiple DisplayObjects within the same
337 /// depth, not tested and a rare case)
338 void remove_display_object(int depth, int /*id*/);
340 void unloadMovie();
342 /// Attach the given DisplayObject instance to current display list
344 /// @param newch The DisplayObject instance to attach.
345 /// @param depth The depth to assign to the instance.
346 void attachCharacter(DisplayObject& newch, int depth, as_object* initObject);
348 /// Handle placement event
350 /// This callback will (not known to be a problem):
352 /// (1) Register ourselves with the global instance list
353 /// (2) Take note of our original target path
354 /// (3) Register as listener of core broadcasters
355 /// (4) Execute tags of frame 0
357 /// The callback will also (known to be bogus):
359 /// (1) Construct this instance as an ActionScript object.
360 /// See constructAsScriptObject() method, including constructing
361 /// registered class and adding properties.
362 virtual void construct(as_object* initObj = 0);
364 /// Mark this sprite as destroyed
366 /// This is an override of DisplayObject::destroy()
368 /// A sprite should be destroyed when is removed from the display
369 /// list and is not more needed for names (target) resolutions.
370 /// Sprites are needed for names resolution whenever themselves
371 /// or a contained object has an onUnload event handler defined,
372 /// in which case we want the event handler to find the 'this'
373 /// variable w/out attempting to rebind it.
375 /// When a sprite is destroyed, all its children are also destroyed.
376 ///
377 /// Note: this function will release most memory associated with
378 /// the sprite as no members or drawable should be needed anymore.
379 void destroy();
381 /// Add the given action buffer to the list of action
382 /// buffers to be processed at the end of the next
383 /// frame advance.
384 void add_action_buffer(const action_buffer* a)
386 if (!_callingFrameActions) queueAction(*a);
387 else execute_action(*a);
391 /// \brief
392 /// Execute the given init action buffer, if not done yet
393 /// for the target DisplayObject id.
395 /// The action will normally be pushed on queue, but will
396 /// be executed immediately if we are executing actions
397 /// resulting from a callFame instead.
399 /// @param a
400 /// The action buffer to execute
402 /// @param cid
403 /// The referenced DisplayObject id
404 void execute_init_action_buffer(const action_buffer& a, int cid);
406 /// Execute a single action buffer (DOACTION block)
407 void execute_action(const action_buffer& ab);
409 MovieClip* to_movie () { return this; }
411 /// The various methods for sending data in requests.
413 /// Used in loadMovie, getURL, loadVariables etc.
414 enum VariablesMethod
416 METHOD_NONE = 0,
417 METHOD_GET,
418 METHOD_POST
421 // See dox in DisplayObject.h
422 virtual void getLoadedMovie(Movie* newMovie);
424 /// \brief
425 /// Load url-encoded variables from the given url, optionally
426 /// sending variables from this timeline too.
428 /// A LoadVariablesThread will be started to load and parse variables
429 /// and added to the _loadVariableRequests. Then, at every ::advance_sprite
430 /// any completed threads will be processed
431 /// (see processCompletedLoadVariableRequests)
433 /// NOTE: the given url will be security-checked
435 /// @param urlstr: The url to load variables from.
437 /// @param sendVarsMethod: The VariablesMethod to use. If METHOD_NONE,
438 /// no data will be sent.
439 void loadVariables(const std::string& urlstr,
440 VariablesMethod sendVarsMethod);
442 /// Get TextField variables
444 /// TODO: this is unlikely to be the best way of doing it, and it would
445 /// simplify things if this function could be dropped.
446 bool getTextFieldVariables(const ObjectURI& uri, as_value& val);
448 // Set TextField variables
450 /// TODO: this is also unlikely to be the best way to do it.
451 bool setTextFieldVariables(const ObjectURI& uri, const as_value& val);
453 /// Search for a named object on the DisplayList
455 /// These are properties, but not attached as genuine members to the
456 /// MovieClip object. They take priority over DisplayObject magic
457 /// properties and inherited properties, but not over own properties.
459 /// @param name Object identifier. This function handles
460 /// case-sensitivity.
461 /// @return The object if found, otherwise 0.
462 DisplayObject* getDisplayListObject(const ObjectURI& uri);
464 /// Overridden to look in DisplayList for a match
465 as_object* pathElement(const ObjectURI& uri);
467 /// Execute the actions for the specified frame.
469 /// The frame_spec could be an integer or a string.
470 virtual void call_frame_actions(const as_value& frame_spec);
472 // delegates to movie_root
473 virtual void stop_drag();
475 /// Duplicate this sprite in its timeline
477 /// Add the new DisplayObject at a the given depth to this sprite
478 /// parent displaylist.
480 /// NOTE: the call will fail for the root movie (no parent).
481 /// NOTE2: any DisplayObject at the given target depth will be
482 /// replaced by the new DisplayObject
483 /// NOTE3: event handlers will also be copied
485 /// @param newname
486 /// Name for the copy
488 /// @param newdepth
489 /// Depth for the copy
491 /// @param init_object
492 /// If not null, will be used to copy properties over.
493 MovieClip* duplicateMovieClip(const std::string& newname,
494 int newdepth, as_object* init_object=NULL);
496 /// Dispatch event handler(s), if any.
497 virtual void notifyEvent(const event_id& id);
499 // inherited from DisplayObject class, see dox in DisplayObject.h
500 virtual as_environment& get_environment() {
501 return _environment;
504 /// \brief
505 /// Set a TextField variable to this timeline
507 /// A TextField variable is a variable that acts
508 /// as a setter/getter for a TextField 'text' member.
509 void set_textfield_variable(const ObjectURI& name, TextField* ch);
511 void add_invalidated_bounds(InvalidatedRanges& ranges, bool force);
513 const DisplayList& getDisplayList() const {
514 return _displayList;
517 /// Return the next highest available depth
519 /// Placing an object at the depth returned by
520 /// this function should result in a DisplayObject
521 /// that is displayd above all others
522 int getNextHighestDepth() const {
523 return _displayList.getNextHighestDepth();
526 /// Set the currently playing m_sound_stream_id
528 // TODO: rename to setStreamingSoundId
529 void setStreamSoundId(int id);
531 /// Remove this sprite from the stage.
533 /// This function is intended to be called by
534 /// effect of a removeMovieClip() ActionScript call
535 /// and implements the checks required for this specific
536 /// case.
538 /// Callers are:
539 /// - The ActionRemoveClip tag handler.
540 /// - The global removeMovieClip(target) function.
541 /// - The MovieClip.removeMovieClip() method.
543 /// The removal will not occur if the depth of this
544 /// DisplayObjects is not in the "dynamic" range [0..1048575]
545 /// as described at the following URL:
546 ///
547 /// http://www.senocular.com/flash/tutorials/depths/?page=2
549 /// A testcases for this behaviour can be found in
551 /// testsuite/misc-ming.all/displaylist_depths_test.swf
552 void removeMovieClip();
554 /// Direct access to the Graphics object for drawing.
555 DynamicShape& graphics() {
556 set_invalidated();
557 return _drawable;
560 /// Set focus to this MovieClip
562 /// @return true if this MovieClip can receive focus.
563 virtual bool handleFocus();
565 /// @} Drawing API
567 /// Set all variables in the given map with their corresponding values
568 DSOEXPORT void setVariables(const MovieVariables& vars);
570 /// Enumerate child DisplayObjects
572 /// See DisplayObject::enumerateNonProperties for more info.
573 virtual void visitNonProperties(KeyVisitor& v) const;
575 /// Delete DisplayObjects removed from the stage
576 /// from the display lists
577 void cleanupDisplayList();
579 /// Queue the given action buffer
581 /// The action will be pushed on the current
582 /// global list (see movie_root).
584 void queueAction(const action_buffer& buf);
586 /// Construct this instance as an ActionScript object
588 /// This method invokes the constructor associated with our
589 /// definition, either MovieClip or any user-speficied one
590 /// (see sprite_definition::registerClass).
591 /// It will also invoke the onClipConstruct and onConstruct handlers.
592 void constructAsScriptObject();
594 /// Return true if getAsRoot() should return the *relative* root,
595 /// false otherwise.
596 bool getLockRoot() const { return _lockroot; }
598 /// Set whether getAsRoot() should return the *relative* root,
599 /// false otherwise. True for relative root.
600 void setLockRoot(bool lr) { _lockroot=lr; }
602 /// Return the version of the SWF this MovieClip was parsed from.
603 virtual int getDefinitionVersion() const;
605 protected:
607 /// Unload all contents in the displaylist and this instance
609 /// Return true if there was an unloadHandler.
610 virtual bool unloadChildren();
612 /// Mark sprite-specific reachable resources.
614 /// sprite-specific reachable resources are:
615 /// - DisplayList items (current, backup and frame0 ones)
616 /// - Canvas for dynamic drawing (_drawable)
617 /// - sprite environment
618 /// - definition the sprite has been instantiated from
619 /// - Textfields having an associated variable registered in this instance.
620 /// - Relative root of this instance (_swf)
622 virtual void markOwnResources() const;
624 // Used by BitmapMovie.
625 void placeDisplayObject(DisplayObject* ch, int depth) {
626 _displayList.placeDisplayObject(ch, depth);
629 private:
631 /// Process any completed loadVariables request
632 void processCompletedLoadVariableRequests();
634 /// Process a completed loadVariables request
635 void processCompletedLoadVariableRequest(LoadVariablesThread& request);
638 /// Execute the tags associated with the specified frame.
640 /// @param frame
641 /// Frame number. 0-based
643 /// @param dlist
644 /// The display list to have control tags act upon.
646 /// @param typeflags
647 /// Which kind of control tags we want to execute.
648 void executeFrameTags(size_t frame, DisplayList& dlist,
649 int typeflags = SWF::ControlTag::TAG_DLIST |
650 SWF::ControlTag::TAG_ACTION);
652 void stopStreamSound();
654 /// Return value of the 'enabled' property cast to a boolean value.
656 /// This is true if not found (undefined to bool evaluates to false).
658 /// When a MovieClip is "disabled", its handlers of button-like events
659 /// are disabled, and automatic tab ordering won't include it.
660 bool isEnabled() const;
662 /// Check whether a point hits our drawable shape.
664 /// This is possible because the drawable does not have its own
665 /// transform, so we can use our own. The points are expressed in
666 /// world space.
667 bool hitTestDrawable(boost::int32_t x, boost::int32_t y) const;
669 /// Advance to a previous frame.
671 /// This function will basically restore the DisplayList as it supposedly
672 /// was *before* executing tags in target frame and then execute target
673 /// frame tags (both DLIST and ACTION ones).
675 /// In practice, it will:
677 /// - Remove from current DisplayList:
678 /// - Timeline instances constructed after target frame
679 /// - Timeline instances constructed before or at the target frame but no
680 /// more at the original depth
681 /// - Dynamic instances found in the static depth zone
682 /// - Execute all displaylist tags from first to one-before target frame,
683 /// appropriately setting _currentFrame as it goes, finally execute
684 /// both displaylist and action
685 /// tags for target frame.
687 /// Callers of this methods are:
688 /// - goto_frame (for jump-backs)
689 /// - advance_sprite (for loop-back)
691 /// See:
692 // http://www.gnashdev.org/wiki/index.php/TimelineControl
693 /// #Timeline_instances
695 /// @param targetFrame
696 /// The target frame for which we're willing to restore the static
697 /// DisplayList.
698 /// 0-based.
700 /// POSTCONDITIONS:
702 /// - _currentFrame == targetFrame
704 /// TODO: consider using this same function for jump-forward too,
705 /// with some modifications...
707 void restoreDisplayList(size_t targetFrame);
709 /// Execute the actions in the action list
711 /// The list of action will be consumed starting from the first
712 /// element. When the function returns the list should be empty.
714 void execute_actions(ActionList& action_list);
716 /// Increment _currentFrame, and take care of looping.
717 void increment_frame_and_check_for_loop();
719 /// Unregister textfield variables bound to unloaded TextFields
720 void cleanup_textfield_variables();
722 /// This is either sprite_definition (for sprites defined by
723 /// DefineSprite tag) or movie_def_impl (for the top-level movie).
724 const boost::intrusive_ptr<const movie_definition> _def;
726 /// List of loadVariables requests
727 typedef boost::ptr_list<LoadVariablesThread> LoadVariablesThreads;
729 /// List of active loadVariable requests
731 /// At ::advance_sprite time, all completed requests will
732 /// be processed (variables imported in this timeline scope)
733 /// and removed from the list.
734 LoadVariablesThreads _loadVariableRequests;
736 /// The SWF that this MovieClip belongs to.
737 Movie* _swf;
739 /// The canvas for dynamic drawing
740 DynamicShape _drawable;
742 PlayState _playState;
744 /// This timeline's variable scope
745 as_environment _environment;
747 /// We'll only allocate Textfield variables map if
748 /// we need them (ie: anyone calls set_textfield_variable)
750 std::auto_ptr<TextFieldIndex> _text_variables;
752 std::string _droptarget;
754 // 0-based index to current frame
755 size_t _currentFrame;
757 /// soundid for current playing stream. If no stream set to -1
758 int m_sound_stream_id;
760 // true if this sprite reached the last frame and restarted
761 bool _hasLooped;
763 // true is we're calling frame actions
764 bool _callingFrameActions;
766 bool _lockroot;
769 } // end of namespace gnash
771 #endif // GNASH_SPRITE_INSTANCE_H