Skip to content

Commit

Permalink
Merge pull request #1314 from derezzedex/dev/system-information
Browse files Browse the repository at this point in the history
feat: fetch system information
  • Loading branch information
hecrj committed May 11, 2022
2 parents d4ed8af + b440df9 commit 2e7757a
Show file tree
Hide file tree
Showing 26 changed files with 482 additions and 56 deletions.
7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ smol = ["iced_futures/smol"]
palette = ["iced_core/palette"]
# Enables pure, virtual widgets in the `pure` module
pure = ["iced_pure", "iced_graphics/pure"]
# Enables querying system information
system = ["iced_winit/system"]

[badges]
maintenance = { status = "actively-developed" }
Expand Down Expand Up @@ -82,19 +84,20 @@ members = [
"examples/stopwatch",
"examples/styling",
"examples/svg",
"examples/system_information",
"examples/todos",
"examples/tooltip",
"examples/tour",
"examples/url_handler",
"examples/websocket",
"examples/pure/component",
"examples/pure/counter",
"examples/pure/game_of_life",
"examples/pure/pane_grid",
"examples/pure/pick_list",
"examples/pure/todos",
"examples/pure/tour",
"examples/pure/tooltip",
"examples/websocket",
"examples/pure/tour",
]

[dependencies]
Expand Down
10 changes: 10 additions & 0 deletions examples/system_information/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "system_information"
version = "0.1.0"
authors = ["Richard <richardsoncusto@gmail.com>"]
edition = "2021"
publish = false

[dependencies]
iced = { path = "../..", features = ["system"] }
bytesize = { version = "1.1.0" }
165 changes: 165 additions & 0 deletions examples/system_information/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
use iced::{
button, executor, system, Application, Button, Column, Command, Container,
Element, Length, Settings, Text,
};

use bytesize::ByteSize;

pub fn main() -> iced::Result {
Example::run(Settings::default())
}

enum Example {
Loading,
Loaded {
information: system::Information,
refresh_button: button::State,
},
}

#[derive(Clone, Debug)]
enum Message {
InformationReceived(system::Information),
Refresh,
}

impl Application for Example {
type Message = Message;
type Executor = executor::Default;
type Flags = ();

fn new(_flags: ()) -> (Self, Command<Message>) {
(
Self::Loading,
system::fetch_information(Message::InformationReceived),
)
}

fn title(&self) -> String {
String::from("System Information - Iced")
}

fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Refresh => {
*self = Self::Loading;

return system::fetch_information(Message::InformationReceived);
}
Message::InformationReceived(information) => {
let refresh_button = button::State::new();
*self = Self::Loaded {
information,
refresh_button,
};
}
}

Command::none()
}

fn view(&mut self) -> Element<Message> {
let content: Element<Message> = match self {
Example::Loading => Text::new("Loading...").size(40).into(),
Example::Loaded {
information,
refresh_button,
} => {
let system_name = Text::new(format!(
"System name: {}",
information
.system_name
.as_ref()
.unwrap_or(&"unknown".to_string())
));

let system_kernel = Text::new(format!(
"System kernel: {}",
information
.system_kernel
.as_ref()
.unwrap_or(&"unknown".to_string())
));

let system_version = Text::new(format!(
"System version: {}",
information
.system_version
.as_ref()
.unwrap_or(&"unknown".to_string())
));

let cpu_brand = Text::new(format!(
"Processor brand: {}",
information.cpu_brand
));

let cpu_cores = Text::new(format!(
"Processor cores: {}",
information
.cpu_cores
.map_or("unknown".to_string(), |cores| cores
.to_string())
));

let memory_readable =
ByteSize::kb(information.memory_total).to_string();

let memory_total = Text::new(format!(
"Memory (total): {}",
format!(
"{} kb ({})",
information.memory_total, memory_readable
)
));

let memory_text = if let Some(memory_used) =
information.memory_used
{
let memory_readable = ByteSize::kb(memory_used).to_string();

format!("{} kb ({})", memory_used, memory_readable)
} else {
String::from("None")
};

let memory_used =
Text::new(format!("Memory (used): {}", memory_text));

let graphics_adapter = Text::new(format!(
"Graphics adapter: {}",
information.graphics_adapter
));

let graphics_backend = Text::new(format!(
"Graphics backend: {}",
information.graphics_backend
));

Column::with_children(vec![
system_name.size(30).into(),
system_kernel.size(30).into(),
system_version.size(30).into(),
cpu_brand.size(30).into(),
cpu_cores.size(30).into(),
memory_total.size(30).into(),
memory_used.size(30).into(),
graphics_adapter.size(30).into(),
graphics_backend.size(30).into(),
Button::new(refresh_button, Text::new("Refresh"))
.on_press(Message::Refresh)
.into(),
])
.spacing(10)
.into()
}
};

Container::new(content)
.center_x()
.center_y()
.width(Length::Fill)
.height(Length::Fill)
.into()
}
}
14 changes: 13 additions & 1 deletion glow/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub use iced_graphics::Antialiasing;
/// The settings of a [`Backend`].
///
/// [`Backend`]: crate::Backend
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Settings {
/// The bytes of the font that will be used by default.
///
Expand Down Expand Up @@ -39,6 +39,18 @@ impl Default for Settings {
}
}

impl std::fmt::Debug for Settings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Settings")
// Instead of printing the font bytes, we simply show a `bool` indicating if using a default font or not.
.field("default_font", &self.default_font.is_none())
.field("default_text_size", &self.default_text_size)
.field("text_multithreading", &self.text_multithreading)
.field("antialiasing", &self.antialiasing)
.finish()
}
}

impl Settings {
/// Creates new [`Settings`] using environment configuration.
///
Expand Down
13 changes: 12 additions & 1 deletion glow/src/window/compositor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{Backend, Color, Error, Renderer, Settings, Viewport};

use core::ffi::c_void;
use glow::HasContext;
use iced_graphics::{Antialiasing, Size};
use iced_graphics::{compositor, Antialiasing, Size};

/// A window graphics backend for iced powered by `glow`.
#[allow(missing_debug_implementations)]
Expand All @@ -20,6 +20,8 @@ impl iced_graphics::window::GLCompositor for Compositor {
) -> Result<(Self, Self::Renderer), Error> {
let gl = glow::Context::from_loader_function(loader_function);

log::info!("{:#?}", settings);

let version = gl.version();
log::info!("Version: {:?}", version);
log::info!("Embedded: {}", version.is_embedded);
Expand Down Expand Up @@ -65,6 +67,15 @@ impl iced_graphics::window::GLCompositor for Compositor {
}
}

fn fetch_information(&self) -> compositor::Information {
let adapter = unsafe { self.gl.get_parameter_string(glow::RENDERER) };

compositor::Information {
backend: format!("{:?}", self.gl.version()),
adapter,
}
}

fn present<T: AsRef<str>>(
&mut self,
renderer: &mut Self::Renderer,
Expand Down
4 changes: 4 additions & 0 deletions glutin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ categories = ["gui"]

[features]
debug = ["iced_winit/debug"]
system = ["iced_winit/system"]

[dependencies.log]
version = "0.4"

[dependencies.glutin]
version = "0.28"
Expand Down
26 changes: 24 additions & 2 deletions glutin/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ where
settings.id,
);

log::info!("Window builder: {:#?}", builder);

let opengl_builder = ContextBuilder::new()
.with_vsync(true)
.with_multisampling(C::sample_count(&compositor_settings) as u16);
Expand All @@ -75,17 +77,35 @@ where
(opengl_builder, opengles_builder)
};

log::info!("Trying first builder: {:#?}", first_builder);

let context = first_builder
.build_windowed(builder.clone(), &event_loop)
.or_else(|_| second_builder.build_windowed(builder, &event_loop))
.or_else(|_| {
log::info!("Trying second builder: {:#?}", second_builder);
second_builder.build_windowed(builder, &event_loop)
})
.map_err(|error| {
use glutin::CreationError;
use iced_graphics::Error as ContextError;

match error {
CreationError::Window(error) => {
Error::WindowCreationFailed(error)
}
_ => Error::GraphicsAdapterNotFound,
CreationError::OpenGlVersionNotSupported => {
Error::GraphicsCreationFailed(
ContextError::VersionNotSupported,
)
}
CreationError::NoAvailablePixelFormat => {
Error::GraphicsCreationFailed(
ContextError::NoAvailablePixelFormat,
)
}
error => Error::GraphicsCreationFailed(
ContextError::BackendError(error.to_string()),
),
}
})?;

Expand All @@ -110,6 +130,7 @@ where
&mut clipboard,
&mut proxy,
context.window(),
|| compositor.fetch_information(),
);
runtime.track(subscription);

Expand Down Expand Up @@ -244,6 +265,7 @@ async fn run_instance<A, E, C>(
&mut debug,
&mut messages,
context.window(),
|| compositor.fetch_information(),
);

// Update window
Expand Down
13 changes: 2 additions & 11 deletions glutin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,11 @@
#![forbid(rust_2018_idioms)]

pub use glutin;

#[doc(no_inline)]
pub use iced_native::*;
pub use iced_winit::*;

pub mod application;

pub use iced_winit::clipboard;
pub use iced_winit::conversion;
pub use iced_winit::settings;
pub use iced_winit::window;
pub use iced_winit::{Error, Mode};

#[doc(no_inline)]
pub use application::Application;
#[doc(no_inline)]
pub use clipboard::Clipboard;
#[doc(no_inline)]
pub use settings::Settings;
18 changes: 15 additions & 3 deletions graphics/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
/// A graphical error that occurred while running an application.
/// An error that occurred while creating an application's graphical context.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// A suitable graphics adapter or device could not be found
/// The requested backend version is not supported.
#[error("the requested backend version is not supported")]
VersionNotSupported,

/// Failed to find any pixel format that matches the criteria.
#[error("failed to find any pixel format that matches the criteria")]
NoAvailablePixelFormat,

/// A suitable graphics adapter or device could not be found.
#[error("a suitable graphics adapter or device could not be found")]
AdapterNotFound,
GraphicsAdapterNotFound,

/// An error occured in the context's internal backend
#[error("an error occured in the context's internal backend")]
BackendError(String),
}
1 change: 1 addition & 0 deletions graphics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub use primitive::Primitive;
pub use renderer::Renderer;
pub use transformation::Transformation;
pub use viewport::Viewport;
pub use window::compositor;

pub use iced_native::alignment;
pub use iced_native::{
Expand Down
Loading

0 comments on commit 2e7757a

Please sign in to comment.