-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathos_api.rs
523 lines (481 loc) · 18.5 KB
/
os_api.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
use openxr_sys::pfn::{
EnumerateDisplayRefreshRatesFB, EnumerateEnvironmentBlendModes, GetDisplayRefreshRateFB,
RequestDisplayRefreshRateFB,
};
use openxr_sys::{EnvironmentBlendMode, Instance, Result, Session, SystemId, ViewConfigurationType};
use crate::sk::SkInfo;
use crate::system::{Backend, BackendOpenXR, BackendXRType, Log};
use std::ffi::OsString;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::{cell::RefCell, rc::Rc};
pub enum PathEntry {
File(OsString),
Dir(OsString),
}
/// For bin tools only
pub fn get_shaders_source_dir() -> String {
std::env::var("SK_RUST_SHADERS_SOURCE_DIR").unwrap_or("shaders_src".into())
}
/// Where sks shaders are store under assets dir. For bin tools and none android exe. For Android use app.asset_manager()
pub fn get_shaders_sks_dir() -> String {
std::env::var("SK_RUST_SHADERS_SKS_DIR").unwrap_or("shaders".into())
}
/// For bin tools and non android exe. For Android use app.asset_manager()
pub fn get_assets_dir() -> String {
std::env::var("SK_RUST_ASSETS_DIR").unwrap_or("assets".into())
}
/// Read all the assets of a given assets sub directory
#[cfg(target_os = "android")]
pub fn get_assets(sk_info: Rc<RefCell<SkInfo>>, sub_dir: PathBuf, file_extensions: &Vec<String>) -> Vec<PathEntry> {
use std::ffi::CString;
let mut sk_i = sk_info.borrow_mut();
let app = sk_i.get_android_app();
let mut exts = vec![];
for extension in file_extensions {
let extension = extension[1..].to_string();
exts.push(OsString::from(extension));
}
let mut vec = vec![];
if let Ok(cstring) = CString::new(sub_dir.to_str().unwrap_or("Error!!!")) {
if let Some(asset_dir) = app.asset_manager().open_dir(cstring.as_c_str()) {
for entry in asset_dir {
if let Ok(entry_string) = entry.into_string() {
let path = PathBuf::from(entry_string.clone());
if exts.is_empty() {
if let Some(file_name) = path.file_name() {
vec.push(PathEntry::File(file_name.into()))
} else {
Log::err(format!("get_assets, path {:?} don't have a file_name", path));
}
} else if let Some(extension) = path.extension() {
if exts.contains(&extension.to_os_string()) {
if let Some(file_name) = path.file_name() {
vec.push(PathEntry::File(file_name.into()))
}
}
}
}
}
}
}
vec
}
/// Read all the assets of a given assets sub directory
#[cfg(not(target_os = "android"))]
pub fn get_assets(_sk_info: Rc<RefCell<SkInfo>>, sub_dir: PathBuf, file_extensions: &Vec<String>) -> Vec<PathEntry> {
use std::{env, fs::read_dir};
let sub_dir = sub_dir.to_str().unwrap_or("");
let mut exts = vec![];
for extension in file_extensions {
let extension = extension[1..].to_string();
exts.push(OsString::from(extension));
}
let path_text = env::current_dir().unwrap().to_owned().join(get_assets_dir());
let path_asset = path_text.join(sub_dir);
let mut vec = vec![];
if path_asset.exists() {
if path_asset.is_dir() {
match read_dir(&path_asset) {
Ok(read_dir) => {
for file in read_dir.flatten() {
let path = file.path();
if file.path().is_file() {
if exts.is_empty() {
vec.push(PathEntry::File(file.file_name()))
} else if let Some(extension) = path.extension() {
if exts.is_empty() || exts.contains(&extension.to_os_string()) {
vec.push(PathEntry::File(file.file_name()))
}
}
}
}
}
Err(err) => {
Log::diag(format!("Unable to read {:?}: {}", path_asset, err));
}
}
} else {
Log::diag(format!("{:?} is not a dir", path_asset));
}
} else {
Log::diag(format!("{:?} do not exists", path_asset));
}
vec
}
/// Get the path to internal data directory for Android
#[cfg(target_os = "android")]
pub fn get_internal_path(sk_info: Rc<RefCell<SkInfo>>) -> Option<PathBuf> {
let mut sk_i = sk_info.borrow_mut();
let app = sk_i.get_android_app();
app.internal_data_path()
}
/// Get the path to internal data directory for non android
#[cfg(not(target_os = "android"))]
pub fn get_internal_path(_sk_info: Rc<RefCell<SkInfo>>) -> Option<PathBuf> {
None
}
/// Get the path to external data directory for Android
#[cfg(target_os = "android")]
pub fn get_external_path(sk_info: Rc<RefCell<SkInfo>>) -> Option<PathBuf> {
let mut sk_i = sk_info.borrow_mut();
let app = sk_i.get_android_app();
app.external_data_path()
}
/// Get the path to internal data directory for non android (assets)
#[cfg(not(target_os = "android"))]
pub fn get_external_path(_sk_info: Rc<RefCell<SkInfo>>) -> Option<PathBuf> {
use std::env;
let path_assets = env::current_dir().unwrap().join(get_assets_dir());
Some(path_assets)
}
/// Open an asset like a file
#[cfg(target_os = "android")]
pub fn open_asset(sk_info: Rc<RefCell<SkInfo>>, asset_path: impl AsRef<Path>) -> Option<File> {
use std::ffi::CString;
let mut sk_i = sk_info.borrow_mut();
let app = sk_i.get_android_app();
if let Ok(cstring) = CString::new(asset_path.as_ref().to_str().unwrap_or("Error!!!")) {
if let Some(asset) = app.asset_manager().open(cstring.as_c_str()) {
if let Ok(o_file_desc) = asset.open_file_descriptor() {
Some(File::from(o_file_desc.fd))
} else {
Log::err(format!("open_asset, {:?} cannot get a new file_descriptor", asset_path.as_ref()));
None
}
} else {
Log::err(format!("open_asset, path {:?} cannot be a opened", asset_path.as_ref()));
None
}
} else {
Log::err(format!("open_asset, path {:?} cannot be a cstring", asset_path.as_ref()));
None
}
}
/// Open an asset like a file
#[cfg(not(target_os = "android"))]
pub fn open_asset(_sk_info: Rc<RefCell<SkInfo>>, asset_path: impl AsRef<Path>) -> Option<File> {
use std::env;
let path_assets = env::current_dir().unwrap().join(get_assets_dir());
let path_asset = path_assets.join(asset_path);
File::open(path_asset).ok()
}
/// Read the files and eventually the sub directory of a given directory
pub fn get_files(
_sk_info: Rc<RefCell<SkInfo>>,
dir: PathBuf,
file_extensions: &Vec<String>,
show_other_dirs: bool,
) -> Vec<PathEntry> {
use std::fs::read_dir;
let mut exts = vec![];
for extension in file_extensions {
exts.push(OsString::from(extension));
}
let mut vec = vec![];
if dir.exists() && dir.is_dir() {
if let Ok(read_dir) = read_dir(dir) {
for file in read_dir.flatten() {
let path = file.path();
if file.path().is_file() {
if exts.is_empty() {
vec.push(PathEntry::File(file.file_name()))
} else if let Some(extension) = path.extension() {
if exts.is_empty() || exts.contains(&extension.to_os_string()) {
vec.push(PathEntry::File(file.file_name()))
}
}
} else if show_other_dirs && file.path().is_dir() {
vec.push(PathEntry::Dir(file.file_name()))
}
}
}
}
vec
}
/// Open winit IME keyboard
#[cfg(target_os = "android")]
pub fn show_soft_input_ime(sk_info: Rc<RefCell<SkInfo>>, show: bool) -> bool {
let mut sk_i = sk_info.borrow_mut();
let app = sk_i.get_android_app();
if show {
app.show_soft_input(false);
} else {
app.hide_soft_input(false);
}
true
}
/// Open nothing has we don't have a winit IME keyboard
#[cfg(not(target_os = "android"))]
pub fn show_soft_input_ime(_sk_info: Rc<RefCell<SkInfo>>, _show: bool) -> bool {
false
}
/// Open Android IMS keyboard
#[cfg(target_os = "android")]
pub fn show_soft_input(show: bool) -> bool {
use jni::objects::JValue;
let ctx = ndk_context::android_context();
let vm = match unsafe { jni::JavaVM::from_raw(ctx.vm() as _) } {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no vm !! : {:?}", e));
return false;
}
};
let activity = unsafe { jni::objects::JObject::from_raw(ctx.context() as _) };
let mut env = match vm.attach_current_thread() {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no env !! : {:?}", e));
return false;
}
};
let class_ctxt = match env.find_class("android/content/Context") {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no class_ctxt !! : {:?}", e));
return false;
}
};
let ims = match env.get_static_field(class_ctxt, "INPUT_METHOD_SERVICE", "Ljava/lang/String;") {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no ims !! : {:?}", e));
return false;
}
};
let im_manager = match env
.call_method(&activity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", &[ims.borrow()])
.unwrap()
.l()
{
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no im_manager !! : {:?}", e));
return false;
}
};
let jni_window = match env.call_method(&activity, "getWindow", "()Landroid/view/Window;", &[]).unwrap().l() {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no jni_window !! : {:?}", e));
return false;
}
};
let view = match env.call_method(jni_window, "getDecorView", "()Landroid/view/View;", &[]).unwrap().l() {
Ok(value) => value,
Err(e) => {
Log::err(format!("virtual_kbd : no view !! : {:?}", e));
return false;
}
};
if show {
let result = env
.call_method(im_manager, "showSoftInput", "(Landroid/view/View;I)Z", &[JValue::Object(&view), 0i32.into()])
.unwrap()
.z()
.unwrap();
result
} else {
let window_token = env.call_method(view, "getWindowToken", "()Landroid/os/IBinder;", &[]).unwrap().l().unwrap();
let jvalue_window_token = jni::objects::JValueGen::Object(&window_token);
let result = env
.call_method(
im_manager,
"hideSoftInputFromWindow",
"(Landroid/os/IBinder;I)Z",
&[jvalue_window_token, 0i32.into()],
)
.unwrap()
.z()
.unwrap();
result
}
}
/// Open nothing has we don't have a virtual keyboard
#[cfg(not(target_os = "android"))]
pub fn show_soft_input(_show: bool) -> bool {
false
}
pub const USUAL_FPS_SUSPECTS: [i32; 12] = [30, 60, 72, 80, 90, 100, 110, 120, 144, 165, 240, 360];
/// Return and maybe Log all the display refresh rates available.
pub fn get_all_display_refresh_rates(with_log: bool) -> Vec<f32> {
let mut array = [0.0; 40];
let mut count = 5u32;
if BackendOpenXR::ext_enabled("XR_FB_display_refresh_rate") {
if let Some(rate_display) =
BackendOpenXR::get_function::<EnumerateDisplayRefreshRatesFB>("xrEnumerateDisplayRefreshRatesFB")
{
match unsafe {
rate_display(Session::from_raw(BackendOpenXR::session()), 0, &mut count, array.as_mut_ptr())
} {
Result::SUCCESS => {
if count > 40 {
count = 40
}
match unsafe {
rate_display(Session::from_raw(BackendOpenXR::session()), count, &mut count, array.as_mut_ptr())
} {
Result::SUCCESS => {
if with_log {
Log::info(format!("There is {} display rate:", count));
for (i, iter) in array.iter().enumerate() {
if i >= count as usize {
break;
}
Log::info(format!(" {:?} ", iter));
}
}
}
otherwise => {
Log::err(format!("xrEnumerateDisplayRefreshRatesFB failed: {otherwise}"));
}
}
}
otherwise => {
Log::err(format!("xrEnumerateDisplayRefreshRatesFB failed: {otherwise}"));
}
}
} else {
Log::err("xrEnumerateDisplayRefreshRatesFB binding function error !")
}
}
array[0..(count as usize)].into()
}
/// Get the display rates available from the given list
/// (see also USUAL_FPS_SUSPECT)
pub fn get_display_refresh_rates(fps_to_get: &[i32], with_log: bool) -> Vec<f32> {
let default_refresh_rate = get_display_refresh_rate();
let mut available_rates = vec![];
for rate in fps_to_get {
if set_display_refresh_rate(*rate as f32, false) {
available_rates.push(*rate as f32);
}
}
if let Some(rate) = default_refresh_rate {
set_display_refresh_rate(rate, with_log);
}
if with_log {
Log::info(format!("There is {} display rate from the given selection:", available_rates.len()));
for iter in &available_rates {
Log::info(format!(" {:?} ", iter));
}
}
available_rates
}
/// Get the current display rate if possible
pub fn get_display_refresh_rate() -> Option<f32> {
if BackendOpenXR::ext_enabled("XR_FB_display_refresh_rate") {
if let Some(get_default_rate) =
BackendOpenXR::get_function::<GetDisplayRefreshRateFB>("xrGetDisplayRefreshRateFB")
{
let mut default_rate = 0.0;
match unsafe { get_default_rate(Session::from_raw(BackendOpenXR::session()), &mut default_rate) } {
Result::SUCCESS => Some(default_rate),
otherwise => {
Log::err(format!("xrGetDisplayRefreshRateFB failed: {otherwise}"));
None
}
}
} else {
Log::err("xrRequestDisplayRefreshRateFB binding function error !");
None
}
} else {
None
}
}
/// set the current display rate if possible.
/// Possible values on Quest are 60 - 80 - 72 - 90 - 120
/// returns true if the given value was accepted
pub fn set_display_refresh_rate(rate: f32, with_log: bool) -> bool {
if BackendOpenXR::ext_enabled("XR_FB_display_refresh_rate") {
//>>>>>>>>>>> Set the value
if let Some(set_new_rate) =
BackendOpenXR::get_function::<RequestDisplayRefreshRateFB>("xrRequestDisplayRefreshRateFB")
{
match unsafe { set_new_rate(Session::from_raw(BackendOpenXR::session()), rate) } {
Result::SUCCESS => true,
otherwise => {
if with_log {
Log::err(format!("xrRequestDisplayRefreshRateFB failed: {otherwise}"));
}
false
}
}
} else {
Log::err("xrRequestDisplayRefreshRateFB binding function error !");
false
}
} else {
false
}
}
/// Get the list of environnement blend_modes available on this device
/// see also [`crate::system::Device::valid_blend()`]
pub fn get_env_blend_modes(with_log: bool) -> Vec<EnvironmentBlendMode> {
//>>>>>>>>>>> Get the env blend mode
let mut count = 0u32;
let mut modes = [EnvironmentBlendMode::OPAQUE; 20];
if Backend::xr_type() != BackendXRType::OpenXR {
return vec![];
}
if let Some(get_modes) =
BackendOpenXR::get_function::<EnumerateEnvironmentBlendModes>("xrEnumerateEnvironmentBlendModes")
{
match unsafe {
get_modes(
Instance::from_raw(BackendOpenXR::instance()),
SystemId::from_raw(BackendOpenXR::system_id()),
ViewConfigurationType::PRIMARY_STEREO,
0,
&mut count,
modes.as_mut_ptr(),
)
} {
Result::SUCCESS => {
if with_log {
if count > 20 {
count = 20
}
match unsafe {
get_modes(
Instance::from_raw(BackendOpenXR::instance()),
SystemId::from_raw(BackendOpenXR::system_id()),
ViewConfigurationType::PRIMARY_STEREO,
count,
&mut count,
modes.as_mut_ptr(),
)
} {
Result::SUCCESS => {
if with_log {
Log::info(format!("There is {} env blend modes:", count));
for (i, iter) in modes.iter().enumerate() {
if i >= count as usize {
break;
}
Log::info(format!(" {:?} ", iter));
}
}
}
otherwise => {
if with_log {
Log::err(format!("xrEnumerateEnvironmentBlendModes failed: {otherwise}"));
}
}
}
}
}
otherwise => {
if with_log {
Log::err(format!("xrEnumerateEnvironmentBlendModes failed: {otherwise}"));
}
}
}
} else {
Log::err("xrEnumerateEnvironmentBlendModes binding function error !");
}
modes[0..(count as usize)].into()
}