forked from ruffle-rs/ruffle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.rs
More file actions
2764 lines (2421 loc) · 104 KB
/
loader.rs
File metadata and controls
2764 lines (2421 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Management of async loaders
use crate::avm1::{Activation, ActivationIdentifier};
use crate::avm1::{Attribute, Avm1};
use crate::avm1::{ExecutionReason, NativeObject};
use crate::avm1::{Object, ObjectHandle, Value};
use crate::avm2::bytearray::ByteArrayStorage;
use crate::avm2::globals::flash::utils::byte_array::strip_bom;
use crate::avm2::object::{
ByteArrayObject, EventObject as Avm2EventObject, FileReferenceObject,
FileReferenceObjectHandle, LoaderInfoObject, LoaderStream, ScriptObject as Avm2ScriptObject,
ScriptObjectHandle as Avm2ScriptObjectHandle, SoundLoadingState, SoundObject,
SoundObjectHandle, TObject as _,
};
use crate::avm2::{
Activation as Avm2Activation, Avm2, BitmapDataObject, Domain as Avm2Domain,
Object as Avm2Object,
};
use crate::avm2_stub_method_context;
use crate::backend::navigator::{
ErrorResponse, FetchReason, OwnedFuture, Request, SuccessResponse,
};
use crate::backend::ui::DialogResultFuture;
use crate::bitmap::bitmap_data::BitmapData;
use crate::bitmap::bitmap_data::Color;
use crate::context::{ActionQueue, ActionType, UpdateContext};
use crate::display_object::{
DisplayObject, MovieClip, MovieClipHandle, TDisplayObject, TDisplayObjectContainer,
TInteractiveObject,
};
use crate::events::ClipEvent;
use crate::frame_lifecycle::catchup_display_object_to_frame;
use crate::limits::ExecutionLimit;
use crate::player::{Player, PostFrameCallback};
use crate::streams::{NetStream, NetStreamHandle};
use crate::string::{AvmString, StringContext};
use crate::tag_utils::SwfMovie;
use crate::vminterface::Instantiator;
use chardetng::EncodingDetector;
use encoding_rs::{UTF_8, WINDOWS_1252};
use gc_arena::Collect;
use indexmap::IndexMap;
use ruffle_macros::istr;
use ruffle_render::utils::{JpegTagFormat, determine_jpeg_tag_format};
use slotmap::{SlotMap, new_key_type};
use std::borrow::Borrow;
use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use swf::read::{extract_swz, read_compression_type};
use thiserror::Error;
use url::{ParseError, Url, form_urlencoded};
new_key_type! {
pub struct LoaderHandle;
}
/// The depth of AVM1 movies that AVM2 loads.
const LOADER_INSERTED_AVM1_DEPTH: i32 = -0xF000;
/// How Ruffle should load movies.
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LoadBehavior {
/// Allow movies to execute before they have finished loading.
///
/// Frames/bytes loaded values will tick up normally and progress events
/// will be fired at regular intervals. Movie preload animations will play
/// normally.
Streaming,
/// Delay execution of loaded movies until they have finished loading.
///
/// Movies will see themselves load immediately. Preload animations will be
/// skipped. This may break movies that depend on loading during execution.
Delayed,
/// Block Ruffle until movies have finished loading.
///
/// This has the same implications as `Delay`, but tag processing will be
/// done synchronously. Complex movies will visibly block the player from
/// accepting user input and the application will appear to freeze.
Blocking,
}
impl fmt::Display for LoadBehavior {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
LoadBehavior::Streaming => "streaming",
LoadBehavior::Delayed => "delayed",
LoadBehavior::Blocking => "blocking",
})
}
}
pub struct ParseEnumError;
impl FromStr for LoadBehavior {
type Err = ParseEnumError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let behavior = match s {
"streaming" => LoadBehavior::Streaming,
"delayed" => LoadBehavior::Delayed,
"blocking" => LoadBehavior::Blocking,
_ => return Err(ParseEnumError),
};
Ok(behavior)
}
}
/// Enumeration of all content types that `Loader` can handle.
///
/// This is a superset of `JpegTagFormat`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContentType {
Swf,
Jpeg,
Png,
Gif,
Unknown,
}
impl From<JpegTagFormat> for ContentType {
fn from(jtf: JpegTagFormat) -> Self {
match jtf {
JpegTagFormat::Jpeg => Self::Jpeg,
JpegTagFormat::Png => Self::Png,
JpegTagFormat::Gif => Self::Gif,
JpegTagFormat::Unknown => Self::Unknown,
}
}
}
impl fmt::Display for ContentType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Swf => write!(f, "SWF"),
Self::Jpeg => write!(f, "JPEG"),
Self::Png => write!(f, "PNG"),
Self::Gif => write!(f, "GIF"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
impl ContentType {
fn sniff(data: &[u8]) -> ContentType {
if read_compression_type(data).is_ok() {
ContentType::Swf
} else {
determine_jpeg_tag_format(data).into()
}
}
/// Assert that content is of a given type, and error otherwise.
fn expect(self, expected: Self) -> Result<Self, Error> {
if self == expected {
Ok(self)
} else {
Err(Error::UnexpectedData(expected, self))
}
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("Load cancelled")]
Cancelled,
#[error("HTTP Status is not OK: {0} status: {1} redirected: {2} length: {3}")]
HttpNotOk(String, u16, bool, u64),
/// The domain could not be resolved, either because it is invalid or a DNS error occurred
#[error("Domain resolution failure: {0}")]
InvalidDomain(String),
#[error("Blocked host: {0}")]
BlockedHost(String),
#[error("Invalid SWF: {0}")]
InvalidSwf(#[from] swf::error::Error),
#[error("Invalid bitmap")]
InvalidBitmap(#[from] ruffle_render::error::Error),
#[error("Invalid sound: {0}")]
InvalidSound(#[from] crate::backend::audio::DecodeError),
#[error("Unexpected content of type {1}, expected {0}")]
UnexpectedData(ContentType, ContentType),
#[error("Could not fetch: {0:?}")]
FetchError(String),
// TODO: We can't support lifetimes on this error object yet (or we'll need some backends inside
// the GC arena). We're losing info here. How do we fix that?
#[error("Error running avm1 script: {0}")]
Avm1Error(String),
#[error("System I/O error: {0}")]
IoError(#[from] std::io::Error),
#[error("Cannot parse integer value: {0}")]
ParseIntError(#[from] std::num::ParseIntError),
}
impl From<crate::avm1::Error<'_>> for Error {
fn from(error: crate::avm1::Error<'_>) -> Self {
Error::Avm1Error(error.to_string())
}
}
/// Holds all in-progress loads for the player.
#[derive(Collect)]
#[collect(no_drop)]
pub struct LoadManager<'gc>(SlotMap<LoaderHandle, MovieLoader<'gc>>);
impl<'gc> LoadManager<'gc> {
/// Construct a new `LoadManager`.
pub fn new() -> Self {
Self(SlotMap::with_key())
}
/// Add a new loader to the `LoadManager`.
///
/// Returns the loader handle for later inspection. A loader handle is
/// valid for as long as the load operation.
///
/// After the load finishes, the loader should be removed (and the handle
/// invalidated). This can be done with remove_loader.
/// Movie loaders are removed automatically after the loader status is set
/// accordingly.
pub fn add_loader(&mut self, loader: MovieLoader<'gc>) -> LoaderHandle {
let handle = self.0.insert(loader);
let loader = self.get_loader_mut(handle).unwrap();
loader.self_handle = Some(handle);
handle
}
/// Remove a completed loader.
/// This is used to remove a loader after the loading or unloading process has completed.
pub fn remove_loader(&mut self, handle: LoaderHandle) {
self.0.remove(handle);
}
/// Retrieve a loader by handle.
pub fn get_loader(&self, handle: LoaderHandle) -> Option<&MovieLoader<'gc>> {
self.0.get(handle)
}
/// Retrieve a loader by handle for mutation.
pub fn get_loader_mut(&mut self, handle: LoaderHandle) -> Option<&mut MovieLoader<'gc>> {
self.0.get_mut(handle)
}
/// Kick off a movie clip load.
///
/// Returns the loader's async process, which you will need to spawn.
pub fn load_movie_into_clip(
&mut self,
player: Arc<Mutex<Player>>,
target_clip: DisplayObject<'gc>,
request: Request,
loader_url: Option<String>,
vm_data: MovieLoaderVMData<'gc>,
) -> OwnedFuture<(), Error> {
// When an AVM2 movie loads an AVM1 movie, that AVM1 movie cannot load
// another movie over itself, as in loadMovie(..., _root). Attempts to
// do so will be silently ignored.
//
// However, if the AVM1 movie uses MovieClipLoader.loadClip to load into
// its _root, FP32 will segfault. We don't reproduce that behavior.
if matches!(vm_data, MovieLoaderVMData::Avm1 { .. }) {
// This check works because the only time AVM1 can access an MC with
// `loader_info` set is when that MC is the root MC of an AVM1 movie
// that was loaded by AVM2
if target_clip
.as_movie_clip()
.and_then(|mc| mc.loader_info())
.is_some()
{
// Return a future that does nothing
return Box::pin(async move { Ok(()) });
}
}
let loader = MovieLoader {
self_handle: None,
target_clip,
vm_data,
loader_status: LoaderStatus::Pending,
from_bytes: false,
movie: None,
};
let handle = self.add_loader(loader);
let loader = self.get_loader_mut(handle).unwrap();
loader.movie_loader(player, request, loader_url)
}
pub fn load_asset_movie(
uc: &UpdateContext<'gc>,
request: Request,
importer_movie: MovieClip<'gc>,
) -> OwnedFuture<(), Error> {
let player = uc.player_handle();
let importer_movie = MovieClipHandle::stash(uc, importer_movie);
Box::pin(async move {
let fetch = player.lock().unwrap().fetch(request, FetchReason::LoadSwf);
match wait_for_full_response(fetch).await {
Ok((body, url, _status, _redirected)) => {
let content_type = ContentType::sniff(&body);
tracing::info!("Loading imported movie: {:?}", url);
match content_type {
ContentType::Swf => {
let movie = SwfMovie::from_data(&body, url.clone(), Some(url.clone()))
.expect("Could not load movie");
let movie = Arc::new(movie);
player.lock().unwrap().mutate_with_update_context(|uc| {
let importer_movie = importer_movie.fetch(uc);
let clip = MovieClip::new_import_assets(uc, movie, importer_movie);
clip.set_cur_preload_frame(0);
let mut execution_limit = ExecutionLimit::none();
tracing::debug!("Preloading swf to run exports {:?}", url);
// Create library for exports before preloading
uc.library.library_for_movie_mut(clip.movie());
let res = clip.preload(uc, &mut execution_limit);
tracing::debug!(
"Preloaded swf to run exports result {:?} {}",
url,
res
);
importer_movie.finish_importing();
});
Ok(())
}
_ => {
tracing::warn!(
"Unsupported content type for ImportAssets: {:?}",
content_type
);
Ok(())
}
}
}
Err(e) => Err(Error::FetchError(format!(
"Could not fetch: {:?} because {:?}",
e.url, e.error
))),
}
})
}
/// Kick off a movie clip load.
///
/// Returns the loader's async process, which you will need to spawn.
pub fn load_movie_into_clip_bytes(
context: &mut UpdateContext<'gc>,
target_clip: DisplayObject<'gc>,
bytes: Vec<u8>,
vm_data: MovieLoaderVMData<'gc>,
) -> Result<(), Error> {
let loader = MovieLoader {
self_handle: None,
target_clip,
vm_data,
loader_status: LoaderStatus::Pending,
movie: None,
from_bytes: true,
};
let handle = context.load_manager.add_loader(loader);
MovieLoader::movie_loader_bytes(handle, context, bytes)
}
/// Fires the `onLoad` listener event for every MovieClip that has been
/// initialized (ran its first frame).
///
/// This also removes all movie loaders that have completed.
pub fn movie_clip_on_load(
&mut self,
queue: &mut ActionQueue<'gc>,
strings: &StringContext<'gc>,
) {
// FIXME: This relies on the iteration order of the slotmap, which
// is not defined. The container should be replaced with something
// that preserves insertion order, such as `LinkedHashMap` -
// unfortunately that doesn't provide automatic key generation.
let mut loaders: Vec<_> = self.0.keys().collect();
// `SlotMap` doesn't provide reverse iteration, so reversing afterwards.
loaders.reverse();
// Removing the keys from `loaders` whose movie hasn't loaded yet.
loaders.retain(|handle| {
self.0
.get_mut(*handle)
.expect("valid key")
.movie_clip_loaded(queue, strings)
});
// Cleaning up the loaders that are done.
for index in loaders {
self.0.remove(index);
}
}
/// Process tags on all loaders in the Parsing phase.
///
/// Returns true if *all* loaders finished preloading.
pub fn preload_tick(context: &mut UpdateContext<'gc>, limit: &mut ExecutionLimit) -> bool {
let mut did_finish = true;
let handles: Vec<_> = context.load_manager.0.iter().map(|(h, _)| h).collect();
for handle in handles {
let status = match context.load_manager.get_loader(handle) {
Some(MovieLoader { loader_status, .. }) => Some(loader_status),
_ => None,
};
if matches!(status, Some(LoaderStatus::Parsing)) {
match MovieLoader::preload_tick(handle, context, limit, 0, false) {
Ok(f) => did_finish = did_finish && f,
Err(e) => tracing::error!("Error encountered while preloading movie: {}", e),
}
}
}
did_finish
}
pub fn run_exit_frame(context: &mut UpdateContext<'gc>) {
// The root movie might not have come from a loader, so check it separately.
// `fire_init_and_complete_events` is idempotent, so we unconditionally call it here
if let Some(movie) = context
.stage
.child_by_index(0)
.and_then(|o| o.as_movie_clip())
{
movie.try_fire_loaderinfo_events(context);
}
let handles: Vec<_> = context.load_manager.0.iter().map(|(h, _)| h).collect();
for handle in handles {
if let Some(MovieLoader { target_clip, .. }) = context.load_manager.get_loader(handle)
&& let Some(movie) = target_clip.as_movie_clip()
&& movie.try_fire_loaderinfo_events(context)
{
context.load_manager.remove_loader(handle)
}
}
}
}
impl Default for LoadManager<'_> {
fn default() -> Self {
Self::new()
}
}
async fn wait_for_full_response(
response: OwnedFuture<Box<dyn SuccessResponse>, ErrorResponse>,
) -> Result<(Vec<u8>, String, u16, bool), ErrorResponse> {
let response = response.await?;
let url = response.url().to_string();
let status = response.status();
let redirected = response.redirected();
let body = response.body().await;
match body {
Ok(body) => Ok((body, url, status, redirected)),
Err(error) => Err(ErrorResponse { url, error }),
}
}
/// The completion status of a `Loader` loading a movie.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LoaderStatus {
/// The movie hasn't been loaded yet.
Pending,
/// The movie is currently being parsed (e.g. mc.preload)
Parsing,
/// The movie loaded successfully.
Succeeded,
/// An error occurred while loading the movie.
Failed,
}
#[derive(Collect, Clone, Copy)]
#[collect(no_drop)]
pub enum MovieLoaderVMData<'gc> {
Avm1 {
broadcaster: Option<Object<'gc>>,
/// The clip that loads the movie.
///
/// Used as base clip for invoking loader events.
base_clip: DisplayObject<'gc>,
},
Avm2 {
loader_info: LoaderInfoObject<'gc>,
/// The context of the SWF being loaded.
context: Option<Avm2Object<'gc>>,
/// The default domain this SWF will use.
default_domain: Avm2Domain<'gc>,
},
}
/// A struct that holds the state for asynchronous movie loads.
#[derive(Collect)]
#[collect(no_drop)]
pub struct MovieLoader<'gc> {
/// The handle to refer to this loader instance.
#[collect(require_static)]
self_handle: Option<LoaderHandle>,
/// The target movie clip to load the movie into.
target_clip: DisplayObject<'gc>,
// Virtual-machine specific data (AVM1 or AVM2)
vm_data: MovieLoaderVMData<'gc>,
/// Indicates the completion status of this loader.
///
/// This flag exists to prevent a situation in which loading a movie
/// into a clip that has not yet fired its Load event causes the
/// loader to be prematurely removed. This flag is only set when either
/// the movie has been replaced (and thus Load events can be trusted)
/// or an error has occurred (in which case we don't care about the
/// loader anymore).
#[collect(require_static)]
loader_status: LoaderStatus,
/// The SWF being loaded.
///
/// This is only available if the asynchronous loader path has
/// completed and we expect the Player to periodically tick preload
/// until loading completes.
movie: Option<Arc<SwfMovie>>,
/// Whether or not this was loaded as a result of a `Loader.loadBytes` call
from_bytes: bool,
}
impl<'gc> MovieLoader<'gc> {
fn replace_root_movie(&mut self, new_root: DisplayObject<'gc>) {
self.target_clip = new_root;
if let MovieLoaderVMData::Avm1 { base_clip, .. } = &mut self.vm_data {
*base_clip = new_root;
}
}
/// Process tags on a loaded movie.
///
/// Is only callable on Movie loaders, panics otherwise. Will
/// do nothing unless the movie is ready to be preloaded. Movies which
/// complete their preload will fire all events and be removed from the
/// load manager queue.
///
/// Returns true if the movie finished preloading.
///
/// Returns any AVM errors encountered while sending events to user code.
fn preload_tick(
handle: LoaderHandle,
context: &mut UpdateContext<'gc>,
limit: &mut ExecutionLimit,
status: u16,
redirected: bool,
) -> Result<bool, Error> {
let mc = match context.load_manager.get_loader(handle) {
Some(Self {
target_clip,
movie,
from_bytes,
..
}) => {
if movie.is_none() {
//Non-SWF load or file not loaded yet
return Ok(false);
}
// Loader.loadBytes movies never participate in preloading
if *from_bytes {
return Ok(true);
}
if target_clip.as_movie_clip().is_none() {
// Non-movie-clip loads should not be handled in preload_tick
tracing::error!("Cannot preload non-movie-clip loader");
return Ok(false);
}
*target_clip
}
None => return Err(Error::Cancelled),
};
let mc = mc.as_movie_clip().unwrap();
let did_finish = mc.preload(context, limit);
MovieLoader::movie_loader_progress(
handle,
context,
mc.compressed_loaded_bytes() as usize,
mc.compressed_total_bytes() as usize,
)?;
if did_finish {
MovieLoader::movie_loader_complete(
handle,
context,
Some(mc.into()),
status,
redirected,
)?;
}
Ok(did_finish)
}
/// Construct a future for the given movie loader.
///
/// The given future should be passed immediately to an executor; it will
/// take responsibility for running the loader to completion.
///
/// If the loader is not a movie then the returned future will yield an
/// error immediately once spawned.
fn movie_loader(
&mut self,
player: Arc<Mutex<Player>>,
request: Request,
loader_url: Option<String>,
) -> OwnedFuture<(), Error> {
let handle = self.self_handle.expect("Loader not self-introduced");
Box::pin(async move {
let request_url = request.url().to_string();
let resolved_url = player.lock().unwrap().navigator().resolve_url(&request_url);
let fetch = player.lock().unwrap().fetch(request, FetchReason::LoadSwf);
let mut replacing_root_movie = false;
player.lock().unwrap().update(|uc| -> Result<(), Error> {
let clip = match uc.load_manager.get_loader(handle) {
Some(MovieLoader { target_clip, .. }) => *target_clip,
None => return Err(Error::Cancelled),
};
replacing_root_movie = uc
.stage
.root_clip()
.map(|root| DisplayObject::ptr_eq(clip, root))
.unwrap_or(false);
if let Some(mc) = clip.as_movie_clip() {
if !mc.movie().is_action_script_3() {
mc.avm1_unload(uc);
// Clear deletable properties on the target before loading
// Properties written during the subsequent onLoad events will persist
if let Some(clip_object) = mc.object1() {
let mut activation = Activation::from_nothing(
uc,
ActivationIdentifier::root("unknown"),
clip,
);
for key in clip_object.get_keys(&mut activation, true) {
clip_object.delete(&mut activation, key);
}
}
}
// Before the actual SWF is loaded, an initial loading state is entered.
MovieLoader::load_initial_loading_swf(mc, uc, &request_url, resolved_url);
}
MovieLoader::movie_loader_start(handle, uc)
})?;
let response = wait_for_full_response(fetch).await;
let player = player.lock().unwrap();
match response {
Ok((body, url, status, redirected)) if replacing_root_movie => {
Self::on_success_root_movie(
player, handle, loader_url, body, url, status, redirected,
)?;
}
Ok((body, url, status, redirected)) => {
Self::on_success(player, handle, loader_url, body, url, status, redirected)?;
}
Err(response) => {
Self::on_error(player, handle, response)?;
}
}
Ok(())
})
}
fn on_success_root_movie(
mut player: MutexGuard<'_, Player>,
handle: LoaderHandle,
loader_url: Option<String>,
body: Vec<u8>,
url: String,
status: u16,
redirected: bool,
) -> Result<(), Error> {
ContentType::sniff(&body).expect(ContentType::Swf)?;
let movie = SwfMovie::from_data(&body, url, loader_url)?;
player.mutate_with_update_context(|uc| {
// Make a copy of the properties on the root, so we can put them back after replacing it
let mut root_properties: IndexMap<AvmString, Value> = IndexMap::new();
if let Some(root) = uc.stage.root_clip()
&& let Some(root_object) = root.object1()
{
let mut activation =
Activation::from_nothing(uc, ActivationIdentifier::root("unknown"), root);
for key in root_object.get_keys(&mut activation, true) {
let val = root_object
.get_stored(key, &mut activation)
.unwrap_or(Value::Undefined);
root_properties.insert(key, val);
}
}
uc.replace_root_movie(movie);
if let Some(root_clip) = uc.stage.root_clip()
&& let Some(ml) = uc.load_manager.get_loader_mut(handle)
{
// Further AVM1 events are dispatched in relation to the new root.
// TODO Maybe we could use a MCR here?
ml.replace_root_movie(root_clip);
}
// Add the copied properties back onto the new root
if !root_properties.is_empty()
&& let Some(root) = uc.stage.root_clip()
&& let Some(clip_object) = root.object1()
{
let mut activation =
Activation::from_nothing(uc, ActivationIdentifier::root("unknown"), root);
for (key, val) in root_properties {
let _ = clip_object.set(key, val, &mut activation);
}
}
// For some reason, progress event is dispatched twice here.
MovieLoader::movie_loader_progress(handle, uc, body.len(), body.len())?;
MovieLoader::movie_loader_progress(handle, uc, body.len(), body.len())?;
MovieLoader::movie_loader_complete(handle, uc, None, status, redirected)
})?;
Ok(())
}
fn on_success(
mut player: MutexGuard<'_, Player>,
handle: LoaderHandle,
loader_url: Option<String>,
body: Vec<u8>,
url: String,
status: u16,
redirected: bool,
) -> Result<(), Error> {
player.mutate_with_update_context(|uc| {
MovieLoader::movie_loader_data(
handle,
uc,
&body,
url.to_string(),
status,
redirected,
loader_url,
)
})?;
Ok(())
}
fn on_error(
mut player: MutexGuard<'_, Player>,
handle: LoaderHandle,
response: ErrorResponse,
) -> Result<(), Error> {
tracing::error!(
"Error during movie loading of {:?}: {:?}",
response.url,
response.error
);
player.update(|uc| -> Result<(), Error> {
// FIXME - match Flash's error message
let (status_code, redirected) =
if let Error::HttpNotOk(_, status_code, redirected, _) = response.error {
(status_code, redirected)
} else {
(0, false)
};
MovieLoader::movie_loader_error(
handle,
uc,
"Movie loader error",
status_code,
redirected,
response.url,
)
})?;
Ok(())
}
pub fn movie_loader_bytes(
handle: LoaderHandle,
uc: &mut UpdateContext<'gc>,
bytes: Vec<u8>,
) -> Result<(), Error> {
let clip = match uc.load_manager.get_loader(handle) {
Some(Self { target_clip, .. }) => *target_clip,
None => return Err(Error::Cancelled),
};
let replacing_root_movie = uc
.stage
.root_clip()
.map(|root| DisplayObject::ptr_eq(clip, root))
.unwrap_or(false);
if let Some(mc) = clip.as_movie_clip() {
if !mc.movie().is_action_script_3() {
mc.avm1_unload(uc);
}
mc.replace_with_movie(uc, None, false, None);
}
let loader_url = Some(uc.root_swf.url().to_string());
if replacing_root_movie {
ContentType::sniff(&bytes).expect(ContentType::Swf)?;
let movie = SwfMovie::from_data(&bytes, "file:///".into(), loader_url)?;
avm2_stub_method_context!(
uc,
"flash.display.Loader",
"loadBytes",
"replacing root movie"
);
uc.replace_root_movie(movie);
return Ok(());
}
MovieLoader::movie_loader_data(handle, uc, &bytes, "file:///".into(), 0, false, loader_url)
}
}
/// Kick off the root movie load.
///
/// The root movie is special because it determines a few bits of player
/// state, such as the size of the stage and the current frame rate. Ergo,
/// this method should only be called once, by the player that is trying to
/// kick off its root movie load.
#[must_use]
pub fn load_root_movie<'gc>(
uc: &UpdateContext<'gc>,
request: Request,
parameters: Vec<(String, String)>,
on_metadata: Box<dyn FnOnce(&swf::HeaderExt)>,
) -> OwnedFuture<(), Error> {
let player = uc.player_handle();
Box::pin(async move {
let fetch = player.lock().unwrap().fetch(request, FetchReason::LoadSwf);
let response = fetch.await.map_err(|error| {
player
.lock()
.unwrap()
.ui()
.display_root_movie_download_failed_message(false, error.error.to_string());
error.error
})?;
let swf_url = response.url().into_owned();
let body = response.body().await.inspect_err(|error| {
player
.lock()
.unwrap()
.ui()
.display_root_movie_download_failed_message(true, error.to_string());
})?;
// The spoofed root movie URL takes precedence over the actual URL.
let spoofed_or_swf_url = player
.lock()
.unwrap()
.spoofed_url()
.map(|u| u.to_string())
.unwrap_or(swf_url);
let mut movie =
SwfMovie::from_data(&body, spoofed_or_swf_url, None).inspect_err(|error| {
player
.lock()
.unwrap()
.ui()
.display_root_movie_download_failed_message(true, error.to_string());
})?;
on_metadata(movie.header());
movie.append_parameters(parameters);
player.lock().unwrap().mutate_with_update_context(|uc| {
uc.set_root_movie(movie);
});
Ok(())
})
}
/// Kick off a form data load into an AVM1 object.
///
/// Returns the loader's async process, which you will need to spawn.
#[must_use]
pub fn load_form_into_object<'gc>(
uc: &UpdateContext<'gc>,
target_object: Object<'gc>,
request: Request,
) -> OwnedFuture<(), Error> {
let player = uc.player_handle();
let target_object = ObjectHandle::stash(uc, target_object);
Box::pin(async move {
let fetch = player.lock().unwrap().fetch(request, FetchReason::Other);
let response = fetch.await.map_err(|e| e.error)?;
let response_encoding = response.text_encoding();
let body = response.body().await?;
// Fire the load handler.
player.lock().unwrap().update(|uc| {
let that = target_object.fetch(uc);
let mut activation =
Activation::from_stub(uc, ActivationIdentifier::root("[Form Loader]"));
let utf8_string;
let utf8_body = if activation.context.system.use_codepage {
// Determine the encoding
let encoding = if let Some(encoding) = response_encoding {
encoding
} else {
let mut encoding_detector = EncodingDetector::new();
encoding_detector.feed(&body, true);
encoding_detector.guess(None, true)
};
// Convert the text into UTF-8
utf8_string = encoding.decode(&body).0;
utf8_string.as_bytes()
} else if activation.context.root_swf.version() <= 5 {
utf8_string = WINDOWS_1252.decode(&body).0;
utf8_string.as_bytes()
} else {
&body
};
for (k, v) in form_urlencoded::parse(utf8_body) {
let k = AvmString::new_utf8(activation.gc(), k);
let v = AvmString::new_utf8(activation.gc(), v);
that.set(k, v.into(), &mut activation)?;
}
// Fire the onData method and event.
if let Some(display_object) = that.as_display_object()
&& let Some(movie_clip) = display_object.as_movie_clip()
{
activation.context.action_queue.queue_action(
movie_clip.into(),
ActionType::Method {
object: that,
name: istr!("onData"),
args: vec![],
},
false,
);
movie_clip.event_dispatch(activation.context, ClipEvent::Data);
}
Ok(())
})
})
}
/// Kick off a form data load into an `LoadVars` AVM1 object.
///
/// Returns the loader's async process, which you will need to spawn.