-
-
Notifications
You must be signed in to change notification settings - Fork 864
/
Copy pathplayer.rs
3066 lines (2715 loc) · 113 KB
/
player.rs
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
use crate::avm1::Attribute;
use crate::avm1::Avm1;
use crate::avm1::Object;
use crate::avm1::SystemProperties;
use crate::avm1::VariableDumper;
use crate::avm1::{Activation, ActivationIdentifier};
use crate::avm1::{TObject, Value};
use crate::avm2::object::{EventObject as Avm2EventObject, Object as Avm2Object};
use crate::avm2::{Activation as Avm2Activation, Avm2, CallStack};
use crate::backend::ui::FontDefinition;
use crate::backend::{
audio::{AudioBackend, AudioManager},
log::LogBackend,
navigator::{NavigatorBackend, Request},
storage::StorageBackend,
ui::{MouseCursor, UiBackend},
};
use crate::compatibility_rules::CompatibilityRules;
use crate::config::Letterbox;
use crate::context::{ActionQueue, ActionType, RenderContext, UpdateContext};
use crate::context_menu::{
BuiltInItemFlags, ContextMenuCallback, ContextMenuItem, ContextMenuState,
};
use crate::display_object::Avm2MousePick;
use crate::display_object::{
EditText, InteractiveObject, Stage, StageAlign, StageDisplayState, StageScaleMode,
TInteractiveObject, WindowMode,
};
use crate::events::GamepadButton;
use crate::events::{ButtonKeyCode, ClipEvent, ClipEventResult, KeyCode, MouseButton, PlayerEvent};
use crate::external::{ExternalInterface, ExternalInterfaceProvider, NullFsCommandProvider};
use crate::external::{FsCommandProvider, Value as ExternalValue};
use crate::focus_tracker::NavigationDirection;
use crate::frame_lifecycle::{run_all_phases_avm2, FramePhase};
use crate::input::InputEvent;
use crate::input::InputManager;
use crate::library::Library;
use crate::limits::ExecutionLimit;
use crate::loader::{LoadBehavior, LoadManager};
use crate::local_connection::LocalConnections;
use crate::locale::get_current_date_time;
use crate::net_connection::NetConnections;
use crate::prelude::*;
use crate::socket::Sockets;
use crate::streams::StreamManager;
use crate::string::{AvmStringInterner, StringContext};
use crate::stub::StubCollection;
use crate::tag_utils::SwfMovie;
use crate::timer::Timers;
use crate::vminterface::Instantiator;
use crate::DefaultFont;
use gc_arena::lock::GcRefLock;
use gc_arena::{Collect, DynamicRootSet, Mutation, Rootable};
use rand::{rngs::SmallRng, SeedableRng};
use ruffle_macros::istr;
use ruffle_render::backend::{null::NullRenderer, RenderBackend, ViewportDimensions};
use ruffle_render::commands::CommandList;
use ruffle_render::quality::StageQuality;
use ruffle_render::transform::TransformStack;
use ruffle_video::backend::VideoBackend;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::ops::{Deref, DerefMut};
use std::rc::{Rc, Weak as RcWeak};
use std::str::FromStr;
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use tracing::instrument;
use web_time::Instant;
/// The newest known Flash Player version, serves as a default to
/// `player_version`.
pub const NEWEST_PLAYER_VERSION: u8 = 32;
#[cfg(feature = "default_font")]
pub const FALLBACK_DEVICE_FONT: &[u8] = include_bytes!("../assets/notosans-regular.subset.ttf.gz");
#[derive(Collect)]
#[collect(no_drop)]
struct GcRoot<'gc> {
avm2_callstack: GcRefLock<'gc, CallStack<'gc>>,
data: GcRefLock<'gc, GcRootData<'gc>>,
}
#[derive(Clone)]
pub struct StaticCallstack {
arena: RcWeak<RefCell<GcArena>>,
}
impl StaticCallstack {
pub fn avm2(&self, f: impl for<'gc> FnOnce(&CallStack<'gc>)) {
if let Some(arena) = self.arena.upgrade() {
if let Ok(arena) = arena.try_borrow() {
arena.mutate(|_, root| {
let callstack = root.avm2_callstack.borrow();
if !callstack.is_empty() {
f(&callstack);
}
})
}
}
}
}
#[derive(Collect)]
#[collect(no_drop)]
pub struct MouseData<'gc> {
/// The object that the mouse is currently hovering over.
pub hovered: Option<InteractiveObject<'gc>>,
/// If the mouse is down, the object that the mouse is currently pressing.
pub pressed: Option<InteractiveObject<'gc>>,
pub right_pressed: Option<InteractiveObject<'gc>>,
pub middle_pressed: Option<InteractiveObject<'gc>>,
}
impl<'gc> MouseData<'gc> {
pub fn pressed(&self, button: MouseButton) -> Option<InteractiveObject<'gc>> {
match button {
MouseButton::Unknown => None,
MouseButton::Left => self.pressed,
MouseButton::Right => self.right_pressed,
MouseButton::Middle => self.middle_pressed,
}
}
pub fn set_pressed(&mut self, button: MouseButton, value: Option<InteractiveObject<'gc>>) {
match button {
MouseButton::Unknown => {}
MouseButton::Left => self.pressed = value,
MouseButton::Right => self.right_pressed = value,
MouseButton::Middle => self.middle_pressed = value,
}
}
}
#[derive(Collect)]
#[collect(no_drop)]
struct GcRootData<'gc> {
library: Library<'gc>,
/// The root of the display object hierarchy.
///
/// It's children are the `level`s of AVM1, it may also be directly
/// accessed in AVM2.
stage: Stage<'gc>,
mouse_data: MouseData<'gc>,
/// The object being dragged via a `startDrag` action.
drag_object: Option<DragObject<'gc>>,
/// Interpreter state for AVM1 code.
avm1: Avm1<'gc>,
/// Interpreter state for AVM2 code.
avm2: Avm2<'gc>,
action_queue: ActionQueue<'gc>,
interner: AvmStringInterner<'gc>,
/// Object which manages asynchronous processes that need to interact with
/// data in the GC arena.
load_manager: LoadManager<'gc>,
avm1_shared_objects: HashMap<String, Object<'gc>>,
avm2_shared_objects: HashMap<String, Avm2Object<'gc>>,
/// Text fields with unbound variable bindings.
unbound_text_fields: Vec<EditText<'gc>>,
/// Timed callbacks created with `setInterval`/`setTimeout`.
timers: Timers<'gc>,
current_context_menu: Option<ContextMenuState<'gc>>,
/// External interface for (for example) JavaScript <-> ActionScript interaction
external_interface: ExternalInterface<'gc>,
/// Manager of active sound instances.
audio_manager: AudioManager<'gc>,
/// List of actively playing streams to decode.
stream_manager: StreamManager<'gc>,
sockets: Sockets<'gc>,
/// List of active NetConnection objects.
net_connections: NetConnections<'gc>,
local_connections: LocalConnections<'gc>,
/// Dynamic root for allowing handles to GC objects to exist outside of the GC.
dynamic_root: DynamicRootSet<'gc>,
post_frame_callbacks: Vec<PostFrameCallback<'gc>>,
}
#[derive(Collect)]
#[collect(no_drop)]
pub struct PostFrameCallback<'gc> {
#[collect(require_static)]
#[allow(clippy::type_complexity)]
pub callback: Box<dyn for<'b> FnOnce(&mut UpdateContext<'b>, DisplayObject<'b>) + 'static>,
pub data: DisplayObject<'gc>,
}
impl<'gc> GcRootData<'gc> {
/// Splits out parameters for creating an `UpdateContext`
/// (because we can borrow fields of `self` independently)
#[allow(clippy::type_complexity)]
fn update_context_params(
&mut self,
) -> (
Stage<'gc>,
&mut Library<'gc>,
&mut ActionQueue<'gc>,
&mut AvmStringInterner<'gc>,
&mut Avm1<'gc>,
&mut Avm2<'gc>,
&mut Option<DragObject<'gc>>,
&mut LoadManager<'gc>,
&mut HashMap<String, Object<'gc>>,
&mut HashMap<String, Avm2Object<'gc>>,
&mut Vec<EditText<'gc>>,
&mut Timers<'gc>,
&mut Option<ContextMenuState<'gc>>,
&mut ExternalInterface<'gc>,
&mut AudioManager<'gc>,
&mut StreamManager<'gc>,
&mut Sockets<'gc>,
&mut NetConnections<'gc>,
&mut LocalConnections<'gc>,
&mut Vec<PostFrameCallback<'gc>>,
&mut MouseData<'gc>,
DynamicRootSet<'gc>,
) {
(
self.stage,
&mut self.library,
&mut self.action_queue,
&mut self.interner,
&mut self.avm1,
&mut self.avm2,
&mut self.drag_object,
&mut self.load_manager,
&mut self.avm1_shared_objects,
&mut self.avm2_shared_objects,
&mut self.unbound_text_fields,
&mut self.timers,
&mut self.current_context_menu,
&mut self.external_interface,
&mut self.audio_manager,
&mut self.stream_manager,
&mut self.sockets,
&mut self.net_connections,
&mut self.local_connections,
&mut self.post_frame_callbacks,
&mut self.mouse_data,
self.dynamic_root,
)
}
}
type GcArena = gc_arena::Arena<Rootable![GcRoot<'_>]>;
type Audio = Box<dyn AudioBackend>;
type Navigator = Box<dyn NavigatorBackend>;
type Renderer = Box<dyn RenderBackend>;
type Storage = Box<dyn StorageBackend>;
type Log = Box<dyn LogBackend>;
type Ui = Box<dyn UiBackend>;
type Video = Box<dyn VideoBackend>;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum RunState {
Playing,
Suspended,
Stepping,
}
pub struct Player {
/// The version of the player we're emulating.
///
/// This serves a few purposes, primarily for compatibility:
///
/// * ActionScript can query the player version, ostensibly for graceful
/// degradation on older platforms. Certain SWF files broke with the
/// release of Flash Player 10 because the version string contains two
/// digits. This allows the user to play those old files.
/// * Player-specific behavior that was not properly versioned in Flash
/// Player can be enabled by setting a particular player version.
player_version: u8,
/// The runtime we're emulating (Flash Player or Adobe AIR).
/// In Adobe AIR mode, additional classes are available
#[allow(unused)]
player_runtime: PlayerRuntime,
/// Whether we're emulating the release or the debug build.
player_mode: PlayerMode,
swf: Arc<SwfMovie>,
run_state: RunState,
needs_render: bool,
renderer: Renderer,
audio: Audio,
navigator: Navigator,
storage: Storage,
log: Log,
ui: Ui,
video: Video,
transform_stack: TransformStack,
rng: SmallRng,
gc_arena: Rc<RefCell<GcArena>>,
frame_rate: f64,
forced_frame_rate: bool,
actions_since_timeout_check: u16,
frame_phase: FramePhase,
stub_tracker: StubCollection,
/// A time budget for executing frames.
/// Gained by passage of time between host frames, spent by executing SWF frames.
/// This is how we support custom SWF framerates
/// and compensate for small lags by "catching up" (up to MAX_FRAMES_PER_TICK).
frame_accumulator: f64,
recent_run_frame_timings: VecDeque<f64>,
/// Faked time passage for fooling hand-written busy-loop FPS limiters.
time_offset: u32,
input: InputManager,
mouse_in_stage: bool,
mouse_position: Point<Twips>,
/// The current mouse cursor icon.
mouse_cursor: MouseCursor,
mouse_cursor_needs_check: bool,
system: SystemProperties,
page_url: Option<String>,
/// The current instance ID. Used to generate default `instanceN` names.
instance_counter: i32,
/// Time remaining until the next timer will fire.
time_til_next_timer: Option<f64>,
/// The instant at which the SWF was launched.
start_time: Instant,
/// The maximum amount of time that can be called before a `Error::ExecutionTimeout`
/// is raised. This defaults to 15 seconds but can be changed.
max_execution_duration: Duration,
/// Self-reference to ourselves.
///
/// This is a weak reference that is upgraded and handed out in various
/// contexts to other parts of the player. It can be used to ensure the
/// player lives across `await` calls in async code.
self_reference: Weak<Mutex<Self>>,
/// The current frame of the main timeline, if available.
/// The first frame is frame 1.
current_frame: Option<u16>,
/// How Ruffle should load movies.
load_behavior: LoadBehavior,
/// The root SWF URL provided to ActionScript. If None,
/// the actual loaded url will be used
spoofed_url: Option<String>,
/// Any compatibility rules to apply for this movie.
compatibility_rules: CompatibilityRules,
/// Debug UI windows
#[cfg(feature = "egui")]
debug_ui: Rc<RefCell<crate::debug_ui::DebugUi>>,
}
impl Player {
// This method will panic if called inside an `enter_arena_mut` call.
fn enter_arena<F, T>(&self, f: F) -> T
where
F: for<'gc> FnOnce(&'gc Mutation<'gc>, &'gc GcRootData<'gc>, &'gc Self) -> T,
{
let borrow = self.gc_arena.try_borrow().ok();
let result = borrow.and_then(|arena| {
arena.mutate(|mc, root| {
let root = root.data.try_borrow().ok()?;
// SAFETY: The 'gc lifetime is generative, and can be soundly conflated with
// the lifetime of shorter borrows, as `&'gc T`s aren't `Collect` and cannot
// outlive the closure.
Some(unsafe {
let root = &*(root.deref() as *const _);
let this = &*(self as *const _);
f(mc, root, this)
})
})
});
result.expect("arena already mutably borrowed")
}
// This method will panic if called inside another `enter_arena_mut` call.
fn enter_arena_mut<F, T>(&mut self, f: F) -> T
where
F: for<'gc> FnOnce(&'gc Mutation<'gc>, &'gc mut GcRootData<'gc>, &'gc mut Self) -> T,
{
// To allow passing a `&mut Self` to the user-provided function, we avoid borrowing directly from self.
let arena = Rc::clone(&self.gc_arena);
// Do not borrow the arena mutably, to keep it accessible while inside a panic handler.
let borrow = arena.try_borrow().ok();
let result = borrow.and_then(|arena| {
arena.mutate(|mc, root| {
let mut root = root.data.try_borrow_mut(mc).ok()?;
// SAFETY: The 'gc lifetime is generative, and can be soundly conflated with
// the lifetime of shorter borrows, as `&'gc T`s aren't `Collect` and cannot
// outlive the closure.
Some(unsafe {
let root = &mut *(root.deref_mut() as *mut _);
let this = &mut *(self as *mut _);
f(mc, root, this)
})
})
});
result.expect("arena already borrowed")
}
/// Fetch the root movie.
///
/// This should not be called if a root movie fetch has already been kicked
/// off.
///
/// `parameters` are *extra* parameters to set on the LoaderInfo -
/// parameters from `movie_url` query parameters will be automatically added.
pub fn fetch_root_movie(
&mut self,
movie_url: String,
parameters: Vec<(String, String)>,
on_metadata: Box<dyn FnOnce(&swf::HeaderExt)>,
) {
self.mutate_with_update_context(|context| {
let future = context.load_manager.load_root_movie(
context.player.clone(),
Request::get(movie_url),
parameters,
on_metadata,
);
context.navigator.spawn_future(future);
});
}
/// Get rough estimate of the max # of times we can update the frame.
///
/// In some cases, we might want to update several times in a row.
/// For example, if the game runs at 60FPS, but the host runs at 30FPS
/// Or if for some reason the we miss a couple of frames.
/// However, if the code is simply slow, this is the opposite of what we want;
/// If run_frame() consistently takes say 100ms, we don't want `tick` to try to "catch up",
/// as this will only make it worse.
///
/// This rough heuristic manages this job; for example if average run_frame()
/// takes more than 1/3 of frame_time, we shouldn't run it more than twice in a row.
/// This logic is far from perfect, as it doesn't take into account
/// that things like rendering also take time. But for now it's good enough.
fn max_frames_per_tick(&self) -> u32 {
const MAX_FRAMES_PER_TICK: u32 = 5;
if self.recent_run_frame_timings.is_empty() {
5
} else {
let frame_time = self.frame_time(1000.0);
let average_run_frame_time = self.recent_run_frame_timings.iter().sum::<f64>()
/ self.recent_run_frame_timings.len() as f64;
((frame_time / average_run_frame_time) as u32).clamp(1, MAX_FRAMES_PER_TICK)
}
}
fn add_frame_timing(&mut self, elapsed: f64) {
self.recent_run_frame_timings.push_back(elapsed);
if self.recent_run_frame_timings.len() >= 10 {
self.recent_run_frame_timings.pop_front();
}
}
fn frame_time(&self, time_unit: f64) -> f64 {
let frame_rate = self.frame_rate;
if frame_rate == 0.0 || frame_rate.is_nan() {
0.0
} else {
time_unit / frame_rate
}
}
pub fn tick(&mut self, dt: f64) {
if !self.is_playing() {
return;
}
self.frame_accumulator += dt;
let frame_time = self.frame_time(1000.0);
let max_frames_per_tick = self.max_frames_per_tick();
let mut frame = 0;
while frame < max_frames_per_tick && self.frame_accumulator >= frame_time {
let timer = Instant::now();
self.run_frame();
let elapsed = timer.elapsed().as_millis() as f64;
self.add_frame_timing(elapsed);
self.frame_accumulator -= frame_time;
frame += 1;
// The script probably tried implementing an FPS limiter with a busy loop.
// We fooled the busy loop by pretending that more time has passed that actually did.
// Then we need to actually pass this time, by decreasing frame_accumulator
// to delay the future frame.
if self.time_offset > 0 {
self.frame_accumulator -= self.time_offset as f64;
}
// If we are stepping a single frame, immediately suspend ourselves.
if self.run_state == RunState::Stepping {
self.set_run_state(RunState::Suspended);
break;
}
}
// Now that we're done running code,
// we can stop pretending that more time passed than actually did.
// Note: update_timers(dt) doesn't need to see this either.
// Timers will run at correct times and see correct time.
// Also note that in Flash, a blocking busy loop would delay setTimeout
// and cancel some setInterval callbacks, but here busy loops don't block
// so timer callbacks won't get cancelled/delayed.
self.time_offset = 0;
// Sanity: If we had too many frames to tick, just reset the accumulator
// to prevent running at turbo speed.
if self.frame_accumulator >= frame_time {
self.frame_accumulator = 0.0;
}
// Adjust playback speed for next frame to stay in sync with timeline audio tracks ("stream" sounds).
let cur_frame_offset = self.frame_accumulator;
self.frame_accumulator += self.mutate_with_update_context(|context| {
context
.audio_manager
.audio_skew_time(context.audio, cur_frame_offset)
* 1000.0
});
self.update_sockets();
self.update_net_connections();
self.update_timers(dt);
self.update(|context| {
StreamManager::tick(context, dt);
});
self.audio.tick();
}
pub fn time_til_next_timer(&self) -> Option<f64> {
self.time_til_next_timer
}
/// Returns the approximate duration of time until the next frame is due to run.
/// This is only an approximation to be used for sleep durations.
pub fn time_til_next_frame(&self) -> std::time::Duration {
let frame_time = self.frame_time(1000.0);
let mut dt = if self.frame_accumulator <= 0.0 {
frame_time
} else if self.frame_accumulator >= frame_time {
0.0
} else {
frame_time - self.frame_accumulator
};
if let Some(time_til_next_timer) = self.time_til_next_timer {
dt = dt.min(time_til_next_timer)
}
dt = dt.max(0.0);
std::time::Duration::from_micros(dt as u64 * 1000)
}
pub fn is_playing(&self) -> bool {
match self.run_state {
RunState::Playing | RunState::Stepping => true,
RunState::Suspended => false,
}
}
pub fn mouse_in_stage(&self) -> bool {
self.mouse_in_stage
}
pub fn set_mouse_in_stage(&mut self, is_in: bool) {
self.mouse_in_stage = is_in;
}
/// Returns the master volume of the player. 1.0 is 100% volume.
///
/// The volume is linear and not adapted for logarithmic hearing.
pub fn volume(&self) -> f32 {
self.audio.volume()
}
/// Sets the master volume of the player. 1.0 is 100% volume.
///
/// The volume should be linear and not adapted for logarithmic hearing.
pub fn set_volume(&mut self, volume: f32) {
self.audio.set_volume(volume)
}
pub fn prepare_context_menu(&mut self) -> Vec<ContextMenuItem> {
self.mutate_with_update_context(|context| {
if !context.stage.show_menu() {
return vec![];
}
let display_obj = Player::get_context_menu_display_object(context);
let menu = if let Some(Value::Object(obj)) = display_obj.map(|obj| obj.object()) {
let mut activation =
Activation::from_stub(context, ActivationIdentifier::root("[ContextMenu]"));
let menu_object = if let Ok(Value::Object(menu)) =
obj.get(istr!("menu"), &mut activation)
{
if let Ok(Value::Object(on_select)) =
menu.get(istr!("onSelect"), &mut activation)
{
Self::run_context_menu_custom_callback(menu, on_select, activation.context);
}
Some(menu)
} else {
None
};
crate::avm1::make_context_menu_state(menu_object, display_obj, &mut activation)
} else if let Some(Avm2Value::Object(hit_obj)) = display_obj.map(|obj| obj.object2()) {
let mut activation = Avm2Activation::from_nothing(context);
let menu_object = display_obj
.expect("Root is confirmed to exist here")
.as_interactive()
.map(|iobj| iobj.context_menu())
.and_then(|v| v.as_object());
if let Some(menu_object) = menu_object {
// TODO: contextMenuOwner and mouseTarget might not be the same
let context_menu_event_cls = activation.avm2().classes().contextmenuevent;
let menu_evt = Avm2EventObject::from_class_and_args(
&mut activation,
context_menu_event_cls,
&[
"menuSelect".into(),
false.into(),
false.into(),
hit_obj.into(),
hit_obj.into(),
],
);
Avm2::dispatch_event(activation.context, menu_evt, menu_object);
}
crate::avm2::make_context_menu_state(menu_object, display_obj, &mut activation)
} else {
// no AVM1 or AVM2 object - so just prepare the builtin items
let mut menu = ContextMenuState::new();
let builtin_items = BuiltInItemFlags::for_stage(context.stage);
menu.build_builtin_items(builtin_items, context);
menu
};
let ret = menu.info().clone();
*context.current_context_menu = Some(menu);
ret
})
}
pub fn clear_custom_menu_items(&mut self) {
self.enter_arena_mut(|_, gc_root, _| {
gc_root.current_context_menu = None;
});
}
pub fn run_context_menu_callback(&mut self, index: usize) {
self.mutate_with_update_context(|context| {
let menu = &context.current_context_menu;
if let Some(ref menu) = menu {
match menu.callback(index) {
ContextMenuCallback::Avm1 { item, callback } => {
Self::run_context_menu_custom_callback(*item, *callback, context)
}
ContextMenuCallback::Play => Self::toggle_play_root_movie(context),
ContextMenuCallback::Forward => Self::forward_root_movie(context),
ContextMenuCallback::Back => Self::back_root_movie(context),
ContextMenuCallback::Rewind => Self::rewind_root_movie(context),
ContextMenuCallback::Avm2 { item } => {
if let Some(display_obj) = menu.get_display_object() {
let menu_item = *item;
let mut activation = Avm2Activation::from_nothing(context);
let menu_obj = display_obj
.as_interactive()
.map(|iobj| iobj.context_menu())
.and_then(|v| v.as_object());
if menu_obj.is_some() {
// TODO: contextMenuOwner and mouseTarget might not be the same (see above comment)
let context_menu_event_cls =
activation.avm2().classes().contextmenuevent;
let menu_evt = Avm2EventObject::from_class_and_args(
&mut activation,
context_menu_event_cls,
&[
"menuItemSelect".into(),
false.into(),
false.into(),
display_obj.object2(),
display_obj.object2(),
],
);
Avm2::dispatch_event(context, menu_evt, menu_item);
}
}
}
ContextMenuCallback::QualityLow => {
context.stage.set_quality(context, StageQuality::Low)
}
ContextMenuCallback::QualityMedium => {
context.stage.set_quality(context, StageQuality::Medium)
}
ContextMenuCallback::QualityHigh => {
context.stage.set_quality(context, StageQuality::High)
}
ContextMenuCallback::TextControl { code, text } => {
text.text_control_input(*code, context)
}
_ => {}
}
Self::run_actions(context);
}
});
}
fn run_context_menu_custom_callback<'gc>(
item: Object<'gc>,
callback: Object<'gc>,
context: &mut UpdateContext<'gc>,
) {
if let Some(menu_state) = context.current_context_menu {
if let Some(display_object) = menu_state.get_display_object() {
let mut activation = Activation::from_nothing(
context,
ActivationIdentifier::root("[Context Menu Callback]"),
display_object,
);
let params = vec![display_object.object(), Value::Object(item)];
let _ = callback.call(
"[Context Menu Callback]",
&mut activation,
Value::Undefined,
¶ms,
);
}
}
}
///Returns the first display object that the mouse is hovering over that has a custom context menu. Returns root if none is found.
fn get_context_menu_display_object<'gc>(
context: &mut UpdateContext<'gc>,
) -> Option<DisplayObject<'gc>> {
let mut picked_obj =
run_mouse_pick(context, false).map(|picked_obj| picked_obj.as_displayobject());
while let Some(display_obj) = picked_obj {
if let Value::Object(obj) = display_obj.object() {
let mut activation =
Activation::from_stub(context, ActivationIdentifier::root("[ContextMenu]"));
if let Ok(Value::Object(_)) = obj.get(istr!("menu"), &mut activation) {
return Some(display_obj);
}
}
picked_obj = display_obj.parent();
}
context.stage.root_clip()
}
pub fn is_fullscreen(&mut self) -> bool {
self.mutate_with_update_context(|context| {
context.stage.display_state() != StageDisplayState::Normal
})
}
pub fn set_fullscreen(&mut self, is_fullscreen: bool) {
self.mutate_with_update_context(|context| {
let display_state = if is_fullscreen {
StageDisplayState::FullScreen
} else {
StageDisplayState::Normal
};
context.stage.set_display_state(context, display_state);
});
}
fn toggle_play_root_movie(context: &mut UpdateContext<'_>) {
if let Some(mc) = context
.stage
.root_clip()
.and_then(|root| root.as_movie_clip())
{
if mc.playing() {
mc.stop(context);
} else {
mc.play(context);
}
}
}
fn rewind_root_movie(context: &mut UpdateContext<'_>) {
if let Some(mc) = context
.stage
.root_clip()
.and_then(|root| root.as_movie_clip())
{
mc.goto_frame(context, 1, true)
}
}
fn forward_root_movie(context: &mut UpdateContext<'_>) {
if let Some(mc) = context
.stage
.root_clip()
.and_then(|root| root.as_movie_clip())
{
mc.next_frame(context);
}
}
fn back_root_movie(context: &mut UpdateContext<'_>) {
if let Some(mc) = context
.stage
.root_clip()
.and_then(|root| root.as_movie_clip())
{
mc.prev_frame(context);
}
}
fn set_run_state(&mut self, state: RunState) {
let play_audio = match state {
RunState::Playing => true,
RunState::Suspended => false,
// Do not run audio when stepping frame-by-frame,
// to avoid unpleasant short bursts of sound.
RunState::Stepping => false,
};
if play_audio {
// Allow auto-play after user gesture for web backends.
self.audio.play();
} else {
self.audio.pause();
}
self.run_state = state;
}
pub fn set_is_playing(&mut self, v: bool) {
self.set_run_state(if v {
RunState::Playing
} else {
RunState::Suspended
});
}
pub fn suspend_after_next_frame(&mut self) {
self.set_run_state(RunState::Stepping);
}
pub fn needs_render(&self) -> bool {
self.needs_render
}
pub fn background_color(&mut self) -> Option<Color> {
self.mutate_with_update_context(|context| context.stage.background_color())
}
pub fn set_background_color(&mut self, color: Option<Color>) {
self.mutate_with_update_context(|context| {
context.stage.set_background_color(context.gc(), color)
})
}
pub fn letterbox(&mut self) -> Letterbox {
self.mutate_with_update_context(|context| context.stage.letterbox())
}
pub fn set_letterbox(&mut self, letterbox: Letterbox) {
self.mutate_with_update_context(|context| {
context.stage.set_letterbox(context.gc(), letterbox)
})
}
pub fn movie_width(&mut self) -> u32 {
self.mutate_with_update_context(|context| context.stage.movie_size().0)
}
pub fn movie_height(&mut self) -> u32 {
self.mutate_with_update_context(|context| context.stage.movie_size().1)
}
pub fn viewport_dimensions(&mut self) -> ViewportDimensions {
self.mutate_with_update_context(|context| context.renderer.viewport_dimensions())
}
pub fn set_viewport_dimensions(&mut self, dimensions: ViewportDimensions) {
self.mutate_with_update_context(|context| {
context.renderer.set_viewport_dimensions(dimensions);
context.stage.build_matrices(context);
})
}
pub fn set_show_menu(&mut self, show_menu: bool) {
self.mutate_with_update_context(|context| {
let stage = context.stage;
stage.set_show_menu(context, show_menu);
})
}
/// Set whether the Stage's display state can be changed.
pub fn set_allow_fullscreen(&mut self, allow_fullscreen: bool) {
self.mutate_with_update_context(|context| {
let stage = context.stage;
stage.set_allow_fullscreen(context, allow_fullscreen);
})
}
pub fn quality(&mut self) -> StageQuality {
self.mutate_with_update_context(|context| context.stage.quality())
}
pub fn set_quality(&mut self, quality: StageQuality) {
self.mutate_with_update_context(|context| {
context.stage.set_quality(context, quality);
})
}
pub fn set_window_mode(&mut self, window_mode: &str) {
self.mutate_with_update_context(|context| {
let stage = context.stage;
if let Ok(window_mode) = WindowMode::from_str(window_mode) {
stage.set_window_mode(context, window_mode);
}
})
}
pub fn scale_mode(&mut self) -> StageScaleMode {
self.mutate_with_update_context(|context| context.stage.scale_mode())
}
pub fn set_scale_mode(&mut self, scale_mode: StageScaleMode) {
self.mutate_with_update_context(|context| {
context.stage.set_scale_mode(context, scale_mode, false);
})
}
pub fn forced_scale_mode(&mut self) -> bool {
self.mutate_with_update_context(|context| context.stage.forced_scale_mode())
}
pub fn set_forced_scale_mode(&mut self, force: bool) {
self.mutate_with_update_context(|context| {
context.stage.set_forced_scale_mode(context, force);
})
}