native-activity example

This commit is contained in:
ardocrat
2023-04-10 16:02:53 +03:00
commit ed95fe341a
51 changed files with 6134 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Build hooks to spit out version+build time info
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
// build and versioning information
let mut opts = built::Options::default();
opts.set_dependencies(true);
let out_dir_path = format!("{}{}", env::var("OUT_DIR").unwrap(), "/built.rs");
// don't fail the build if something's missing, may just be cargo release
let _ = built::write_built_file_with_opts(
&opts,
Path::new(env!("CARGO_MANIFEST_DIR")),
Path::new(&out_dir_path),
);
}
+73
View File
@@ -0,0 +1,73 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::LevelFilter::{Debug, Info, Trace, Warn};
#[cfg(target_os = "android")]
use winit::platform::android::activity::AndroidApp;
use crate::gui::renderer::Event;
#[allow(dead_code)]
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app: AndroidApp) {
#[cfg(debug_assertions)]
{
std::env::set_var("RUST_BACKTRACE", "full");
android_logger::init_once(
android_logger::Config::default().with_max_level(Info).with_tag("grim"),
);
}
use winit::platform::android::EventLoopBuilderExtAndroid;
let event_loop = winit::event_loop::EventLoopBuilder::<Event>::with_user_event()
.with_android_app(app)
.build();
crate::gui::start(event_loop);
}
#[allow(dead_code)]
#[cfg(not(target_os = "android"))]
fn main() {
#[cfg(debug_assertions)]
env_logger::builder()
.filter_level(Debug)
.parse_default_env()
.init();
let event_loop = winit::event_loop::EventLoopBuilder::<Event>::with_user_event().build();
crate::gui::start(event_loop);
}
mod built_info {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
pub fn info_strings() -> (String, String) {
(
format!(
"This is Grim version {}{}, built for {} by {}.",
built_info::PKG_VERSION,
built_info::GIT_VERSION.map_or_else(|| "".to_owned(), |v| format!(" (git {})", v)),
built_info::TARGET,
built_info::RUSTC_VERSION,
),
format!(
"Built with profile \"{}\", features \"{}\".",
built_info::PROFILE,
built_info::FEATURES_STR,
),
)
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod renderer;
pub use self::renderer::start;
+328
View File
@@ -0,0 +1,328 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::iter;
use std::time::Instant;
use egui::FontDefinitions;
use egui_wgpu_backend::{RenderPass, ScreenDescriptor};
use egui_winit_platform::{Platform, PlatformDescriptor};
use log::{debug, error, trace, warn};
use wgpu::{CompositeAlphaMode, InstanceDescriptor};
use winit::event::Event::*;
use winit::event::StartCause;
use winit::event_loop::EventLoop;
use winit::event_loop::ControlFlow;
use winit::platform::run_return::EventLoopExtRunReturn;
#[derive(Debug, Clone, Copy)]
pub enum Event {
RequestRedraw,
}
pub fn start(mut event_loop: EventLoop<Event>) {
let window = winit::window::WindowBuilder::new()
.with_transparent(false)
.with_title("Grim")
.build(&event_loop)
.unwrap_or_else(|e| {
panic!(
"Failed to init window at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
});
let instance_descriptor = InstanceDescriptor::default();
let mut instance = wgpu::Instance::new(instance_descriptor);
let mut size = window.inner_size();
let outer_size = window.outer_size();
warn!("outer_size = {:?}", outer_size);
warn!("size = {:?}", size);
let mut platform = Platform::new(PlatformDescriptor {
physical_width: size.width as u32,
physical_height: size.height as u32,
scale_factor: window.scale_factor(),
font_definitions: FontDefinitions::default(),
style: Default::default(),
});
#[cfg(target_os = "android")]
let mut platform = {
event_loop.run_return(|main_event, tgt, control_flow| {
control_flow.set_poll();
warn!(
"Got event: {:?} at {} line {}",
&main_event,
file!(),
line!()
);
match main_event {
NewEvents(e) => match e {
StartCause::ResumeTimeReached { .. } => {}
StartCause::WaitCancelled { .. } => {}
StartCause::Poll => {}
StartCause::Init => {}
},
WindowEvent {
window_id,
ref event,
} => {
if let winit::event::WindowEvent::Resized(r) = event {
size = *r;
}
}
DeviceEvent { .. } => {}
UserEvent(_) => {}
Suspended => {
control_flow.set_poll();
}
Resumed => {
if let Some(primary_mon) = tgt.primary_monitor() {
size = primary_mon.size();
window.set_inner_size(size);
warn!(
"Set to new size: {:?} at {} line {}",
&size,
file!(),
line!()
);
} else if let Some(other_mon) = tgt.available_monitors().next() {
size = other_mon.size();
window.set_inner_size(size);
warn!(
"Set to new size: {:?} at {} line {}",
&size,
file!(),
line!()
);
}
control_flow.set_exit();
}
MainEventsCleared => {}
RedrawRequested(rdr) => {}
RedrawEventsCleared => {}
LoopDestroyed => {}
};
platform.handle_event(&main_event);
});
Platform::new(PlatformDescriptor {
physical_width: size.width as u32,
physical_height: size.height as u32,
scale_factor: window.scale_factor(),
font_definitions: FontDefinitions::default(),
style: Default::default(),
})
};
warn!("WGPU new surface at {} line {}", file!(), line!());
let mut surface = unsafe { instance.create_surface(&window).unwrap_or_else(|e| {
panic!(
"Failed to create surface at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
}) };
warn!("instance request_adapter at {} line {}", file!(), line!());
// WGPU 0.11+ support force fallback (if HW implementation not supported), set it to true or false (optional).
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.unwrap_or_else(|| panic!("Failed get adapter at {} line {}", file!(), line!()));
warn!("adapter request_device at {} line {}", file!(), line!());
let (device, queue) = pollster::block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::default(),
limits: wgpu::Limits::downlevel_defaults(),
label: None,
},
None,
))
.unwrap_or_else(|e| {
panic!(
"Failed to request device at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
});
let surface_capabilities = surface.get_capabilities(&adapter);
let surface_format = surface_capabilities.formats[0];
let mut surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width as u32,
height: size.height as u32,
present_mode: wgpu::PresentMode::AutoNoVsync,
alpha_mode: CompositeAlphaMode::Auto,
view_formats: vec![surface_format],
};
warn!("surface configure at {} line {}", file!(), line!());
surface.configure(&device, &surface_config);
warn!("RenderPass new at {} line {}", file!(), line!());
let mut egui_rpass = RenderPass::new(&device, surface_format, 1);
warn!("DemoWindows default at {} line {}", file!(), line!());
// Display the demo application that ships with egui.
let mut demo_app = egui_demo_lib::DemoWindows::default();
let start_time = Instant::now();
let mut in_bad_state = false;
warn!("Enter the loop");
event_loop.run(move |event, _, control_flow| {
// Pass the winit events to the platform integration.
debug!("Got event: {:?} at {} line {}", &event, file!(), line!());
platform.handle_event(&event);
match event {
RedrawRequested(..) => {
platform.update_time(start_time.elapsed().as_secs_f64());
let output_frame = match surface.get_current_texture() {
Ok(frame) => frame,
Err(wgpu::SurfaceError::Outdated) => {
// This error occurs when the app is minimized on Windows.
// Silently return here to prevent spamming the console with:
error!("The underlying surface has changed, and therefore the swap chain must be updated");
in_bad_state = true;
return;
}
Err(wgpu::SurfaceError::Lost) => {
// This error occurs when the app is minimized on Windows.
// Silently return here to prevent spamming the console with:
error!("LOST surface, drop frame. Originally: \"The swap chain has been lost and needs to be recreated\"");
in_bad_state = true;
return;
}
Err(e) => {
error!("Dropped frame with error: {}", e);
return;
}
};
let output_view = output_frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// Begin to draw the UI frame.
platform.begin_frame();
// Draw the demo application.
demo_app.ui(&platform.context());
// End the UI frame. We could now handle the output and draw the UI with the backend.
let full_output = platform.end_frame(Some(&window));
let paint_jobs = platform.context().tessellate(full_output.shapes);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("encoder"),
});
// Upload all resources for the GPU.
let screen_descriptor = ScreenDescriptor {
physical_width: surface_config.width,
physical_height: surface_config.height,
scale_factor: window.scale_factor() as f32
};
let tdelta: egui::TexturesDelta = full_output.textures_delta;
egui_rpass
.add_textures(&device, &queue, &tdelta)
.expect("add texture ok");
egui_rpass.update_buffers(&device, &queue, &paint_jobs, &screen_descriptor);
// Record all render passes.
egui_rpass
.execute(
&mut encoder,
&output_view,
&paint_jobs,
&screen_descriptor,
Some(wgpu::Color::BLACK),
)
.unwrap_or_else(|e| panic!("Failed to render pass at {} line {} with error\n{:?}", file!(), line!(), e));
// Submit the commands.
queue.submit(iter::once(encoder.finish()));
// Redraw egui
output_frame.present();
egui_rpass
.remove_textures(tdelta)
.expect("remove texture ok");
// Support reactive on windows only, but not on linux.
// if _output.needs_repaint {
// *control_flow = ControlFlow::Poll;
// } else {
// *control_flow = ControlFlow::Wait;
// }
}
MainEventsCleared | UserEvent(Event::RequestRedraw) => {
window.request_redraw();
}
WindowEvent { event, .. } => match event {
winit::event::WindowEvent::Resized(size) => {
// Resize with 0 width and height is used by winit to signal a minimize event on Windows.
// See: https://github.com/rust-windowing/winit/issues/208
// This solves an issue where the app would panic when minimizing on Windows.
if size.width > 0 && size.height > 0 {
surface_config.width = size.width;
surface_config.height = size.height;
surface.configure(&device, &surface_config);
}
}
winit::event::WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}
winit::event::WindowEvent::Focused(focused) => {
in_bad_state |= !focused;
},
_ => {}
},
Resumed => {
if in_bad_state {
//https://github.com/gfx-rs/wgpu/issues/2302
warn!("WGPU new surface at {} line {}", file!(), line!());
surface = unsafe { instance.create_surface(&window).unwrap_or_else(|e| {
panic!(
"Failed to create surface at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
}) };
warn!("surface configure at {} line {}", file!(), line!());
surface.configure(&device, &surface_config);
in_bad_state = false;
}
},
Suspended => (),
_ => (),
}
});
}
+19
View File
@@ -0,0 +1,19 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod node;
mod wallet;
mod gui;
pub mod grim;
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod node;
pub use self::node::start;
+74
View File
@@ -0,0 +1,74 @@
// // Copyright 2023 The Grin Developers
// //
// // Licensed under the Apache License, Version 2.0 (the "License");
// // you may not use this file except in compliance with the License.
// // You may obtain a copy of the License at
// //
// // http://www.apache.org/licenses/LICENSE-2.0
// //
// // Unless required by applicable law or agreed to in writing, software
// // distributed under the License is distributed on an "AS IS" BASIS,
// // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// // See the License for the specific language governing permissions and
// // limitations under the License.
use std::sync::mpsc;
use grin_config::{config, GlobalConfig};
use grin_core::global;
use grin_core::global::ChainTypes;
use grin_util::logger::LogEntry;
use log::info;
use futures::channel::oneshot;
pub fn start(chain_type: &ChainTypes) {
let node_config = Some(
config::initial_setup_server(&ChainTypes::Mainnet).unwrap_or_else(|e| {
//TODO: Error handling
panic!("Error loading server configuration: {}", e);
}),
);
let config = node_config.clone().unwrap();
let mut server_config = config.members.as_ref().unwrap().server.clone();
// Initialize our global chain_type, feature flags (NRD kernel support currently), accept_fee_base, and future_time_limit.
// These are read via global and not read from config beyond this point.
global::init_global_chain_type(config.members.as_ref().unwrap().server.chain_type);
info!("Chain: {:?}", global::get_chain_type());
match global::get_chain_type() {
ChainTypes::Mainnet => {
// Set various mainnet specific feature flags.
global::init_global_nrd_enabled(false);
}
_ => {
// Set various non-mainnet feature flags.
global::init_global_nrd_enabled(true);
}
}
let afb = config
.members
.as_ref()
.unwrap()
.server
.pool_config
.accept_fee_base;
global::init_global_accept_fee_base(afb);
info!("Accept Fee Base: {:?}", global::get_accept_fee_base());
global::init_global_future_time_limit(config.members.unwrap().server.future_time_limit);
info!("Future Time Limit: {:?}", global::get_future_time_limit());
let api_chan: &'static mut (oneshot::Sender<()>, oneshot::Receiver<()>) =
Box::leak(Box::new(oneshot::channel::<()>()));
grin_servers::Server::start(
server_config,
None,
|serv: grin_servers::Server, info: Option<mpsc::Receiver<LogEntry>>| {
serv.get_server_stats();
info!("Info callback")
//serv.stop();
},
None,
api_chan
)
.unwrap();
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod wallet;
// pub use self::wallet::{init, init_from_seed};
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2023 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub fn create_from_seed() {
}
pub fn create() {
}