aboutsummaryrefslogtreecommitdiffstats
path: root/ports/jniapi/src/lib.rs
blob: 917788466e27a7a98fd9ce421960fd26b4bfbddb (plain) (blame)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

#![allow(non_snake_case)]

mod gl_glue;
mod simpleservo;

use std::collections::HashMap;
use std::os::raw::{c_char, c_int, c_void};
use std::sync::Arc;
use std::thread;

use android_logger::{self, Config, FilterBuilder};
use jni::objects::{GlobalRef, JClass, JObject, JString, JValue};
use jni::sys::{jboolean, jfloat, jint, jstring, JNI_TRUE};
use jni::{JNIEnv, JavaVM};
use libc::{dup2, pipe, read};
use log::{debug, error, info, warn};
use simpleservo::{
    Coordinates, DeviceIntRect, EventLoopWaker, HostTrait, InitOptions, InputMethodType,
    MediaSessionPlaybackState, PromptResult, ServoGlue, SERVO,
};

struct HostCallbacks {
    callbacks: GlobalRef,
    jvm: JavaVM,
}

extern "C" {
    fn ANativeWindow_fromSurface(env: *mut jni::sys::JNIEnv, surface: JObject) -> *mut c_void;
}

#[no_mangle]
pub extern "C" fn android_main() {
    // FIXME(mukilan): this android_main is only present to stop
    // the java side 'System.loadLibrary('simpleservo') call from
    // failing due to undefined reference to android_main introduced
    // by winit's android-activity crate. There is no way to disable
    // this currently.
}

fn call<F>(env: &JNIEnv, f: F)
where
    F: Fn(&mut ServoGlue) -> Result<(), &str>,
{
    SERVO.with(|s| {
        if let Err(error) = match s.borrow_mut().as_mut() {
            Some(ref mut s) => (f)(s),
            None => Err("Servo not available in this thread"),
        } {
            throw(env, error);
        }
    });
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_version(
    env: JNIEnv,
    _class: JClass,
) -> jstring {
    let v = simpleservo::servo_version();
    new_string(&env, &v).unwrap_or_else(|null| null)
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_init(
    env: JNIEnv,
    _: JClass,
    _activity: JObject,
    opts: JObject,
    callbacks_obj: JObject,
    surface: JObject,
) {
    let (opts, log, log_str, _gst_debug_str) = match get_options(&env, opts, surface) {
        Ok((opts, log, log_str, gst_debug_str)) => (opts, log, log_str, gst_debug_str),
        Err(err) => {
            throw(&env, &err);
            return;
        },
    };

    if log {
        // Note: Android debug logs are stripped from a release build.
        // debug!() will only show in a debug build. Use info!() if logs
        // should show up in adb logcat with a release build.
        let filters = [
            "servo",
            "simpleservo",
            "simpleservo::jniapi",
            "simpleservo::gl_glue::egl",
            // Show JS errors by default.
            "script::dom::bindings::error",
            // Show GL errors by default.
            "canvas::webgl_thread",
            "compositing::compositor",
            "constellation::constellation",
        ];
        let mut filter_builder = FilterBuilder::new();
        for &module in &filters {
            filter_builder.filter_module(module, log::LevelFilter::Debug);
        }
        if let Some(log_str) = log_str {
            for module in log_str.split(',') {
                filter_builder.filter_module(module, log::LevelFilter::Debug);
            }
        }

        android_logger::init_once(
            Config::default()
                .with_max_level(log::LevelFilter::Debug)
                .with_filter(filter_builder.build())
                .with_tag("simpleservo"),
        )
    }

    info!("init");

    redirect_stdout_to_logcat();

    let callbacks_ref = match env.new_global_ref(callbacks_obj) {
        Ok(r) => r,
        Err(_) => {
            throw(&env, "Failed to get global reference of callback argument");
            return;
        },
    };

    let wakeup = Box::new(WakeupCallback::new(callbacks_ref.clone(), &env));
    let callbacks = Box::new(HostCallbacks::new(callbacks_ref, &env));

    if let Err(err) = gl_glue::egl::init()
        .and_then(|egl_init| simpleservo::init(opts, egl_init.gl_wrapper, wakeup, callbacks))
    {
        throw(&env, err)
    };
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_setBatchMode(
    env: JNIEnv,
    _: JClass,
    batch: jboolean,
) {
    debug!("setBatchMode");
    call(&env, |s| s.set_batch_mode(batch == JNI_TRUE));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_requestShutdown(env: JNIEnv, _class: JClass) {
    debug!("requestShutdown");
    call(&env, |s| s.request_shutdown());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_deinit(_env: JNIEnv, _class: JClass) {
    debug!("deinit");
    simpleservo::deinit();
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_resize(
    env: JNIEnv,
    _: JClass,
    coordinates: JObject,
) {
    let coords = jni_coords_to_rust_coords(&env, coordinates);
    debug!("resize {:#?}", coords);
    match coords {
        Ok(coords) => call(&env, |s| s.resize(coords.clone())),
        Err(error) => throw(&env, &error),
    }
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_performUpdates(env: JNIEnv, _class: JClass) {
    debug!("performUpdates");
    call(&env, |s| s.perform_updates());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_loadUri(
    env: JNIEnv,
    _class: JClass,
    url: JString,
) {
    debug!("loadUri");
    match env.get_string(url) {
        Ok(url) => {
            let url: String = url.into();
            call(&env, |s| s.load_uri(&url));
        },
        Err(_) => {
            throw(&env, "Failed to convert Java string");
        },
    };
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_reload(env: JNIEnv, _class: JClass) {
    debug!("reload");
    call(&env, |s| s.reload());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_stop(env: JNIEnv, _class: JClass) {
    debug!("stop");
    call(&env, |s| s.stop());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_refresh(env: JNIEnv, _class: JClass) {
    debug!("refresh");
    call(&env, |s| s.refresh());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_goBack(env: JNIEnv, _class: JClass) {
    debug!("goBack");
    call(&env, |s| s.go_back());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_goForward(env: JNIEnv, _class: JClass) {
    debug!("goForward");
    call(&env, |s| s.go_forward());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_scrollStart(
    env: JNIEnv,
    _: JClass,
    dx: jint,
    dy: jint,
    x: jint,
    y: jint,
) {
    debug!("scrollStart");
    call(&env, |s| {
        s.scroll_start(dx as f32, dy as f32, x as i32, y as i32)
    });
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_scrollEnd(
    env: JNIEnv,
    _: JClass,
    dx: jint,
    dy: jint,
    x: jint,
    y: jint,
) {
    debug!("scrollEnd");
    call(&env, |s| {
        s.scroll_end(dx as f32, dy as f32, x as i32, y as i32)
    });
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_scroll(
    env: JNIEnv,
    _: JClass,
    dx: jint,
    dy: jint,
    x: jint,
    y: jint,
) {
    debug!("scroll");
    call(&env, |s| s.scroll(dx as f32, dy as f32, x as i32, y as i32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_touchDown(
    env: JNIEnv,
    _: JClass,
    x: jfloat,
    y: jfloat,
    pointer_id: jint,
) {
    debug!("touchDown");
    call(&env, |s| s.touch_down(x, y, pointer_id as i32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_touchUp(
    env: JNIEnv,
    _: JClass,
    x: jfloat,
    y: jfloat,
    pointer_id: jint,
) {
    debug!("touchUp");
    call(&env, |s| s.touch_up(x, y, pointer_id as i32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_touchMove(
    env: JNIEnv,
    _: JClass,
    x: jfloat,
    y: jfloat,
    pointer_id: jint,
) {
    debug!("touchMove");
    call(&env, |s| s.touch_move(x, y, pointer_id as i32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_touchCancel(
    env: JNIEnv,
    _: JClass,
    x: jfloat,
    y: jfloat,
    pointer_id: jint,
) {
    debug!("touchCancel");
    call(&env, |s| s.touch_cancel(x, y, pointer_id as i32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_pinchZoomStart(
    env: JNIEnv,
    _: JClass,
    factor: jfloat,
    x: jint,
    y: jint,
) {
    debug!("pinchZoomStart");
    call(&env, |s| {
        s.pinchzoom_start(factor as f32, x as u32, y as u32)
    });
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_pinchZoom(
    env: JNIEnv,
    _: JClass,
    factor: jfloat,
    x: jint,
    y: jint,
) {
    debug!("pinchZoom");
    call(&env, |s| s.pinchzoom(factor as f32, x as u32, y as u32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_pinchZoomEnd(
    env: JNIEnv,
    _: JClass,
    factor: jfloat,
    x: jint,
    y: jint,
) {
    debug!("pinchZoomEnd");
    call(&env, |s| s.pinchzoom_end(factor as f32, x as u32, y as u32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_click(
    env: JNIEnv,
    _: JClass,
    x: jfloat,
    y: jfloat,
) {
    debug!("click");
    call(&env, |s| s.click(x as f32, y as f32));
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_pauseCompositor(env: JNIEnv, _: JClass) {
    debug!("pauseCompositor");
    call(&env, |s| s.pause_compositor());
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_resumeCompositor(
    env: JNIEnv,
    _: JClass,
    surface: JObject,
    coordinates: JObject,
) {
    debug!("resumeCompositor");
    let widget = unsafe { ANativeWindow_fromSurface(env.get_native_interface(), surface) };
    let coords = jni_coords_to_rust_coords(&env, coordinates);
    match coords {
        Ok(coords) => call(&env, |s| s.resume_compositor(widget, coords.clone())),
        Err(error) => throw(&env, &error),
    }
}

#[no_mangle]
pub extern "C" fn Java_org_mozilla_servoview_JNIServo_mediaSessionAction(
    env: JNIEnv,
    _: JClass,
    action: jint,
) {
    debug!("mediaSessionAction");
    call(&env, |s| s.media_session_action((action as i32).into()));
}

pub struct WakeupCallback {
    callback: GlobalRef,
    jvm: Arc<JavaVM>,
}

impl WakeupCallback {
    pub fn new(callback: GlobalRef, env: &JNIEnv) -> WakeupCallback {
        let jvm = Arc::new(env.get_java_vm().unwrap());
        WakeupCallback { callback, jvm }
    }
}

impl EventLoopWaker for WakeupCallback {
    fn clone_box(&self) -> Box<dyn EventLoopWaker> {
        Box::new(WakeupCallback {
            callback: self.callback.clone(),
            jvm: self.jvm.clone(),
        })
    }
    fn wake(&self) {
        debug!("wakeup");
        let env = self.jvm.attach_current_thread().unwrap();
        env.call_method(self.callback.as_obj(), "wakeup", "()V", &[])
            .unwrap();
    }
}

impl HostCallbacks {
    pub fn new(callbacks: GlobalRef, env: &JNIEnv) -> HostCallbacks {
        let jvm = env.get_java_vm().unwrap();
        HostCallbacks { callbacks, jvm }
    }
}

impl HostTrait for HostCallbacks {
    fn prompt_alert(&self, message: String, _trusted: bool) {
        debug!("prompt_alert");
        let env = self.jvm.get_env().unwrap();
        let s = match new_string(&env, &message) {
            Ok(s) => s,
            Err(_) => return,
        };
        let s = JValue::from(JObject::from(s));
        env.call_method(
            self.callbacks.as_obj(),
            "onAlert",
            "(Ljava/lang/String;)V",
            &[s],
        )
        .unwrap();
    }

    fn prompt_ok_cancel(&self, message: String, _trusted: bool) -> PromptResult {
        warn!("Prompt not implemented. Cancelled. {}", message);
        PromptResult::Secondary
    }

    fn prompt_yes_no(&self, message: String, _trusted: bool) -> PromptResult {
        warn!("Prompt not implemented. Cancelled. {}", message);
        PromptResult::Secondary
    }

    fn prompt_input(&self, message: String, default: String, _trusted: bool) -> Option<String> {
        warn!("Input prompt not implemented. {}", message);
        Some(default)
    }

    fn on_load_started(&self) {
        debug!("on_load_started");
        let env = self.jvm.get_env().unwrap();
        env.call_method(self.callbacks.as_obj(), "onLoadStarted", "()V", &[])
            .unwrap();
    }

    fn on_load_ended(&self) {
        debug!("on_load_ended");
        let env = self.jvm.get_env().unwrap();
        env.call_method(self.callbacks.as_obj(), "onLoadEnded", "()V", &[])
            .unwrap();
    }

    fn on_shutdown_complete(&self) {
        debug!("on_shutdown_complete");
        let env = self.jvm.get_env().unwrap();
        env.call_method(self.callbacks.as_obj(), "onShutdownComplete", "()V", &[])
            .unwrap();
    }

    fn on_title_changed(&self, title: Option<String>) {
        debug!("on_title_changed");
        let env = self.jvm.get_env().unwrap();
        let title = title.unwrap_or_else(String::new);
        let s = match new_string(&env, &title) {
            Ok(s) => s,
            Err(_) => return,
        };
        let s = JValue::from(JObject::from(s));
        env.call_method(
            self.callbacks.as_obj(),
            "onTitleChanged",
            "(Ljava/lang/String;)V",
            &[s],
        )
        .unwrap();
    }

    fn on_allow_navigation(&self, url: String) -> bool {
        debug!("on_allow_navigation");
        let env = self.jvm.get_env().unwrap();
        let s = match new_string(&env, &url) {
            Ok(s) => s,
            Err(_) => return false,
        };
        let s = JValue::from(JObject::from(s));
        let allow = env.call_method(
            self.callbacks.as_obj(),
            "onAllowNavigation",
            "(Ljava/lang/String;)Z",
            &[s],
        );
        match allow {
            Ok(allow) => return allow.z().unwrap(),
            Err(_) => return true,
        }
    }

    fn on_url_changed(&self, url: String) {
        debug!("on_url_changed");
        let env = self.jvm.get_env().unwrap();
        let s = match new_string(&env, &url) {
            Ok(s) => s,
            Err(_) => return,
        };
        let s = JValue::Object(JObject::from(s));
        env.call_method(
            self.callbacks.as_obj(),
            "onUrlChanged",
            "(Ljava/lang/String;)V",
            &[s],
        )
        .unwrap();
    }

    fn on_history_changed(&self, can_go_back: bool, can_go_forward: bool) {
        debug!("on_history_changed");
        let env = self.jvm.get_env().unwrap();
        let can_go_back = JValue::Bool(can_go_back as jboolean);
        let can_go_forward = JValue::Bool(can_go_forward as jboolean);
        env.call_method(
            self.callbacks.as_obj(),
            "onHistoryChanged",
            "(ZZ)V",
            &[can_go_back, can_go_forward],
        )
        .unwrap();
    }

    fn on_animating_changed(&self, animating: bool) {
        debug!("on_animating_changed");
        let env = self.jvm.get_env().unwrap();
        let animating = JValue::Bool(animating as jboolean);
        env.call_method(
            self.callbacks.as_obj(),
            "onAnimatingChanged",
            "(Z)V",
            &[animating],
        )
        .unwrap();
    }

    fn on_ime_show(
        &self,
        _input_type: InputMethodType,
        _text: Option<(String, i32)>,
        _multiline: bool,
        _rect: DeviceIntRect,
    ) {
    }
    fn on_ime_hide(&self) {}

    fn get_clipboard_contents(&self) -> Option<String> {
        None
    }

    fn set_clipboard_contents(&self, _contents: String) {}

    fn on_media_session_metadata(&self, title: String, artist: String, album: String) {
        info!("on_media_session_metadata");
        let env = self.jvm.get_env().unwrap();
        let title = match new_string(&env, &title) {
            Ok(s) => s,
            Err(_) => return,
        };
        let title = JValue::Object(JObject::from(title));

        let artist = match new_string(&env, &artist) {
            Ok(s) => s,
            Err(_) => return,
        };
        let artist = JValue::Object(JObject::from(artist));

        let album = match new_string(&env, &album) {
            Ok(s) => s,
            Err(_) => return,
        };
        let album = JValue::Object(JObject::from(album));
        env.call_method(
            self.callbacks.as_obj(),
            "onMediaSessionMetadata",
            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
            &[title, artist, album],
        )
        .unwrap();
    }

    fn on_media_session_playback_state_change(&self, state: MediaSessionPlaybackState) {
        info!("on_media_session_playback_state_change {:?}", state);
        let env = self.jvm.get_env().unwrap();
        let state = state as i32;
        let state = JValue::Int(state as jint);
        env.call_method(
            self.callbacks.as_obj(),
            "onMediaSessionPlaybackStateChange",
            "(I)V",
            &[state],
        )
        .unwrap();
    }

    fn on_media_session_set_position_state(
        &self,
        duration: f64,
        position: f64,
        playback_rate: f64,
    ) {
        info!(
            "on_media_session_playback_state_change ({:?}, {:?}, {:?})",
            duration, position, playback_rate
        );
        let env = self.jvm.get_env().unwrap();
        let duration = JValue::Float(duration as jfloat);
        let position = JValue::Float(position as jfloat);
        let playback_rate = JValue::Float(playback_rate as jfloat);

        env.call_method(
            self.callbacks.as_obj(),
            "onMediaSessionSetPositionState",
            "(FFF)V",
            &[duration, position, playback_rate],
        )
        .unwrap();
    }

    fn on_devtools_started(&self, port: Result<u16, ()>, _token: String) {
        match port {
            Ok(p) => info!("Devtools Server running on port {}", p),
            Err(()) => error!("Error running devtools server"),
        }
    }

    fn show_context_menu(&self, _title: Option<String>, _items: Vec<String>) {}

    fn on_panic(&self, _reason: String, _backtrace: Option<String>) {}
}

extern "C" {
    pub fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int;
}

fn redirect_stdout_to_logcat() {
    // The first step is to redirect stdout and stderr to the logs.
    // We redirect stdout and stderr to a custom descriptor.
    let mut pfd: [c_int; 2] = [0, 0];
    unsafe {
        pipe(pfd.as_mut_ptr());
        dup2(pfd[1], 1);
        dup2(pfd[1], 2);
    }

    let descriptor = pfd[0];

    // Then we spawn a thread whose only job is to read from the other side of the
    // pipe and redirect to the logs.
    let _detached = thread::spawn(move || {
        const BUF_LENGTH: usize = 512;
        let mut buf = vec![b'\0' as c_char; BUF_LENGTH];

        // Always keep at least one null terminator
        const BUF_AVAILABLE: usize = BUF_LENGTH - 1;
        let buf = &mut buf[..BUF_AVAILABLE];

        let mut cursor = 0_usize;

        let tag = b"simpleservo\0".as_ptr() as _;

        loop {
            let result = {
                let read_into = &mut buf[cursor..];
                unsafe {
                    read(
                        descriptor,
                        read_into.as_mut_ptr() as *mut _,
                        read_into.len(),
                    )
                }
            };

            let end = if result == 0 {
                return;
            } else if result < 0 {
                unsafe {
                    __android_log_write(
                        3,
                        tag,
                        b"error in log thread; closing\0".as_ptr() as *const _,
                    );
                }
                return;
            } else {
                result as usize + cursor
            };

            // Only modify the portion of the buffer that contains real data.
            let buf = &mut buf[0..end];

            if let Some(last_newline_pos) = buf.iter().rposition(|&c| c == b'\n' as c_char) {
                buf[last_newline_pos] = b'\0' as c_char;
                unsafe {
                    __android_log_write(3, tag, buf.as_ptr());
                }
                if last_newline_pos < buf.len() - 1 {
                    let pos_after_newline = last_newline_pos + 1;
                    let len_not_logged_yet = buf[pos_after_newline..].len();
                    for j in 0..len_not_logged_yet as usize {
                        buf[j] = buf[pos_after_newline + j];
                    }
                    cursor = len_not_logged_yet;
                } else {
                    cursor = 0;
                }
            } else if end == BUF_AVAILABLE {
                // No newline found but the buffer is full, flush it anyway.
                // `buf.as_ptr()` is null-terminated by BUF_LENGTH being 1 less than BUF_AVAILABLE.
                unsafe {
                    __android_log_write(3, tag, buf.as_ptr());
                }
                cursor = 0;
            } else {
                cursor = end;
            }
        }
    });
}

fn throw(env: &JNIEnv, err: &str) {
    if let Err(e) = env.throw(("java/lang/Exception", err)) {
        warn!(
            "Failed to throw Java exception: `{}`. Exception was: `{}`",
            e, err
        );
    }
}

fn new_string(env: &JNIEnv, s: &str) -> Result<jstring, jstring> {
    match env.new_string(s) {
        Ok(s) => Ok(s.into_inner()),
        Err(_) => {
            throw(&env, "Couldn't create java string");
            Err(JObject::null().into_inner())
        },
    }
}

fn jni_coords_to_rust_coords(env: &JNIEnv, obj: JObject) -> Result<Coordinates, String> {
    let x = get_non_null_field(env, obj, "x", "I")?
        .i()
        .map_err(|_| "x not an int")? as i32;
    let y = get_non_null_field(env, obj, "y", "I")?
        .i()
        .map_err(|_| "y not an int")? as i32;
    let width = get_non_null_field(env, obj, "width", "I")?
        .i()
        .map_err(|_| "width not an int")? as i32;
    let height = get_non_null_field(env, obj, "height", "I")?
        .i()
        .map_err(|_| "height not an int")? as i32;
    let fb_width = get_non_null_field(env, obj, "fb_width", "I")?
        .i()
        .map_err(|_| "fb_width not an int")? as i32;
    let fb_height = get_non_null_field(env, obj, "fb_height", "I")?
        .i()
        .map_err(|_| "fb_height not an int")? as i32;
    Ok(Coordinates::new(x, y, width, height, fb_width, fb_height))
}

fn get_field<'a>(
    env: &'a JNIEnv,
    obj: JObject<'a>,
    field: &str,
    type_: &str,
) -> Result<Option<JValue<'a>>, String> {
    if env.get_field_id(obj, field, type_).is_err() {
        return Err(format!("Can't find `{}` field", field));
    }
    env.get_field(obj, field, type_)
        .map(|value| Some(value))
        .or_else(|_| Err(format!("Can't find `{}` field", field)))
}

fn get_non_null_field<'a>(
    env: &'a JNIEnv,
    obj: JObject<'a>,
    field: &str,
    type_: &str,
) -> Result<JValue<'a>, String> {
    match get_field(env, obj, field, type_)? {
        None => Err(format!("Field {} is null", field)),
        Some(f) => Ok(f),
    }
}

fn get_string(env: &JNIEnv, obj: JObject, field: &str) -> Result<Option<String>, String> {
    let value = get_field(env, obj, field, "Ljava/lang/String;")?;
    match value {
        Some(value) => {
            let string = value
                .l()
                .map_err(|_| format!("field `{}` is not an Object", field))?
                .into();
            Ok(env.get_string(string).map(|s| s.into()).ok())
        },
        None => Ok(None),
    }
}

fn get_options(
    env: &JNIEnv,
    opts: JObject,
    surface: JObject,
) -> Result<(InitOptions, bool, Option<String>, Option<String>), String> {
    let args = get_string(env, opts, "args")?;
    let url = get_string(env, opts, "url")?;
    let log_str = get_string(env, opts, "logStr")?;
    let gst_debug_str = get_string(env, opts, "gstDebugStr")?;
    let density = get_non_null_field(env, opts, "density", "F")?
        .f()
        .map_err(|_| "densitiy not a float")? as f32;
    let log = get_non_null_field(env, opts, "enableLogs", "Z")?
        .z()
        .map_err(|_| "enableLogs not a boolean")?;
    let coordinates = get_non_null_field(
        env,
        opts,
        "coordinates",
        "Lorg/mozilla/servoview/JNIServo$ServoCoordinates;",
    )?
    .l()
    .map_err(|_| "coordinates is not an object")?;
    let coordinates = jni_coords_to_rust_coords(&env, coordinates)?;

    let args = match args {
        Some(args) => serde_json::from_str(&args)
            .map_err(|_| "Invalid arguments. Servo arguments must be formatted as a JSON array")?,
        None => None,
    };

    let native_window = unsafe { ANativeWindow_fromSurface(env.get_native_interface(), surface) };

    // FIXME: enable JIT compilation on 32-bit Android after the startup crash issue (#31134) is fixed.
    let prefs = if cfg!(target_pointer_width = "32") {
        let mut prefs = HashMap::new();
        prefs.insert("js.baseline_interpreter.enabled".to_string(), false.into());
        prefs.insert("js.baseline_jit.enabled".to_string(), false.into());
        prefs.insert("js.ion.enabled".to_string(), false.into());
        Some(prefs)
    } else {
        None
    };

    let opts = InitOptions {
        args: args.unwrap_or(vec![]),
        url,
        coordinates,
        density,
        xr_discovery: None,
        surfman_integration: simpleservo::SurfmanIntegration::Widget(native_window),
        prefs,
    };

    Ok((opts, log, log_str, gst_debug_str))
}