/
jniapi.rs
695 lines (621 loc) · 19.3 KB
/
jniapi.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
/* 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)]
use android_logger::{self, Filter};
use crate::api::{self, EventLoopWaker, HostTrait, InitOptions, ReadFileTrait, ServoGlue, SERVO};
use crate::gl_glue;
use jni::objects::{GlobalRef, JClass, JObject, JString, JValue};
use jni::sys::{jboolean, jfloat, jint, jstring, JNI_TRUE};
use jni::{errors, JNIEnv, JavaVM};
use libc::{dup2, pipe, read};
use log::Level;
use std::os::raw::{c_char, c_int, c_void};
use std::sync::{Arc, Mutex};
use std::thread;
struct HostCallbacks {
callbacks: GlobalRef,
jvm: JavaVM,
}
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 fn Java_org_mozilla_servoview_JNIServo_version(env: JNIEnv, _class: JClass) -> jstring {
let v = api::servo_version();
new_string(&env, &v).unwrap_or_else(|null| null)
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_init(
env: JNIEnv,
_: JClass,
activity: JObject,
opts: JObject,
callbacks_obj: JObject,
) {
let (opts, log, log_str) = match get_options(&env, opts) {
Ok((opts, log, log_str)) => (opts, log, log_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 = [
"simpleservo::api",
"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 = Filter::default().with_min_level(Level::Debug);
for &module in &filters {
filter = filter.with_allowed_module_path(module);
}
if let Some(log_str) = log_str {
for module in log_str.split(',') {
filter = filter.with_allowed_module_path(module);
}
}
android_logger::init_once(filter, Some("simpleservo"));
}
info!("init");
initialize_android_glue(&env, activity);
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 readfile = Box::new(ReadFileCallback::new(callbacks_ref.clone(), &env));
let callbacks = Box::new(HostCallbacks::new(callbacks_ref, &env));
if let Err(err) =
gl_glue::egl::init().and_then(|gl| api::init(opts, gl, wakeup, readfile, callbacks))
{
throw(&env, err)
};
}
#[no_mangle]
pub 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 fn Java_org_mozilla_servoview_JNIServo_requestShutdown(env: JNIEnv, _class: JClass) {
debug!("requestShutdown");
call(&env, |s| s.request_shutdown());
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_deinit(_env: JNIEnv, _class: JClass) {
debug!("deinit");
api::deinit();
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_resize(
env: JNIEnv,
_: JClass,
width: jint,
height: jint,
) {
debug!("resize {}/{}", width, height);
call(&env, |s| s.resize(width as u32, height as u32));
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_performUpdates(env: JNIEnv, _class: JClass) {
debug!("performUpdates");
call(&env, |s| s.perform_updates());
}
#[no_mangle]
pub 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 fn Java_org_mozilla_servoview_JNIServo_reload(env: JNIEnv, _class: JClass) {
debug!("reload");
call(&env, |s| s.reload());
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_stop(env: JNIEnv, _class: JClass) {
debug!("stop");
call(&env, |s| s.stop());
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_refresh(env: JNIEnv, _class: JClass) {
debug!("refresh");
call(&env, |s| s.refresh());
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_goBack(env: JNIEnv, _class: JClass) {
debug!("goBack");
call(&env, |s| s.go_back());
}
#[no_mangle]
pub fn Java_org_mozilla_servoview_JNIServo_goForward(env: JNIEnv, _class: JClass) {
debug!("goForward");
call(&env, |s| s.go_forward());
}
#[no_mangle]
pub 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 i32, dy as i32, x as u32, y as u32)
});
}
#[no_mangle]
pub 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 i32, dy as i32, x as u32, y as u32)
});
}
#[no_mangle]
pub 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 i32, dy as i32, x as u32, y as u32));
}
#[no_mangle]
pub 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 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 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 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 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 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 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 fn Java_org_mozilla_servoview_JNIServo_click(env: JNIEnv, _: JClass, x: jint, y: jint) {
debug!("click");
call(&env, |s| s.click(x as u32, y as u32));
}
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(&self) -> Box<EventLoopWaker + Send> {
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();
}
}
pub struct ReadFileCallback {
callback: Mutex<GlobalRef>,
jvm: JavaVM,
}
impl ReadFileCallback {
pub fn new(callback: GlobalRef, env: &JNIEnv) -> ReadFileCallback {
let jvm = env.get_java_vm().unwrap();
let callback = Mutex::new(callback);
ReadFileCallback { callback, jvm }
}
}
impl ReadFileTrait for ReadFileCallback {
fn readfile(&self, file: &str) -> Vec<u8> {
// FIXME: we'd rather use attach_current_thread but it detaches the VM too early.
let env = self.jvm.attach_current_thread_as_daemon().unwrap();
let s = match new_string(&env, &file) {
Ok(s) => s,
Err(_) => return vec![],
};
let s = JValue::from(JObject::from(s));
let array = env.call_method(
self.callback.lock().unwrap().as_obj(),
"readfile",
"(Ljava/lang/String;)[B",
&[s],
);
let array = array.unwrap().l().unwrap().into_inner();
env.convert_byte_array(array).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 flush(&self) {
debug!("flush");
let env = self.jvm.get_env().unwrap();
env.call_method(self.callbacks.as_obj(), "flush", "()V", &[])
.unwrap();
}
fn make_current(&self) {
debug!("make_current");
let env = self.jvm.get_env().unwrap();
env.call_method(self.callbacks.as_obj(), "makeCurrent", "()V", &[])
.unwrap();
}
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: String) {
debug!("on_title_changed");
let env = self.jvm.get_env().unwrap();
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_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 initialize_android_glue(env: &JNIEnv, activity: JObject) {
use android_injected_glue::{ffi, ANDROID_APP};
// From jni-rs to android_injected_glue
let mut app: ffi::android_app = unsafe { std::mem::zeroed() };
let mut native_activity: ffi::ANativeActivity = unsafe { std::mem::zeroed() };
let clazz = Box::into_raw(Box::new(env.new_global_ref(activity).unwrap()));
native_activity.clazz = unsafe { (*clazz).as_obj().into_inner() as *mut c_void };
let vm = env.get_java_vm().unwrap().get_java_vm_pointer();
native_activity.vm = vm as *mut ffi::_JavaVM;
app.activity = Box::into_raw(Box::new(native_activity));
unsafe {
ANDROID_APP = Box::into_raw(Box::new(app));
}
}
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 get_field<'a>(
env: &'a JNIEnv,
obj: JObject,
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(|e| match *e.kind() {
errors::ErrorKind::NullPtr(_) => Ok(None),
_ => Err(format!(
"Can't find `{}` field: {}",
&field,
e.description()
)),
})
}
fn get_non_null_field<'a>(
env: &'a JNIEnv,
obj: JObject,
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) -> Result<(InitOptions, bool, 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 width = get_non_null_field(env, opts, "width", "I")?
.i()
.map_err(|_| "width not an int")? as u32;
let height = get_non_null_field(env, opts, "height", "I")?
.i()
.map_err(|_| "height not an int")? as u32;
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 enable_subpixel_text_antialiasing =
get_non_null_field(env, opts, "enableSubpixelTextAntialiasing", "Z")?
.z()
.map_err(|_| "enableSubpixelTextAntialiasing not a boolean")?;
let opts = InitOptions {
args,
url,
width,
height,
density,
enable_subpixel_text_antialiasing,
};
Ok((opts, log, log_str))
}