forked from ruffle-rs/ruffle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1761 lines (1587 loc) · 65.2 KB
/
lib.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
#![deny(clippy::unwrap_used)]
//! Ruffle web frontend.
mod audio;
mod log_adapter;
mod navigator;
mod storage;
mod ui;
use generational_arena::{Arena, Index};
use js_sys::{Array, Error as JsError, Function, Object, Promise, Uint8Array};
use ruffle_core::backend::navigator::OpenURLMode;
use ruffle_core::compatibility_rules::CompatibilityRules;
use ruffle_core::config::{Letterbox, NetworkingAccessMode};
use ruffle_core::context::UpdateContext;
use ruffle_core::events::{KeyCode, MouseButton, MouseWheelDelta};
use ruffle_core::external::{
ExternalInterfaceMethod, ExternalInterfaceProvider, Value as ExternalValue, Value,
};
use ruffle_core::tag_utils::SwfMovie;
use ruffle_core::{
Color, Player, PlayerBuilder, PlayerEvent, SandboxType, StageScaleMode, StaticCallstack,
ViewportDimensions,
};
use ruffle_render::quality::StageQuality;
use ruffle_video_software::backend::SoftwareVideoBackend;
use ruffle_web_common::JsResult;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::str::FromStr;
use std::sync::Once;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{cell::RefCell, error::Error, num::NonZeroI32};
use tracing_subscriber::layer::{Layered, SubscriberExt};
use tracing_subscriber::registry::Registry;
use tracing_wasm::{WASMLayer, WASMLayerConfigBuilder};
use url::Url;
use wasm_bindgen::{prelude::*, JsCast, JsValue};
use web_sys::{
AddEventListenerOptions, Element, Event, EventTarget, HtmlCanvasElement, HtmlElement,
KeyboardEvent, PointerEvent, WheelEvent, Window,
};
static RUFFLE_GLOBAL_PANIC: Once = Once::new();
thread_local! {
/// We store the actual instances of the ruffle core in a static pool.
/// This gives us a clear boundary between the JS side and Rust side, avoiding
/// issues with lifetimes and type parameters (which cannot be exported with wasm-bindgen).
static INSTANCES: RefCell<Arena<RefCell<RuffleInstance>>> = RefCell::new(Arena::new());
static CURRENT_CONTEXT: RefCell<Option<*mut UpdateContext<'static, 'static>>> = RefCell::new(None);
}
type AnimationHandler = Closure<dyn FnMut(f64)>;
struct RuffleInstance {
core: Arc<Mutex<Player>>,
callstack: Option<StaticCallstack>,
js_player: JavascriptPlayer,
canvas: HtmlCanvasElement,
canvas_width: i32,
canvas_height: i32,
device_pixel_ratio: f64,
window: Window,
timestamp: Option<f64>,
animation_handler: Option<AnimationHandler>, // requestAnimationFrame callback
animation_handler_id: Option<NonZeroI32>, // requestAnimationFrame id
#[allow(dead_code)]
mouse_move_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
mouse_enter_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
mouse_leave_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
mouse_down_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
player_mouse_down_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
window_mouse_down_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
mouse_up_callback: Option<Closure<dyn FnMut(PointerEvent)>>,
mouse_wheel_callback: Option<Closure<dyn FnMut(WheelEvent)>>,
key_down_callback: Option<Closure<dyn FnMut(KeyboardEvent)>>,
key_up_callback: Option<Closure<dyn FnMut(KeyboardEvent)>>,
unload_callback: Option<Closure<dyn FnMut(Event)>>,
has_focus: bool,
trace_observer: Arc<RefCell<JsValue>>,
log_subscriber: Arc<Layered<WASMLayer, Registry>>,
}
#[wasm_bindgen(raw_module = "./ruffle-player")]
extern "C" {
#[wasm_bindgen(extends = EventTarget)]
#[derive(Clone)]
pub type JavascriptPlayer;
#[wasm_bindgen(method, js_name = "onCallbackAvailable")]
fn on_callback_available(this: &JavascriptPlayer, name: &str);
#[wasm_bindgen(method, catch, js_name = "onFSCommand")]
fn on_fs_command(this: &JavascriptPlayer, command: &str, args: &str) -> Result<bool, JsValue>;
#[wasm_bindgen(method)]
fn panic(this: &JavascriptPlayer, error: &JsError);
#[wasm_bindgen(method, js_name = "displayUnsupportedMessage")]
fn display_unsupported_message(this: &JavascriptPlayer);
#[wasm_bindgen(method, js_name = "displayRootMovieDownloadFailedMessage")]
fn display_root_movie_download_failed_message(this: &JavascriptPlayer);
#[wasm_bindgen(method, js_name = "displayMessage")]
fn display_message(this: &JavascriptPlayer, message: &str);
#[wasm_bindgen(method, getter, js_name = "isFullscreen")]
fn is_fullscreen(this: &JavascriptPlayer) -> bool;
#[wasm_bindgen(catch, method, js_name = "setFullscreen")]
fn set_fullscreen(this: &JavascriptPlayer, is_full: bool) -> Result<(), JsValue>;
#[wasm_bindgen(method, js_name = "setMetadata")]
fn set_metadata(this: &JavascriptPlayer, metadata: JsValue);
#[wasm_bindgen(method, js_name = "openVirtualKeyboard")]
fn open_virtual_keyboard(this: &JavascriptPlayer);
}
struct JavascriptInterface {
js_player: JavascriptPlayer,
}
fn deserialize_log_level<'de, D>(deserializer: D) -> Result<tracing::Level, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let value: String = serde::Deserialize::deserialize(deserializer)?;
tracing::Level::from_str(&value).map_err(Error::custom)
}
fn deserialize_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
struct DurationVisitor;
impl<'de> serde::de::Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str(
"Either a non-negative number (indicating seconds) or a {secs: number, nanos: number}."
)
}
fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Duration::from_secs_f64(if value < 1 {
1.0
} else {
value as f64
}))
}
fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Duration::from_secs_f64(if value.is_nan() || value < 1.0 {
1.0
} else {
value
}))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut secs = None;
let mut nanos = None;
while let Some(key) = map.next_key::<String>()? {
let key_s = key.as_str();
match key_s {
"secs" => {
if secs.is_some() {
return Err(Error::duplicate_field("secs"));
}
secs = Some(map.next_value()?);
}
"nanos" => {
if nanos.is_some() {
return Err(Error::duplicate_field("nanos"));
}
nanos = Some(map.next_value()?);
}
_ => return Err(Error::unknown_field(key_s, &["secs", "nanos"])),
}
}
let secs = secs.ok_or_else(|| Error::missing_field("secs"))?;
let nanos = nanos.ok_or_else(|| Error::missing_field("nanos"))?;
Ok(Duration::new(secs, nanos))
}
}
deserializer.deserialize_any(DurationVisitor)
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Config {
allow_script_access: bool,
background_color: Option<String>,
letterbox: Letterbox,
upgrade_to_https: bool,
compatibility_rules: bool,
#[serde(rename = "base")]
base_url: Option<String>,
#[serde(rename = "menu")]
show_menu: bool,
salign: Option<String>,
quality: Option<String>,
scale: Option<String>,
force_scale: bool,
frame_rate: Option<f64>,
wmode: Option<String>,
warn_on_unsupported_content: bool,
#[serde(deserialize_with = "deserialize_log_level")]
log_level: tracing::Level,
#[serde(deserialize_with = "deserialize_duration")]
max_execution_duration: Duration,
player_version: Option<u8>,
preferred_renderer: Option<String>,
open_url_mode: OpenURLMode,
allow_networking: NetworkingAccessMode,
}
/// Metadata about the playing SWF file to be passed back to JavaScript.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct MovieMetadata {
width: f64,
height: f64,
frame_rate: f32,
num_frames: u16,
swf_version: u8,
background_color: Option<String>,
is_action_script_3: bool,
#[serde(rename = "uncompressedLength")]
uncompressed_len: u32,
}
/// An opaque handle to a `RuffleInstance` inside the pool.
///
/// This type is exported to JS, and is used to interact with the library.
#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct Ruffle(Index);
#[wasm_bindgen]
impl Ruffle {
#[allow(clippy::new_ret_no_self)]
#[wasm_bindgen(constructor)]
pub fn new(parent: HtmlElement, js_player: JavascriptPlayer, config: JsValue) -> Promise {
wasm_bindgen_futures::future_to_promise(async move {
let config: Config = serde_wasm_bindgen::from_value(config)
.map_err(|e| format!("Error parsing config: {e}"))?;
if RUFFLE_GLOBAL_PANIC.is_completed() {
// If an actual panic happened, then we can't trust the state it left us in.
// Prevent future players from loading so that they can inform the user about the error.
return Err("Ruffle is panicking!".into());
}
set_panic_handler();
let ruffle = Ruffle::new_internal(parent, js_player, config)
.await
.map_err(|_| JsValue::from("Error creating player"))?;
Ok(JsValue::from(ruffle))
})
}
/// Stream an arbitrary movie file from (presumably) the Internet.
///
/// This method should only be called once per player.
pub fn stream_from(&mut self, movie_url: String, parameters: JsValue) -> Result<(), JsValue> {
let _ = self.with_core_mut(|core| {
let parameters_to_load = parse_movie_parameters(¶meters);
let ruffle = *self;
let on_metadata = move |swf_header: &ruffle_core::swf::HeaderExt| {
ruffle.on_metadata(swf_header);
};
core.fetch_root_movie(movie_url, parameters_to_load, Box::new(on_metadata));
});
Ok(())
}
/// Play an arbitrary movie on this instance.
///
/// This method should only be called once per player.
pub fn load_data(
&mut self,
swf_data: Uint8Array,
parameters: JsValue,
swf_name: String,
) -> Result<(), JsValue> {
let window = web_sys::window().ok_or("Expected window")?;
let mut url = Url::from_str(&window.location().href()?)
.map_err(|e| format!("Error creating url: {e}"))?;
url.set_query(None);
url.set_fragment(None);
if let Ok(mut segments) = url.path_segments_mut() {
segments.pop();
segments.push(&swf_name);
}
let mut movie = SwfMovie::from_data(&swf_data.to_vec(), url.to_string(), None)
.map_err(|e| format!("Error loading movie: {e}"))?;
movie.append_parameters(parse_movie_parameters(¶meters));
self.on_metadata(movie.header());
let _ = self.with_core_mut(move |core| {
core.set_root_movie(movie);
});
Ok(())
}
pub fn play(&mut self) {
let _ = self.with_core_mut(|core| {
core.set_is_playing(true);
});
}
pub fn pause(&mut self) {
let _ = self.with_core_mut(|core| {
core.set_is_playing(false);
});
}
pub fn is_playing(&mut self) -> bool {
self.with_core(|core| core.is_playing()).unwrap_or_default()
}
pub fn volume(&self) -> f32 {
self.with_core(|core| core.volume()).unwrap_or_default()
}
pub fn set_volume(&mut self, value: f32) {
let _ = self.with_core_mut(|core| core.set_volume(value));
}
pub fn renderer_debug_info(&self) -> JsValue {
self.with_core(|core| JsValue::from_str(&core.renderer().debug_info()))
.unwrap_or(JsValue::NULL)
}
pub fn renderer_name(&self) -> JsValue {
self.with_core(|core| JsValue::from_str(core.renderer().name()))
.unwrap_or(JsValue::NULL)
}
// after the context menu is closed, remember to call `clear_custom_menu_items`!
pub fn prepare_context_menu(&mut self) -> JsValue {
self.with_core_mut(|core| {
let info = core.prepare_context_menu();
serde_wasm_bindgen::to_value(&info).unwrap_or(JsValue::UNDEFINED)
})
.unwrap_or(JsValue::UNDEFINED)
}
pub fn run_context_menu_callback(&mut self, index: usize) {
let _ = self.with_core_mut(|core| core.run_context_menu_callback(index));
}
pub fn set_fullscreen(&mut self, is_fullscreen: bool) {
let _ = self.with_core_mut(|core| core.set_fullscreen(is_fullscreen));
}
pub fn clear_custom_menu_items(&mut self) {
let _ = self.with_core_mut(Player::clear_custom_menu_items);
}
pub fn destroy(&mut self) {
// Remove instance from the active list.
if let Ok(mut instance) = self.remove_instance() {
instance.canvas.remove();
// Stop all audio playing from the instance.
let _ = instance.with_core_mut(|core| {
core.audio_mut().stop_all_sounds();
core.flush_shared_objects();
});
// Clean up all event listeners.
if let Some(mouse_move_callback) = instance.mouse_move_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"pointermove",
mouse_move_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(mouse_enter_callback) = instance.mouse_enter_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"pointerenter",
mouse_enter_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(mouse_leave_callback) = instance.mouse_leave_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"pointerleave",
mouse_leave_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(mouse_down_callback) = instance.mouse_down_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"pointerdown",
mouse_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(player_mouse_down_callback) = instance.player_mouse_down_callback.take() {
instance
.js_player
.remove_event_listener_with_callback(
"pointerdown",
player_mouse_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(window_mouse_down_callback) = instance.window_mouse_down_callback.take() {
instance
.window
.remove_event_listener_with_callback_and_bool(
"pointerdown",
window_mouse_down_callback.as_ref().unchecked_ref(),
true,
)
.warn_on_error();
}
if let Some(mouse_up_callback) = instance.mouse_up_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"pointerup",
mouse_up_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(mouse_wheel_callback) = instance.mouse_wheel_callback.take() {
instance
.canvas
.remove_event_listener_with_callback(
"wheel",
mouse_wheel_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(key_down_callback) = instance.key_down_callback.take() {
instance
.window
.remove_event_listener_with_callback(
"keydown",
key_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(key_up_callback) = instance.key_up_callback.take() {
instance
.window
.remove_event_listener_with_callback(
"keyup",
key_up_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
if let Some(unload_callback) = instance.unload_callback.take() {
instance
.window
.remove_event_listener_with_callback(
"unload",
unload_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
}
// Cancel the animation handler, if it's still active.
if let Some(id) = instance.animation_handler_id {
instance
.window
.cancel_animation_frame(id.into())
.warn_on_error();
}
}
// Player is dropped at this point.
}
#[allow(clippy::boxed_local)] // for js_bind
pub fn call_exposed_callback(&self, name: &str, args: Box<[JsValue]>) -> JsValue {
let args: Vec<ExternalValue> = args.iter().map(js_to_external_value).collect();
// Re-entrant callbacks need to return through the hole that was punched through for them
// We record the context of external functions, and then if we get an internal callback
// during the same call we'll reuse that.
// This is unsafe by nature. I don't know any safe way to do this.
if let Some(context) = CURRENT_CONTEXT.with(|v| *v.borrow()) {
unsafe {
if let Some(callback) = (*context).external_interface.get_callback(name) {
return external_to_js_value(callback.call(&mut *context, name, args));
}
}
}
self.with_core_mut(|core| external_to_js_value(core.call_internal_interface(name, args)))
.unwrap_or(JsValue::UNDEFINED)
}
pub fn set_trace_observer(&self, observer: JsValue) {
let _ = self.with_instance(|instance| {
*instance.trace_observer.borrow_mut() = observer;
});
}
/// Returns the web AudioContext used by this player.
/// Returns `None` if the audio backend does not use Web Audio.
pub fn audio_context(&self) -> Option<web_sys::AudioContext> {
self.with_core_mut(|core| {
core.audio()
.downcast_ref::<audio::WebAudioBackend>()
.map(|audio| audio.audio_context().clone())
})
.unwrap_or_default()
}
/// Returns whether the `simd128` target feature was enabled at build time.
/// This is intended to discriminate between the two WebAssembly module
/// versions, one of which uses WebAssembly extensions, and the other one
/// being "vanilla". `simd128` is used as proxy for most extensions, since
/// no other WebAssembly target feature is exposed to `cfg!`.
pub fn is_wasm_simd_used() -> bool {
cfg!(target_feature = "simd128")
}
}
impl Ruffle {
async fn new_internal(
parent: HtmlElement,
js_player: JavascriptPlayer,
config: Config,
) -> Result<Ruffle, Box<dyn Error>> {
// Redirect Log to Tracing if it isn't already
let _ = tracing_log::LogTracer::builder()
// wgpu crates are extremely verbose
.ignore_crate("wgpu_hal")
.ignore_crate("wgpu_core")
.init();
let log_subscriber = Arc::new(
Registry::default().with(WASMLayer::new(
WASMLayerConfigBuilder::new()
.set_report_logs_in_timings(cfg!(feature = "profiling"))
.set_max_level(config.log_level)
.build(),
)),
);
let _subscriber = tracing::subscriber::set_default(log_subscriber.clone());
let allow_script_access = config.allow_script_access;
let allow_networking = config.allow_networking;
let window = web_sys::window().ok_or("Expected window")?;
let document = window.document().ok_or("Expected document")?;
let (mut builder, canvas) =
create_renderer(PlayerBuilder::new(), &document, &config).await?;
parent
.append_child(&canvas.clone().into())
.into_js_result()?;
if let Ok(audio) = audio::WebAudioBackend::new(log_subscriber.clone()) {
builder = builder.with_audio(audio);
} else {
tracing::error!("Unable to create audio backend. No audio will be played.");
}
builder = builder.with_navigator(navigator::WebNavigatorBackend::new(
allow_script_access,
allow_networking,
config.upgrade_to_https,
config.base_url,
log_subscriber.clone(),
config.open_url_mode,
));
match window.local_storage() {
Ok(Some(s)) => {
builder = builder.with_storage(storage::LocalStorageBackend::new(s));
}
err => {
tracing::warn!("Unable to use localStorage: {:?}\nData will not save.", err);
}
};
let default_quality = if ruffle_web_common::is_mobile_or_tablet() {
tracing::info!("Running on a mobile device; defaulting to low quality");
StageQuality::Low
} else {
StageQuality::High
};
let trace_observer = Arc::new(RefCell::new(JsValue::UNDEFINED));
let core = builder
.with_log(log_adapter::WebLogBackend::new(trace_observer.clone()))
.with_ui(ui::WebUiBackend::new(js_player.clone(), &canvas))
.with_video(SoftwareVideoBackend::new())
.with_letterbox(config.letterbox)
.with_max_execution_duration(config.max_execution_duration)
.with_warn_on_unsupported_content(config.warn_on_unsupported_content)
.with_player_version(config.player_version)
.with_compatibility_rules(if config.compatibility_rules {
CompatibilityRules::default()
} else {
CompatibilityRules::empty()
})
.with_quality(
config
.quality
.and_then(|q| StageQuality::from_str(&q).ok())
.unwrap_or(default_quality),
)
.with_scale_mode(
config
.scale
.and_then(|s| StageScaleMode::from_str(&s).ok())
.unwrap_or(StageScaleMode::ShowAll),
config.force_scale,
)
.with_frame_rate(config.frame_rate)
// FIXME - should this be configurable?
.with_sandbox_type(SandboxType::Remote)
.build();
let mut callstack = None;
if let Ok(mut core) = core.try_lock() {
// Set config parameters.
if let Some(color) = config.background_color.and_then(parse_html_color) {
core.set_background_color(Some(color));
}
core.set_show_menu(config.show_menu);
core.set_stage_align(config.salign.as_deref().unwrap_or(""));
core.set_window_mode(config.wmode.as_deref().unwrap_or("window"));
// Create the external interface.
if allow_script_access && allow_networking == NetworkingAccessMode::All {
core.add_external_interface(Box::new(JavascriptInterface::new(js_player.clone())));
}
callstack = Some(core.callstack());
}
// Create instance.
let instance = RuffleInstance {
core,
callstack,
js_player: js_player.clone(),
canvas: canvas.clone(),
canvas_width: 0, // Initialize canvas width and height to 0 to force an initial canvas resize.
canvas_height: 0,
device_pixel_ratio: window.device_pixel_ratio(),
window: window.clone(),
animation_handler: None,
animation_handler_id: None,
mouse_move_callback: None,
mouse_enter_callback: None,
mouse_leave_callback: None,
mouse_down_callback: None,
player_mouse_down_callback: None,
window_mouse_down_callback: None,
mouse_up_callback: None,
mouse_wheel_callback: None,
key_down_callback: None,
key_up_callback: None,
unload_callback: None,
timestamp: None,
has_focus: false,
trace_observer,
log_subscriber,
};
// Prevent touch-scrolling on canvas.
canvas
.style()
.set_property("touch-action", "none")
.warn_on_error();
// Register the instance and create the animation frame closure.
let mut ruffle = Ruffle::add_instance(instance)?;
// Create the animation frame closure.
ruffle.with_instance_mut(|instance| {
instance.animation_handler = Some(Closure::new(move |timestamp| {
ruffle.tick(timestamp);
}));
// Create mouse move handler.
let mouse_move_callback = Closure::new(move |js_event: PointerEvent| {
let _ = ruffle.with_instance(move |instance| {
let event = PlayerEvent::MouseMove {
x: f64::from(js_event.offset_x()) * instance.device_pixel_ratio,
y: f64::from(js_event.offset_y()) * instance.device_pixel_ratio,
};
let _ = instance.with_core_mut(|core| {
core.handle_event(event);
});
if instance.has_focus {
js_event.prevent_default();
}
});
});
canvas
.add_event_listener_with_callback(
"pointermove",
mouse_move_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.mouse_move_callback = Some(mouse_move_callback);
// Create mouse enter handler.
let mouse_enter_callback = Closure::new(move |_js_event: PointerEvent| {
let _ = ruffle.with_instance(move |instance| {
let _ = instance.with_core_mut(|core| {
core.set_mouse_in_stage(true);
});
});
});
canvas
.add_event_listener_with_callback(
"pointerenter",
mouse_enter_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.mouse_enter_callback = Some(mouse_enter_callback);
// Create mouse leave handler.
let mouse_leave_callback = Closure::new(move |_js_event: PointerEvent| {
let _ = ruffle.with_instance(move |instance| {
let _ = instance.with_core_mut(|core| {
core.set_mouse_in_stage(false);
core.handle_event(PlayerEvent::MouseLeave);
});
});
});
canvas
.add_event_listener_with_callback(
"pointerleave",
mouse_leave_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.mouse_leave_callback = Some(mouse_leave_callback);
// Create mouse down handler.
let mouse_down_callback = Closure::new(move |js_event: PointerEvent| {
let _ = ruffle.with_instance(move |instance| {
if let Some(target) = js_event.current_target() {
let _ = target
.unchecked_ref::<Element>()
.set_pointer_capture(js_event.pointer_id());
}
let device_pixel_ratio = instance.device_pixel_ratio;
let event = PlayerEvent::MouseDown {
x: f64::from(js_event.offset_x()) * device_pixel_ratio,
y: f64::from(js_event.offset_y()) * device_pixel_ratio,
button: match js_event.button() {
0 => MouseButton::Left,
1 => MouseButton::Middle,
2 => MouseButton::Right,
_ => MouseButton::Unknown,
},
};
let _ = instance.with_core_mut(|core| {
core.handle_event(event);
});
js_event.prevent_default();
});
});
canvas
.add_event_listener_with_callback(
"pointerdown",
mouse_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.mouse_down_callback = Some(mouse_down_callback);
// Create player mouse down handler.
let player_mouse_down_callback = Closure::new(move |_js_event| {
let _ = ruffle.with_instance_mut(|instance| {
instance.has_focus = true;
// Ensure the parent window gets focus. This is necessary for events
// to be received when the player is inside a frame.
instance.window.focus().warn_on_error();
});
});
js_player
.add_event_listener_with_callback(
"pointerdown",
player_mouse_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.player_mouse_down_callback = Some(player_mouse_down_callback);
// Create window mouse down handler.
let window_mouse_down_callback = Closure::new(move |_js_event| {
let _ = ruffle.with_instance_mut(|instance| {
// If we actually clicked on the player, this will be reset to true
// after the event bubbles down to the player.
instance.has_focus = false;
});
});
window
.add_event_listener_with_callback_and_bool(
"pointerdown",
window_mouse_down_callback.as_ref().unchecked_ref(),
true, // Use capture so this first *before* the player mouse down handler.
)
.warn_on_error();
instance.window_mouse_down_callback = Some(window_mouse_down_callback);
// Create mouse up handler.
let mouse_up_callback = Closure::new(move |js_event: PointerEvent| {
let _ = ruffle.with_instance(|instance| {
if let Some(target) = js_event.current_target() {
let _ = target
.unchecked_ref::<Element>()
.release_pointer_capture(js_event.pointer_id());
}
let event = PlayerEvent::MouseUp {
x: f64::from(js_event.offset_x()) * instance.device_pixel_ratio,
y: f64::from(js_event.offset_y()) * instance.device_pixel_ratio,
button: match js_event.button() {
0 => MouseButton::Left,
1 => MouseButton::Middle,
2 => MouseButton::Right,
_ => MouseButton::Unknown,
},
};
let _ = instance.with_core_mut(|core| {
core.handle_event(event);
});
if instance.has_focus {
js_event.prevent_default();
}
});
});
canvas
.add_event_listener_with_callback(
"pointerup",
mouse_up_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.mouse_up_callback = Some(mouse_up_callback);
// Create mouse wheel handler.
let mouse_wheel_callback = Closure::new(move |js_event: WheelEvent| {
let _ = ruffle.with_instance(|instance| {
let delta = match js_event.delta_mode() {
WheelEvent::DOM_DELTA_LINE => MouseWheelDelta::Lines(-js_event.delta_y()),
WheelEvent::DOM_DELTA_PIXEL => MouseWheelDelta::Pixels(-js_event.delta_y()),
_ => return,
};
let _ = instance.with_core_mut(|core| {
core.handle_event(PlayerEvent::MouseWheel { delta });
if core.should_prevent_scrolling() {
js_event.prevent_default();
}
});
});
});
canvas
.add_event_listener_with_callback_and_add_event_listener_options(
"wheel",
mouse_wheel_callback.as_ref().unchecked_ref(),
AddEventListenerOptions::new().passive(false),
)
.warn_on_error();
instance.mouse_wheel_callback = Some(mouse_wheel_callback);
// Create keydown event handler.
let key_down_callback = Closure::new(move |js_event: KeyboardEvent| {
let _ = ruffle.with_instance(|instance| {
if instance.has_focus {
let _ = instance.with_core_mut(|core| {
let key_code = web_to_ruffle_key_code(&js_event.code());
let key_char = web_key_to_codepoint(&js_event.key());
core.handle_event(PlayerEvent::KeyDown { key_code, key_char });
if let Some(codepoint) = key_char {
core.handle_event(PlayerEvent::TextInput { codepoint });
}
});
js_event.prevent_default();
}
});
});
window
.add_event_listener_with_callback(
"keydown",
key_down_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.key_down_callback = Some(key_down_callback);
// Create keyup event handler.
let key_up_callback = Closure::new(move |js_event: KeyboardEvent| {
let _ = ruffle.with_instance(|instance| {
if instance.has_focus {
let _ = instance.with_core_mut(|core| {
let key_code = web_to_ruffle_key_code(&js_event.code());
let key_char = web_key_to_codepoint(&js_event.key());
core.handle_event(PlayerEvent::KeyUp { key_code, key_char });
});
js_event.prevent_default();
}
});
});
window
.add_event_listener_with_callback("keyup", key_up_callback.as_ref().unchecked_ref())
.warn_on_error();
instance.key_up_callback = Some(key_up_callback);
let unload_callback = Closure::new(move |_| {
let _ = ruffle.with_core_mut(|core| {
core.flush_shared_objects();
});
});
window
.add_event_listener_with_callback(
"unload",
unload_callback.as_ref().unchecked_ref(),
)
.warn_on_error();
instance.unload_callback = Some(unload_callback);
})?;
// Set initial timestamp and do initial tick to start animation loop.
ruffle.tick(0.0);
Ok(ruffle)
}
/// Registers a new Ruffle instance and returns the handle to the instance.
fn add_instance(instance: RuffleInstance) -> Result<Ruffle, RuffleInstanceError> {
INSTANCES.try_with(|instances| {
let mut instances = instances.try_borrow_mut()?;
let ruffle = Ruffle(instances.insert(RefCell::new(instance)));
Ok(ruffle)