repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/either.rs | druid/src/widget/either.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget that switches dynamically between two child views.
use crate::debug_state::DebugState;
use crate::widget::prelude::*;
use crate::{Data, Point, WidgetPod};
use tracing::instrument;
/// A widget that switches between two possible child views.
pub struct Either<T> {
closure: Box<dyn Fn(&T, &Env) -> bool>,
true_branch: WidgetPod<T, Box<dyn Widget<T>>>,
false_branch: WidgetPod<T, Box<dyn Widget<T>>>,
current: bool,
}
impl<T> Either<T> {
/// Create a new widget that switches between two views.
///
/// The given closure is evaluated on data change. If its value is `true`, then
/// the `true_branch` widget is shown, otherwise `false_branch`.
pub fn new(
closure: impl Fn(&T, &Env) -> bool + 'static,
true_branch: impl Widget<T> + 'static,
false_branch: impl Widget<T> + 'static,
) -> Either<T> {
Either {
closure: Box::new(closure),
true_branch: WidgetPod::new(true_branch).boxed(),
false_branch: WidgetPod::new(false_branch).boxed(),
current: false,
}
}
}
impl<T: Data> Widget<T> for Either<T> {
#[instrument(name = "Either", level = "trace", skip(self, ctx, event, data, env), fields(branch = self.current))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
if event.should_propagate_to_hidden() {
self.true_branch.event(ctx, event, data, env);
self.false_branch.event(ctx, event, data, env);
} else {
self.current_widget().event(ctx, event, data, env)
}
}
#[instrument(name = "Either", level = "trace", skip(self, ctx, event, data, env), fields(branch = self.current))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
if let LifeCycle::WidgetAdded = event {
self.current = (self.closure)(data, env);
}
if event.should_propagate_to_hidden() {
self.true_branch.lifecycle(ctx, event, data, env);
self.false_branch.lifecycle(ctx, event, data, env);
} else {
self.current_widget().lifecycle(ctx, event, data, env)
}
}
#[instrument(name = "Either", level = "trace", skip(self, ctx, _old_data, data, env), fields(branch = self.current))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
let current = (self.closure)(data, env);
if current != self.current {
self.current = current;
ctx.children_changed();
}
self.current_widget().update(ctx, data, env)
}
#[instrument(name = "Either", level = "trace", skip(self, ctx, bc, data, env), fields(branch = self.current))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let current_widget = self.current_widget();
let size = current_widget.layout(ctx, bc, data, env);
current_widget.set_origin(ctx, Point::ORIGIN);
ctx.set_paint_insets(current_widget.paint_insets());
size
}
#[instrument(name = "Either", level = "trace", skip(self, ctx, data, env), fields(branch = self.current))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
self.current_widget().paint(ctx, data, env)
}
fn debug_state(&self, data: &T) -> DebugState {
let current_widget = if self.current {
&self.true_branch
} else {
&self.false_branch
};
DebugState {
display_name: self.short_type_name().to_string(),
children: vec![current_widget.widget().debug_state(data)],
..Default::default()
}
}
}
impl<T> Either<T> {
fn current_widget(&mut self) -> &mut WidgetPod<T, Box<dyn Widget<T>>> {
if self.current {
&mut self.true_branch
} else {
&mut self.false_branch
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/scope.rs | druid/src/widget/scope.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use std::marker::PhantomData;
use crate::widget::prelude::*;
use crate::widget::WidgetWrapper;
use crate::{Data, Lens, Point, WidgetPod};
use tracing::instrument;
/// A policy that controls how a [`Scope`] will interact with its surrounding
/// application data. Specifically, how to create an initial State from the
/// input, and how to synchronise the two using a [`ScopeTransfer`].
///
/// [`Scope`]: struct.Scope.html
/// [`ScopeTransfer`]: trait.ScopeTransfer.html
pub trait ScopePolicy {
/// The type of data that comes in from the surrounding application or scope.
type In: Data;
/// The type of data that the `Scope` will maintain internally.
/// This will usually be larger than the input data, and will embed the input data.
type State: Data;
/// The type of transfer that will be used to synchronise internal and application state
type Transfer: ScopeTransfer<In = Self::In, State = Self::State>;
/// Make a new state and transfer from the input.
///
/// This consumes the policy, so non-cloneable items can make their way
/// into the state this way.
fn create(self, inner: &Self::In) -> (Self::State, Self::Transfer);
}
/// A `ScopeTransfer` knows how to synchronise input data with its counterpart
/// within a [`Scope`].
///
/// It is separate from the policy mainly to allow easy use of lenses to do
/// synchronisation, with a custom [`ScopePolicy`].
///
/// [`Scope`]: struct.Scope.html
/// [`ScopePolicy`]: trait.ScopePolicy.html
pub trait ScopeTransfer {
/// The type of data that comes in from the surrounding application or scope.
type In: Data;
/// The type of data that the Scope will maintain internally.
type State: Data;
/// Replace the input we have within our State with a new one from outside
fn read_input(&self, state: &mut Self::State, input: &Self::In);
/// Take the modifications we have made and write them back
/// to our input.
fn write_back_input(&self, state: &Self::State, input: &mut Self::In);
}
/// A default implementation of [`ScopePolicy`] that takes a function and a transfer.
///
/// [`ScopePolicy`]: trait.ScopePolicy.html
pub struct DefaultScopePolicy<F: FnOnce(Transfer::In) -> Transfer::State, Transfer: ScopeTransfer> {
make_state: F,
transfer: Transfer,
}
impl<F: FnOnce(Transfer::In) -> Transfer::State, Transfer: ScopeTransfer>
DefaultScopePolicy<F, Transfer>
{
/// Create a `ScopePolicy` from a factory function and a `ScopeTransfer`.
pub fn new(make_state: F, transfer: Transfer) -> Self {
DefaultScopePolicy {
make_state,
transfer,
}
}
}
impl<F: FnOnce(In) -> State, L: Lens<State, In>, In: Data, State: Data>
DefaultScopePolicy<F, LensScopeTransfer<L, In, State>>
{
/// Create a `ScopePolicy` from a factory function and a lens onto that
/// `Scope`'s state.
pub fn from_lens(make_state: F, lens: L) -> Self {
Self::new(make_state, LensScopeTransfer::new(lens))
}
}
impl<F: FnOnce(Transfer::In) -> Transfer::State, Transfer: ScopeTransfer> ScopePolicy
for DefaultScopePolicy<F, Transfer>
{
type In = Transfer::In;
type State = Transfer::State;
type Transfer = Transfer;
fn create(self, input: &Self::In) -> (Self::State, Self::Transfer) {
let state = (self.make_state)(input.clone());
(state, self.transfer)
}
}
/// A `ScopeTransfer` that uses a Lens to synchronise between a large internal
/// state and a small input.
pub struct LensScopeTransfer<L: Lens<State, In>, In, State> {
lens: L,
phantom_in: PhantomData<In>,
phantom_state: PhantomData<State>,
}
impl<L: Lens<State, In>, In, State> LensScopeTransfer<L, In, State> {
/// Create a `ScopeTransfer` from a Lens onto a portion of the `Scope`'s state.
pub fn new(lens: L) -> Self {
LensScopeTransfer {
lens,
phantom_in: PhantomData,
phantom_state: PhantomData,
}
}
}
impl<L: Lens<State, In>, In: Data, State: Data> ScopeTransfer for LensScopeTransfer<L, In, State> {
type In = In;
type State = State;
fn read_input(&self, state: &mut State, data: &In) {
self.lens.with_mut(state, |inner| {
if !inner.same(data) {
*inner = data.clone()
}
});
}
fn write_back_input(&self, state: &State, data: &mut In) {
self.lens.with(state, |inner| {
if !inner.same(data) {
*data = inner.clone();
}
});
}
}
enum ScopeContent<SP: ScopePolicy> {
Policy {
policy: Option<SP>,
},
Transfer {
state: SP::State,
transfer: SP::Transfer,
},
}
/// A widget that allows encapsulation of application state.
///
/// This is useful in circumstances where
/// * A (potentially reusable) widget is composed of a tree of multiple cooperating child widgets
/// * Those widgets communicate amongst themselves using Druid's reactive data mechanisms
/// * It is undesirable to complicate the surrounding application state with the internal details
/// of the widget.
///
///
/// Examples include:
/// * In a tabs widget composed of a tab bar, and a widget switching body, those widgets need to
/// cooperate on which tab is selected. However not every user of a tabs widget wishes to
/// encumber their application state with this internal detail - especially as many tabs widgets may
/// reasonably exist in an involved application.
/// * In a table/grid widget composed of various internal widgets, many things need to be synchronised.
/// Scroll position, heading moves, drag operations, sort/filter operations. For many applications
/// access to this internal data outside of the table widget isn't needed.
/// For this reason it may be useful to use a Scope to establish private state.
///
/// A scope embeds some input state (from its surrounding application or parent scope)
/// into a larger piece of internal state. This is controlled by a user provided policy.
///
/// The ScopePolicy needs to do two things
/// a) Create a new scope from the initial value of its input,
/// b) Provide two way synchronisation between the input and the state via a ScopeTransfer
///
/// Convenience methods are provided to make a policy from a function and a lens.
/// It may sometimes be advisable to implement ScopePolicy directly if you need to
/// mention the type of a Scope.
///
/// # Examples
/// ```
/// use druid::{Data, Lens, WidgetExt};
/// use druid::widget::{TextBox, Scope};
/// #[derive(Clone, Data, Lens)]
/// struct AppState {
/// name: String,
/// }
///
/// #[derive(Clone, Data, Lens)]
/// struct PrivateState {
/// text: String,
/// other: u32,
/// }
///
/// impl PrivateState {
/// pub fn new(text: String) -> Self {
/// PrivateState { text, other: 0 }
/// }
/// }
///
/// fn main() {
/// let scope = Scope::from_lens(
/// PrivateState::new,
/// PrivateState::text,
/// TextBox::new().lens(PrivateState::text),
/// );
/// }
/// ```
pub struct Scope<SP: ScopePolicy, W: Widget<SP::State>> {
content: ScopeContent<SP>,
inner: WidgetPod<SP::State, W>,
}
impl<SP: ScopePolicy, W: Widget<SP::State>> Scope<SP, W> {
/// Create a new scope from a policy and an inner widget
pub fn new(policy: SP, inner: W) -> Self {
Scope {
content: ScopeContent::Policy {
policy: Some(policy),
},
inner: WidgetPod::new(inner),
}
}
/// A reference to the contents of the `Scope`'s state.
///
/// This allows you to access the content from outside the widget.
pub fn state(&self) -> Option<&SP::State> {
if let ScopeContent::Transfer { ref state, .. } = &self.content {
Some(state)
} else {
None
}
}
/// A mutable reference to the contents of the [`Scope`]'s state.
///
/// This allows you to mutably access the content of the `Scope`' s state from
/// outside the widget. Mainly useful for composite widgets.
///
/// # Note:
///
/// If you modify the state through this reference, the Scope will not
/// call update on its children until the next event it receives.
pub fn state_mut(&mut self) -> Option<&mut SP::State> {
if let ScopeContent::Transfer { ref mut state, .. } = &mut self.content {
Some(state)
} else {
None
}
}
fn with_state<V>(
&mut self,
data: &SP::In,
mut f: impl FnMut(&mut SP::State, &mut WidgetPod<SP::State, W>) -> V,
) -> V {
match &mut self.content {
ScopeContent::Policy { policy } => {
// We know that the policy is a Some - it is an option to allow
// us to take ownership before replacing the content.
let (mut state, policy) = policy.take().unwrap().create(data);
let v = f(&mut state, &mut self.inner);
self.content = ScopeContent::Transfer {
state,
transfer: policy,
};
v
}
ScopeContent::Transfer {
ref mut state,
transfer,
} => {
transfer.read_input(state, data);
f(state, &mut self.inner)
}
}
}
fn write_back_input(&mut self, data: &mut SP::In) {
if let ScopeContent::Transfer { state, transfer } = &mut self.content {
transfer.write_back_input(state, data)
}
}
}
impl<
F: FnOnce(Transfer::In) -> Transfer::State,
Transfer: ScopeTransfer,
W: Widget<Transfer::State>,
> Scope<DefaultScopePolicy<F, Transfer>, W>
{
/// Create a new policy from a function creating the state, and a ScopeTransfer synchronising it
pub fn from_function(make_state: F, transfer: Transfer, inner: W) -> Self {
Self::new(DefaultScopePolicy::new(make_state, transfer), inner)
}
}
impl<In: Data, State: Data, F: Fn(In) -> State, L: Lens<State, In>, W: Widget<State>>
Scope<DefaultScopePolicy<F, LensScopeTransfer<L, In, State>>, W>
{
/// Create a new policy from a function creating the state, and a Lens synchronising it
pub fn from_lens(make_state: F, lens: L, inner: W) -> Self {
Self::new(DefaultScopePolicy::from_lens(make_state, lens), inner)
}
}
impl<SP: ScopePolicy, W: Widget<SP::State>> Widget<SP::In> for Scope<SP, W> {
#[instrument(name = "Scope", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut SP::In, env: &Env) {
self.with_state(data, |state, inner| inner.event(ctx, event, state, env));
self.write_back_input(data);
ctx.request_update()
}
#[instrument(name = "Scope", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &SP::In, env: &Env) {
self.with_state(data, |state, inner| inner.lifecycle(ctx, event, state, env));
}
#[instrument(name = "Scope", level = "trace", skip(self, ctx, _old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &SP::In, data: &SP::In, env: &Env) {
self.with_state(data, |state, inner| inner.update(ctx, state, env));
}
#[instrument(name = "Scope", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &SP::In,
env: &Env,
) -> Size {
self.with_state(data, |state, inner| {
let size = inner.layout(ctx, bc, state, env);
inner.set_origin(ctx, Point::ORIGIN);
size
})
}
#[instrument(name = "Scope", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &SP::In, env: &Env) {
self.with_state(data, |state, inner| inner.paint_raw(ctx, state, env));
}
// TODO
// fn debug_state(&self, data: &SP::In) -> DebugState;
}
impl<SP: ScopePolicy, W: Widget<SP::State>> WidgetWrapper for Scope<SP, W> {
widget_wrapper_pod_body!(W, inner);
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/progress_bar.rs | druid/src/widget/progress_bar.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A progress bar widget.
use crate::debug_state::DebugState;
use crate::widget::prelude::*;
use crate::{theme, LinearGradient, Point, Rect, UnitPoint};
use tracing::instrument;
/// A progress bar, displaying a numeric progress value.
///
/// This type impls `Widget<f64>`, expecting a float in the range `0.0..1.0`.
#[derive(Debug, Clone, Default)]
pub struct ProgressBar;
impl ProgressBar {
/// Return a new `ProgressBar`.
pub fn new() -> ProgressBar {
Self
}
}
impl Widget<f64> for ProgressBar {
#[instrument(
name = "ProgressBar",
level = "trace",
skip(self, _ctx, _event, _data, _env)
)]
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut f64, _env: &Env) {}
#[instrument(
name = "ProgressBar",
level = "trace",
skip(self, _ctx, _event, _data, _env)
)]
fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &f64, _env: &Env) {}
#[instrument(
name = "ProgressBar",
level = "trace",
skip(self, ctx, _old_data, _data, _env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &f64, _data: &f64, _env: &Env) {
ctx.request_paint();
}
#[instrument(
name = "ProgressBar",
level = "trace",
skip(self, _layout_ctx, bc, _data, env)
)]
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &f64,
env: &Env,
) -> Size {
bc.debug_check("ProgressBar");
bc.constrain(Size::new(
env.get(theme::WIDE_WIDGET_WIDTH),
env.get(theme::BASIC_WIDGET_HEIGHT),
))
}
#[instrument(name = "ProgressBar", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) {
let height = env.get(theme::BASIC_WIDGET_HEIGHT);
let corner_radius = env.get(theme::PROGRESS_BAR_RADIUS);
let clamped = data.clamp(0.0, 1.0);
let stroke_width = 2.0;
let inset = -stroke_width / 2.0;
let size = ctx.size();
let rounded_rect = Size::new(size.width, height)
.to_rect()
.inset(inset)
.to_rounded_rect(corner_radius);
// Paint the border
ctx.stroke(rounded_rect, &env.get(theme::BORDER_DARK), stroke_width);
// Paint the background
let background_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::BACKGROUND_LIGHT),
env.get(theme::BACKGROUND_DARK),
),
);
ctx.fill(rounded_rect, &background_gradient);
// Paint the bar
let calculated_bar_width = clamped * rounded_rect.width();
let rounded_rect = Rect::from_origin_size(
Point::new(-inset, 0.),
Size::new(calculated_bar_width, height),
)
.inset((0.0, inset))
.to_rounded_rect(corner_radius);
let bar_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(env.get(theme::PRIMARY_LIGHT), env.get(theme::PRIMARY_DARK)),
);
ctx.fill(rounded_rect, &bar_gradient);
}
fn debug_state(&self, data: &f64) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
main_value: data.to_string(),
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/align.rs | druid/src/widget/align.rs | // Copyright 2018 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget that aligns its child (for example, centering it).
use crate::debug_state::DebugState;
use crate::widget::prelude::*;
use crate::{Data, Rect, Size, UnitPoint, WidgetPod};
use tracing::{instrument, trace};
/// A widget that aligns its child.
pub struct Align<T> {
align: UnitPoint,
child: WidgetPod<T, Box<dyn Widget<T>>>,
width_factor: Option<f64>,
height_factor: Option<f64>,
}
impl<T> Align<T> {
/// Create widget with alignment.
///
/// Note that the `align` parameter is specified as a `UnitPoint` in
/// terms of left and right. This is inadequate for bidi-aware layout
/// and thus the API will change when Druid gains bidi capability.
pub fn new(align: UnitPoint, child: impl Widget<T> + 'static) -> Align<T> {
Align {
align,
child: WidgetPod::new(child).boxed(),
width_factor: None,
height_factor: None,
}
}
/// Create centered widget.
pub fn centered(child: impl Widget<T> + 'static) -> Align<T> {
Align::new(UnitPoint::CENTER, child)
}
/// Create right-aligned widget.
pub fn right(child: impl Widget<T> + 'static) -> Align<T> {
Align::new(UnitPoint::RIGHT, child)
}
/// Create left-aligned widget.
pub fn left(child: impl Widget<T> + 'static) -> Align<T> {
Align::new(UnitPoint::LEFT, child)
}
/// Align only in the horizontal axis, keeping the child's size in the vertical.
pub fn horizontal(align: UnitPoint, child: impl Widget<T> + 'static) -> Align<T> {
Align {
align,
child: WidgetPod::new(child).boxed(),
width_factor: None,
height_factor: Some(1.0),
}
}
/// Align only in the vertical axis, keeping the child's size in the horizontal.
pub fn vertical(align: UnitPoint, child: impl Widget<T> + 'static) -> Align<T> {
Align {
align,
child: WidgetPod::new(child).boxed(),
width_factor: Some(1.0),
height_factor: None,
}
}
}
impl<T: Data> Widget<T> for Align<T> {
#[instrument(name = "Align", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
self.child.event(ctx, event, data, env)
}
#[instrument(name = "Align", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.child.lifecycle(ctx, event, data, env)
}
#[instrument(name = "Align", level = "trace", skip(self, ctx, _old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
self.child.update(ctx, data, env);
}
#[instrument(name = "Align", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
trace!("Layout constraints: {:?}", bc);
bc.debug_check("Align");
let size = self.child.layout(ctx, &bc.loosen(), data, env);
log_size_warnings(size);
let mut my_size = size;
if bc.is_width_bounded() {
my_size.width = bc.max().width;
}
if bc.is_height_bounded() {
my_size.height = bc.max().height;
}
if let Some(width) = self.width_factor {
my_size.width = size.width * width;
}
if let Some(height) = self.height_factor {
my_size.height = size.height * height;
}
my_size = bc.constrain(my_size);
let extra_width = (my_size.width - size.width).max(0.);
let extra_height = (my_size.height - size.height).max(0.);
let origin = self
.align
.resolve(Rect::new(0., 0., extra_width, extra_height))
.expand();
self.child.set_origin(ctx, origin);
let my_insets = self.child.compute_parent_paint_insets(my_size);
ctx.set_paint_insets(my_insets);
if self.height_factor.is_some() {
let baseline_offset = self.child.baseline_offset();
if baseline_offset > 0f64 {
ctx.set_baseline_offset(baseline_offset + extra_height / 2.0);
}
}
trace!(
"Computed layout: origin={}, size={}, insets={:?}",
origin,
my_size,
my_insets
);
my_size
}
#[instrument(name = "Align", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
self.child.paint(ctx, data, env);
}
fn debug_state(&self, data: &T) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
children: vec![self.child.widget().debug_state(data)],
..Default::default()
}
}
}
fn log_size_warnings(size: Size) {
if size.width.is_infinite() {
tracing::warn!("Align widget's child has an infinite width.");
}
if size.height.is_infinite() {
tracing::warn!("Align widget's child has an infinite height.");
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/intrinsic_width.rs | druid/src/widget/intrinsic_width.rs | // Copyright 2022 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget that sizes its child to the child's maximum intrinsic width.
use crate::widget::Axis;
use crate::{
BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx, Size,
UpdateCtx, Widget,
};
/// A widget that sizes its child to the child's maximum intrinsic width.
///
/// This widget is useful, for example, when unlimited width is available and you would like a child
/// that would otherwise attempt to expand infinitely to instead size itself to a more reasonable
/// width.
///
/// The constraints that this widget passes to its child will adhere to the parent's
/// constraints, so if the constraints are not large enough to satisfy the child's maximum intrinsic
/// width, then the child will get less width than it otherwise would. Likewise, if the minimum
/// width constraint is larger than the child's maximum intrinsic width, the child will be given
/// more width than it otherwise would.
pub struct IntrinsicWidth<T> {
child: Box<dyn Widget<T>>,
}
impl<T: Data> IntrinsicWidth<T> {
/// Wrap the given `child` in this widget.
pub fn new(child: impl Widget<T> + 'static) -> Self {
Self {
child: Box::new(child),
}
}
}
impl<T: Data> Widget<T> for IntrinsicWidth<T> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
self.child.event(ctx, event, data, env);
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.child.lifecycle(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
self.child.update(ctx, old_data, data, env);
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let iw = self
.child
.compute_max_intrinsic(Axis::Horizontal, ctx, bc, data, env);
let new_bc = bc.shrink_max_width_to(iw);
self.child.layout(ctx, &new_bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
self.child.paint(ctx, data, env);
}
fn compute_max_intrinsic(
&mut self,
axis: Axis,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &T,
env: &Env,
) -> f64 {
match axis {
Axis::Horizontal => self.child.compute_max_intrinsic(axis, ctx, bc, data, env),
Axis::Vertical => {
if !bc.is_width_bounded() {
let w = self
.child
.compute_max_intrinsic(Axis::Horizontal, ctx, bc, data, env);
let new_bc = bc.shrink_max_width_to(w);
self.child
.compute_max_intrinsic(axis, ctx, &new_bc, data, env)
} else {
self.child.compute_max_intrinsic(axis, ctx, bc, data, env)
}
}
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/mod.rs | druid/src/widget/mod.rs | // Copyright 2018 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Common widgets.
// First as it defines macros
#[macro_use]
mod widget_wrapper;
mod added;
mod align;
mod aspect_ratio_box;
mod button;
mod checkbox;
mod click;
mod clip_box;
mod common;
mod container;
mod controller;
mod disable_if;
mod either;
mod env_scope;
mod flex;
mod identity_wrapper;
mod image;
mod intrinsic_width;
mod invalidation;
mod label;
mod lens_wrap;
mod list;
mod maybe;
mod padding;
mod painter;
mod parse;
mod progress_bar;
mod radio;
mod scope;
mod scroll;
mod sized_box;
mod slider;
mod spinner;
mod split;
mod stepper;
#[cfg(feature = "svg")]
#[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
mod svg;
mod switch;
mod tabs;
mod textbox;
mod value_textbox;
mod view_switcher;
#[allow(clippy::module_inception)]
mod widget;
mod widget_ext;
mod z_stack;
pub use self::image::Image;
pub use added::Added;
pub use align::Align;
pub use aspect_ratio_box::AspectRatioBox;
pub use button::Button;
pub use checkbox::Checkbox;
pub use click::Click;
pub use clip_box::{ClipBox, Viewport};
pub use common::FillStrat;
pub use container::Container;
pub use controller::{Controller, ControllerHost};
pub use disable_if::DisabledIf;
pub use either::Either;
pub use env_scope::EnvScope;
pub use flex::{Axis, CrossAxisAlignment, Flex, FlexParams, MainAxisAlignment};
pub use identity_wrapper::IdentityWrapper;
pub use intrinsic_width::IntrinsicWidth;
pub use label::{Label, LabelText, LineBreaking, RawLabel};
pub use lens_wrap::LensWrap;
pub use list::{List, ListIter};
pub use maybe::Maybe;
pub use padding::Padding;
pub use painter::{BackgroundBrush, Painter};
#[allow(deprecated)]
pub use parse::Parse;
pub use progress_bar::ProgressBar;
pub use radio::{Radio, RadioGroup};
pub use scope::{DefaultScopePolicy, LensScopeTransfer, Scope, ScopePolicy, ScopeTransfer};
pub use scroll::Scroll;
pub use sized_box::SizedBox;
pub use slider::{KnobStyle, RangeSlider, Slider};
pub use spinner::Spinner;
pub use split::Split;
pub use stepper::Stepper;
#[cfg(feature = "svg")]
pub use svg::{Svg, SvgData};
pub use switch::Switch;
pub use tabs::{AddTab, TabInfo, Tabs, TabsEdge, TabsPolicy, TabsState, TabsTransition};
pub use textbox::TextBox;
pub use value_textbox::{TextBoxEvent, ValidationDelegate, ValueTextBox};
pub use view_switcher::ViewSwitcher;
pub use widget::{Widget, WidgetId};
pub use widget_ext::WidgetExt;
pub use widget_wrapper::WidgetWrapper;
pub use z_stack::ZStack;
/// The types required to implement a [`Widget`].
pub mod prelude {
// Wildcard because rustdoc has trouble inlining docs of two things called Data
pub use crate::data::*;
#[doc(inline)]
pub use crate::{
BoxConstraints, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx,
RenderContext, Size, UpdateCtx, Widget, WidgetId,
};
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/widget_wrapper.rs | druid/src/widget/widget_wrapper.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
/// A trait for widgets that wrap a single child to expose that child for access and mutation
pub trait WidgetWrapper {
/// The type of the wrapped widget.
/// Maybe we would like to constrain this to `Widget<impl Data>` (if existential bounds were supported).
/// Any other scheme leads to `T` being unconstrained in unification at some point
type Wrapped;
/// Get immutable access to the wrapped child
fn wrapped(&self) -> &Self::Wrapped;
/// Get mutable access to the wrapped child
fn wrapped_mut(&mut self) -> &mut Self::Wrapped;
}
/// A macro to help implementation of WidgetWrapper for a direct wrapper.
/// Use it in the body of the impl.
///
#[macro_export]
macro_rules! widget_wrapper_body {
($wrapped:ty, $field:ident) => {
type Wrapped = $wrapped;
fn wrapped(&self) -> &Self::Wrapped {
&self.$field
}
fn wrapped_mut(&mut self) -> &mut Self::Wrapped {
&mut self.$field
}
};
}
/// A macro to help implementation of WidgetWrapper for a wrapper of a typed pod.
/// Use it in the body of the impl.
///
#[macro_export]
macro_rules! widget_wrapper_pod_body {
($wrapped:ty, $field:ident) => {
type Wrapped = $wrapped;
fn wrapped(&self) -> &Self::Wrapped {
self.$field.widget()
}
fn wrapped_mut(&mut self) -> &mut Self::Wrapped {
self.$field.widget_mut()
}
};
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/added.rs | druid/src/widget/added.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A [`Controller`] widget that responds to [`LifeCycle::WidgetAdded`] event.
//!
//! [`Controller`]: crate::widget::Controller
//! [`LifeCycle::WidgetAdded`]: crate::LifeCycle::WidgetAdded
use crate::widget::Controller;
use crate::{Data, Env, LifeCycleCtx, Widget};
use tracing::{instrument, trace};
/// This [`Controller`] widget responds to [`LifeCycle::WidgetAdded`] event
/// with the provided closure. Pass this and a child widget to [`ControllerHost`]
/// to respond to the event when the child widget is added to the widget tree.
/// This is also available, for convenience, as an `on_added` method
/// via [`WidgetExt`].
///
/// [`Controller`]: crate::widget::Controller
/// [`ControllerHost`]: crate::widget::ControllerHost
/// [`WidgetExt`]: crate::widget::WidgetExt
/// [`LifeCycle::WidgetAdded`]: crate::LifeCycle::WidgetAdded
pub struct Added<T, W> {
/// A closure that will be invoked when the child widget is added
/// to the widget tree
action: Box<dyn Fn(&mut W, &mut LifeCycleCtx, &T, &Env)>,
}
impl<T: Data, W: Widget<T>> Added<T, W> {
/// Create a new [`Controller`] widget to respond to widget added to tree event.
pub fn new(action: impl Fn(&mut W, &mut LifeCycleCtx, &T, &Env) + 'static) -> Self {
Self {
action: Box::new(action),
}
}
}
impl<T: Data, W: Widget<T>> Controller<T, W> for Added<T, W> {
#[instrument(
name = "Added",
level = "trace",
skip(self, child, ctx, event, data, env)
)]
fn lifecycle(
&mut self,
child: &mut W,
ctx: &mut LifeCycleCtx,
event: &crate::LifeCycle,
data: &T,
env: &Env,
) {
if let crate::LifeCycle::WidgetAdded = event {
trace!("Widget added");
(self.action)(child, ctx, data, env);
}
child.lifecycle(ctx, event, data, env)
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/radio.rs | druid/src/widget/radio.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A radio button widget.
use crate::debug_state::DebugState;
use crate::kurbo::Circle;
use crate::widget::prelude::*;
use crate::widget::{Axis, CrossAxisAlignment, Flex, Label, LabelText};
use crate::{theme, Data, LinearGradient, UnitPoint};
use tracing::{instrument, trace};
const DEFAULT_RADIO_RADIUS: f64 = 7.0;
const INNER_CIRCLE_RADIUS: f64 = 2.0;
/// A group of radio buttons
#[derive(Debug, Clone)]
pub struct RadioGroup;
impl RadioGroup {
/// Given a vector of `(label_text, enum_variant)` tuples, create a group of Radio buttons
/// along the vertical axis.
pub fn column<T: Data + PartialEq>(
variants: impl IntoIterator<Item = (impl Into<LabelText<T>> + 'static, T)>,
) -> impl Widget<T> {
RadioGroup::for_axis(Axis::Vertical, variants)
}
/// Given a vector of `(label_text, enum_variant)` tuples, create a group of Radio buttons
/// along the horizontal axis.
pub fn row<T: Data + PartialEq>(
variants: impl IntoIterator<Item = (impl Into<LabelText<T>> + 'static, T)>,
) -> impl Widget<T> {
RadioGroup::for_axis(Axis::Horizontal, variants)
}
/// Given a vector of `(label_text, enum_variant)` tuples, create a group of Radio buttons
/// along the specified axis.
pub fn for_axis<T: Data + PartialEq>(
axis: Axis,
variants: impl IntoIterator<Item = (impl Into<LabelText<T>> + 'static, T)>,
) -> impl Widget<T> {
let mut col = Flex::for_axis(axis).cross_axis_alignment(CrossAxisAlignment::Start);
let mut is_first = true;
for (label, variant) in variants.into_iter() {
if !is_first {
col.add_default_spacer();
}
let radio = Radio::new(label, variant);
col.add_child(radio);
is_first = false;
}
col
}
}
/// A single radio button
pub struct Radio<T> {
variant: T,
child_label: Label<T>,
}
impl<T: Data> Radio<T> {
/// Create a lone Radio button from label text and an enum variant
pub fn new(label: impl Into<LabelText<T>>, variant: T) -> Radio<T> {
Radio {
variant,
child_label: Label::new(label),
}
}
}
impl<T: Data + PartialEq> Widget<T> for Radio<T> {
#[instrument(name = "Radio", level = "trace", skip(self, ctx, event, data, _env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, _env: &Env) {
match event {
Event::MouseDown(_) => {
if !ctx.is_disabled() {
ctx.set_active(true);
ctx.request_paint();
trace!("Radio button {:?} pressed", ctx.widget_id());
}
}
Event::MouseUp(_) => {
if ctx.is_active() && !ctx.is_disabled() {
if ctx.is_hot() {
*data = self.variant.clone();
}
ctx.request_paint();
trace!("Radio button {:?} released", ctx.widget_id());
}
ctx.set_active(false);
}
_ => (),
}
}
#[instrument(name = "Radio", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.child_label.lifecycle(ctx, event, data, env);
if let LifeCycle::HotChanged(_) | LifeCycle::DisabledChanged(_) = event {
ctx.request_paint();
}
}
#[instrument(name = "Radio", level = "trace", skip(self, ctx, old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
self.child_label.update(ctx, old_data, data, env);
if !old_data.same(data) {
ctx.request_paint();
}
}
#[instrument(name = "Radio", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
bc.debug_check("Radio");
let label_size = self.child_label.layout(ctx, bc, data, env);
let radio_diam = env.get(theme::BASIC_WIDGET_HEIGHT);
let x_padding = env.get(theme::WIDGET_CONTROL_COMPONENT_PADDING);
let desired_size = Size::new(
label_size.width + radio_diam + x_padding,
radio_diam.max(label_size.height),
);
let size = bc.constrain(desired_size);
trace!("Computed size: {}", size);
size
}
#[instrument(name = "Radio", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
let size = env.get(theme::BASIC_WIDGET_HEIGHT);
let x_padding = env.get(theme::WIDGET_CONTROL_COMPONENT_PADDING);
let circle = Circle::new((size / 2., size / 2.), DEFAULT_RADIO_RADIUS);
// Paint the background
let background_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::BACKGROUND_LIGHT),
env.get(theme::BACKGROUND_DARK),
),
);
ctx.fill(circle, &background_gradient);
let border_color = if ctx.is_hot() && !ctx.is_disabled() {
env.get(theme::BORDER_LIGHT)
} else {
env.get(theme::BORDER_DARK)
};
ctx.stroke(circle, &border_color, 1.);
// Check if data enum matches our variant
if *data == self.variant {
let inner_circle = Circle::new((size / 2., size / 2.), INNER_CIRCLE_RADIUS);
let fill = if ctx.is_disabled() {
env.get(theme::DISABLED_TEXT_COLOR)
} else {
env.get(theme::CURSOR_COLOR)
};
ctx.fill(inner_circle, &fill);
}
// Paint the text label
self.child_label.draw_at(ctx, (size + x_padding, 0.0));
}
fn debug_state(&self, data: &T) -> DebugState {
let value_text = if *data == self.variant {
format!("[X] {}", self.child_label.text())
} else {
self.child_label.text().to_string()
};
DebugState {
display_name: self.short_type_name().to_string(),
main_value: value_text,
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/view_switcher.rs | druid/src/widget/view_switcher.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget that can dynamically switch between one of many views.
use crate::widget::prelude::*;
use crate::{Data, Point, WidgetPod};
use tracing::instrument;
type ChildPicker<T, U> = dyn Fn(&T, &Env) -> U;
type ChildBuilder<T, U> = dyn Fn(&U, &T, &Env) -> Box<dyn Widget<T>>;
/// A widget that switches dynamically between multiple children.
pub struct ViewSwitcher<T, U> {
child_picker: Box<ChildPicker<T, U>>,
child_builder: Box<ChildBuilder<T, U>>,
active_child: Option<WidgetPod<T, Box<dyn Widget<T>>>>,
active_child_id: Option<U>,
}
impl<T: Data, U: Data> ViewSwitcher<T, U> {
/// Create a new view switcher.
///
/// The `child_picker` closure is called every time the application data changes.
/// If the value it returns is the same as the one it returned during the previous
/// data change, nothing happens. If it returns a different value, then the
/// `child_builder` closure is called with the new value.
///
/// The `child_builder` closure creates a new child widget based on
/// the value passed to it.
///
/// # Examples
/// ```
/// use druid::{
/// widget::{Label, ViewSwitcher},
/// Data, Widget,
/// };
///
/// #[derive(Clone, PartialEq, Data)]
/// enum Foo {
/// A,
/// B,
/// C,
/// }
///
/// fn ui() -> impl Widget<Foo> {
/// ViewSwitcher::new(
/// |data: &Foo, _env| data.clone(),
/// |selector, _data, _env| match selector {
/// Foo::A => Box::new(Label::new("A")),
/// _ => Box::new(Label::new("Not A")),
/// },
/// )
/// }
/// ```
pub fn new(
child_picker: impl Fn(&T, &Env) -> U + 'static,
child_builder: impl Fn(&U, &T, &Env) -> Box<dyn Widget<T>> + 'static,
) -> Self {
Self {
child_picker: Box::new(child_picker),
child_builder: Box::new(child_builder),
active_child: None,
active_child_id: None,
}
}
}
impl<T: Data, U: Data> Widget<T> for ViewSwitcher<T, U> {
#[instrument(
name = "ViewSwitcher",
level = "trace",
skip(self, ctx, event, data, env)
)]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
if let Some(child) = self.active_child.as_mut() {
child.event(ctx, event, data, env);
}
}
#[instrument(
name = "ViewSwitcher",
level = "trace",
skip(self, ctx, event, data, env)
)]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
if let LifeCycle::WidgetAdded = event {
let child_id = (self.child_picker)(data, env);
self.active_child = Some(WidgetPod::new((self.child_builder)(&child_id, data, env)));
self.active_child_id = Some(child_id);
}
if let Some(child) = self.active_child.as_mut() {
child.lifecycle(ctx, event, data, env);
}
}
#[instrument(
name = "ViewSwitcher",
level = "trace",
skip(self, ctx, _old_data, data, env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
let child_id = (self.child_picker)(data, env);
// Safe to unwrap because self.active_child_id should not be empty
if !child_id.same(self.active_child_id.as_ref().unwrap()) {
self.active_child = Some(WidgetPod::new((self.child_builder)(&child_id, data, env)));
self.active_child_id = Some(child_id);
ctx.children_changed();
// Because the new child has not yet been initialized, we have to skip the update after switching.
} else if let Some(child) = self.active_child.as_mut() {
child.update(ctx, data, env);
}
}
#[instrument(name = "ViewSwitcher", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
match self.active_child {
Some(ref mut child) => {
let size = child.layout(ctx, bc, data, env);
child.set_origin(ctx, Point::ORIGIN);
size
}
None => bc.max(),
}
}
#[instrument(name = "ViewSwitcher", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
if let Some(ref mut child) = self.active_child {
child.paint_raw(ctx, data, env);
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/checkbox.rs | druid/src/widget/checkbox.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A checkbox widget.
use crate::debug_state::DebugState;
use crate::kurbo::{BezPath, Size};
use crate::piet::{LineCap, LineJoin, LinearGradient, RenderContext, StrokeStyle, UnitPoint};
use crate::theme;
use crate::widget::{prelude::*, Label, LabelText};
use tracing::{instrument, trace};
/// A checkbox that toggles a `bool`.
pub struct Checkbox {
child_label: Label<bool>,
}
impl Checkbox {
/// Create a new `Checkbox` with a text label.
pub fn new(text: impl Into<LabelText<bool>>) -> Checkbox {
Self::from_label(Label::new(text))
}
/// Create a new `Checkbox` with the provided [`Label`].
pub fn from_label(label: Label<bool>) -> Checkbox {
Checkbox { child_label: label }
}
/// Update the text label.
pub fn set_text(&mut self, label: impl Into<LabelText<bool>>) {
self.child_label.set_text(label);
}
}
impl Widget<bool> for Checkbox {
#[instrument(name = "CheckBox", level = "trace", skip(self, ctx, event, data, _env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut bool, _env: &Env) {
match event {
Event::MouseDown(_) => {
if !ctx.is_disabled() {
ctx.set_active(true);
ctx.request_paint();
trace!("Checkbox {:?} pressed", ctx.widget_id());
}
}
Event::MouseUp(_) => {
if ctx.is_active() && !ctx.is_disabled() {
if ctx.is_hot() {
if *data {
*data = false;
trace!("Checkbox {:?} released - unchecked", ctx.widget_id());
} else {
*data = true;
trace!("Checkbox {:?} released - checked", ctx.widget_id());
}
}
ctx.request_paint();
}
ctx.set_active(false);
}
_ => (),
}
}
#[instrument(name = "CheckBox", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &bool, env: &Env) {
self.child_label.lifecycle(ctx, event, data, env);
if let LifeCycle::HotChanged(_) | LifeCycle::DisabledChanged(_) = event {
ctx.request_paint();
}
}
#[instrument(
name = "CheckBox",
level = "trace",
skip(self, ctx, old_data, data, env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &bool, data: &bool, env: &Env) {
self.child_label.update(ctx, old_data, data, env);
ctx.request_paint();
}
#[instrument(name = "CheckBox", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &bool, env: &Env) -> Size {
bc.debug_check("Checkbox");
let x_padding = env.get(theme::WIDGET_CONTROL_COMPONENT_PADDING);
let check_size = env.get(theme::BASIC_WIDGET_HEIGHT);
let label_size = self.child_label.layout(ctx, bc, data, env);
let desired_size = Size::new(
check_size + x_padding + label_size.width,
check_size.max(label_size.height),
);
let our_size = bc.constrain(desired_size);
let baseline = self.child_label.baseline_offset() + (our_size.height - label_size.height);
ctx.set_baseline_offset(baseline);
trace!("Computed layout: size={}, baseline={}", our_size, baseline);
our_size
}
#[instrument(name = "CheckBox", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &bool, env: &Env) {
let size = env.get(theme::BASIC_WIDGET_HEIGHT);
let x_padding = env.get(theme::WIDGET_CONTROL_COMPONENT_PADDING);
let border_width = 1.;
let rect = Size::new(size, size)
.to_rect()
.inset(-border_width / 2.)
.to_rounded_rect(2.);
//Paint the background
let background_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::BACKGROUND_LIGHT),
env.get(theme::BACKGROUND_DARK),
),
);
ctx.fill(rect, &background_gradient);
let border_color = if ctx.is_hot() && !ctx.is_disabled() {
env.get(theme::BORDER_LIGHT)
} else {
env.get(theme::BORDER_DARK)
};
ctx.stroke(rect, &border_color, border_width);
if *data {
// Paint the checkmark
let x_offset = (rect.width() - 10.0) / 2.0;
let y_offset = (rect.height() - 8.0) / 2.0;
let mut path = BezPath::new();
path.move_to((x_offset, y_offset + 4.0));
path.line_to((x_offset + 4.0, y_offset + 8.0));
path.line_to((x_offset + 10.0, y_offset));
let style = StrokeStyle::new()
.line_cap(LineCap::Round)
.line_join(LineJoin::Round);
let brush = if ctx.is_disabled() {
env.get(theme::DISABLED_TEXT_COLOR)
} else {
env.get(theme::TEXT_COLOR)
};
ctx.stroke_styled(path, &brush, 2., &style);
}
// Paint the text label
self.child_label.draw_at(ctx, (size + x_padding, 0.0));
}
fn debug_state(&self, data: &bool) -> DebugState {
let display_value = if *data {
format!("[X] {}", self.child_label.text())
} else {
format!("[_] {}", self.child_label.text())
};
DebugState {
display_name: self.short_type_name().to_string(),
main_value: display_value,
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/common.rs | druid/src/widget/common.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use crate::{Affine, Data, Size};
// These are based on https://api.flutter.dev/flutter/painting/BoxFit.html
/// Strategies for inscribing a rectangle inside another rectangle.
#[derive(Default, Clone, Data, Copy, PartialEq, Eq)]
pub enum FillStrat {
/// As large as possible without changing aspect ratio of image and all of image shown
#[default]
Contain,
/// As large as possible with no dead space so that some of the image may be clipped
Cover,
/// Fill the widget with no dead space, aspect ratio of widget is used
Fill,
/// Fill the height with the images aspect ratio, some of the image may be clipped
FitHeight,
/// Fill the width with the images aspect ratio, some of the image may be clipped
FitWidth,
/// Do not scale
None,
/// Scale down to fit but do not scale up
ScaleDown,
}
impl FillStrat {
/// Calculate an origin and scale for an image with a given `FillStrat`.
///
/// This takes some properties of a widget and a fill strategy and returns an affine matrix
/// used to position and scale the image in the widget.
pub fn affine_to_fill(self, parent: Size, fit_box: Size) -> Affine {
let raw_scalex = parent.width / fit_box.width;
let raw_scaley = parent.height / fit_box.height;
let (scalex, scaley) = match self {
FillStrat::Contain => {
let scale = raw_scalex.min(raw_scaley);
(scale, scale)
}
FillStrat::Cover => {
let scale = raw_scalex.max(raw_scaley);
(scale, scale)
}
FillStrat::Fill => (raw_scalex, raw_scaley),
FillStrat::FitHeight => (raw_scaley, raw_scaley),
FillStrat::FitWidth => (raw_scalex, raw_scalex),
FillStrat::ScaleDown => {
let scale = raw_scalex.min(raw_scaley).min(1.0);
(scale, scale)
}
FillStrat::None => (1.0, 1.0),
};
let origin_x = (parent.width - (fit_box.width * scalex)) / 2.0;
let origin_y = (parent.height - (fit_box.height * scaley)) / 2.0;
Affine::new([scalex, 0., 0., scaley, origin_x, origin_y])
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/maybe.rs | druid/src/widget/maybe.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget for optional data, with different `Some` and `None` children.
use crate::debug_state::DebugState;
use druid::{
BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx,
Point, Size, UpdateCtx, Widget, WidgetExt, WidgetPod,
};
use druid::widget::SizedBox;
/// A widget that switches between two possible child views, for `Data` that
/// is `Option<T>`.
pub struct Maybe<T> {
some_maker: Box<dyn Fn() -> Box<dyn Widget<T>>>,
none_maker: Box<dyn Fn() -> Box<dyn Widget<()>>>,
widget: MaybeWidget<T>,
}
/// Internal widget, which is either the `Some` variant, or the `None` variant.
#[allow(clippy::large_enum_variant)]
enum MaybeWidget<T> {
Some(WidgetPod<T, Box<dyn Widget<T>>>),
None(WidgetPod<(), Box<dyn Widget<()>>>),
}
impl<T: Data> Maybe<T> {
/// Create a new `Maybe` widget with a `Some` and a `None` branch.
pub fn new<W1, W2>(
// we make these generic so that the caller doesn't have to explicitly
// box. We don't technically *need* to box, but it seems simpler.
some_maker: impl Fn() -> W1 + 'static,
none_maker: impl Fn() -> W2 + 'static,
) -> Maybe<T>
where
W1: Widget<T> + 'static,
W2: Widget<()> + 'static,
{
let widget = MaybeWidget::Some(WidgetPod::new(some_maker().boxed()));
Maybe {
some_maker: Box::new(move || some_maker().boxed()),
none_maker: Box::new(move || none_maker().boxed()),
widget,
}
}
/// Create a new `Maybe` widget where the `None` branch is an empty widget.
pub fn or_empty<W1: Widget<T> + 'static>(some_maker: impl Fn() -> W1 + 'static) -> Maybe<T> {
Self::new(some_maker, SizedBox::empty)
}
/// Re-create the internal widget, usually in response to the optional going `Some` -> `None`
/// or the reverse.
fn rebuild_widget(&mut self, is_some: bool) {
if is_some {
self.widget = MaybeWidget::Some(WidgetPod::new((self.some_maker)()));
} else {
self.widget = MaybeWidget::None(WidgetPod::new((self.none_maker)()));
}
}
}
impl<T: Data> Widget<Option<T>> for Maybe<T> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut Option<T>, env: &Env) {
if data.is_some() == self.widget.is_some() {
match data.as_mut() {
Some(d) => self.widget.with_some(|w| w.event(ctx, event, d, env)),
None => self.widget.with_none(|w| w.event(ctx, event, &mut (), env)),
};
}
}
fn lifecycle(
&mut self,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &Option<T>,
env: &Env,
) {
if data.is_some() != self.widget.is_some() {
// possible if getting lifecycle after an event that changed the data,
// or on WidgetAdded
self.rebuild_widget(data.is_some());
}
assert_eq!(data.is_some(), self.widget.is_some(), "{event:?}");
match data.as_ref() {
Some(d) => self.widget.with_some(|w| w.lifecycle(ctx, event, d, env)),
None => self.widget.with_none(|w| w.lifecycle(ctx, event, &(), env)),
};
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &Option<T>, data: &Option<T>, env: &Env) {
if old_data.is_some() != data.is_some() {
self.rebuild_widget(data.is_some());
ctx.children_changed();
} else {
match data {
Some(new) => self.widget.with_some(|w| w.update(ctx, new, env)),
None => self.widget.with_none(|w| w.update(ctx, &(), env)),
};
}
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &Option<T>,
env: &Env,
) -> Size {
match data.as_ref() {
Some(d) => self.widget.with_some(|w| {
let size = w.layout(ctx, bc, d, env);
w.set_origin(ctx, Point::ORIGIN);
size
}),
None => self.widget.with_none(|w| {
let size = w.layout(ctx, bc, &(), env);
w.set_origin(ctx, Point::ORIGIN);
size
}),
}
.unwrap_or_default()
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &Option<T>, env: &Env) {
match data.as_ref() {
Some(d) => self.widget.with_some(|w| w.paint(ctx, d, env)),
None => self.widget.with_none(|w| w.paint(ctx, &(), env)),
};
}
fn debug_state(&self, data: &Option<T>) -> DebugState {
let child_state = match (&self.widget, data.as_ref()) {
(MaybeWidget::Some(widget_pod), Some(d)) => vec![widget_pod.widget().debug_state(d)],
(MaybeWidget::None(widget_pod), None) => vec![widget_pod.widget().debug_state(&())],
_ => vec![],
};
DebugState {
display_name: self.short_type_name().to_string(),
children: child_state,
..Default::default()
}
}
}
impl<T> MaybeWidget<T> {
/// Like `Option::is_some`.
fn is_some(&self) -> bool {
match self {
Self::Some(_) => true,
Self::None(_) => false,
}
}
/// Lens to the `Some` variant.
fn with_some<R, F: FnOnce(&mut WidgetPod<T, Box<dyn Widget<T>>>) -> R>(
&mut self,
f: F,
) -> Option<R> {
match self {
Self::Some(widget) => Some(f(widget)),
Self::None(_) => {
tracing::trace!("`MaybeWidget::with_some` called on `None` value");
None
}
}
}
/// Lens to the `None` variant.
fn with_none<R, F: FnOnce(&mut WidgetPod<(), Box<dyn Widget<()>>>) -> R>(
&mut self,
f: F,
) -> Option<R> {
match self {
Self::None(widget) => Some(f(widget)),
Self::Some(_) => {
tracing::trace!("`MaybeWidget::with_none` called on `Some` value");
None
}
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/label.rs | druid/src/widget/label.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A label widget.
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use druid_shell::Cursor;
use crate::debug_state::DebugState;
use crate::kurbo::Vec2;
use crate::text::TextStorage;
use crate::widget::prelude::*;
use crate::widget::Axis;
use crate::{
ArcStr, Color, Data, FontDescriptor, KeyOrValue, LocalizedString, Point, TextAlignment,
TextLayout,
};
use tracing::{instrument, trace, warn};
// added padding between the edges of the widget and the text.
const LABEL_X_PADDING: f64 = 2.0;
/// A label that displays static or dynamic text.
///
/// This type manages an inner [`RawLabel`], updating its text based on the
/// current [`Data`] and [`Env`] as required.
///
/// If your [`Data`] is *already* text, you may use a [`RawLabel`] directly.
/// As a convenience, you can create a [`RawLabel`] with the [`Label::raw`]
/// constructor method.
///
/// A label is the easiest way to display text in Druid. A label is instantiated
/// with some [`LabelText`] type, such as an [`ArcStr`] or a [`LocalizedString`],
/// and also has methods for setting the default font, font-size, text color,
/// and other attributes.
///
/// In addition to being a [`Widget`], `Label` is also regularly used as a
/// component in other widgets that wish to display text; to facilitate this
/// it has a [`draw_at`] method that allows the caller to easily draw the label's
/// text at the desired position on screen.
///
/// # Examples
///
/// Make a label to say something **very** important:
///
/// ```
/// # use druid::widget::{Label, SizedBox};
/// # use druid::*;
///
/// let font = FontDescriptor::new(FontFamily::SYSTEM_UI)
/// .with_weight(FontWeight::BOLD)
/// .with_size(48.0);
///
/// let important_label = Label::new("WATCH OUT!")
/// .with_font(font)
/// .with_text_color(Color::rgb(1.0, 0.2, 0.2));
/// # // our data type T isn't known; this is just a trick for the compiler
/// # // to keep our example clean
/// # let _ = SizedBox::<()>::new(important_label);
/// ```
///
/// [`draw_at`]: Label::draw_at
pub struct Label<T> {
label: RawLabel<ArcStr>,
current_text: ArcStr,
text: LabelText<T>,
// for debugging, we track if the user modifies the text and we don't get
// an update call, which might cause us to display stale text.
text_should_be_updated: bool,
}
/// A widget that displays text data.
///
/// This requires the `Data` to implement [`TextStorage`]; to handle static, dynamic, or
/// localized text, use [`Label`].
pub struct RawLabel<T> {
layout: TextLayout<T>,
line_break_mode: LineBreaking,
disabled: bool,
default_text_color: KeyOrValue<Color>,
}
/// Options for handling lines that are too wide for the label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Data)]
pub enum LineBreaking {
/// Lines are broken at word boundaries.
WordWrap,
/// Lines are truncated to the width of the label.
Clip,
/// Lines overflow the label.
Overflow,
}
/// The text for a [`Label`].
///
/// This can be one of three things; either an [`ArcStr`], a [`LocalizedString`],
/// or a closure with the signature `Fn(&T, &Env) -> impl Into<ArcStr>`, where
/// `T` is the `Data` at this point in the tree.
#[derive(Clone)]
pub enum LabelText<T> {
/// Localized string that will be resolved through `Env`.
Localized(LocalizedString<T>),
/// Static text.
Static(Static),
/// The provided closure is called on update, and its return
/// value is used as the text for the label.
Dynamic(Dynamic<T>),
}
/// Text that is computed dynamically.
#[derive(Clone)]
pub struct Dynamic<T> {
f: Arc<dyn Fn(&T, &Env) -> ArcStr>,
resolved: ArcStr,
}
/// Static text.
#[derive(Debug, Clone)]
pub struct Static {
/// The text.
string: ArcStr,
/// Whether or not the `resolved` method has been called yet.
///
/// We want to return `true` from that method when it is first called,
/// so that callers will know to retrieve the text. This matches
/// the behaviour of the other variants.
resolved: bool,
}
impl<T: TextStorage> RawLabel<T> {
/// Create a new `RawLabel`.
pub fn new() -> Self {
Self {
layout: TextLayout::new(),
line_break_mode: LineBreaking::Overflow,
disabled: false,
default_text_color: crate::theme::TEXT_COLOR.into(),
}
}
/// Builder-style method for setting the text color.
///
/// The argument can be either a `Color` or a [`Key<Color>`].
///
/// [`Key<Color>`]: crate::Key
pub fn with_text_color(mut self, color: impl Into<KeyOrValue<Color>>) -> Self {
self.set_text_color(color);
self
}
/// Builder-style method for setting the text size.
///
/// The argument can be either an `f64` or a [`Key<f64>`].
///
/// [`Key<f64>`]: crate::Key
pub fn with_text_size(mut self, size: impl Into<KeyOrValue<f64>>) -> Self {
self.set_text_size(size);
self
}
/// Builder-style method for setting the font.
///
/// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`]
/// that refers to a font defined in the [`Env`].
///
/// [`Key<FontDescriptor>`]: crate::Key
pub fn with_font(mut self, font: impl Into<KeyOrValue<FontDescriptor>>) -> Self {
self.set_font(font);
self
}
/// Builder-style method to set the [`LineBreaking`] behaviour.
pub fn with_line_break_mode(mut self, mode: LineBreaking) -> Self {
self.set_line_break_mode(mode);
self
}
/// Builder-style method to set the [`TextAlignment`].
pub fn with_text_alignment(mut self, alignment: TextAlignment) -> Self {
self.set_text_alignment(alignment);
self
}
/// Set the text color.
///
/// The argument can be either a `Color` or a [`Key<Color>`].
///
/// If you change this property, you are responsible for calling
/// [`request_layout`] to ensure the label is updated.
///
/// [`request_layout`]: EventCtx::request_layout
/// [`Key<Color>`]: crate::Key
pub fn set_text_color(&mut self, color: impl Into<KeyOrValue<Color>>) {
let color = color.into();
if !self.disabled {
self.layout.set_text_color(color.clone());
}
self.default_text_color = color;
}
/// Set the text size.
///
/// The argument can be either an `f64` or a [`Key<f64>`].
///
/// If you change this property, you are responsible for calling
/// [`request_layout`] to ensure the label is updated.
///
/// [`request_layout`]: EventCtx::request_layout
/// [`Key<f64>`]: crate::Key
pub fn set_text_size(&mut self, size: impl Into<KeyOrValue<f64>>) {
self.layout.set_text_size(size);
}
/// Set the font.
///
/// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`]
/// that refers to a font defined in the [`Env`].
///
/// If you change this property, you are responsible for calling
/// [`request_layout`] to ensure the label is updated.
///
/// [`request_layout`]: EventCtx::request_layout
/// [`Key<FontDescriptor>`]: crate::Key
pub fn set_font(&mut self, font: impl Into<KeyOrValue<FontDescriptor>>) {
self.layout.set_font(font);
}
/// Set the [`LineBreaking`] behaviour.
///
/// If you change this property, you are responsible for calling
/// [`request_layout`] to ensure the label is updated.
///
/// [`request_layout`]: EventCtx::request_layout
pub fn set_line_break_mode(&mut self, mode: LineBreaking) {
self.line_break_mode = mode;
}
/// Set the [`TextAlignment`] for this layout.
pub fn set_text_alignment(&mut self, alignment: TextAlignment) {
self.layout.set_text_alignment(alignment);
}
/// Draw this label's text at the provided `Point`, without internal padding.
///
/// This is a convenience for widgets that want to use Label as a way
/// of managing a dynamic or localized string, but want finer control
/// over where the text is drawn.
pub fn draw_at(&self, ctx: &mut PaintCtx, origin: impl Into<Point>) {
self.layout.draw(ctx, origin)
}
/// Return the offset of the first baseline relative to the bottom of the widget.
pub fn baseline_offset(&self) -> f64 {
let text_metrics = self.layout.layout_metrics();
text_metrics.size.height - text_metrics.first_baseline
}
}
impl<T: TextStorage> Label<T> {
/// Create a new [`RawLabel`].
///
/// This can display text `Data` directly.
pub fn raw() -> RawLabel<T> {
RawLabel::new()
}
}
impl<T: Data> Label<T> {
/// Construct a new `Label` widget.
///
/// ```
/// use druid::LocalizedString;
/// use druid::widget::Label;
///
/// // Construct a new Label using static string.
/// let _: Label<u32> = Label::new("Hello world");
///
/// // Construct a new Label using localized string.
/// let text = LocalizedString::new("hello-counter").with_arg("count", |data: &u32, _env| (*data).into());
/// let _: Label<u32> = Label::new(text);
///
/// // Construct a new dynamic Label. Text will be updated when data changes.
/// let _: Label<u32> = Label::new(|data: &u32, _env: &_| format!("Hello world: {}", data));
/// ```
pub fn new(text: impl Into<LabelText<T>>) -> Self {
let text = text.into();
let current_text = text.display_text();
Self {
text,
current_text,
label: RawLabel::new(),
text_should_be_updated: true,
}
}
/// Construct a new dynamic label.
///
/// The contents of this label are generated from the data using a closure.
///
/// This is provided as a convenience; a closure can also be passed to [`new`],
/// but due to limitations of the implementation of that method, the types in
/// the closure need to be annotated, which is not true for this method.
///
/// # Examples
///
/// The following are equivalent.
///
/// ```
/// use druid::Env;
/// use druid::widget::Label;
/// let label1: Label<u32> = Label::new(|data: &u32, _: &Env| format!("total is {}", data));
/// let label2: Label<u32> = Label::dynamic(|data, _| format!("total is {}", data));
/// ```
///
/// [`new`]: Label::new
pub fn dynamic(text: impl Fn(&T, &Env) -> String + 'static) -> Self {
let text: LabelText<T> = text.into();
Label::new(text)
}
/// Return the current value of the label's text.
pub fn text(&self) -> ArcStr {
self.text.display_text()
}
/// Set the label's text.
///
/// # Note
///
/// If you change this property, at runtime, you **must** ensure that [`update`]
/// is called in order to correctly recompute the text. If you are unsure,
/// call [`request_update`] explicitly.
///
/// [`update`]: Widget::update
/// [`request_update`]: EventCtx::request_update
pub fn set_text(&mut self, text: impl Into<LabelText<T>>) {
self.text = text.into();
self.text_should_be_updated = true;
}
/// Builder-style method for setting the text color.
///
/// The argument can be either a `Color` or a [`Key<Color>`].
///
/// [`Key<Color>`]: crate::Key
pub fn with_text_color(mut self, color: impl Into<KeyOrValue<Color>>) -> Self {
self.label.set_text_color(color);
self
}
/// Builder-style method for setting the text size.
///
/// The argument can be either an `f64` or a [`Key<f64>`].
///
/// [`Key<f64>`]: crate::Key
pub fn with_text_size(mut self, size: impl Into<KeyOrValue<f64>>) -> Self {
self.label.set_text_size(size);
self
}
/// Builder-style method for setting the font.
///
/// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`]
/// that refers to a font defined in the [`Env`].
///
/// [`Key<FontDescriptor>`]: crate::Key
pub fn with_font(mut self, font: impl Into<KeyOrValue<FontDescriptor>>) -> Self {
self.label.set_font(font);
self
}
/// Builder-style method to set the [`LineBreaking`] behaviour.
pub fn with_line_break_mode(mut self, mode: LineBreaking) -> Self {
self.label.set_line_break_mode(mode);
self
}
/// Builder-style method to set the [`TextAlignment`].
pub fn with_text_alignment(mut self, alignment: TextAlignment) -> Self {
self.label.set_text_alignment(alignment);
self
}
/// Draw this label's text at the provided `Point`, without internal padding.
///
/// This is a convenience for widgets that want to use Label as a way
/// of managing a dynamic or localized string, but want finer control
/// over where the text is drawn.
pub fn draw_at(&self, ctx: &mut PaintCtx, origin: impl Into<Point>) {
self.label.draw_at(ctx, origin)
}
}
impl Static {
fn new(s: ArcStr) -> Self {
Static {
string: s,
resolved: false,
}
}
fn resolve(&mut self) -> bool {
let is_first_call = !self.resolved;
self.resolved = true;
is_first_call
}
}
impl<T> Dynamic<T> {
fn resolve(&mut self, data: &T, env: &Env) -> bool {
let new = (self.f)(data, env);
let changed = new != self.resolved;
self.resolved = new;
changed
}
}
impl<T: Data> LabelText<T> {
/// Call callback with the text that should be displayed.
pub fn with_display_text<V>(&self, mut cb: impl FnMut(&str) -> V) -> V {
match self {
LabelText::Static(s) => cb(&s.string),
LabelText::Localized(s) => cb(&s.localized_str()),
LabelText::Dynamic(s) => cb(&s.resolved),
}
}
/// Return the current resolved text.
pub fn display_text(&self) -> ArcStr {
match self {
LabelText::Static(s) => s.string.clone(),
LabelText::Localized(s) => s.localized_str(),
LabelText::Dynamic(s) => s.resolved.clone(),
}
}
/// Update the localization, if necessary.
/// This ensures that localized strings are up to date.
///
/// Returns `true` if the string has changed.
pub fn resolve(&mut self, data: &T, env: &Env) -> bool {
match self {
LabelText::Static(s) => s.resolve(),
LabelText::Localized(s) => s.resolve(data, env),
LabelText::Dynamic(s) => s.resolve(data, env),
}
}
}
impl<T: Data> Widget<T> for Label<T> {
#[instrument(name = "Label", level = "trace", skip(self, _ctx, _event, _data, _env))]
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut T, _env: &Env) {}
#[instrument(name = "Label", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
if matches!(event, LifeCycle::WidgetAdded) {
self.text.resolve(data, env);
self.text_should_be_updated = false;
}
self.label
.lifecycle(ctx, event, &self.text.display_text(), env);
}
#[instrument(name = "Label", level = "trace", skip(self, ctx, _old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
let data_changed = self.text.resolve(data, env);
self.text_should_be_updated = false;
if data_changed {
let new_text = self.text.display_text();
self.label.update(ctx, &self.current_text, &new_text, env);
self.current_text = new_text;
} else if ctx.env_changed() {
self.label
.update(ctx, &self.current_text, &self.current_text, env);
}
}
#[instrument(name = "Label", level = "trace", skip(self, ctx, bc, _data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size {
self.label.layout(ctx, bc, &self.current_text, env)
}
#[instrument(name = "Label", level = "trace", skip(self, ctx, _data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) {
if self.text_should_be_updated {
tracing::warn!("Label text changed without call to update. See LabelAdapter::set_text for information.");
}
self.label.paint(ctx, &self.current_text, env)
}
fn debug_state(&self, _data: &T) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
main_value: self.current_text.to_string(),
..Default::default()
}
}
fn compute_max_intrinsic(
&mut self,
axis: Axis,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &T,
env: &Env,
) -> f64 {
self.label
.compute_max_intrinsic(axis, ctx, bc, &self.current_text, env)
}
}
impl<T: TextStorage> Widget<T> for RawLabel<T> {
#[instrument(
name = "RawLabel",
level = "trace",
skip(self, ctx, event, _data, _env)
)]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut T, _env: &Env) {
match event {
Event::MouseUp(event) => {
// Account for the padding
let pos = event.pos - Vec2::new(LABEL_X_PADDING, 0.0);
if let Some(link) = self.layout.link_for_pos(pos) {
ctx.submit_command(link.command.clone());
}
}
Event::MouseMove(event) => {
// Account for the padding
let pos = event.pos - Vec2::new(LABEL_X_PADDING, 0.0);
if self.layout.link_for_pos(pos).is_some() {
ctx.set_cursor(&Cursor::Pointer);
} else {
ctx.clear_cursor();
}
}
_ => {}
}
}
#[instrument(name = "RawLabel", level = "trace", skip(self, ctx, event, data, _env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, _env: &Env) {
match event {
LifeCycle::WidgetAdded => {
self.layout.set_text(data.to_owned());
}
LifeCycle::DisabledChanged(disabled) => {
let color = if *disabled {
KeyOrValue::Key(crate::theme::DISABLED_TEXT_COLOR)
} else {
self.default_text_color.clone()
};
self.layout.set_text_color(color);
ctx.request_layout();
}
_ => {}
}
}
#[instrument(
name = "RawLabel",
level = "trace",
skip(self, ctx, old_data, data, _env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, _env: &Env) {
if !old_data.same(data) {
self.layout.set_text(data.clone());
ctx.request_layout();
}
if self.layout.needs_rebuild_after_update(ctx) {
ctx.request_layout();
}
}
#[instrument(name = "RawLabel", level = "trace", skip(self, ctx, bc, _data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size {
bc.debug_check("Label");
let width = match self.line_break_mode {
LineBreaking::WordWrap => bc.max().width - LABEL_X_PADDING * 2.0,
_ => f64::INFINITY,
};
self.layout.set_wrap_width(width);
self.layout.rebuild_if_needed(ctx.text(), env);
let text_metrics = self.layout.layout_metrics();
ctx.set_baseline_offset(text_metrics.size.height - text_metrics.first_baseline);
let size = bc.constrain(Size::new(
text_metrics.size.width + 2. * LABEL_X_PADDING,
text_metrics.size.height,
));
trace!("Computed size: {}", size);
size
}
#[instrument(name = "RawLabel", level = "trace", skip(self, ctx, _data, _env))]
fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, _env: &Env) {
let origin = Point::new(LABEL_X_PADDING, 0.0);
let label_size = ctx.size();
if self.line_break_mode == LineBreaking::Clip {
ctx.clip(label_size.to_rect());
}
self.draw_at(ctx, origin)
}
fn compute_max_intrinsic(
&mut self,
axis: Axis,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &T,
env: &Env,
) -> f64 {
match axis {
Axis::Horizontal => {
match self.line_break_mode {
LineBreaking::WordWrap => {
// Height is irrelevant for labels. So max preferred/intrinsic width of a label is the size
// it'd take without any word wrapping.
self.line_break_mode = LineBreaking::Clip;
let s = self.layout(ctx, bc, data, env);
self.line_break_mode = LineBreaking::WordWrap;
s.width
}
_ => self.layout(ctx, bc, data, env).width,
}
}
Axis::Vertical => {
warn!("Max intrinsic height of a label is not implemented.");
0.
}
}
}
}
impl<T: TextStorage> Default for RawLabel<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Deref for Label<T> {
type Target = RawLabel<ArcStr>;
fn deref(&self) -> &Self::Target {
&self.label
}
}
impl<T> DerefMut for Label<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.label
}
}
impl<T> From<String> for LabelText<T> {
fn from(src: String) -> LabelText<T> {
LabelText::Static(Static::new(src.into()))
}
}
impl<T> From<&str> for LabelText<T> {
fn from(src: &str) -> LabelText<T> {
LabelText::Static(Static::new(src.into()))
}
}
impl<T> From<ArcStr> for LabelText<T> {
fn from(string: ArcStr) -> LabelText<T> {
LabelText::Static(Static::new(string))
}
}
impl<T> From<LocalizedString<T>> for LabelText<T> {
fn from(src: LocalizedString<T>) -> LabelText<T> {
LabelText::Localized(src)
}
}
impl<T, S, F> From<F> for LabelText<T>
where
S: Into<Arc<str>>,
F: Fn(&T, &Env) -> S + 'static,
{
fn from(src: F) -> LabelText<T> {
let f = Arc::new(move |state: &T, env: &Env| src(state, env).into());
LabelText::Dynamic(Dynamic {
f,
resolved: ArcStr::from(""),
})
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/spinner.rs | druid/src/widget/spinner.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An animated spinner widget.
use std::f64::consts::PI;
use tracing::{instrument, trace};
use druid::kurbo::Line;
use druid::widget::prelude::*;
use druid::{theme, Color, Data, KeyOrValue, Point, Vec2};
/// An animated spinner widget for showing a loading state.
///
/// To customize the spinner's size, you can place it inside a [`SizedBox`]
/// that has a fixed width and height.
///
/// [`SizedBox`]: super::SizedBox
pub struct Spinner {
t: f64,
color: KeyOrValue<Color>,
}
impl Spinner {
/// Create a spinner widget
pub fn new() -> Spinner {
Spinner::default()
}
/// Builder-style method for setting the spinner's color.
///
/// The argument can be either a [`Color`] or a [`Key<Color>`].
///
/// [`Key<Color>`]: crate::Key
pub fn with_color(mut self, color: impl Into<KeyOrValue<Color>>) -> Self {
self.color = color.into();
self
}
/// Set the spinner's color.
///
/// The argument can be either a [`Color`] or a [`Key<Color>`].
///
/// [`Key<Color>`]: crate::Key
pub fn set_color(&mut self, color: impl Into<KeyOrValue<Color>>) {
self.color = color.into();
}
}
impl Default for Spinner {
fn default() -> Self {
Spinner {
t: 0.0,
color: theme::TEXT_COLOR.into(),
}
}
}
impl<T: Data> Widget<T> for Spinner {
#[instrument(name = "Spinner", level = "trace", skip(self, ctx, event, _data, _env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut T, _env: &Env) {
if let Event::AnimFrame(interval) = event {
self.t += (*interval as f64) * 1e-9;
if self.t >= 1.0 {
self.t = 0.0;
}
ctx.request_anim_frame();
ctx.request_paint();
}
}
#[instrument(name = "Spinner", level = "trace", skip(self, ctx, event, _data, _env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &T, _env: &Env) {
if let LifeCycle::WidgetAdded = event {
ctx.request_anim_frame();
ctx.request_paint();
}
}
#[instrument(
name = "Spinner",
level = "trace",
skip(self, _ctx, _old_data, _data, _env)
)]
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &T, _data: &T, _env: &Env) {}
#[instrument(
name = "Spinner",
level = "trace",
skip(self, _layout_ctx, bc, _data, env)
)]
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &T,
env: &Env,
) -> Size {
bc.debug_check("Spinner");
let size = if bc.is_width_bounded() && bc.is_height_bounded() {
bc.max()
} else {
bc.constrain(Size::new(
env.get(theme::BASIC_WIDGET_HEIGHT),
env.get(theme::BASIC_WIDGET_HEIGHT),
))
};
trace!("Computed size: {}", size);
size
}
#[instrument(name = "Spinner", level = "trace", skip(self, ctx, _data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) {
let t = self.t;
let (width, height) = (ctx.size().width, ctx.size().height);
let center = Point::new(width / 2.0, height / 2.0);
let (r, g, b, original_alpha) = Color::as_rgba(self.color.resolve(env));
let scale_factor = width.min(height) / 40.0;
for step in 1..=12 {
let step = f64::from(step);
let fade_t = (t * 12.0 + 1.0).trunc();
let fade = ((fade_t + step).rem_euclid(12.0) / 12.0) + 1.0 / 12.0;
let angle = Vec2::from_angle((step / 12.0) * -2.0 * PI);
let ambit_start = center + (10.0 * scale_factor * angle);
let ambit_end = center + (20.0 * scale_factor * angle);
let color = Color::rgba(r, g, b, fade * original_alpha);
ctx.stroke(
Line::new(ambit_start, ambit_end),
&color,
3.0 * scale_factor,
);
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/disable_if.rs | druid/src/widget/disable_if.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use crate::debug_state::DebugState;
use crate::{
BoxConstraints, Data, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx,
Point, Size, UpdateCtx, Widget, WidgetPod,
};
/// A widget wrapper which disables the child widget if the provided closure return true.
///
/// See [`is_disabled`] or [`set_disabled`] for more info about disabled state.
///
/// [`is_disabled`]: crate::EventCtx::is_disabled
/// [`set_disabled`]: crate::EventCtx::set_disabled
pub struct DisabledIf<T, W> {
child: WidgetPod<T, W>,
disabled_if: Box<dyn Fn(&T, &Env) -> bool>,
}
impl<T: Data, W: Widget<T>> DisabledIf<T, W> {
/// Creates a new `DisabledIf` widget with the child widget and the closure to decide if the
/// widget should be [`disabled`].
///
/// [`disabled`]: crate::EventCtx::is_disabled
pub fn new(widget: W, disabled_if: impl Fn(&T, &Env) -> bool + 'static) -> Self {
DisabledIf {
child: WidgetPod::new(widget),
disabled_if: Box::new(disabled_if),
}
}
}
impl<T: Data, W: Widget<T>> Widget<T> for DisabledIf<T, W> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
self.child.event(ctx, event, data, env);
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
if let LifeCycle::WidgetAdded = event {
ctx.set_disabled((self.disabled_if)(data, env));
}
self.child.lifecycle(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, _: &T, data: &T, env: &Env) {
ctx.set_disabled((self.disabled_if)(data, env));
self.child.update(ctx, data, env);
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let size = self.child.layout(ctx, bc, data, env);
self.child.set_origin(ctx, Point::ZERO);
ctx.set_baseline_offset(self.child.baseline_offset());
size
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
self.child.paint(ctx, data, env);
}
fn debug_state(&self, data: &T) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
children: vec![self.child.widget().debug_state(data)],
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/lens_wrap.rs | druid/src/widget/lens_wrap.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A [`Widget`] that uses a [`Lens`] to change the [`Data`] of its child.
use std::marker::PhantomData;
use crate::debug_state::DebugState;
use crate::widget::prelude::*;
use crate::widget::WidgetWrapper;
use crate::{Data, Lens};
use tracing::{instrument, trace};
/// A wrapper for its widget subtree to have access to a part
/// of its parent's data.
///
/// Every widget in Druid is instantiated with access to data of some
/// type; the root widget has access to the entire application data.
/// Often, a part of the widget hierarchy is only concerned with a part
/// of that data. The `LensWrap` widget is a way to "focus" the data
/// reference down, for the subtree. One advantage is performance;
/// data changes that don't intersect the scope of the lens aren't
/// propagated.
///
/// Another advantage is generality and reuse. If a widget (or tree of
/// widgets) is designed to work with some chunk of data, then with a
/// lens that same code can easily be reused across all occurrences of
/// that chunk within the application state.
///
/// This wrapper takes a [`Lens`] as an argument, which is a specification
/// of a struct field, or some other way of narrowing the scope.
pub struct LensWrap<T, U, L, W> {
child: W,
lens: L,
// The following is a workaround for otherwise getting E0207.
// the 'in' data type of the lens
phantom_u: PhantomData<U>,
// the 'out' data type of the lens
phantom_t: PhantomData<T>,
}
impl<T, U, L, W> LensWrap<T, U, L, W> {
/// Wrap a widget with a lens.
///
/// When the lens has type `Lens<T, U>`, the child widget has data
/// of type `U`, and the wrapped widget has data of type `T`.
pub fn new(child: W, lens: L) -> LensWrap<T, U, L, W> {
LensWrap {
child,
lens,
phantom_u: Default::default(),
phantom_t: Default::default(),
}
}
/// Get a reference to the lens.
pub fn lens(&self) -> &L {
&self.lens
}
/// Get a mutable reference to the lens.
pub fn lens_mut(&mut self) -> &mut L {
&mut self.lens
}
}
impl<T, U, L, W> Widget<T> for LensWrap<T, U, L, W>
where
T: Data,
U: Data,
L: Lens<T, U>,
W: Widget<U>,
{
#[instrument(name = "LensWrap", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
let child = &mut self.child;
self.lens
.with_mut(data, |data| child.event(ctx, event, data, env))
}
#[instrument(name = "LensWrap", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
let child = &mut self.child;
self.lens
.with(data, |data| child.lifecycle(ctx, event, data, env))
}
#[instrument(
name = "LensWrap",
level = "trace",
skip(self, ctx, old_data, data, env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
let child = &mut self.child;
let lens = &self.lens;
lens.with(old_data, |old_data| {
lens.with(data, |data| {
if ctx.has_requested_update() || !old_data.same(data) || ctx.env_changed() {
child.update(ctx, old_data, data, env);
} else {
trace!("skipping child update");
}
})
})
}
#[instrument(name = "LensWrap", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let child = &mut self.child;
self.lens
.with(data, |data| child.layout(ctx, bc, data, env))
}
#[instrument(name = "LensWrap", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
let child = &mut self.child;
self.lens.with(data, |data| child.paint(ctx, data, env));
}
fn id(&self) -> Option<WidgetId> {
self.child.id()
}
fn debug_state(&self, data: &T) -> DebugState {
let child_state = self.lens.with(data, |data| self.child.debug_state(data));
DebugState {
display_name: "LensWrap".to_string(),
children: vec![child_state],
..Default::default()
}
}
}
impl<T, U, L, W> WidgetWrapper for LensWrap<T, U, L, W> {
widget_wrapper_body!(W, child);
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/switch.rs | druid/src/widget/switch.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A toggle switch widget.
use std::time::Duration;
use tracing::{instrument, trace};
use crate::debug_state::DebugState;
use crate::kurbo::{Circle, Shape};
use crate::piet::{LinearGradient, RenderContext, UnitPoint};
use crate::widget::prelude::*;
use crate::{theme, ArcStr, Point, TextLayout};
const SWITCH_CHANGE_TIME: f64 = 0.2;
const SWITCH_PADDING: f64 = 3.;
const SWITCH_WIDTH_RATIO: f64 = 2.75;
/// A switch that toggles a `bool`.
#[derive(Debug, Clone)]
pub struct Switch {
knob_pos: Point,
knob_hovered: bool,
knob_dragged: bool,
animation_in_progress: bool,
on_text: TextLayout<ArcStr>,
off_text: TextLayout<ArcStr>,
}
impl Default for Switch {
fn default() -> Self {
Switch {
knob_pos: Point::ZERO,
knob_hovered: false,
knob_dragged: false,
animation_in_progress: false,
//TODO: use localized strings, also probably make these configurable?
on_text: TextLayout::from_text("ON"),
off_text: TextLayout::from_text("OFF"),
}
}
}
impl Switch {
/// Create a new `Switch`.
pub fn new() -> Switch {
Self::default()
}
fn knob_hit_test(&self, knob_width: f64, mouse_pos: Point) -> bool {
let knob_circle = Circle::new(self.knob_pos, knob_width / 2.);
knob_circle.winding(mouse_pos) > 0
}
fn paint_labels(&mut self, ctx: &mut PaintCtx, env: &Env, switch_width: f64) {
self.on_text.rebuild_if_needed(ctx.text(), env);
self.off_text.rebuild_if_needed(ctx.text(), env);
let switch_height = env.get(theme::BORDERED_WIDGET_HEIGHT);
let knob_size = switch_height - 2. * SWITCH_PADDING;
let on_size = self.on_text.size();
let off_size = self.off_text.size();
let label_y = (switch_height - on_size.height).max(0.0) / 2.0;
let label_x_space = switch_width - knob_size - SWITCH_PADDING * 2.0;
let off_pos = knob_size / 2. + SWITCH_PADDING;
let knob_delta = self.knob_pos.x - off_pos;
let on_label_width = on_size.width;
let on_base_x_pos =
-on_label_width - (label_x_space - on_label_width) / 2.0 + SWITCH_PADDING;
let on_label_origin = Point::new(on_base_x_pos + knob_delta, label_y);
let off_base_x_pos = knob_size + (label_x_space - off_size.width) / 2.0 + SWITCH_PADDING;
let off_label_origin = Point::new(off_base_x_pos + knob_delta, label_y);
self.on_text.draw(ctx, on_label_origin);
self.off_text.draw(ctx, off_label_origin);
}
}
impl Widget<bool> for Switch {
#[instrument(name = "Switch", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut bool, env: &Env) {
let switch_height = env.get(theme::BORDERED_WIDGET_HEIGHT);
let switch_width = switch_height * SWITCH_WIDTH_RATIO;
let knob_size = switch_height - 2. * SWITCH_PADDING;
let on_pos = switch_width - knob_size / 2. - SWITCH_PADDING;
let off_pos = knob_size / 2. + SWITCH_PADDING;
match event {
Event::MouseDown(_) => {
if !ctx.is_disabled() {
ctx.set_active(true);
ctx.request_paint();
}
}
Event::MouseUp(_) => {
if !ctx.is_disabled() {
if self.knob_dragged {
// toggle value when dragging if knob has been moved far enough
*data = self.knob_pos.x > switch_width / 2.;
} else if ctx.is_active() {
// toggle value on click
*data = !*data;
}
}
ctx.set_active(false);
self.knob_dragged = false;
self.animation_in_progress = true;
ctx.request_anim_frame();
}
Event::MouseMove(mouse) => {
if !ctx.is_disabled() {
if ctx.is_active() {
self.knob_pos.x = mouse.pos.x.clamp(off_pos, on_pos);
self.knob_dragged = true;
}
if ctx.is_hot() {
self.knob_hovered = self.knob_hit_test(knob_size, mouse.pos)
}
ctx.request_paint();
} else {
ctx.set_active(false);
}
}
Event::AnimFrame(interval) => {
let delta = Duration::from_nanos(*interval).as_secs_f64();
// move knob to right position depending on the value
if self.animation_in_progress {
let change_time = if *data {
SWITCH_CHANGE_TIME
} else {
-SWITCH_CHANGE_TIME
};
let change = (switch_width / change_time) * delta;
self.knob_pos.x = (self.knob_pos.x + change).clamp(off_pos, on_pos);
if (self.knob_pos.x > off_pos && !*data) || (self.knob_pos.x < on_pos && *data)
{
ctx.request_anim_frame();
} else {
self.animation_in_progress = false;
}
ctx.request_paint();
}
}
_ => (),
}
}
#[instrument(name = "Switch", level = "trace", skip(self, ctx, event, _data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &bool, env: &Env) {
match event {
LifeCycle::WidgetAdded => {
self.on_text.rebuild_if_needed(ctx.text(), env);
self.off_text.rebuild_if_needed(ctx.text(), env);
}
LifeCycle::DisabledChanged(true) if self.knob_dragged => {
self.knob_dragged = false;
self.animation_in_progress = true;
ctx.request_anim_frame();
}
LifeCycle::DisabledChanged(disabled) => {
ctx.request_paint();
let color = if *disabled {
theme::DISABLED_TEXT_COLOR
} else {
theme::TEXT_COLOR
};
self.off_text.set_text_color(color.clone());
self.on_text.set_text_color(color);
ctx.request_paint();
}
_ => {}
}
}
#[instrument(
name = "Switch",
level = "trace",
skip(self, ctx, old_data, data, _env)
)]
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &bool, data: &bool, _env: &Env) {
if old_data != data {
self.animation_in_progress = true;
ctx.request_anim_frame();
}
}
#[instrument(name = "Switch", level = "trace", skip(self, ctx, bc, _data, env))]
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &bool,
env: &Env,
) -> Size {
self.on_text.rebuild_if_needed(ctx.text(), env);
let text_metrics = self.on_text.layout_metrics();
let height = env.get(theme::BORDERED_WIDGET_HEIGHT);
let width = height * SWITCH_WIDTH_RATIO;
let label_y = (height - text_metrics.size.height).max(0.0) / 2.0;
let text_bottom_padding = height - (text_metrics.size.height + label_y);
let text_baseline_offset = text_metrics.size.height - text_metrics.first_baseline;
ctx.set_baseline_offset(text_bottom_padding + text_baseline_offset);
let size = bc.constrain(Size::new(width, height));
trace!("Computed size: {}", size);
size
}
#[instrument(name = "Switch", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &bool, env: &Env) {
let switch_height = env.get(theme::BORDERED_WIDGET_HEIGHT);
let switch_width = switch_height * SWITCH_WIDTH_RATIO;
let knob_size = switch_height - 2. * SWITCH_PADDING;
let on_pos = switch_width - knob_size / 2. - SWITCH_PADDING;
let off_pos = knob_size / 2. + SWITCH_PADDING;
let stroke_width = 2.0;
let background_rect = Size::new(switch_width, switch_height)
.to_rect()
.inset(-stroke_width / 2.0)
.to_rounded_rect(switch_height / 2.);
// position knob
if !self.animation_in_progress && !self.knob_dragged {
if *data {
self.knob_pos.x = on_pos;
} else {
self.knob_pos.x = off_pos;
}
};
self.knob_pos = Point::new(self.knob_pos.x, knob_size / 2. + SWITCH_PADDING);
let knob_circle = Circle::new(self.knob_pos, knob_size / 2.);
// paint different background for on and off state
// opacity of background color depends on knob position
// todo: make color configurable
let opacity = if ctx.is_disabled() {
0.0
} else {
(self.knob_pos.x - off_pos) / (on_pos - off_pos)
};
let background_gradient_on_state = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::PRIMARY_LIGHT).with_alpha(opacity),
env.get(theme::PRIMARY_DARK).with_alpha(opacity),
),
);
let background_gradient_off_state = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::BACKGROUND_LIGHT).with_alpha(1. - opacity),
env.get(theme::BACKGROUND_DARK).with_alpha(1. - opacity),
),
);
ctx.stroke(background_rect, &env.get(theme::BORDER_DARK), stroke_width);
ctx.fill(background_rect, &background_gradient_on_state);
ctx.fill(background_rect, &background_gradient_off_state);
ctx.clip(background_rect);
// paint the knob
let is_active = ctx.is_active();
let is_hovered = self.knob_hovered;
let knob_gradient = if ctx.is_disabled() {
LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::DISABLED_FOREGROUND_LIGHT),
env.get(theme::DISABLED_FOREGROUND_DARK),
),
)
} else if is_active {
LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::FOREGROUND_DARK),
env.get(theme::FOREGROUND_LIGHT),
),
)
} else {
LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::FOREGROUND_LIGHT),
env.get(theme::FOREGROUND_DARK),
),
)
};
// paint the border
let border_color = if is_hovered || is_active {
env.get(theme::FOREGROUND_LIGHT)
} else {
env.get(theme::FOREGROUND_DARK)
};
ctx.stroke(knob_circle, &border_color, 2.);
ctx.fill(knob_circle, &knob_gradient);
// paint on/off label
self.paint_labels(ctx, env, switch_width);
}
fn debug_state(&self, data: &bool) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
main_value: data.to_string(),
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/padding.rs | druid/src/widget/padding.rs | // Copyright 2018 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget that just adds padding during layout.
use crate::debug_state::DebugState;
use crate::widget::{prelude::*, Axis, WidgetWrapper};
use crate::{Data, Insets, KeyOrValue, Point, WidgetPod};
use tracing::{instrument, trace};
/// A widget that just adds padding around its child.
pub struct Padding<T, W> {
insets: KeyOrValue<Insets>,
child: WidgetPod<T, W>,
}
impl<T, W: Widget<T>> Padding<T, W> {
/// Create a new `Padding` with the specified padding and child.
///
/// The `insets` argument can either be an instance of [`Insets`],
/// a [`Key`] referring to [`Insets`] in the [`Env`],
/// an `f64` for uniform padding, an `(f64, f64)` for axis-uniform padding,
/// or `(f64, f64, f64, f64)` (left, top, right, bottom) values.
///
/// # Examples
///
/// Uniform padding:
///
/// ```
/// use druid::widget::{Label, Padding};
/// use druid::kurbo::Insets;
///
/// let _: Padding<(), _> = Padding::new(10.0, Label::new("uniform!"));
/// let _: Padding<(), _> = Padding::new(Insets::uniform(10.0), Label::new("uniform!"));
/// ```
///
/// Uniform padding across each axis:
///
/// ```
/// use druid::widget::{Label, Padding};
/// use druid::kurbo::Insets;
///
/// let child: Label<()> = Label::new("I need my space!");
/// let _: Padding<(), _> = Padding::new((10.0, 20.0), Label::new("more y than x!"));
/// // equivalent:
/// let _: Padding<(), _> = Padding::new(Insets::uniform_xy(10.0, 20.0), Label::new("ditto :)"));
/// ```
///
/// [`Key`]: crate::Key
pub fn new(insets: impl Into<KeyOrValue<Insets>>, child: W) -> Padding<T, W> {
Padding {
insets: insets.into(),
child: WidgetPod::new(child),
}
}
}
impl<T, W> WidgetWrapper for Padding<T, W> {
widget_wrapper_pod_body!(W, child);
}
impl<T: Data, W: Widget<T>> Widget<T> for Padding<T, W> {
#[instrument(name = "Padding", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
self.child.event(ctx, event, data, env)
}
#[instrument(name = "Padding", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.child.lifecycle(ctx, event, data, env)
}
#[instrument(name = "Padding", level = "trace", skip(self, ctx, _old, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old: &T, data: &T, env: &Env) {
if ctx.env_key_changed(&self.insets) {
ctx.request_layout();
}
self.child.update(ctx, data, env);
}
#[instrument(name = "Padding", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
bc.debug_check("Padding");
let insets = self.insets.resolve(env);
let hpad = insets.x0 + insets.x1;
let vpad = insets.y0 + insets.y1;
let child_bc = bc.shrink((hpad, vpad));
let size = self.child.layout(ctx, &child_bc, data, env);
let origin = Point::new(insets.x0, insets.y0);
self.child.set_origin(ctx, origin);
let my_size = Size::new(size.width + hpad, size.height + vpad);
let my_insets = self.child.compute_parent_paint_insets(my_size);
ctx.set_paint_insets(my_insets);
let baseline_offset = self.child.baseline_offset();
if baseline_offset > 0f64 {
ctx.set_baseline_offset(baseline_offset + insets.y1);
}
trace!("Computed layout: size={}, insets={:?}", my_size, my_insets);
my_size
}
#[instrument(name = "Padding", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
self.child.paint(ctx, data, env);
}
fn debug_state(&self, data: &T) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
children: vec![self.child.widget().debug_state(data)],
..Default::default()
}
}
fn compute_max_intrinsic(
&mut self,
axis: Axis,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &T,
env: &Env,
) -> f64 {
let inset_size = self.insets.resolve(env).size();
let child_bc = bc.shrink(inset_size);
let child_max_intrinsic_width = self
.child
.widget_mut()
.compute_max_intrinsic(axis, ctx, &child_bc, data, env);
child_max_intrinsic_width + axis.major(inset_size)
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/split.rs | druid/src/widget/split.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A widget which splits an area in two, with a settable ratio, and optional draggable resizing.
use crate::debug_state::DebugState;
use crate::kurbo::Line;
use crate::widget::flex::Axis;
use crate::widget::prelude::*;
use crate::{theme, Color, Cursor, Data, Point, Rect, WidgetPod};
use tracing::{instrument, trace, warn};
/// A container containing two other widgets, splitting the area either horizontally or vertically.
pub struct Split<T> {
split_axis: Axis,
split_point_chosen: f64,
split_point_effective: f64,
min_size: (f64, f64), // Integers only
bar_size: f64, // Integers only
min_bar_area: f64, // Integers only
solid: bool,
draggable: bool,
/// The split bar is hovered by the mouse. This state is locked to `true` if the
/// widget is active (the bar is being dragged) to avoid cursor and painting jitter
/// if the mouse moves faster than the layout and temporarily gets outside of the
/// bar area while still being dragged.
is_bar_hover: bool,
/// Offset from the split point (bar center) to the actual mouse position when the
/// bar was clicked. This is used to ensure a click without mouse move is a no-op,
/// instead of re-centering the bar on the mouse.
click_offset: f64,
child1: WidgetPod<T, Box<dyn Widget<T>>>,
old_bc_1: BoxConstraints,
child2: WidgetPod<T, Box<dyn Widget<T>>>,
old_bc_2: BoxConstraints,
}
impl<T> Split<T> {
/// Create a new split panel, with the specified axis being split in two.
///
/// Horizontal split axis means that the children are left and right.
/// Vertical split axis means that the children are up and down.
fn new(
split_axis: Axis,
child1: impl Widget<T> + 'static,
child2: impl Widget<T> + 'static,
) -> Self {
Split {
split_axis,
split_point_chosen: 0.5,
split_point_effective: 0.5,
min_size: (0.0, 0.0),
bar_size: 6.0,
min_bar_area: 6.0,
solid: false,
draggable: false,
is_bar_hover: false,
click_offset: 0.0,
child1: WidgetPod::new(child1).boxed(),
old_bc_1: BoxConstraints::tight(Size::ZERO),
child2: WidgetPod::new(child2).boxed(),
old_bc_2: BoxConstraints::tight(Size::ZERO),
}
}
/// Create a new split panel, with the horizontal axis split in two by a vertical bar.
pub fn columns(
left_child: impl Widget<T> + 'static,
right_child: impl Widget<T> + 'static,
) -> Self {
Self::new(Axis::Horizontal, left_child, right_child)
}
/// Create a new split panel, with the vertical axis split in two by a horizontal bar.
pub fn rows(
upper_child: impl Widget<T> + 'static,
lower_child: impl Widget<T> + 'static,
) -> Self {
Self::new(Axis::Vertical, upper_child, lower_child)
}
/// Builder-style method to set the split point as a fraction of the split axis.
///
/// The value must be between `0.0` and `1.0`, inclusive.
/// The default split point is `0.5`.
pub fn split_point(mut self, split_point: f64) -> Self {
assert!(
(0.0..=1.0).contains(&split_point),
"split_point must be in the range [0.0-1.0]!"
);
self.split_point_chosen = split_point;
self
}
/// Builder-style method to set the minimum size for both sides of the split axis.
///
/// The value must be greater than or equal to `0.0`.
/// The value will be rounded up to the nearest integer.
pub fn min_size(mut self, first: f64, second: f64) -> Self {
assert!(first >= 0.0);
assert!(second >= 0.0);
self.min_size = (first.ceil(), second.ceil());
self
}
/// Builder-style method to set the size of the splitter bar.
///
/// The value must be positive or zero.
/// The value will be rounded up to the nearest integer.
/// The default splitter bar size is `6.0`.
pub fn bar_size(mut self, bar_size: f64) -> Self {
assert!(bar_size >= 0.0, "bar_size must be 0.0 or greater!");
self.bar_size = bar_size.ceil();
self
}
/// Builder-style method to set the minimum size of the splitter bar area.
///
/// The minimum splitter bar area defines the minimum size of the area
/// where mouse hit detection is done for the splitter bar.
/// The final area is either this or the splitter bar size, whichever is greater.
///
/// This can be useful when you want to use a very narrow visual splitter bar,
/// but don't want to sacrifice user experience by making it hard to click on.
///
/// The value must be positive or zero.
/// The value will be rounded up to the nearest integer.
/// The default minimum splitter bar area is `6.0`.
pub fn min_bar_area(mut self, min_bar_area: f64) -> Self {
assert!(min_bar_area >= 0.0, "min_bar_area must be 0.0 or greater!");
self.min_bar_area = min_bar_area.ceil();
self
}
/// Builder-style method to set whether the split point can be changed by dragging.
pub fn draggable(mut self, draggable: bool) -> Self {
self.draggable = draggable;
self
}
/// Builder-style method to set whether the splitter bar is drawn as a solid rectangle.
///
/// If this is `false` (the default), the bar will be drawn as two parallel lines.
pub fn solid_bar(mut self, solid: bool) -> Self {
self.solid = solid;
self
}
/// Returns the size of the splitter bar area.
#[inline]
fn bar_area(&self) -> f64 {
self.bar_size.max(self.min_bar_area)
}
/// Returns the padding size added to each side of the splitter bar.
#[inline]
fn bar_padding(&self) -> f64 {
(self.bar_area() - self.bar_size) / 2.0
}
/// Returns the position of the split point (split bar center).
fn bar_position(&self, size: Size) -> f64 {
let bar_area = self.bar_area();
match self.split_axis {
Axis::Horizontal => {
let reduced_width = size.width - bar_area;
let edge1 = (reduced_width * self.split_point_effective).floor();
edge1 + bar_area / 2.0
}
Axis::Vertical => {
let reduced_height = size.height - bar_area;
let edge1 = (reduced_height * self.split_point_effective).floor();
edge1 + bar_area / 2.0
}
}
}
/// Returns the location of the edges of the splitter bar area,
/// given the specified total size.
fn bar_edges(&self, size: Size) -> (f64, f64) {
let bar_area = self.bar_area();
match self.split_axis {
Axis::Horizontal => {
let reduced_width = size.width - bar_area;
let edge1 = (reduced_width * self.split_point_effective).floor();
let edge2 = edge1 + bar_area;
(edge1, edge2)
}
Axis::Vertical => {
let reduced_height = size.height - bar_area;
let edge1 = (reduced_height * self.split_point_effective).floor();
let edge2 = edge1 + bar_area;
(edge1, edge2)
}
}
}
/// Returns true if the provided mouse position is inside the splitter bar area.
fn bar_hit_test(&self, size: Size, mouse_pos: Point) -> bool {
let (edge1, edge2) = self.bar_edges(size);
match self.split_axis {
Axis::Horizontal => mouse_pos.x >= edge1 && mouse_pos.x <= edge2,
Axis::Vertical => mouse_pos.y >= edge1 && mouse_pos.y <= edge2,
}
}
/// Returns the minimum and maximum split coordinate of the provided size.
fn split_side_limits(&self, size: Size) -> (f64, f64) {
let split_axis_size = self.split_axis.major(size);
let (mut min_limit, min_second) = self.min_size;
let mut max_limit = (split_axis_size - min_second).max(0.0);
if min_limit > max_limit {
min_limit = 0.5 * (min_limit + max_limit);
max_limit = min_limit;
}
(min_limit, max_limit)
}
/// Set a new chosen split point.
fn update_split_point(&mut self, size: Size, mouse_pos: Point) {
let (min_limit, max_limit) = self.split_side_limits(size);
self.split_point_chosen = match self.split_axis {
Axis::Horizontal => mouse_pos.x.clamp(min_limit, max_limit) / size.width,
Axis::Vertical => mouse_pos.y.clamp(min_limit, max_limit) / size.height,
}
}
/// Returns the color of the splitter bar.
fn bar_color(&self, env: &Env) -> Color {
if self.draggable {
env.get(theme::BORDER_LIGHT)
} else {
env.get(theme::BORDER_DARK)
}
}
fn paint_solid_bar(&mut self, ctx: &mut PaintCtx, env: &Env) {
let size = ctx.size();
let (edge1, edge2) = self.bar_edges(size);
let padding = self.bar_padding();
let rect = match self.split_axis {
Axis::Horizontal => Rect::from_points(
Point::new(edge1 + padding.ceil(), 0.0),
Point::new(edge2 - padding.floor(), size.height),
),
Axis::Vertical => Rect::from_points(
Point::new(0.0, edge1 + padding.ceil()),
Point::new(size.width, edge2 - padding.floor()),
),
};
let splitter_color = self.bar_color(env);
ctx.fill(rect, &splitter_color);
}
fn paint_stroked_bar(&mut self, ctx: &mut PaintCtx, env: &Env) {
let size = ctx.size();
// Set the line width to a third of the splitter bar size,
// because we'll paint two equal lines at the edges.
let line_width = (self.bar_size / 3.0).floor();
let line_midpoint = line_width / 2.0;
let (edge1, edge2) = self.bar_edges(size);
let padding = self.bar_padding();
let (line1, line2) = match self.split_axis {
Axis::Horizontal => (
Line::new(
Point::new(edge1 + line_midpoint + padding.ceil(), 0.0),
Point::new(edge1 + line_midpoint + padding.ceil(), size.height),
),
Line::new(
Point::new(edge2 - line_midpoint - padding.floor(), 0.0),
Point::new(edge2 - line_midpoint - padding.floor(), size.height),
),
),
Axis::Vertical => (
Line::new(
Point::new(0.0, edge1 + line_midpoint + padding.ceil()),
Point::new(size.width, edge1 + line_midpoint + padding.ceil()),
),
Line::new(
Point::new(0.0, edge2 - line_midpoint - padding.floor()),
Point::new(size.width, edge2 - line_midpoint - padding.floor()),
),
),
};
let splitter_color = self.bar_color(env);
ctx.stroke(line1, &splitter_color, line_width);
ctx.stroke(line2, &splitter_color, line_width);
}
}
impl<T: Data> Widget<T> for Split<T> {
#[instrument(name = "Split", level = "trace", skip(self, ctx, event, data, env))]
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
if self.child1.is_active() {
self.child1.event(ctx, event, data, env);
if ctx.is_handled() {
return;
}
}
if self.child2.is_active() {
self.child2.event(ctx, event, data, env);
if ctx.is_handled() {
return;
}
}
if self.draggable {
match event {
Event::MouseDown(mouse) => {
if mouse.button.is_left() && self.bar_hit_test(ctx.size(), mouse.pos) {
ctx.set_handled();
ctx.set_active(true);
// Save the delta between the mouse click position and the split point
self.click_offset = match self.split_axis {
Axis::Horizontal => mouse.pos.x,
Axis::Vertical => mouse.pos.y,
} - self.bar_position(ctx.size());
// If not already hovering, force and change cursor appropriately
if !self.is_bar_hover {
self.is_bar_hover = true;
match self.split_axis {
Axis::Horizontal => ctx.set_cursor(&Cursor::ResizeLeftRight),
Axis::Vertical => ctx.set_cursor(&Cursor::ResizeUpDown),
};
}
}
}
Event::MouseUp(mouse) => {
if mouse.button.is_left() && ctx.is_active() {
ctx.set_handled();
ctx.set_active(false);
// Dependending on where the mouse cursor is when the button is released,
// the cursor might or might not need to be changed
self.is_bar_hover =
ctx.is_hot() && self.bar_hit_test(ctx.size(), mouse.pos);
if !self.is_bar_hover {
ctx.clear_cursor()
}
}
}
Event::MouseMove(mouse) => {
if ctx.is_active() {
// If active, assume always hover/hot
let effective_pos = match self.split_axis {
Axis::Horizontal => {
Point::new(mouse.pos.x - self.click_offset, mouse.pos.y)
}
Axis::Vertical => {
Point::new(mouse.pos.x, mouse.pos.y - self.click_offset)
}
};
self.update_split_point(ctx.size(), effective_pos);
ctx.request_layout();
} else {
// If not active, set cursor when hovering state changes
let hover = ctx.is_hot() && self.bar_hit_test(ctx.size(), mouse.pos);
if hover != self.is_bar_hover {
self.is_bar_hover = hover;
if hover {
match self.split_axis {
Axis::Horizontal => ctx.set_cursor(&Cursor::ResizeLeftRight),
Axis::Vertical => ctx.set_cursor(&Cursor::ResizeUpDown),
};
} else {
ctx.clear_cursor();
}
}
}
}
_ => {}
}
}
if !self.child1.is_active() {
self.child1.event(ctx, event, data, env);
}
if !self.child2.is_active() {
self.child2.event(ctx, event, data, env);
}
}
#[instrument(name = "Split", level = "trace", skip(self, ctx, event, data, env))]
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.child1.lifecycle(ctx, event, data, env);
self.child2.lifecycle(ctx, event, data, env);
}
#[instrument(name = "Split", level = "trace", skip(self, ctx, _old_data, data, env))]
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
self.child1.update(ctx, data, env);
self.child2.update(ctx, data, env);
}
#[instrument(name = "Split", level = "trace", skip(self, ctx, bc, data, env))]
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
bc.debug_check("Split");
match self.split_axis {
Axis::Horizontal => {
if !bc.is_width_bounded() {
warn!("A Split widget was given an unbounded width to split.")
}
}
Axis::Vertical => {
if !bc.is_height_bounded() {
warn!("A Split widget was given an unbounded height to split.")
}
}
}
let mut my_size = bc.max();
let bar_area = self.bar_area();
let reduced_size = Size::new(
(my_size.width - bar_area).max(0.),
(my_size.height - bar_area).max(0.),
);
// Update our effective split point to respect our constraints
self.split_point_effective = {
let (min_limit, max_limit) = self.split_side_limits(reduced_size);
let reduced_axis_size = self.split_axis.major(reduced_size);
if reduced_axis_size.is_infinite() || reduced_axis_size <= f64::EPSILON {
0.5
} else {
self.split_point_chosen
.clamp(min_limit / reduced_axis_size, max_limit / reduced_axis_size)
}
};
let (child1_bc, child2_bc) = match self.split_axis {
Axis::Horizontal => {
let child1_width = (reduced_size.width * self.split_point_effective)
.floor()
.max(0.0);
let child2_width = (reduced_size.width - child1_width).max(0.0);
(
BoxConstraints::new(
Size::new(child1_width, bc.min().height),
Size::new(child1_width, bc.max().height),
),
BoxConstraints::new(
Size::new(child2_width, bc.min().height),
Size::new(child2_width, bc.max().height),
),
)
}
Axis::Vertical => {
let child1_height = (reduced_size.height * self.split_point_effective)
.floor()
.max(0.0);
let child2_height = (reduced_size.height - child1_height).max(0.0);
(
BoxConstraints::new(
Size::new(bc.min().width, child1_height),
Size::new(bc.max().width, child1_height),
),
BoxConstraints::new(
Size::new(bc.min().width, child2_height),
Size::new(bc.max().width, child2_height),
),
)
}
};
let child1_size = if self.old_bc_1 != child1_bc || self.child1.layout_requested() {
self.child1.layout(ctx, &child1_bc, data, env)
} else {
self.child1.layout_rect().size()
};
self.old_bc_1 = child1_bc;
let child2_size = if self.old_bc_2 != child2_bc || self.child2.layout_requested() {
self.child2.layout(ctx, &child2_bc, data, env)
} else {
self.child2.layout_rect().size()
};
self.old_bc_2 = child2_bc;
// Top-left align for both children, out of laziness.
// Reduce our unsplit direction to the larger of the two widgets
let child1_pos = Point::ORIGIN;
let child2_pos = match self.split_axis {
Axis::Horizontal => {
my_size.height = child1_size.height.max(child2_size.height);
Point::new(child1_size.width + bar_area, 0.0)
}
Axis::Vertical => {
my_size.width = child1_size.width.max(child2_size.width);
Point::new(0.0, child1_size.height + bar_area)
}
};
self.child1.set_origin(ctx, child1_pos);
self.child2.set_origin(ctx, child2_pos);
let paint_rect = self.child1.paint_rect().union(self.child2.paint_rect());
let insets = paint_rect - my_size.to_rect();
ctx.set_paint_insets(insets);
trace!("Computed layout: size={}, insets={:?}", my_size, insets);
my_size
}
#[instrument(name = "Split", level = "trace", skip(self, ctx, data, env))]
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
if self.solid {
self.paint_solid_bar(ctx, env);
} else {
self.paint_stroked_bar(ctx, env);
}
self.child1.paint(ctx, data, env);
self.child2.paint(ctx, data, env);
}
fn debug_state(&self, data: &T) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
children: vec![
self.child1.widget().debug_state(data),
self.child2.widget().debug_state(data),
],
..Default::default()
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/z_stack.rs | druid/examples/z_stack.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A simple test of overlapping widgets.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Button, Label, ZStack};
use druid::{AppLauncher, Data, Lens, UnitPoint, Vec2, WindowDesc};
#[derive(Clone, Data, Lens)]
struct State {
counter: usize,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("Hello World!")
.window_size((400.0, 400.0));
// create the initial app state
let initial_state: State = State { counter: 0 };
// start the application. Here we pass in the application state.
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<State> {
ZStack::new(
Button::from_label(Label::dynamic(|state: &State, _| {
format!(
"Very large button with text! Count up (currently {})",
state.counter
)
}))
.on_click(|_, state: &mut State, _| state.counter += 1),
)
.with_child(
Button::new("Reset").on_click(|_, state: &mut State, _| state.counter = 0),
Vec2::new(1.0, 1.0),
Vec2::ZERO,
UnitPoint::LEFT,
Vec2::new(10.0, 0.0),
)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/styled_text.rs | druid/examples/styled_text.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Example of dynamic text styling
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
#[allow(deprecated)]
use druid::widget::Parse;
use druid::widget::{
Checkbox, CrossAxisAlignment, Flex, Label, LensWrap, MainAxisAlignment, Painter, Scroll,
Stepper, TextBox,
};
use druid::{
theme, AppLauncher, Color, Data, FontDescriptor, FontFamily, Key, Lens, LensExt,
LocalizedString, PlatformError, RenderContext, Widget, WidgetExt, WindowDesc,
};
use std::fmt::Display;
// This is a custom key we'll use with Env to set and get our font.
const MY_CUSTOM_FONT: Key<FontDescriptor> = Key::new("org.linebender.example.my-custom-font");
const COLUMN_WIDTH: f64 = 360.0;
#[derive(Clone, Lens, Data)]
struct AppData {
text: String,
size: f64,
mono: bool,
}
impl Display for AppData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Size {:.1}{}: {}",
self.size,
if self.mono { " mono" } else { "" },
self.text
)
}
}
pub fn main() -> Result<(), PlatformError> {
let main_window = WindowDesc::new(ui_builder()).title(
LocalizedString::new("styled-text-demo-window-title").with_placeholder("Type Styler"),
);
let data = AppData {
text: "Here's some sample text".to_string(),
size: 24.0,
mono: false,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)?;
Ok(())
}
fn ui_builder() -> impl Widget<AppData> {
let my_painter = Painter::new(|ctx, _, _| {
let bounds = ctx.size().to_rect();
if ctx.is_hot() {
ctx.fill(bounds, &Color::rgba8(0, 0, 0, 128));
}
if ctx.is_active() {
ctx.stroke(bounds, &Color::WHITE, 2.0);
}
});
// This is Druid's default text style.
// It's set by theme::LABEL_COLOR and theme::UI_FONT
let label =
Label::new(|data: &String, _env: &_| format!("Default: {data}")).lens(AppData::text);
// The text_color, text_size, and font builder methods can override the
// defaults provided by the theme by passing in a Key or a concrete value.
//
// In this example, text_color receives a Key from the theme, text_size
// gets a custom key which we set with the env_scope wrapper, and the
// default font key (theme::FONT_NAME) is overridden in the env_scope
// wrapper. (Like text_color and text_size, the font can be set using the
// with_font builder method, but overriding here makes it easy to fall back
// to the default font)
let styled_label = Label::new(|data: &AppData, _env: &_| format!("{data}"))
.with_text_color(theme::PRIMARY_LIGHT)
.with_font(MY_CUSTOM_FONT)
.background(my_painter)
.on_click(|_, data, _| {
data.size *= 1.1;
})
.env_scope(|env: &mut druid::Env, data: &AppData| {
let new_font = if data.mono {
FontDescriptor::new(FontFamily::MONOSPACE)
} else {
FontDescriptor::new(FontFamily::SYSTEM_UI)
}
.with_size(data.size);
env.set(MY_CUSTOM_FONT, new_font);
});
let labels = Scroll::new(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(label)
.with_default_spacer()
.with_child(styled_label),
)
.expand_height()
.fix_width(COLUMN_WIDTH);
let stepper = Stepper::new()
.with_range(0.0, 100.0)
.with_step(1.0)
.with_wraparound(false)
.lens(AppData::size);
// TODO: Replace Parse usage with TextBox::with_formatter
#[allow(deprecated)]
let stepper_textbox = LensWrap::new(
Parse::new(TextBox::new()),
AppData::size.map(|x| Some(*x), |x, y| *x = y.unwrap_or(24.0)),
);
let mono_checkbox = Checkbox::new("Monospace").lens(AppData::mono);
let stepper_row = Flex::row()
.with_child(stepper_textbox)
.with_child(stepper)
.with_default_spacer()
.with_child(mono_checkbox);
let input = TextBox::multiline()
.with_placeholder("Your sample text here :)")
.fix_width(COLUMN_WIDTH)
.fix_height(140.0)
.lens(AppData::text);
Flex::column()
.main_axis_alignment(MainAxisAlignment::Center)
.with_default_spacer()
.with_flex_child(labels, 1.0)
.with_default_spacer()
.with_child(input)
.with_default_spacer()
.with_child(stepper_row)
.with_default_spacer()
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/scroll.rs | druid/examples/scroll.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Shows a scroll widget, and also demonstrates how widgets that paint
//! outside their bounds can specify their paint region.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::kurbo::Circle;
use druid::piet::RadialGradient;
use druid::widget::prelude::*;
use druid::widget::{Flex, Padding};
use druid::{AppLauncher, Data, Insets, LocalizedString, Rect, WidgetExt, WindowDesc};
pub fn main() {
let window = WindowDesc::new(build_widget())
.title(LocalizedString::new("scroll-demo-window-title").with_placeholder("Scroll demo"));
AppLauncher::with_window(window)
.log_to_console()
.launch(0u32)
.expect("launch failed");
}
fn build_widget() -> impl Widget<u32> {
let mut col = Flex::column();
for i in 0..30 {
col.add_child(Padding::new(3.0, OverPainter(i)));
}
col.scroll()
}
/// A widget that paints outside of its bounds.
struct OverPainter(u64);
const INSETS: Insets = Insets::uniform(50.);
impl<T: Data> Widget<T> for OverPainter {
fn event(&mut self, _: &mut EventCtx, _: &Event, _: &mut T, _: &Env) {}
fn lifecycle(&mut self, _: &mut LifeCycleCtx, _: &LifeCycle, _: &T, _: &Env) {}
fn update(&mut self, _: &mut UpdateCtx, _: &T, _: &T, _: &Env) {}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _: &T, _: &Env) -> Size {
ctx.set_paint_insets(INSETS);
bc.constrain(Size::new(100., 100.))
}
fn paint(&mut self, ctx: &mut PaintCtx, _: &T, env: &Env) {
let rect = Rect::ZERO.with_size(ctx.size());
let color = env.get_debug_color(self.0);
let radius = (rect + INSETS).size().height / 2.0;
let circle = Circle::new(rect.center(), radius);
let grad = RadialGradient::new(1.0, (color, color.with_alpha(0.0)));
ctx.fill(circle, &grad);
ctx.stroke(rect, &color, 2.0);
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/flex.rs | druid/examples/flex.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Demonstrates alignment of children in the flex container.
//! This example showcases the full set of functionality of flex, giving you
//! knobs to change all the parameters. 99% of the time you will want to
//! hard-code these parameters, which will simplify your code considerably.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::text::ParseFormatter;
use druid::widget::prelude::*;
use druid::widget::{
Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup,
SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt,
};
use druid::{AppLauncher, Color, Data, Lens, WidgetId, WindowDesc};
const DEFAULT_SPACER_SIZE: f64 = 8.;
const SPACER_OPTIONS: [(&str, Spacers); 4] = [
("None", Spacers::None),
("Default", Spacers::Default),
("Flex", Spacers::Flex),
("Fixed:", Spacers::Fixed),
];
const MAIN_AXIS_ALIGNMENT_OPTIONS: [(&str, MainAxisAlignment); 6] = [
("Start", MainAxisAlignment::Start),
("Center", MainAxisAlignment::Center),
("End", MainAxisAlignment::End),
("Between", MainAxisAlignment::SpaceBetween),
("Evenly", MainAxisAlignment::SpaceEvenly),
("Around", MainAxisAlignment::SpaceAround),
];
const CROSS_AXIS_ALIGNMENT_OPTIONS: [(&str, CrossAxisAlignment); 5] = [
("Start", CrossAxisAlignment::Start),
("Center", CrossAxisAlignment::Center),
("End", CrossAxisAlignment::End),
("Baseline", CrossAxisAlignment::Baseline),
("Fill", CrossAxisAlignment::Fill),
];
const FLEX_TYPE_OPTIONS: [(&str, FlexType); 2] =
[("Row", FlexType::Row), ("Column", FlexType::Column)];
#[derive(Clone, Data, Lens)]
struct AppState {
demo_state: DemoState,
params: Params,
}
#[derive(Clone, Data, Lens)]
struct DemoState {
pub input_text: String,
pub enabled: bool,
volume: f64,
}
#[derive(Clone, Data, Lens)]
struct Params {
axis: FlexType,
cross_alignment: CrossAxisAlignment,
main_alignment: MainAxisAlignment,
fill_major_axis: bool,
debug_layout: bool,
fix_minor_axis: bool,
fix_major_axis: bool,
spacers: Spacers,
spacer_size: f64,
}
#[derive(Clone, Copy, PartialEq, Data)]
enum Spacers {
None,
Default,
Flex,
Fixed,
}
#[derive(Clone, Copy, PartialEq, Data)]
enum FlexType {
Row,
Column,
}
/// builds a child Flex widget from some parameters.
struct Rebuilder {
inner: Box<dyn Widget<AppState>>,
}
impl Rebuilder {
fn new() -> Rebuilder {
Rebuilder {
inner: SizedBox::empty().boxed(),
}
}
fn rebuild_inner(&mut self, data: &AppState) {
self.inner = build_widget(&data.params);
}
}
impl Widget<AppState> for Rebuilder {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppState, env: &Env) {
self.inner.event(ctx, event, data, env)
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &AppState, env: &Env) {
if let LifeCycle::WidgetAdded = event {
self.rebuild_inner(data);
}
self.inner.lifecycle(ctx, event, data, env)
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppState, data: &AppState, env: &Env) {
if !old_data.params.same(&data.params) {
self.rebuild_inner(data);
ctx.children_changed();
} else {
self.inner.update(ctx, old_data, data, env);
}
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &AppState,
env: &Env,
) -> Size {
self.inner.layout(ctx, bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) {
self.inner.paint(ctx, data, env)
}
fn id(&self) -> Option<WidgetId> {
self.inner.id()
}
}
fn make_control_row() -> impl Widget<AppState> {
Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("Type:"))
.with_default_spacer()
.with_child(RadioGroup::column(FLEX_TYPE_OPTIONS.to_vec()).lens(Params::axis)),
)
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("CrossAxis:"))
.with_default_spacer()
.with_child(
RadioGroup::column(CROSS_AXIS_ALIGNMENT_OPTIONS.to_vec())
.lens(Params::cross_alignment),
),
)
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("MainAxis:"))
.with_default_spacer()
.with_child(
RadioGroup::column(MAIN_AXIS_ALIGNMENT_OPTIONS.to_vec())
.lens(Params::main_alignment),
),
)
.with_default_spacer()
.with_child(make_spacer_select())
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("Misc:"))
.with_default_spacer()
.with_child(Checkbox::new("Debug layout").lens(Params::debug_layout))
.with_default_spacer()
.with_child(Checkbox::new("Fill main axis").lens(Params::fill_major_axis))
.with_default_spacer()
.with_child(Checkbox::new("Fix minor axis size").lens(Params::fix_minor_axis))
.with_default_spacer()
.with_child(Checkbox::new("Fix major axis size").lens(Params::fix_major_axis)),
)
.padding(10.0)
.border(Color::grey(0.6), 2.0)
.rounded(5.0)
.lens(AppState::params)
}
fn make_spacer_select() -> impl Widget<Params> {
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("Insert Spacers:"))
.with_default_spacer()
.with_child(RadioGroup::column(SPACER_OPTIONS.to_vec()).lens(Params::spacers))
.with_default_spacer()
.with_child(
Flex::row()
.with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(Params::spacer_size)
.fix_width(60.0),
)
.with_spacer(druid::theme::WIDGET_CONTROL_COMPONENT_PADDING)
.with_child(
Stepper::new()
.with_range(2.0, 50.0)
.with_step(2.0)
.lens(Params::spacer_size),
),
)
}
fn space_if_needed<T: Data>(flex: &mut Flex<T>, params: &Params) {
match params.spacers {
Spacers::None => (),
Spacers::Default => flex.add_default_spacer(),
Spacers::Fixed => flex.add_spacer(params.spacer_size),
Spacers::Flex => flex.add_flex_spacer(1.0),
}
}
fn build_widget(state: &Params) -> Box<dyn Widget<AppState>> {
let mut flex = match state.axis {
FlexType::Column => Flex::column(),
FlexType::Row => Flex::row(),
}
.cross_axis_alignment(state.cross_alignment)
.main_axis_alignment(state.main_alignment)
.must_fill_main_axis(state.fill_major_axis);
flex.add_child(
TextBox::new()
.with_placeholder("Sample text")
.lens(DemoState::input_text),
);
space_if_needed(&mut flex, state);
flex.add_child(
Button::new("Clear").on_click(|_ctx, data: &mut DemoState, _env| {
data.input_text.clear();
data.enabled = false;
data.volume = 0.0;
}),
);
space_if_needed(&mut flex, state);
flex.add_child(
Label::new(|data: &DemoState, _: &Env| data.input_text.clone()).with_text_size(32.0),
);
space_if_needed(&mut flex, state);
flex.add_child(Checkbox::new("Demo").lens(DemoState::enabled));
space_if_needed(&mut flex, state);
flex.add_child(Switch::new().lens(DemoState::enabled));
space_if_needed(&mut flex, state);
flex.add_child(Slider::new().lens(DemoState::volume));
space_if_needed(&mut flex, state);
flex.add_child(ProgressBar::new().lens(DemoState::volume));
space_if_needed(&mut flex, state);
flex.add_child(
Stepper::new()
.with_range(0.0, 1.0)
.with_step(0.1)
.with_wraparound(true)
.lens(DemoState::volume),
);
let mut flex = SizedBox::new(flex);
if state.fix_minor_axis {
match state.axis {
FlexType::Row => flex = flex.height(200.),
FlexType::Column => flex = flex.width(200.),
}
}
if state.fix_major_axis {
match state.axis {
FlexType::Row => flex = flex.width(600.),
FlexType::Column => flex = flex.height(300.),
}
}
let flex = flex
.padding(8.0)
.border(Color::grey(0.6), 2.0)
.rounded(5.0)
.lens(AppState::demo_state);
if state.debug_layout {
flex.debug_paint_layout().boxed()
} else {
flex.boxed()
}
}
fn make_ui() -> impl Widget<AppState> {
Flex::column()
.must_fill_main_axis(true)
.with_child(make_control_row())
.with_default_spacer()
.with_flex_child(Rebuilder::new().center(), 1.0)
.padding(10.0)
}
pub fn main() {
let main_window = WindowDesc::new(make_ui())
.window_size((720., 600.))
.with_min_size((620., 300.))
.title("Flex Container Options");
let demo_state = DemoState {
input_text: "hello".into(),
enabled: false,
volume: 0.0,
};
let params = Params {
axis: FlexType::Row,
cross_alignment: CrossAxisAlignment::Center,
main_alignment: MainAxisAlignment::Start,
debug_layout: false,
fix_minor_axis: false,
fix_major_axis: false,
spacers: Spacers::None,
spacer_size: DEFAULT_SPACER_SIZE,
fill_major_axis: false,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(AppState { demo_state, params })
.expect("Failed to launch application");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/sub_window.rs | druid/examples/sub_window.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Example of sub windows.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::commands::CLOSE_WINDOW;
use druid::lens::Unit;
use druid::widget::{
Align, Button, Checkbox, Controller, ControllerHost, EnvScope, Flex, Label, TextBox,
};
use druid::{
theme, Affine, AppLauncher, BoxConstraints, Color, Data, Env, Event, EventCtx, LayoutCtx, Lens,
LensExt, LifeCycle, LifeCycleCtx, LocalizedString, PaintCtx, Point, Rect, RenderContext, Size,
TimerToken, UpdateCtx, Widget, WidgetExt, WindowConfig, WindowDesc, WindowId, WindowSizePolicy,
};
use druid_shell::piet::Text;
use druid_shell::{Screen, WindowLevel};
use instant::{Duration, Instant};
use piet_common::{TextLayout, TextLayoutBuilder};
const VERTICAL_WIDGET_SPACING: f64 = 20.0;
const TEXT_BOX_WIDTH: f64 = 200.0;
const WINDOW_TITLE: LocalizedString<HelloState> = LocalizedString::new("Hello World!");
#[derive(Clone, Data, Lens)]
struct SubState {
my_stuff: String,
}
#[derive(Clone, Data, Lens)]
struct HelloState {
name: String,
sub: SubState,
closeable: bool,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title(WINDOW_TITLE)
.window_size((400.0, 400.0));
// create the initial app state
let initial_state = HelloState {
name: "World".into(),
sub: SubState {
my_stuff: "It's mine!".into(),
},
closeable: true,
};
// start the application
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
enum TooltipState {
Showing(WindowId),
Waiting {
last_move: Instant,
timer_expire: Instant,
token: TimerToken,
position_in_window_coordinates: Point,
},
Fresh,
}
struct TooltipController {
tip: String,
state: TooltipState,
}
impl TooltipController {
pub fn new(tip: impl Into<String>) -> Self {
TooltipController {
tip: tip.into(),
state: TooltipState::Fresh,
}
}
}
impl<T, W: Widget<T>> Controller<T, W> for TooltipController {
fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
let wait_duration = Duration::from_millis(500);
let resched_dur = Duration::from_millis(50);
let cursor_size = Size::new(15., 15.);
let now = Instant::now();
let new_state = match &self.state {
TooltipState::Fresh => match event {
Event::MouseMove(me) if ctx.is_hot() => Some(TooltipState::Waiting {
last_move: now,
timer_expire: now + wait_duration,
token: ctx.request_timer(wait_duration),
position_in_window_coordinates: me.window_pos,
}),
_ => None,
},
TooltipState::Waiting {
last_move,
timer_expire,
token,
position_in_window_coordinates,
} => match event {
Event::MouseMove(me) if ctx.is_hot() => {
let (cur_token, cur_expire) = if *timer_expire - now < resched_dur {
(ctx.request_timer(wait_duration), now + wait_duration)
} else {
(*token, *timer_expire)
};
Some(TooltipState::Waiting {
last_move: now,
timer_expire: cur_expire,
token: cur_token,
position_in_window_coordinates: me.window_pos,
})
}
Event::Timer(tok) if tok == token => {
let deadline = *last_move + wait_duration;
ctx.set_handled();
if deadline > now {
let wait_for = deadline - now;
tracing::info!("Waiting another {:?}", wait_for);
Some(TooltipState::Waiting {
last_move: *last_move,
timer_expire: deadline,
token: ctx.request_timer(wait_for),
position_in_window_coordinates: *position_in_window_coordinates,
})
} else {
let tooltip_position_in_window_coordinates =
(position_in_window_coordinates.to_vec2() + cursor_size.to_vec2())
.to_point();
let win_id = ctx.new_sub_window(
WindowConfig::default()
.show_titlebar(false)
.window_size_policy(WindowSizePolicy::Content)
.set_level(WindowLevel::Tooltip(ctx.window().clone()))
.set_position(tooltip_position_in_window_coordinates),
Label::<()>::new(self.tip.clone()),
(),
env.clone(),
);
Some(TooltipState::Showing(win_id))
}
}
_ => None,
},
TooltipState::Showing(win_id) => {
match event {
Event::MouseMove(me) if !ctx.is_hot() => {
// TODO another timer on leaving
tracing::info!("Sending close window for {:?}", win_id);
ctx.submit_command(CLOSE_WINDOW.to(*win_id));
Some(TooltipState::Waiting {
last_move: now,
timer_expire: now + wait_duration,
token: ctx.request_timer(wait_duration),
position_in_window_coordinates: me.window_pos,
})
}
_ => None,
}
}
};
if let Some(state) = new_state {
self.state = state;
}
if !ctx.is_handled() {
child.event(ctx, event, data, env);
}
}
fn lifecycle(
&mut self,
child: &mut W,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
data: &T,
env: &Env,
) {
if let LifeCycle::HotChanged(false) = event {
if let TooltipState::Showing(win_id) = self.state {
ctx.submit_command(CLOSE_WINDOW.to(win_id));
}
self.state = TooltipState::Fresh;
}
child.lifecycle(ctx, event, data, env)
}
}
struct DragWindowController {
init_pos: Option<Point>,
//dragging: bool
}
impl DragWindowController {
pub fn new() -> Self {
DragWindowController { init_pos: None }
}
}
impl<T, W: Widget<T>> Controller<T, W> for DragWindowController {
fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
match event {
Event::MouseDown(me) if me.buttons.has_left() => {
ctx.set_active(true);
self.init_pos = Some(me.window_pos)
}
Event::MouseMove(me) if ctx.is_active() && me.buttons.has_left() => {
if let Some(init_pos) = self.init_pos {
let within_window_change = me.window_pos.to_vec2() - init_pos.to_vec2();
let old_pos = ctx.window().get_position();
let new_pos = old_pos + within_window_change;
tracing::info!(
"Drag {:?} ",
(
init_pos,
me.window_pos,
within_window_change,
old_pos,
new_pos
)
);
ctx.window().set_position(new_pos)
}
}
Event::MouseUp(_me) if ctx.is_active() => {
self.init_pos = None;
ctx.set_active(false)
}
_ => (),
}
child.event(ctx, event, data, env)
}
}
struct ScreenThing;
impl Widget<()> for ScreenThing {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut (), _env: &Env) {}
fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &(), _env: &Env) {}
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &(), _data: &(), _env: &Env) {}
fn layout(
&mut self,
_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &(),
_env: &Env,
) -> Size {
bc.constrain(Size::new(800.0, 600.0))
}
fn paint(&mut self, ctx: &mut PaintCtx, _data: &(), env: &Env) {
let sz = ctx.size();
let monitors = Screen::get_monitors();
let all = monitors
.iter()
.map(|x| x.virtual_rect())
.fold(Rect::ZERO, |s, r| r.union(s));
if all.width() > 0. && all.height() > 0. {
let trans = Affine::scale(f64::min(sz.width / all.width(), sz.height / all.height()))
* Affine::translate(all.origin().to_vec2()).inverse();
let font = env.get(theme::UI_FONT).family;
for (i, mon) in monitors.iter().enumerate() {
let vr = mon.virtual_rect();
let tr = trans.transform_rect_bbox(vr);
ctx.stroke(tr, &Color::WHITE, 1.0);
if let Ok(tl) = ctx
.text()
.new_text_layout(format!(
"{}:{}x{}@{},{}",
i,
vr.width(),
vr.height(),
vr.x0,
vr.y0
))
.max_width(tr.width() - 5.)
.font(font.clone(), env.get(theme::TEXT_SIZE_NORMAL))
.text_color(Color::WHITE)
.build()
{
ctx.draw_text(&tl, tr.center() - tl.size().to_vec2() * 0.5);
}
}
}
}
}
struct CancelClose;
impl<W: Widget<bool>> Controller<bool, W> for CancelClose {
fn event(
&mut self,
w: &mut W,
ctx: &mut EventCtx<'_, '_>,
event: &Event,
data: &mut bool,
env: &Env,
) {
match (&data, event) {
(false, Event::WindowCloseRequested) => ctx.set_handled(),
_ => w.event(ctx, event, data, env),
}
}
}
fn build_root_widget() -> impl Widget<HelloState> {
let label = EnvScope::new(
|env, _t| env.set(theme::TEXT_COLOR, env.get(theme::PRIMARY_LIGHT)),
ControllerHost::new(
Label::new(|data: &HelloState, _env: &Env| {
format!("Hello {}! {} ", data.name, data.sub.my_stuff)
}),
TooltipController::new("Tips! Are good"),
),
);
// a textbox that modifies `name`.
let textbox = TextBox::new()
.with_placeholder("Who are we greeting?")
.fix_width(TEXT_BOX_WIDTH)
.lens(HelloState::sub.then(SubState::my_stuff));
let button = Button::new("Make sub window")
.on_click(|ctx, data: &mut SubState, env| {
let tb = TextBox::new().lens(SubState::my_stuff);
let drag_thing = Label::new("Drag me").controller(DragWindowController::new());
let col = Flex::column().with_child(drag_thing).with_child(tb);
ctx.new_sub_window(
WindowConfig::default()
.show_titlebar(false)
.window_size(Size::new(100., 100.))
.set_level(WindowLevel::AppWindow),
col,
data.clone(),
env.clone(),
);
})
.center()
.lens(HelloState::sub);
let check_box =
ControllerHost::new(Checkbox::new("Closeable?"), CancelClose).lens(HelloState::closeable);
// arrange the two widgets vertically, with some padding
let layout = Flex::column()
.with_child(label)
.with_flex_child(ScreenThing.lens(Unit).padding(5.), 1.)
.with_spacer(VERTICAL_WIDGET_SPACING)
.with_child(textbox)
.with_child(button)
.with_child(check_box);
// center the two widgets in the available space
Align::centered(layout)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/split_demo.rs | druid/examples/split_demo.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example demonstrates the `Split` widget
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::piet::Color;
use druid::widget::{Align, Container, Label, Padding, Split};
use druid::{AppLauncher, LocalizedString, Widget, WindowDesc};
fn build_app() -> impl Widget<u32> {
let fixed_cols = Padding::new(
10.0,
Container::new(
Split::columns(
Align::centered(Label::new("Left Split")),
Align::centered(Label::new("Right Split")),
)
.split_point(0.5),
)
.border(Color::WHITE, 1.0),
);
let fixed_rows = Padding::new(
10.0,
Container::new(
Split::rows(
Align::centered(Label::new("Top Split")),
Align::centered(Label::new("Bottom Split")),
)
.split_point(0.4)
.bar_size(3.0),
)
.border(Color::WHITE, 1.0),
);
let draggable_cols = Padding::new(
10.0,
Container::new(
Split::columns(
Align::centered(Label::new("Split A")),
Align::centered(Label::new("Split B")),
)
.split_point(0.5)
.draggable(true)
.solid_bar(true)
.min_size(60.0, 60.0),
)
.border(Color::WHITE, 1.0),
);
Padding::new(
10.0,
Container::new(
Split::rows(
Split::rows(fixed_cols, fixed_rows)
.split_point(0.33)
.bar_size(3.0)
.min_bar_area(3.0)
.draggable(true),
draggable_cols,
)
.split_point(0.75)
.bar_size(5.0)
.min_bar_area(11.0)
.draggable(true),
)
.border(Color::WHITE, 1.0),
)
}
pub fn main() {
let window = WindowDesc::new(build_app())
.title(LocalizedString::new("split-demo-window-title").with_placeholder("Split Demo"));
AppLauncher::with_window(window)
.log_to_console()
.launch(0u32)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/custom_widget.rs | druid/examples/custom_widget.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of a custom drawing widget.
//! We draw an image, some text, a shape, and a curve.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::kurbo::BezPath;
use druid::piet::{FontFamily, ImageFormat, InterpolationMode, Text, TextLayoutBuilder};
use druid::widget::prelude::*;
use druid::{
Affine, AppLauncher, Color, FontDescriptor, LocalizedString, Point, Rect, TextLayout,
WindowDesc,
};
struct CustomWidget;
// If this widget has any child widgets it should call its event, update and layout
// (and lifecycle) methods as well to make sure it works. Some things can be filtered,
// but a general rule is to just pass it through unless you really know you don't want it.
impl Widget<String> for CustomWidget {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut String, _env: &Env) {}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_event: &LifeCycle,
_data: &String,
_env: &Env,
) {
}
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &String, _data: &String, _env: &Env) {}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &String,
_env: &Env,
) -> Size {
// BoxConstraints are passed by the parent widget.
// This method can return any Size within those constraints:
// bc.constrain(my_size)
//
// To check if a dimension is infinite or not (e.g. scrolling):
// bc.is_width_bounded() / bc.is_height_bounded()
//
// bx.max() returns the maximum size of the widget. Be careful
// using this, since always make sure the widget is bounded.
// If bx.max() is used in a scrolling widget things will probably
// not work correctly.
if bc.is_width_bounded() && bc.is_height_bounded() {
bc.max()
} else {
let size = Size::new(100.0, 100.0);
bc.constrain(size)
}
}
// The paint method gets called last, after an event flow.
// It goes event -> update -> layout -> paint, and each method can influence the next.
// Basically, anything that changes the appearance of a widget causes a paint.
fn paint(&mut self, ctx: &mut PaintCtx, data: &String, env: &Env) {
// Clear the whole widget with the color of your choice
// (ctx.size() returns the size of the layout rect we're painting in)
// Note: ctx also has a `clear` method, but that clears the whole context,
// and we only want to clear this widget's area.
let size = ctx.size();
let rect = size.to_rect();
ctx.fill(rect, &Color::WHITE);
// We can paint with a Z index, this indicates that this code will be run
// after the rest of the painting. Painting with z-index is done in order,
// so first everything with z-index 1 is painted and then with z-index 2 etc.
// As you can see this(red) curve is drawn on top of the green curve
ctx.paint_with_z_index(1, move |ctx| {
let mut path = BezPath::new();
path.move_to((0.0, size.height));
path.quad_to((40.0, 50.0), (size.width, 0.0));
// Create a color
let stroke_color = Color::rgb8(128, 0, 0);
// Stroke the path with thickness 1.0
ctx.stroke(path, &stroke_color, 5.0);
});
// Create an arbitrary bezier path
let mut path = BezPath::new();
path.move_to(Point::ORIGIN);
path.quad_to((40.0, 50.0), (size.width, size.height));
// Create a color
let stroke_color = Color::rgb8(0, 128, 0);
// Stroke the path with thickness 5.0
ctx.stroke(path, &stroke_color, 5.0);
// Rectangles: the path for practical people
let rect = Rect::from_origin_size((10.0, 10.0), (100.0, 100.0));
// Note the Color:rgba8 which includes an alpha channel (7F in this case)
let fill_color = Color::rgba8(0x00, 0x00, 0x00, 0x7F);
ctx.fill(rect, &fill_color);
// Text is easy; in real use TextLayout should either be stored in the
// widget and reused, or a label child widget to manage it all.
// This is one way of doing it, you can also use a builder-style way.
let mut layout = TextLayout::<String>::from_text(data);
layout.set_font(FontDescriptor::new(FontFamily::SERIF).with_size(24.0));
layout.set_text_color(fill_color);
layout.rebuild_if_needed(ctx.text(), env);
// Let's rotate our text slightly. First we save our current (default) context:
ctx.with_save(|ctx| {
// Now we can rotate the context (or set a clip path, for instance):
// This makes it so that anything drawn after this (in the closure) is
// transformed.
// The transformation is in radians, but be aware it transforms the canvas,
// not just the part you are drawing. So we draw at (80.0, 40.0) on the rotated
// canvas, this is NOT the same position as (80.0, 40.0) on the original canvas.
ctx.transform(Affine::rotate(std::f64::consts::FRAC_PI_4));
layout.draw(ctx, (80.0, 40.0));
});
// When we exit with_save, the original context's rotation is restored
// This is the builder-style way of drawing text.
let text = ctx.text();
let layout = text
.new_text_layout(data.clone())
.font(FontFamily::SERIF, 24.0)
.text_color(Color::rgb8(128, 0, 0))
.build()
.unwrap();
ctx.draw_text(&layout, (100.0, 25.0));
// Let's burn some CPU to make a (partially transparent) image buffer
let image_data = make_image_data(256, 256);
let image = ctx
.make_image(256, 256, &image_data, ImageFormat::RgbaSeparate)
.unwrap();
// The image is automatically scaled to fit the rect you pass to draw_image
ctx.draw_image(&image, size.to_rect(), InterpolationMode::Bilinear);
}
}
pub fn main() {
let window = WindowDesc::new(CustomWidget {}).title(LocalizedString::new("Fancy Colors"));
AppLauncher::with_window(window)
.log_to_console()
.launch("Druid + Piet".to_string())
.expect("launch failed");
}
fn make_image_data(width: usize, height: usize) -> Vec<u8> {
let mut result = vec![0; width * height * 4];
for y in 0..height {
for x in 0..width {
let ix = (y * width + x) * 4;
result[ix] = x as u8;
result[ix + 1] = y as u8;
result[ix + 2] = !(x as u8);
result[ix + 3] = 127;
}
}
result
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/cursor.rs | druid/examples/cursor.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example showing how to change the mouse cursor.
//! Clicking the button should switch your cursor, and
//! the last cursor should be a custom image. Custom
//! image cursors cannot be created before the window is
//! open so we have to work around that. When we receive the
//! `WindowConnected` command we initiate the cursor.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::{
AppLauncher, Color, Cursor, CursorDesc, Data, Env, ImageBuf, Lens, LocalizedString, WidgetExt,
WindowDesc,
};
use druid::widget::prelude::*;
use druid::widget::{Button, Controller};
/// This Controller switches the current cursor based on the selection.
/// The crucial part of this code is actually making and initialising
/// the cursor. This happens here. Because we cannot make the cursor
/// before the window is open we have to do that on `WindowConnected`.
struct CursorArea;
impl<W: Widget<AppState>> Controller<AppState, W> for CursorArea {
fn event(
&mut self,
child: &mut W,
ctx: &mut EventCtx,
event: &Event,
data: &mut AppState,
env: &Env,
) {
if let Event::WindowConnected = event {
data.custom = ctx.window().make_cursor(&data.custom_desc);
}
child.event(ctx, event, data, env);
}
fn update(
&mut self,
child: &mut W,
ctx: &mut UpdateCtx,
old_data: &AppState,
data: &AppState,
env: &Env,
) {
if data.cursor != old_data.cursor {
ctx.set_cursor(&data.cursor);
}
child.update(ctx, old_data, data, env);
}
}
fn ui_builder() -> impl Widget<AppState> {
Button::new("Change cursor")
.on_click(|_ctx, data: &mut AppState, _env| {
data.next_cursor();
})
.padding(50.0)
.controller(CursorArea {})
.border(Color::WHITE, 1.0)
.padding(50.0)
}
#[derive(Clone, Data, Lens)]
struct AppState {
cursor: Cursor,
custom: Option<Cursor>,
// To see what #[data(ignore)] does look at the docs.rs page on `Data`:
// https://docs.rs/druid/latest/druid/trait.Data.html
#[data(ignore)]
custom_desc: CursorDesc,
}
impl AppState {
fn next_cursor(&mut self) {
self.cursor = match self.cursor {
Cursor::Arrow => Cursor::IBeam,
Cursor::IBeam => Cursor::Pointer,
Cursor::Pointer => Cursor::Crosshair,
Cursor::Crosshair => Cursor::NotAllowed,
Cursor::NotAllowed => Cursor::ResizeLeftRight,
Cursor::ResizeLeftRight => Cursor::ResizeUpDown,
Cursor::ResizeUpDown => {
if let Some(custom) = &self.custom {
custom.clone()
} else {
Cursor::Arrow
}
}
Cursor::Custom(_) => Cursor::Arrow,
_ => Cursor::Arrow,
};
}
}
pub fn main() {
let main_window =
WindowDesc::new(ui_builder()).title(LocalizedString::new("Blocking functions"));
let cursor_image = ImageBuf::from_data(include_bytes!("./assets/PicWithAlpha.png")).unwrap();
// The (0,0) refers to where the "hotspot" is located, so where the mouse actually points.
// (0,0) is the top left, and (cursor_image.width(), cursor_image.width()) the bottom right.
let custom_desc = CursorDesc::new(cursor_image, (0.0, 0.0));
let data = AppState {
cursor: Cursor::Arrow,
custom: None,
custom_desc,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/markdown_preview.rs | druid/examples/markdown_preview.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of live markdown preview
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use pulldown_cmark::{Event as ParseEvent, Options, Parser, Tag};
use druid::text::{AttributesAdder, RichText, RichTextBuilder};
use druid::widget::prelude::*;
use druid::widget::{Controller, LineBreaking, RawLabel, Scroll, Split, TextBox};
use druid::{
AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, FontFamily, FontStyle, FontWeight,
Handled, Lens, LocalizedString, Menu, Selector, Target, Widget, WidgetExt, WindowDesc,
WindowId,
};
const WINDOW_TITLE: LocalizedString<AppState> = LocalizedString::new("Minimal Markdown");
const TEXT: &str = "*Hello* ***world***! This is a `TextBox` where you can \
use limited markdown notation, which is reflected in the \
**styling** of the `Label` on the left. ~~Strikethrough even works!~~\n\n\
If you're curious about Druid, a good place to ask questions \
and discuss development work is our [Zulip chat instance], \
in the #druid-help and #druid channels, respectively.\n\n\n\
[Zulip chat instance]: https://xi.zulipchat.com";
const SPACER_SIZE: f64 = 8.0;
const BLOCKQUOTE_COLOR: Color = Color::grey8(0x88);
const LINK_COLOR: Color = Color::rgb8(0, 0, 0xEE);
const OPEN_LINK: Selector<String> = Selector::new("druid-example.open-link");
#[derive(Clone, Data, Lens)]
struct AppState {
raw: String,
rendered: RichText,
}
/// A controller that rebuilds the preview when edits occur
struct RichTextRebuilder;
impl<W: Widget<AppState>> Controller<AppState, W> for RichTextRebuilder {
fn event(
&mut self,
child: &mut W,
ctx: &mut EventCtx,
event: &Event,
data: &mut AppState,
env: &Env,
) {
let pre_data = data.raw.to_owned();
child.event(ctx, event, data, env);
if !data.raw.same(&pre_data) {
data.rendered = rebuild_rendered_text(&data.raw);
}
}
}
struct Delegate;
impl<T: Data> AppDelegate<T> for Delegate {
fn command(
&mut self,
_ctx: &mut DelegateCtx,
_target: Target,
cmd: &Command,
_data: &mut T,
_env: &Env,
) -> Handled {
if let Some(url) = cmd.get(OPEN_LINK) {
#[cfg(not(target_arch = "wasm32"))]
open::that_in_background(url);
#[cfg(target_arch = "wasm32")]
tracing::warn!("opening link({}) not supported on web yet.", url);
Handled::Yes
} else {
Handled::No
}
}
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title(WINDOW_TITLE)
.menu(make_menu)
.window_size((700.0, 600.0));
// create the initial app state
let initial_state = AppState {
raw: TEXT.to_owned(),
rendered: rebuild_rendered_text(TEXT),
};
// start the application
AppLauncher::with_window(main_window)
.log_to_console()
.delegate(Delegate)
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<AppState> {
let label = Scroll::new(
RawLabel::new()
.with_text_color(Color::BLACK)
.with_line_break_mode(LineBreaking::WordWrap)
.lens(AppState::rendered)
.expand_width()
.padding((SPACER_SIZE * 4.0, SPACER_SIZE)),
)
.vertical()
.background(Color::grey8(222))
.expand();
let textbox = TextBox::multiline()
.lens(AppState::raw)
.controller(RichTextRebuilder)
.expand()
.padding(5.0);
Split::columns(label, textbox)
}
/// Parse a markdown string and generate a `RichText` object with
/// the appropriate attributes.
fn rebuild_rendered_text(text: &str) -> RichText {
let mut current_pos = 0;
let mut builder = RichTextBuilder::new();
let mut tag_stack = Vec::new();
let parser = Parser::new_ext(text, Options::ENABLE_STRIKETHROUGH);
for event in parser {
match event {
ParseEvent::Start(tag) => {
tag_stack.push((current_pos, tag));
}
ParseEvent::Text(txt) => {
builder.push(&txt);
current_pos += txt.len();
}
ParseEvent::End(end_tag) => {
let (start_off, tag) = tag_stack
.pop()
.expect("parser does not return unbalanced tags");
assert_eq!(end_tag, tag, "mismatched tags?");
add_attribute_for_tag(
&tag,
builder.add_attributes_for_range(start_off..current_pos),
);
if add_newline_after_tag(&tag) {
builder.push("\n\n");
current_pos += 2;
}
}
ParseEvent::Code(txt) => {
builder.push(&txt).font_family(FontFamily::MONOSPACE);
current_pos += txt.len();
}
ParseEvent::Html(txt) => {
builder
.push(&txt)
.font_family(FontFamily::MONOSPACE)
.text_color(BLOCKQUOTE_COLOR);
current_pos += txt.len();
}
ParseEvent::HardBreak => {
builder.push("\n\n");
current_pos += 2;
}
_ => (),
}
}
builder.build()
}
fn add_newline_after_tag(tag: &Tag) -> bool {
!matches!(
tag,
Tag::Emphasis | Tag::Strong | Tag::Strikethrough | Tag::Link(..)
)
}
fn add_attribute_for_tag(tag: &Tag, mut attrs: AttributesAdder) {
match tag {
Tag::Heading(lvl) => {
let font_size = match lvl {
1 => 38.,
2 => 32.0,
3 => 26.0,
4 => 20.0,
5 => 16.0,
_ => 12.0,
};
attrs.size(font_size).weight(FontWeight::BOLD);
}
Tag::BlockQuote => {
attrs.style(FontStyle::Italic).text_color(BLOCKQUOTE_COLOR);
}
Tag::CodeBlock(_) => {
attrs.font_family(FontFamily::MONOSPACE);
}
Tag::Emphasis => {
attrs.style(FontStyle::Italic);
}
Tag::Strong => {
attrs.weight(FontWeight::BOLD);
}
Tag::Strikethrough => {
attrs.strikethrough(true);
}
Tag::Link(_link_ty, target, _title) => {
attrs
.underline(true)
.text_color(LINK_COLOR)
.link(OPEN_LINK.with(target.to_string()));
}
// ignore other tags for now
_ => (),
}
}
#[allow(unused_assignments, unused_mut)]
fn make_menu<T: Data>(_window_id: Option<WindowId>, _app_state: &AppState, _env: &Env) -> Menu<T> {
let mut base = Menu::empty();
#[cfg(target_os = "macos")]
{
base = base.entry(druid::platform_menus::mac::application::default())
}
#[cfg(any(
target_os = "windows",
target_os = "freebsd",
target_os = "linux",
target_os = "openbsd"
))]
{
base = base.entry(druid::platform_menus::win::file::default());
}
base.entry(
Menu::new(LocalizedString::new("common-menu-edit-menu"))
.entry(druid::platform_menus::common::undo())
.entry(druid::platform_menus::common::redo())
.separator()
.entry(druid::platform_menus::common::cut().enabled(false))
.entry(druid::platform_menus::common::copy())
.entry(druid::platform_menus::common::paste()),
)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/tabs.rs | druid/examples/tabs.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Example of tabs
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::im::Vector;
use druid::widget::{
Axis, Button, CrossAxisAlignment, Flex, Label, MainAxisAlignment, RadioGroup, Split, TabInfo,
Tabs, TabsEdge, TabsPolicy, TabsTransition, TextBox, ViewSwitcher,
};
use druid::{theme, AppLauncher, Color, Data, Env, Lens, Widget, WidgetExt, WindowDesc};
use instant::Duration;
#[derive(Data, Clone, Lens)]
struct DynamicTabData {
highest_tab: usize,
removed_tabs: usize,
tab_labels: Vector<usize>,
}
impl DynamicTabData {
fn new(highest_tab: usize) -> Self {
DynamicTabData {
highest_tab,
removed_tabs: 0,
tab_labels: (1..=highest_tab).collect(),
}
}
fn add_tab(&mut self) {
self.highest_tab += 1;
self.tab_labels.push_back(self.highest_tab);
}
fn remove_tab(&mut self, idx: usize) {
if idx >= self.tab_labels.len() {
tracing::warn!("Attempt to remove non existent tab at index {}", idx)
} else {
self.removed_tabs += 1;
self.tab_labels.remove(idx);
}
}
// This provides a key that will monotonically increase as interactions occur.
fn tabs_key(&self) -> (usize, usize) {
(self.highest_tab, self.removed_tabs)
}
}
#[derive(Data, Clone, Lens)]
struct TabConfig {
axis: Axis,
edge: TabsEdge,
transition: TabsTransition,
}
#[derive(Data, Clone, Lens)]
struct AppState {
tab_config: TabConfig,
advanced: DynamicTabData,
first_tab_name: String,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("Tabs")
.window_size((700.0, 400.0));
// create the initial app state
let initial_state = AppState {
tab_config: TabConfig {
axis: Axis::Horizontal,
edge: TabsEdge::Leading,
transition: Default::default(),
},
first_tab_name: "First tab".into(),
advanced: DynamicTabData::new(2),
};
// start the application
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<AppState> {
fn group<T: Data, W: Widget<T> + 'static>(text: &str, w: W) -> impl Widget<T> {
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(
Label::new(text)
.background(theme::PLACEHOLDER_COLOR)
.expand_width(),
)
.with_default_spacer()
.with_child(w)
.with_default_spacer()
.border(Color::WHITE, 0.5)
}
let axis_picker = group(
"Tab bar axis",
RadioGroup::column(vec![
("Horizontal", Axis::Horizontal),
("Vertical", Axis::Vertical),
])
.lens(TabConfig::axis),
);
let cross_picker = group(
"Tab bar edge",
RadioGroup::column(vec![
("Leading", TabsEdge::Leading),
("Trailing", TabsEdge::Trailing),
])
.lens(TabConfig::edge),
);
let transit_picker = group(
"Transition",
RadioGroup::column(vec![
("Instant", TabsTransition::Instant),
(
"Slide",
TabsTransition::Slide(Duration::from_millis(250).as_nanos() as u64),
),
])
.lens(TabConfig::transition),
);
let sidebar = Flex::column()
.main_axis_alignment(MainAxisAlignment::Start)
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(axis_picker)
.with_default_spacer()
.with_child(cross_picker)
.with_default_spacer()
.with_child(transit_picker)
.with_flex_spacer(1.)
.fix_width(200.0)
.lens(AppState::tab_config);
let vs = ViewSwitcher::new(
|app_s: &AppState, _| app_s.tab_config.clone(),
|tc: &TabConfig, _, _| Box::new(build_tab_widget(tc)),
);
Flex::row().with_child(sidebar).with_flex_child(vs, 1.0)
}
#[derive(Clone, Data)]
struct NumberedTabs;
impl TabsPolicy for NumberedTabs {
type Key = usize;
type Build = ();
type Input = DynamicTabData;
type LabelWidget = Label<DynamicTabData>;
type BodyWidget = Label<DynamicTabData>;
fn tabs_changed(&self, old_data: &DynamicTabData, data: &DynamicTabData) -> bool {
old_data.tabs_key() != data.tabs_key()
}
fn tabs(&self, data: &DynamicTabData) -> Vec<Self::Key> {
data.tab_labels.iter().copied().collect()
}
fn tab_info(&self, key: Self::Key, _data: &DynamicTabData) -> TabInfo<DynamicTabData> {
TabInfo::new(format!("Tab {key:?}"), true)
}
fn tab_body(&self, key: Self::Key, _data: &DynamicTabData) -> Label<DynamicTabData> {
Label::new(format!("Dynamic tab body {key:?}"))
}
fn close_tab(&self, key: Self::Key, data: &mut DynamicTabData) {
if let Some(idx) = data.tab_labels.index_of(&key) {
data.remove_tab(idx)
}
}
fn tab_label(
&self,
_key: Self::Key,
info: TabInfo<Self::Input>,
_data: &Self::Input,
) -> Self::LabelWidget {
Self::default_make_label(info)
}
}
fn build_tab_widget(tab_config: &TabConfig) -> impl Widget<AppState> {
let dyn_tabs = Tabs::for_policy(NumberedTabs)
.with_axis(tab_config.axis)
.with_edge(tab_config.edge)
.with_transition(tab_config.transition)
.lens(AppState::advanced);
let control_dynamic = Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("Control dynamic tabs"))
.with_child(Button::new("Add a tab").on_click(|_c, d: &mut DynamicTabData, _e| d.add_tab()))
.with_child(Label::new(|adv: &DynamicTabData, _e: &Env| {
format!("Highest tab number is {}", adv.highest_tab)
}))
.with_spacer(20.)
.lens(AppState::advanced);
let first_static_tab = Flex::row()
.with_child(Label::new("Rename tab:"))
.with_child(TextBox::new().lens(AppState::first_tab_name));
let main_tabs = Tabs::new()
.with_axis(tab_config.axis)
.with_edge(tab_config.edge)
.with_transition(tab_config.transition)
.with_tab(
|app_state: &AppState, _: &Env| app_state.first_tab_name.to_string(),
first_static_tab,
)
.with_tab("Dynamic", control_dynamic)
.with_tab("Page 3", Label::new("Page 3 content"))
.with_tab("Page 4", Label::new("Page 4 content"))
.with_tab("Page 5", Label::new("Page 5 content"))
.with_tab("Page 6", Label::new("Page 6 content"))
.with_tab_index(1);
Split::rows(main_tabs, dyn_tabs).draggable(true)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/svg.rs | druid/examples/svg.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example shows how to draw an SVG.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use tracing::error;
use druid::{
widget::{Flex, Svg, SvgData, WidgetExt},
AppLauncher, LocalizedString, Widget, WindowDesc,
};
pub fn main() {
let main_window = WindowDesc::new(ui_builder())
.title(LocalizedString::new("svg-demo-window-title").with_placeholder("Rawr!"));
let data = 0_u32;
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn ui_builder() -> impl Widget<u32> {
let tiger_svg = match include_str!("./assets/tiger.svg").parse::<SvgData>() {
Ok(svg) => svg,
Err(err) => {
error!("{}", err);
error!("Using an empty SVG instead.");
SvgData::default()
}
};
let mut col = Flex::column();
col.add_flex_child(Svg::new(tiger_svg.clone()).fix_width(60.0).center(), 1.0);
col.add_flex_child(Svg::new(tiger_svg.clone()), 1.0);
col.add_flex_child(Svg::new(tiger_svg), 1.0);
col.debug_paint_layout()
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/calc.rs | druid/examples/calc.rs | // Copyright 2018 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Simple calculator.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::{
theme, AppLauncher, Color, Data, Lens, LocalizedString, RenderContext, Widget, WidgetExt,
WindowDesc,
};
use druid::widget::{CrossAxisAlignment, Flex, Label, Painter};
#[derive(Clone, Data, Lens)]
struct CalcState {
/// The number displayed. Generally a valid float.
value: String,
operand: f64,
operator: char,
in_num: bool,
}
impl CalcState {
fn digit(&mut self, digit: u8) {
if !self.in_num {
self.value.clear();
self.in_num = true;
}
let ch = (b'0' + digit) as char;
self.value.push(ch);
}
fn display(&mut self) {
// TODO: change hyphen-minus to actual minus
self.value = self.operand.to_string();
}
fn compute(&mut self) {
if self.in_num {
let operand2 = self.value.parse().unwrap_or(0.0);
let result = match self.operator {
'+' => Some(self.operand + operand2),
'−' => Some(self.operand - operand2),
'×' => Some(self.operand * operand2),
'÷' => Some(self.operand / operand2),
_ => None,
};
if let Some(result) = result {
self.operand = result;
self.display();
self.in_num = false;
}
}
}
fn op(&mut self, op: char) {
match op {
'+' | '−' | '×' | '÷' | '=' => {
self.compute();
self.operand = self.value.parse().unwrap_or(0.0);
self.operator = op;
self.in_num = false;
}
'±' => {
if self.in_num {
if self.value.starts_with('−') {
self.value = self.value[3..].to_string();
} else {
self.value = ["−", &self.value].concat();
}
} else {
self.operand = -self.operand;
self.display();
}
}
'.' => {
if !self.in_num {
self.value = "0".to_string();
self.in_num = true;
}
if self.value.find('.').is_none() {
self.value.push('.');
}
}
'c' => {
self.value = "0".to_string();
self.in_num = false;
}
'C' => {
self.value = "0".to_string();
self.operator = 'C';
self.in_num = false;
}
'⌫' => {
if self.in_num {
self.value.pop();
if self.value.is_empty() || self.value == "−" {
self.value = "0".to_string();
self.in_num = false;
}
}
}
_ => unreachable!(),
}
}
}
fn op_button_label(op: char, label: String) -> impl Widget<CalcState> {
let painter = Painter::new(|ctx, _, env| {
let bounds = ctx.size().to_rect();
ctx.fill(bounds, &env.get(theme::PRIMARY_DARK));
if ctx.is_hot() {
ctx.stroke(bounds.inset(-0.5), &Color::WHITE, 1.0);
}
if ctx.is_active() {
ctx.fill(bounds, &env.get(theme::PRIMARY_LIGHT));
}
});
Label::new(label)
.with_text_size(24.)
.center()
.background(painter)
.expand()
.on_click(move |_ctx, data: &mut CalcState, _env| data.op(op))
}
fn op_button(op: char) -> impl Widget<CalcState> {
op_button_label(op, op.to_string())
}
fn digit_button(digit: u8) -> impl Widget<CalcState> {
let painter = Painter::new(|ctx, _, env| {
let bounds = ctx.size().to_rect();
ctx.fill(bounds, &env.get(theme::BACKGROUND_LIGHT));
if ctx.is_hot() {
ctx.stroke(bounds.inset(-0.5), &Color::WHITE, 1.0);
}
if ctx.is_active() {
ctx.fill(bounds, &Color::rgb8(0x71, 0x71, 0x71));
}
});
Label::new(format!("{digit}"))
.with_text_size(24.)
.center()
.background(painter)
.expand()
.on_click(move |_ctx, data: &mut CalcState, _env| data.digit(digit))
}
fn flex_row<T: Data>(
w1: impl Widget<T> + 'static,
w2: impl Widget<T> + 'static,
w3: impl Widget<T> + 'static,
w4: impl Widget<T> + 'static,
) -> impl Widget<T> {
Flex::row()
.with_flex_child(w1, 1.0)
.with_spacer(1.0)
.with_flex_child(w2, 1.0)
.with_spacer(1.0)
.with_flex_child(w3, 1.0)
.with_spacer(1.0)
.with_flex_child(w4, 1.0)
}
fn build_calc() -> impl Widget<CalcState> {
let display = Label::new(|data: &String, _env: &_| data.clone())
.with_text_size(32.0)
.lens(CalcState::value)
.padding(5.0);
Flex::column()
.with_flex_spacer(0.2)
.with_child(display)
.with_flex_spacer(0.2)
.cross_axis_alignment(CrossAxisAlignment::End)
.with_flex_child(
flex_row(
op_button_label('c', "CE".to_string()),
op_button('C'),
op_button('⌫'),
op_button('÷'),
),
1.0,
)
.with_spacer(1.0)
.with_flex_child(
flex_row(
digit_button(7),
digit_button(8),
digit_button(9),
op_button('×'),
),
1.0,
)
.with_spacer(1.0)
.with_flex_child(
flex_row(
digit_button(4),
digit_button(5),
digit_button(6),
op_button('−'),
),
1.0,
)
.with_spacer(1.0)
.with_flex_child(
flex_row(
digit_button(1),
digit_button(2),
digit_button(3),
op_button('+'),
),
1.0,
)
.with_spacer(1.0)
.with_flex_child(
flex_row(
op_button('±'),
digit_button(0),
op_button('.'),
op_button('='),
),
1.0,
)
}
pub fn main() {
let window = WindowDesc::new(build_calc())
.window_size((223., 300.))
.resizable(false)
.title(
LocalizedString::new("calc-demo-window-title").with_placeholder("Simple Calculator"),
);
let calc_state = CalcState {
value: "0".to_string(),
operand: 0.0,
operator: 'C',
in_num: false,
};
AppLauncher::with_window(window)
.log_to_console()
.launch(calc_state)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/game_of_life.rs | druid/examples/game_of_life.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This is an example of how you would implement the game of life with Druid.
//! This example doesn't showcase anything specific in Druid.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use std::ops::{Index, IndexMut};
use std::time::{Duration, Instant};
use druid::widget::prelude::*;
use druid::widget::{Button, Flex, Label, Slider};
use druid::{
AppLauncher, Color, Data, Lens, MouseButton, Point, Rect, TimerToken, WidgetExt, WindowDesc,
};
use std::sync::Arc;
const GRID_SIZE: usize = 41;
const POOL_SIZE: usize = GRID_SIZE * GRID_SIZE;
const BACKGROUND: Color = Color::grey8(23);
static COLOURS: ColorScheme = &[
Color::rgb8(0xEB, 0xF1, 0xF7), //Color::rgb(235, 241, 247)
Color::rgb8(0xA2, 0xFC, 0xF7), //Color::rgb(162,252,247)
Color::rgb8(0xA2, 0xE3, 0xD8), //Color::rgb(162,227,216)
Color::rgb8(0xF2, 0xE6, 0xF1), //Color::rgb(242,230,241)
Color::rgb8(0xE0, 0xAF, 0xAF), //Color::rgb(224,175,175)
];
#[allow(clippy::rc_buffer)]
#[derive(Clone, Data, PartialEq)]
struct Grid {
storage: Arc<Vec<bool>>,
}
impl Grid {
pub fn new() -> Grid {
Grid {
storage: Arc::new(vec![false; POOL_SIZE]),
}
}
pub fn evolve(&mut self) {
let mut indices_to_mutate: Vec<GridPos> = vec![];
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let pos = GridPos { row, col };
let n_lives_around = self.n_neighbors(pos);
match (self[pos], n_lives_around) {
// death by overcrowding
(true, x) if x > 3 => indices_to_mutate.push(pos),
// death by loneliness
(true, x) if x < 2 => indices_to_mutate.push(pos),
// resurrection by life support
(false, 3) => indices_to_mutate.push(pos),
_ => (),
};
}
}
for pos_mut in indices_to_mutate {
self[pos_mut] = !self[pos_mut];
}
}
pub fn neighbors(pos: GridPos) -> [Option<GridPos>; 8] {
let above = pos.above();
let below = pos.below();
let left = pos.left();
let right = pos.right();
let above_left = above.and_then(|pos| pos.left());
let above_right = above.and_then(|pos| pos.right());
let below_left = below.and_then(|pos| pos.left());
let below_right = below.and_then(|pos| pos.right());
[
above,
below,
left,
right,
above_left,
above_right,
below_left,
below_right,
]
}
pub fn n_neighbors(&self, pos: GridPos) -> usize {
Grid::neighbors(pos)
.iter()
.filter(|x| x.is_some() && self[x.unwrap()])
.count()
}
pub fn set_alive(&mut self, positions: &[GridPos]) {
for pos in positions {
self[*pos] = true;
}
}
#[allow(dead_code)]
pub fn set_dead(&mut self, positions: &[GridPos]) {
for pos in positions {
self[*pos] = false;
}
}
pub fn clear(&mut self) {
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
self[GridPos { row, col }] = false;
}
}
}
}
#[derive(Clone, Copy)]
struct GridPos {
row: usize,
col: usize,
}
impl GridPos {
pub fn above(self) -> Option<GridPos> {
if self.row == 0 {
None
} else {
Some(GridPos {
row: self.row - 1,
col: self.col,
})
}
}
pub fn below(self) -> Option<GridPos> {
if self.row == GRID_SIZE - 1 {
None
} else {
Some(GridPos {
row: self.row + 1,
col: self.col,
})
}
}
pub fn left(self) -> Option<GridPos> {
if self.col == 0 {
None
} else {
Some(GridPos {
row: self.row,
col: self.col - 1,
})
}
}
pub fn right(self) -> Option<GridPos> {
if self.col == GRID_SIZE - 1 {
None
} else {
Some(GridPos {
row: self.row,
col: self.col + 1,
})
}
}
}
type ColorScheme = &'static [Color];
#[derive(Clone, Lens, Data)]
struct AppData {
grid: Grid,
drawing: bool,
paused: bool,
updates_per_second: f64,
}
impl AppData {
// allows time interval in the range [100ms, 5000ms]
// equivalently, 0.2 ~ 20ups
pub fn iter_interval(&self) -> u64 {
(1000. / self.updates_per_second) as u64
}
}
struct GameOfLifeWidget {
timer_id: TimerToken,
cell_size: Size,
last_update: Instant,
}
impl GameOfLifeWidget {
fn grid_pos(&self, p: Point) -> Option<GridPos> {
let w0 = self.cell_size.width;
let h0 = self.cell_size.height;
if p.x < 0.0 || p.y < 0.0 || w0 == 0.0 || h0 == 0.0 {
return None;
}
let row = (p.x / w0) as usize;
let col = (p.y / h0) as usize;
if row >= GRID_SIZE || col >= GRID_SIZE {
return None;
}
Some(GridPos { row, col })
}
}
impl Widget<AppData> for GameOfLifeWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppData, _env: &Env) {
match event {
Event::WindowConnected => {
ctx.request_paint();
let deadline = Duration::from_millis(data.iter_interval());
self.last_update = Instant::now();
self.timer_id = ctx.request_timer(deadline);
}
Event::Timer(id) => {
if *id == self.timer_id {
if !data.paused {
data.grid.evolve();
ctx.request_paint();
}
let deadline = Duration::from_millis(data.iter_interval());
self.last_update = Instant::now();
self.timer_id = ctx.request_timer(deadline);
}
}
Event::MouseDown(e) => {
if e.button == MouseButton::Left {
data.drawing = true;
let grid_pos_opt = self.grid_pos(e.pos);
grid_pos_opt
.iter()
.for_each(|pos| data.grid[*pos] = !data.grid[*pos]);
}
}
Event::MouseUp(e) => {
if e.button == MouseButton::Left {
data.drawing = false;
}
}
Event::MouseMove(e) => {
if data.drawing {
if let Some(grid_pos_opt) = self.grid_pos(e.pos) {
data.grid[grid_pos_opt] = true
}
}
}
_ => {}
}
}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_event: &LifeCycle,
_data: &AppData,
_env: &Env,
) {
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppData, data: &AppData, _env: &Env) {
if (data.updates_per_second - old_data.updates_per_second).abs() > 0.001 {
let deadline = Duration::from_millis(data.iter_interval())
.checked_sub(Instant::now().duration_since(self.last_update))
.unwrap_or_else(|| Duration::from_secs(0));
self.timer_id = ctx.request_timer(deadline);
}
if data.grid != old_data.grid {
ctx.request_paint();
}
}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &AppData,
_env: &Env,
) -> Size {
let max_size = bc.max();
let min_side = max_size.height.min(max_size.width);
Size {
width: min_side,
height: min_side,
}
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppData, _env: &Env) {
let size: Size = ctx.size();
let w0 = size.width / GRID_SIZE as f64;
let h0 = size.height / GRID_SIZE as f64;
let cell_size = Size {
width: w0,
height: h0,
};
self.cell_size = cell_size;
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let pos = GridPos { row, col };
if data.grid[pos] {
let point = Point {
x: w0 * row as f64,
y: h0 * col as f64,
};
let rect = Rect::from_origin_size(point, cell_size);
// We divide by 2 so that the colour changes every 2 positions instead of every 1
ctx.fill(
rect,
&COLOURS[((pos.row * GRID_SIZE + pos.col) / 2) % COLOURS.len()],
);
}
}
}
}
}
// gives back positions of a glider pattern
// _____
// | *|
// |* *|
// | **|
// ‾‾‾‾‾
fn glider(left_most: GridPos) -> Option<[GridPos; 5]> {
let center = left_most.right()?;
Some([
left_most,
center.below()?.right()?,
center.below()?,
center.right()?,
center.above()?.right()?,
])
}
// gives back positions of a blinker pattern
// ___
// |*|
// |*|
// |*|
// ‾‾‾
fn blinker(top: GridPos) -> Option<[GridPos; 3]> {
let center = top.below()?;
Some([top, center, center.below()?])
}
fn make_widget() -> impl Widget<AppData> {
Flex::column()
.with_flex_child(
GameOfLifeWidget {
timer_id: TimerToken::INVALID,
cell_size: Size {
width: 0.0,
height: 0.0,
},
last_update: Instant::now(),
},
1.0,
)
.with_child(
Flex::column()
.with_child(
// a row with two buttons
Flex::row()
.with_flex_child(
// pause / resume button
Button::new(|data: &bool, _: &Env| match data {
true => "Resume",
false => "Pause",
})
.on_click(|ctx, data: &mut bool, _: &Env| {
*data = !*data;
ctx.request_layout();
})
.lens(AppData::paused)
.padding((5., 5.)),
1.0,
)
.with_flex_child(
// clear button
Button::new("Clear")
.on_click(|ctx, data: &mut Grid, _: &Env| {
data.clear();
ctx.request_paint();
})
.lens(AppData::grid)
.padding((5., 5.)),
1.0,
)
.padding(8.0),
)
.with_child(
Flex::row()
.with_child(
Label::new(|data: &AppData, _env: &_| {
format!("{:.2}updates/s", data.updates_per_second)
})
.padding(3.0),
)
.with_flex_child(
Slider::new()
.with_range(0.2, 20.0)
.expand_width()
.lens(AppData::updates_per_second),
1.,
)
.padding(8.0),
)
.background(BACKGROUND),
)
}
pub fn main() {
let window = WindowDesc::new(make_widget())
.window_size(Size {
width: 800.0,
height: 800.0,
})
.resizable(false)
.title("Game of Life");
let mut grid = Grid::new();
let pattern0 = glider(GridPos { row: 5, col: 5 });
if let Some(x) = pattern0 {
grid.set_alive(&x);
}
let pattern1 = blinker(GridPos { row: 29, col: 29 });
if let Some(x) = pattern1 {
grid.set_alive(&x);
}
AppLauncher::with_window(window)
.log_to_console()
.launch(AppData {
grid,
drawing: false,
paused: false,
updates_per_second: 10.0,
})
.expect("launch failed");
}
impl Index<GridPos> for Grid {
type Output = bool;
fn index(&self, pos: GridPos) -> &Self::Output {
let idx = pos.row * GRID_SIZE + pos.col;
&self.storage[idx]
}
}
impl IndexMut<GridPos> for Grid {
fn index_mut(&mut self, pos: GridPos) -> &mut Self::Output {
let idx = pos.row * GRID_SIZE + pos.col;
Arc::make_mut(&mut self.storage).index_mut(idx)
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/textbox.rs | druid/examples/textbox.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of various text layout features.
//!
//! I would like to make this a bit fancier (like the flex demo) but for now
//! lets keep it simple.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use std::sync::Arc;
use druid::widget::{Flex, Label, TextBox};
use druid::{
AppLauncher, Color, Data, Env, Lens, LocalizedString, Menu, Widget, WidgetExt, WindowDesc,
WindowId,
};
const WINDOW_TITLE: LocalizedString<AppState> = LocalizedString::new("Text Options");
const EXPLAINER: &str = "\
This example demonstrates some of the possible configurations \
of the TextBox widget.\n\
The top textbox allows a single line of input, with horizontal scrolling \
but no scrollbars. The bottom textbox allows multiple lines of text, wrapping \
words to fit the width, and allowing vertical scrolling when it runs out \
of room to grow vertically.";
#[derive(Clone, Data, Lens)]
struct AppState {
multi: Arc<String>,
single: Arc<String>,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title(WINDOW_TITLE)
.menu(make_menu)
.window_size((400.0, 600.0));
// create the initial app state
let initial_state = AppState {
single: "".to_string().into(),
multi: "".to_string().into(),
};
// start the application
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<AppState> {
let blurb = Label::new(EXPLAINER)
.with_line_break_mode(druid::widget::LineBreaking::WordWrap)
.padding(8.0)
.border(Color::grey(0.6), 2.0)
.rounded(5.0);
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Start)
.with_child(blurb)
.with_spacer(24.0)
.with_child(
TextBox::new()
.with_placeholder("Single")
.lens(AppState::single),
)
.with_default_spacer()
.with_flex_child(
TextBox::multiline()
.with_placeholder("Multi")
.lens(AppState::multi)
.expand_width(),
1.0,
)
.padding(8.0)
}
#[allow(unused_assignments, unused_mut)]
fn make_menu<T: Data>(_window: Option<WindowId>, _data: &AppState, _env: &Env) -> Menu<T> {
let mut base = Menu::empty();
#[cfg(target_os = "macos")]
{
base = base.entry(druid::platform_menus::mac::application::default())
}
#[cfg(any(
target_os = "windows",
target_os = "freebsd",
target_os = "linux",
target_os = "openbsd"
))]
{
base = base.entry(druid::platform_menus::win::file::default());
}
base.entry(
Menu::new(LocalizedString::new("common-menu-edit-menu"))
.entry(druid::platform_menus::common::undo())
.entry(druid::platform_menus::common::redo())
.separator()
.entry(druid::platform_menus::common::cut())
.entry(druid::platform_menus::common::copy())
.entry(druid::platform_menus::common::paste()),
)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/image.rs | druid/examples/image.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This showcase demonstrates how to use the image widget and its
//! properties. You can change the parameters in the GUI to see how
//! everything behaves.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::piet::InterpolationMode;
use druid::text::ParseFormatter;
use druid::widget::{prelude::*, FillStrat, Image};
use druid::widget::{
Checkbox, CrossAxisAlignment, Flex, Label, RadioGroup, SizedBox, TextBox, WidgetExt,
};
use druid::{AppLauncher, Color, Data, ImageBuf, Lens, Rect, WindowDesc};
static FILL_STRAT_OPTIONS: &[(&str, FillStrat)] = &[
("Contain", FillStrat::Contain),
("Cover", FillStrat::Cover),
("Fill", FillStrat::Fill),
("FitHeight", FillStrat::FitHeight),
("FitWidth", FillStrat::FitWidth),
("None", FillStrat::None),
("ScaleDown", FillStrat::ScaleDown),
];
static INTERPOLATION_MODE_OPTIONS: &[(&str, InterpolationMode)] = &[
("Bilinear", InterpolationMode::Bilinear),
("NearestNeighbor", InterpolationMode::NearestNeighbor),
];
#[derive(Clone, Data, Lens)]
struct AppState {
fill_strat: FillStrat,
interpolate: bool,
interpolation_mode: InterpolationMode,
fix_width: bool,
width: f64,
fix_height: bool,
height: f64,
clip: bool,
clip_x: f64,
clip_y: f64,
clip_width: f64,
clip_height: f64,
}
/// builds a child Flex widget from some parameters.
struct Rebuilder {
inner: Box<dyn Widget<AppState>>,
}
impl Rebuilder {
fn new() -> Rebuilder {
Rebuilder {
inner: SizedBox::empty().boxed(),
}
}
fn rebuild_inner(&mut self, data: &AppState) {
self.inner = build_widget(data);
}
}
impl Widget<AppState> for Rebuilder {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut AppState, env: &Env) {
self.inner.event(ctx, event, data, env)
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &AppState, env: &Env) {
if let LifeCycle::WidgetAdded = event {
self.rebuild_inner(data);
}
self.inner.lifecycle(ctx, event, data, env)
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &AppState, data: &AppState, _env: &Env) {
if !old_data.same(data) {
self.rebuild_inner(data);
ctx.children_changed();
}
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &AppState,
env: &Env,
) -> Size {
self.inner.layout(ctx, bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) {
self.inner.paint(ctx, data, env)
}
fn id(&self) -> Option<WidgetId> {
self.inner.id()
}
}
fn make_control_row() -> impl Widget<AppState> {
Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("FillStrat:"))
.with_default_spacer()
.with_child(
RadioGroup::column(FILL_STRAT_OPTIONS.to_vec()).lens(AppState::fill_strat),
),
)
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("interpolation mode:"))
.with_default_spacer()
.with_child(
RadioGroup::column(INTERPOLATION_MODE_OPTIONS.to_vec())
.lens(AppState::interpolation_mode),
),
)
.with_default_spacer()
.with_child(make_width())
.with_default_spacer()
.with_child(make_height())
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("Misc:"))
.with_default_spacer()
.with_child(Checkbox::new("Fix width").lens(AppState::fix_width))
.with_default_spacer()
.with_child(Checkbox::new("Fix height").lens(AppState::fix_height))
.with_default_spacer()
.with_child(Checkbox::new("Clip").lens(AppState::clip))
.with_default_spacer()
.with_child(Checkbox::new("set interpolation mode").lens(AppState::interpolate)),
)
.padding(10.0)
.border(Color::grey(0.6), 2.0)
.rounded(5.0)
}
fn make_width() -> impl Widget<AppState> {
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("width:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::width)
.fix_width(60.0),
),
)
.with_default_spacer()
.with_child(Label::new("clip x:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::clip_x)
.fix_width(60.0),
),
)
.with_default_spacer()
.with_child(Label::new("clip width:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::clip_width)
.fix_width(60.0),
),
)
}
fn make_height() -> impl Widget<AppState> {
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(Label::new("height:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::height)
.fix_width(60.0),
),
)
.with_default_spacer()
.with_child(Label::new("clip y:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::clip_y)
.fix_width(60.0),
),
)
.with_default_spacer()
.with_child(Label::new("clip height:"))
.with_default_spacer()
.with_child(
Flex::row().with_child(
TextBox::new()
.with_formatter(ParseFormatter::new())
.lens(AppState::clip_height)
.fix_width(60.0),
),
)
}
fn build_widget(state: &AppState) -> Box<dyn Widget<AppState>> {
let png_data = ImageBuf::from_data(include_bytes!("./assets/PicWithAlpha.png")).unwrap();
let mut img = Image::new(png_data).fill_mode(state.fill_strat);
if state.interpolate {
img.set_interpolation_mode(state.interpolation_mode)
}
if state.clip {
img.set_clip_area(Some(Rect::new(
state.clip_x,
state.clip_y,
state.clip_x + state.clip_width,
state.clip_y + state.clip_height,
)));
}
let mut sized = SizedBox::new(img);
if state.fix_width {
sized = sized.fix_width(state.width)
}
if state.fix_height {
sized = sized.fix_height(state.height)
}
sized.border(Color::grey(0.6), 2.0).center().boxed()
}
fn make_ui() -> impl Widget<AppState> {
Flex::column()
.must_fill_main_axis(true)
.with_child(make_control_row())
.with_default_spacer()
.with_flex_child(Rebuilder::new().center(), 1.0)
.padding(10.0)
}
pub fn main() {
let main_window = WindowDesc::new(make_ui())
.window_size((650., 450.))
.title("Flex Container Options");
let state = AppState {
fill_strat: FillStrat::Cover,
interpolate: true,
interpolation_mode: InterpolationMode::Bilinear,
fix_width: true,
width: 200.,
fix_height: true,
height: 100.,
clip: false,
clip_x: 0.,
clip_y: 0.,
clip_width: 50.,
clip_height: 50.,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(state)
.expect("Failed to launch application");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/invalidation.rs | druid/examples/invalidation.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Demonstrates how to debug invalidation regions, and also shows the
//! invalidation behavior of several built-in widgets.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::im::Vector;
use druid::kurbo::{self, Shape};
use druid::widget::prelude::*;
use druid::widget::{Button, Flex, Scroll, Split, TextBox};
use druid::{AppLauncher, Color, Data, Lens, LocalizedString, Point, WidgetExt, WindowDesc};
use instant::Instant;
pub fn main() {
let window = WindowDesc::new(build_widget()).title(
LocalizedString::new("invalidate-demo-window-title").with_placeholder("Invalidate demo"),
);
let state = AppState {
label: "My label".into(),
circles: Vector::new(),
};
AppLauncher::with_window(window)
.log_to_console()
.launch(state)
.expect("launch failed");
}
#[derive(Clone, Data, Lens)]
struct AppState {
label: String,
circles: Vector<Circle>,
}
fn build_widget() -> impl Widget<AppState> {
let mut col = Flex::column();
col.add_child(TextBox::new().lens(AppState::label).padding(3.0));
for i in 0..30 {
col.add_child(Button::new(format!("Button {i}")).padding(3.0));
}
Split::columns(Scroll::new(col), CircleView.lens(AppState::circles)).debug_invalidation()
}
struct CircleView;
#[derive(Clone, Data)]
struct Circle {
pos: Point,
#[data(eq)]
time: Instant,
}
const RADIUS: f64 = 25.0;
impl Widget<Vector<Circle>> for CircleView {
fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
if let Event::MouseDown(ev) = ev {
if ev.mods.shift() {
data.push_back(Circle {
pos: ev.pos,
time: Instant::now(),
});
} else if ev.mods.ctrl() {
data.retain(|c| {
if (c.pos - ev.pos).hypot() > RADIUS {
true
} else {
ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
false
}
});
} else {
// Move the circle to a new location, invalidating the old locations. The new location
// will be invalidated during AnimFrame.
for c in data.iter() {
ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
}
data.clear();
data.push_back(Circle {
pos: ev.pos,
time: Instant::now(),
});
}
ctx.request_anim_frame();
} else if let Event::AnimFrame(_) = ev {
for c in &*data {
ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
}
if !data.is_empty() {
ctx.request_anim_frame();
}
}
}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_ev: &LifeCycle,
_data: &Vector<Circle>,
_env: &Env,
) {
}
fn update(
&mut self,
_ctx: &mut UpdateCtx,
_old: &Vector<Circle>,
_new: &Vector<Circle>,
_env: &Env,
) {
}
fn layout(
&mut self,
_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &Vector<Circle>,
_env: &Env,
) -> Size {
bc.max()
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &Vector<Circle>, _env: &Env) {
ctx.with_save(|ctx| {
let rect = ctx.size().to_rect();
ctx.clip(rect);
ctx.fill(rect, &Color::WHITE);
let now = Instant::now();
for c in data {
let color =
Color::BLACK.with_alpha(now.duration_since(c.time).as_secs_f64().cos().abs());
ctx.fill(kurbo::Circle::new(c.pos, RADIUS), &color);
}
});
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/list.rs | druid/examples/list.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Demos basic list widget and list manipulations.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::im::{vector, Vector};
use druid::lens::{self, LensExt};
use druid::widget::{Button, CrossAxisAlignment, Flex, Label, List, Scroll};
use druid::{
AppLauncher, Color, Data, Lens, LocalizedString, UnitPoint, Widget, WidgetExt, WindowDesc,
};
#[derive(Clone, Data, Lens)]
struct AppData {
left: Vector<u32>,
right: Vector<u32>,
l_index: usize,
r_index: usize,
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder())
.title(LocalizedString::new("list-demo-window-title").with_placeholder("List Demo"));
// Set our initial data
let left = vector![1, 2];
let right = vector![1, 2, 3];
let data = AppData {
l_index: left.len(),
r_index: right.len(),
left,
right,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn ui_builder() -> impl Widget<AppData> {
let mut root = Flex::column();
// Build a button to add children to both lists
root.add_child(
Button::new("Add")
.on_click(|_, data: &mut AppData, _| {
// Add child to left list
data.l_index += 1;
data.left.push_back(data.l_index as u32);
// Add child to right list
data.r_index += 1;
data.right.push_back(data.r_index as u32);
})
.fix_height(30.0)
.expand_width(),
);
let mut lists = Flex::row().cross_axis_alignment(CrossAxisAlignment::Start);
// Build a simple list
lists.add_flex_child(
Scroll::new(List::new(|| {
Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
.align_vertical(UnitPoint::LEFT)
.padding(10.0)
.expand()
.height(50.0)
.background(Color::rgb(0.5, 0.5, 0.5))
}))
.vertical()
.lens(AppData::left),
1.0,
);
// Build a list with shared data
lists.add_flex_child(
Scroll::new(
List::new(|| {
Flex::row()
.with_child(
Label::new(|(_, item): &(Vector<u32>, u32), _env: &_| {
format!("List item #{item}")
})
.align_vertical(UnitPoint::LEFT),
)
.with_flex_spacer(1.0)
.with_child(
Button::new("Delete")
.on_click(|_ctx, (shared, item): &mut (Vector<u32>, u32), _env| {
// We have access to both child's data and shared data.
// Remove element from right list.
shared.retain(|v| v != item);
})
.fix_size(80.0, 20.0)
.align_vertical(UnitPoint::CENTER),
)
.padding(10.0)
.background(Color::rgb(0.5, 0.0, 0.5))
.fix_height(50.0)
})
.with_spacing(10.),
)
.vertical()
.lens(lens::Identity.map(
// Expose shared data with children data
|d: &AppData| (d.right.clone(), d.right.clone()),
|d: &mut AppData, x: (Vector<u32>, Vector<u32>)| {
// If shared data was changed reflect the changes in our AppData
d.right = x.0
},
)),
1.0,
);
root.add_flex_child(lists, 1.0);
root.with_child(Label::new("horizontal list"))
.with_child(
Scroll::new(
List::new(|| {
Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
.padding(10.0)
.background(Color::rgb(0.5, 0.5, 0.0))
.fix_height(50.0)
})
.horizontal()
.with_spacing(10.)
.lens(AppData::left),
)
.horizontal(),
)
.debug_paint_layout()
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/disabled.rs | druid/examples/disabled.rs | // Copyright 2021 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example showing the effect of the disabled state on focus-chain and the widgets.
//! When the disabled checkbox is clicked only the widgets not marked as disabled should
//! respond. Pressing Tab should only focus widgets not marked as disabled. If a widget
//! is focused while getting disabled it should resign the focus.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::{
Button, Checkbox, CrossAxisAlignment, Flex, Label, Slider, Stepper, Switch, TextBox,
};
use druid::{AppLauncher, Data, Lens, LocalizedString, UnitPoint, Widget, WidgetExt, WindowDesc};
#[derive(Clone, Data, Lens)]
struct AppData {
option: bool,
text: String,
value: f64,
disabled: bool,
}
fn named_child(name: &str, widget: impl Widget<AppData> + 'static) -> impl Widget<AppData> {
Flex::row()
.with_child(Label::new(name))
.with_default_spacer()
.with_child(widget)
}
fn main_widget() -> impl Widget<AppData> {
Flex::column()
.with_child(named_child("text:", TextBox::new().lens(AppData::text)))
.with_default_spacer()
.with_child(
named_child("text (disabled):", TextBox::new().lens(AppData::text))
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_child(named_child("text:", TextBox::new().lens(AppData::text)))
.with_default_spacer()
.with_child(
named_child("text (disabled):", TextBox::new().lens(AppData::text))
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_default_spacer()
.with_child(
named_child(
"value (disabled):",
Slider::new().with_range(0.0, 10.0).lens(AppData::value),
)
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_child(
named_child(
"value (disabled):",
Stepper::new()
.with_range(0.0, 10.0)
.with_step(0.5)
.lens(AppData::value),
)
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_child(
named_child(
"option (disabled):",
Checkbox::new("option").lens(AppData::option),
)
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_child(
named_child("option (disabled):", Switch::new().lens(AppData::option))
.disabled_if(|data, _| data.disabled),
)
.with_default_spacer()
.with_child(
Flex::row()
.with_child(
Button::new("-")
.on_click(|_, data: &mut f64, _| *data -= 1.0)
.disabled_if(|data, _| *data < 1.0),
)
.with_default_spacer()
.with_child(Label::dynamic(|data: &f64, _| data.to_string()))
.with_default_spacer()
.with_child(
Button::new("+")
.on_click(|_, data: &mut f64, _| *data += 1.0)
.disabled_if(|data, _| *data > 9.0),
)
.lens(AppData::value)
.disabled_if(|data: &AppData, _| data.disabled),
)
.with_default_spacer()
.with_default_spacer()
.with_default_spacer()
.with_child(Checkbox::new("disabled").lens(AppData::disabled))
.with_default_spacer()
.cross_axis_alignment(CrossAxisAlignment::End)
.align_horizontal(UnitPoint::CENTER)
}
pub fn main() {
let window = WindowDesc::new(main_widget()).title(
LocalizedString::new("disabled-demo-window-title").with_placeholder("Disabled demo"),
);
AppLauncher::with_window(window)
.log_to_console()
.launch(AppData {
option: true,
text: "a very important text!".to_string(),
value: 2.0,
disabled: false,
})
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/slider.rs | druid/examples/slider.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This is a demo of the settings of Slider, RangeSlider and Annotated.
//! It contains a `Slider` and `RangeSlider`.
//! Every time the `RangeSlider` is moved the range of the `Slider` is updated.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{
Axis, CrossAxisAlignment, Flex, KnobStyle, Label, RangeSlider, Slider, ViewSwitcher,
};
use druid::{AppLauncher, Color, Data, KeyOrValue, Lens, UnitPoint, WidgetExt, WindowDesc};
const VERTICAL_WIDGET_SPACING: f64 = 20.0;
#[derive(Clone, Data, Lens)]
struct AppState {
range: (f64, f64),
value: f64,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("Slider Demo!")
.window_size((400.0, 400.0));
// create the initial app state
let initial_state: AppState = AppState {
range: (2.0, 8.0),
value: 5.0,
};
// start the application. Here we pass in the application state.
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<AppState> {
let range = Flex::row()
.with_child(Label::dynamic(|value: &(f64, f64), _| {
format!("Value Range: {value:?}")
}))
.with_default_spacer()
.with_child(
RangeSlider::new()
.with_range(0.0, 20.0)
.with_step(1.0)
.track_color(KeyOrValue::Concrete(Color::RED))
.fix_width(250.0),
)
.lens(AppState::range);
let value = Flex::row()
.with_child(Label::dynamic(|value: &AppState, _| {
format!("Value: {:?}", value.value)
}))
.with_default_spacer()
.with_child(ViewSwitcher::new(
|data: &AppState, _| data.range,
|range, _, _| {
Slider::new()
.with_range(range.0, range.1)
.track_color(KeyOrValue::Concrete(Color::RED))
.knob_style(KnobStyle::Wedge)
.axis(Axis::Vertical)
.with_step(0.25)
.annotated(1.0, 0.25)
.fix_height(250.0)
.lens(AppState::value)
.boxed()
},
));
// arrange the two widgets vertically, with some padding
Flex::column()
.with_child(range)
.with_spacer(VERTICAL_WIDGET_SPACING)
.with_child(value)
.cross_axis_alignment(CrossAxisAlignment::End)
.align_vertical(UnitPoint::RIGHT)
.padding(20.0)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/text.rs | druid/examples/text.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of various text layout features.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::piet::{PietTextLayoutBuilder, TextStorage as PietTextStorage};
use druid::text::{Attribute, RichText, TextStorage};
use druid::widget::prelude::*;
use druid::widget::{Controller, Flex, Label, LineBreaking, RadioGroup, RawLabel, Scroll};
use druid::{
AppLauncher, Color, Data, FontFamily, FontStyle, FontWeight, Lens, LocalizedString,
TextAlignment, Widget, WidgetExt, WindowDesc,
};
const WINDOW_TITLE: LocalizedString<AppState> = LocalizedString::new("Text Options");
const TEXT: &str = r#"Contrary to what we would like to believe, there is no such thing as a structureless group. Any group of people of whatever nature that comes together for any length of time for any purpose will inevitably structure itself in some fashion. The structure may be flexible; it may vary over time; it may evenly or unevenly distribute tasks, power and resources over the members of the group. But it will be formed regardless of the abilities, personalities, or intentions of the people involved. The very fact that we are individuals, with different talents, predispositions, and backgrounds makes this inevitable. Only if we refused to relate or interact on any basis whatsoever could we approximate structurelessness -- and that is not the nature of a human group.
This means that to strive for a structureless group is as useful, and as deceptive, as to aim at an "objective" news story, "value-free" social science, or a "free" economy. A "laissez faire" group is about as realistic as a "laissez faire" society; the idea becomes a smokescreen for the strong or the lucky to establish unquestioned hegemony over others. This hegemony can be so easily established because the idea of "structurelessness" does not prevent the formation of informal structures, only formal ones. Similarly "laissez faire" philosophy did not prevent the economically powerful from establishing control over wages, prices, and distribution of goods; it only prevented the government from doing so. Thus structurelessness becomes a way of masking power, and within the women's movement is usually most strongly advocated by those who are the most powerful (whether they are conscious of their power or not). As long as the structure of the group is informal, the rules of how decisions are made are known only to a few and awareness of power is limited to those who know the rules. Those who do not know the rules and are not chosen for initiation must remain in confusion, or suffer from paranoid delusions that something is happening of which they are not quite aware."#;
const SPACER_SIZE: f64 = 8.0;
#[derive(Clone, Data, Lens)]
struct AppState {
text: RichText,
line_break_mode: LineBreaking,
alignment: TextAlignment,
}
//NOTE: we implement these traits for our base data (instead of just lensing
//into the RichText object, for the label) so that our label controller can
//have access to the other fields.
impl PietTextStorage for AppState {
fn as_str(&self) -> &str {
self.text.as_str()
}
}
impl TextStorage for AppState {
fn add_attributes(&self, builder: PietTextLayoutBuilder, env: &Env) -> PietTextLayoutBuilder {
self.text.add_attributes(builder, env)
}
}
/// A controller that updates label properties as required.
struct LabelController;
impl Controller<AppState, RawLabel<AppState>> for LabelController {
#[allow(clippy::float_cmp)]
fn update(
&mut self,
child: &mut RawLabel<AppState>,
ctx: &mut UpdateCtx,
old_data: &AppState,
data: &AppState,
env: &Env,
) {
if old_data.line_break_mode != data.line_break_mode {
child.set_line_break_mode(data.line_break_mode);
ctx.request_layout();
}
if old_data.alignment != data.alignment {
child.set_text_alignment(data.alignment);
ctx.request_layout();
}
child.update(ctx, old_data, data, env);
}
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title(WINDOW_TITLE)
.window_size((400.0, 600.0));
let text = RichText::new(TEXT.into())
.with_attribute(0..9, Attribute::text_color(Color::rgb(1.0, 0.2, 0.1)))
.with_attribute(0..9, Attribute::size(24.0))
.with_attribute(0..9, Attribute::font_family(FontFamily::SERIF))
.with_attribute(194..239, Attribute::weight(FontWeight::BOLD))
.with_attribute(764.., Attribute::size(12.0))
.with_attribute(764.., Attribute::style(FontStyle::Italic));
// create the initial app state
let initial_state = AppState {
line_break_mode: LineBreaking::Clip,
alignment: Default::default(),
text,
};
// start the application
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<AppState> {
let label = Scroll::new(
RawLabel::new()
.with_text_color(Color::BLACK)
.controller(LabelController)
.background(Color::WHITE)
.expand_width()
.padding((SPACER_SIZE * 4.0, SPACER_SIZE))
.background(Color::grey8(222)),
)
.vertical();
let line_break_chooser = Flex::column()
.with_child(Label::new("Line break mode"))
.with_spacer(SPACER_SIZE)
.with_child(RadioGroup::column(vec![
("Clip", LineBreaking::Clip),
("Wrap", LineBreaking::WordWrap),
("Overflow", LineBreaking::Overflow),
]))
.lens(AppState::line_break_mode);
let alignment_picker = Flex::column()
.with_child(Label::new("Justification"))
.with_spacer(SPACER_SIZE)
.with_child(RadioGroup::column(vec![
("Start", TextAlignment::Start),
("End", TextAlignment::End),
("Center", TextAlignment::Center),
("Justified", TextAlignment::Justified),
]))
.lens(AppState::alignment);
let controls = Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Start)
.with_child(alignment_picker)
.with_spacer(SPACER_SIZE)
.with_child(line_break_chooser)
.padding(SPACER_SIZE);
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Start)
.with_child(controls)
.with_flex_child(label, 1.0)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/panels.rs | druid/examples/panels.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example shows how to construct a basic layout.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::kurbo::Circle;
use druid::widget::{Flex, Label, Painter};
use druid::{
AppLauncher, Color, LinearGradient, LocalizedString, PlatformError, RenderContext, UnitPoint,
Widget, WidgetExt, WindowDesc,
};
const DARK_GREY: Color = Color::grey8(0x3a);
const DARKER_GREY: Color = Color::grey8(0x11);
const LIGHTER_GREY: Color = Color::grey8(0xbb);
fn build_app() -> impl Widget<()> {
let gradient = LinearGradient::new(
UnitPoint::TOP_LEFT,
UnitPoint::BOTTOM_RIGHT,
(DARKER_GREY, LIGHTER_GREY),
);
// a custom background
let polka_dots = Painter::new(|ctx, _, _| {
let bounds = ctx.size().to_rect();
let dot_diam = bounds.width().max(bounds.height()) / 20.;
let dot_spacing = dot_diam * 1.8;
for y in 0..((bounds.height() / dot_diam).ceil() as usize) {
for x in 0..((bounds.width() / dot_diam).ceil() as usize) {
let x_offset = (y % 2) as f64 * (dot_spacing / 2.0);
let x = x as f64 * dot_spacing + x_offset;
let y = y as f64 * dot_spacing;
let circ = Circle::new((x, y), dot_diam / 2.0);
let purp = Color::rgb(1.0, 0.22, 0.76);
ctx.fill(circ, &purp);
}
}
});
Flex::column()
.with_flex_child(
Flex::row()
.with_flex_child(
Label::new("top left")
.center()
.border(DARK_GREY, 4.0)
.padding(10.0),
1.0,
)
.with_flex_child(
Label::new("top right")
.center()
.background(DARK_GREY)
.padding(10.0),
1.0,
),
1.0,
)
.with_flex_child(
Flex::row()
.with_flex_child(
Label::new("bottom left")
.center()
.background(gradient)
.rounded(10.0)
.padding(10.0),
1.0,
)
.with_flex_child(
Label::new("bottom right")
.center()
.border(LIGHTER_GREY, 4.0)
.background(polka_dots)
.rounded(10.0)
.padding(10.0),
1.0,
),
1.0,
)
}
pub fn main() -> Result<(), PlatformError> {
let main_window = WindowDesc::new(build_app())
.title(LocalizedString::new("panels-demo-window-title").with_placeholder("Fancy Boxes!"));
AppLauncher::with_window(main_window)
.log_to_console()
.launch(())?;
Ok(())
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/either.rs | druid/examples/either.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example using the Either widget to show/hide a slider.
//! This is a very simple example, it uses a bool to determine
//! which widget gets shown.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Checkbox, Either, Flex, Label, Slider};
use druid::{AppLauncher, Data, Lens, WidgetExt, WindowDesc};
#[derive(Clone, Default, Data, Lens)]
struct AppState {
which: bool,
value: f64,
}
fn ui_builder() -> impl Widget<AppState> {
// Our UI consists of a column with a button and an `Either` widget
let button = Checkbox::new("Toggle slider")
.lens(AppState::which)
.padding(5.0);
// The `Either` widget has two children, only one of which is visible at a time.
// To determine which child is visible, you pass it a closure that takes the
// `Data` and the `Env` and returns a bool; if it returns `true`, the first
// widget will be visible, and if `false`, the second.
let either = Either::new(
|data, _env| data.which,
Slider::new().lens(AppState::value).padding(5.0),
Label::new("Click to reveal slider").padding(5.0),
);
Flex::column().with_child(button).with_child(either)
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder()).title("Switcheroo");
AppLauncher::with_window(main_window)
.log_to_console()
.launch(AppState::default())
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/hello.rs | druid/examples/hello.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This is a very small example of how to setup a Druid application.
//! It does the almost bare minimum while still being useful.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Flex, Label, TextBox};
use druid::{AppLauncher, Data, Lens, UnitPoint, WidgetExt, WindowDesc};
const VERTICAL_WIDGET_SPACING: f64 = 20.0;
const TEXT_BOX_WIDTH: f64 = 200.0;
#[derive(Clone, Data, Lens)]
struct HelloState {
name: String,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("Hello World!")
.window_size((400.0, 400.0));
// create the initial app state
let initial_state: HelloState = HelloState {
name: "World".into(),
};
// start the application. Here we pass in the application state.
AppLauncher::with_window(main_window)
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<HelloState> {
// a label that will determine its text based on the current app data.
let label = Label::new(|data: &HelloState, _env: &Env| {
if data.name.is_empty() {
"Hello anybody!?".to_string()
} else {
format!("Hello {}!", data.name)
}
})
.with_text_size(32.0);
// a textbox that modifies `name`.
let textbox = TextBox::new()
.with_placeholder("Who are we greeting?")
.with_text_size(18.0)
.fix_width(TEXT_BOX_WIDTH)
.lens(HelloState::name);
// arrange the two widgets vertically, with some padding
Flex::column()
.with_child(label)
.with_spacer(VERTICAL_WIDGET_SPACING)
.with_child(textbox)
.align_vertical(UnitPoint::CENTER)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/transparency.rs | druid/examples/transparency.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of a transparent window background.
//! Useful for dropdowns, tooltips and other overlay windows.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Flex, Label, Painter, TextBox, WidgetExt};
use druid::{kurbo::Circle, widget::Controller};
use druid::{AppLauncher, Color, Lens, Rect, WindowDesc};
#[derive(Clone, Data, Lens)]
struct HelloState {
name: String,
}
struct DragController;
impl<T, W: Widget<T>> Controller<T, W> for DragController {
fn event(
&mut self,
_child: &mut W,
ctx: &mut EventCtx,
event: &Event,
_data: &mut T,
_env: &Env,
) {
if let Event::MouseMove(_) = event {
ctx.window().handle_titlebar(true);
}
}
}
pub fn main() {
let window = WindowDesc::new(build_root_widget())
.show_titlebar(false)
.window_size((512., 512.))
.transparent(true)
.resizable(true)
.title("Transparent background");
AppLauncher::with_window(window)
.log_to_console()
.launch(HelloState { name: "".into() })
.expect("launch failed");
}
fn build_root_widget() -> impl Widget<HelloState> {
// Draw red circle, and two semi-transparent rectangles
let circle_and_rects = Painter::new(|ctx, _data, _env| {
let boundaries = ctx.size().to_rect();
let center = (boundaries.width() / 2., boundaries.height() / 2.);
let circle = Circle::new(center, center.0.min(center.1));
ctx.fill(circle, &Color::RED);
let rect1 = Rect::new(0., 0., boundaries.width() / 2., boundaries.height() / 2.);
ctx.fill(rect1, &Color::rgba8(0x0, 0xff, 0, 125));
let rect2 = Rect::new(
boundaries.width() / 2.,
boundaries.height() / 2.,
boundaries.width(),
boundaries.height(),
);
ctx.fill(rect2, &Color::rgba8(0x0, 0x0, 0xff, 125));
});
// This textbox modifies the label, idea here is to test that the background
// invalidation works when you type to the textbox
let textbox = TextBox::new()
.with_placeholder("Type to test clearing")
.with_text_size(18.0)
.lens(HelloState::name)
.fix_width(250.);
let label = Label::new(|data: &HelloState, _env: &Env| {
if data.name.is_empty() {
"Text: ".to_string()
} else {
format!("Text: {}!", data.name)
}
})
.with_text_color(Color::RED)
.with_text_size(32.0);
Flex::column()
.with_flex_child(circle_and_rects.expand().controller(DragController), 10.0)
.with_spacer(4.0)
.with_child(textbox)
.with_spacer(4.0)
.with_child(label)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/timer.rs | druid/examples/timer.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of a timer.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use std::time::Duration;
use druid::widget::prelude::*;
use druid::widget::BackgroundBrush;
use druid::{AppLauncher, Color, LocalizedString, Point, TimerToken, WidgetPod, WindowDesc};
static TIMER_INTERVAL: Duration = Duration::from_millis(10);
struct TimerWidget {
timer_id: TimerToken,
simple_box: WidgetPod<u32, SimpleBox>,
pos: Point,
}
impl TimerWidget {
/// Move the box towards the right, until it reaches the edge,
/// then reset it to the left but move it to another row.
fn adjust_box_pos(&mut self, container_size: Size) {
let box_size = self.simple_box.layout_rect().size();
self.pos.x += 2.;
if self.pos.x + box_size.width > container_size.width {
self.pos.x = 0.;
self.pos.y += box_size.height;
if self.pos.y + box_size.height > container_size.height {
self.pos.y = 0.;
}
}
}
}
impl Widget<u32> for TimerWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut u32, env: &Env) {
match event {
Event::WindowConnected => {
// Start the timer when the application launches
self.timer_id = ctx.request_timer(TIMER_INTERVAL);
}
Event::Timer(id) => {
if *id == self.timer_id {
self.adjust_box_pos(ctx.size());
ctx.request_layout();
self.timer_id = ctx.request_timer(TIMER_INTERVAL);
}
}
_ => (),
}
self.simple_box.event(ctx, event, data, env);
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &u32, env: &Env) {
self.simple_box.lifecycle(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &u32, data: &u32, env: &Env) {
self.simple_box.update(ctx, data, env);
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &u32, env: &Env) -> Size {
self.simple_box.layout(ctx, &bc.loosen(), data, env);
self.simple_box.set_origin(ctx, self.pos);
bc.constrain((500.0, 500.0))
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &u32, env: &Env) {
self.simple_box.paint(ctx, data, env);
}
}
struct SimpleBox;
impl Widget<u32> for SimpleBox {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut u32, _env: &Env) {}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &u32, _env: &Env) {
if let LifeCycle::HotChanged(_) = event {
ctx.request_paint();
}
}
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &u32, _data: &u32, _env: &Env) {}
fn layout(
&mut self,
_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &u32,
_env: &Env,
) -> Size {
bc.constrain((50.0, 50.0))
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &u32, env: &Env) {
let mut background = if ctx.is_hot() {
BackgroundBrush::Color(Color::rgb8(200, 55, 55))
} else {
BackgroundBrush::Color(Color::rgb8(30, 210, 170))
};
background.paint(ctx, data, env);
}
}
pub fn main() {
let window = WindowDesc::new(TimerWidget {
timer_id: TimerToken::INVALID,
simple_box: WidgetPod::new(SimpleBox),
pos: Point::ZERO,
})
.with_min_size((200., 200.))
.title(LocalizedString::new("timer-demo-window-title").with_placeholder("Look at it go!"));
AppLauncher::with_window(window)
.log_to_console()
.launch(0u32)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/anim.rs | druid/examples/anim.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of an animating widget. It is just a widget that
//! requests an animation frame when it needs to, and draws the frame in the
//! `paint` method.
//! Once the animation is over it simply stops requesting animation frames.
//! Usually we would put the state in the `Data`, but for things like animation
//! we don't. This is because the animation state is not useful to know for the
//! rest of the app. If this is something the rest of your widgets should know
//! about, you could put it in the `data`.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use std::f64::consts::PI;
use druid::kurbo::{Circle, Line};
use druid::widget::prelude::*;
use druid::{AppLauncher, Color, LocalizedString, Point, Vec2, WindowDesc};
struct AnimWidget {
t: f64,
}
impl Widget<()> for AnimWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut (), _env: &Env) {
match event {
Event::MouseDown(_) => {
self.t = 0.0;
ctx.request_anim_frame();
}
Event::AnimFrame(interval) => {
ctx.request_paint();
self.t += (*interval as f64) * 1e-9;
if self.t < 1.0 {
ctx.request_anim_frame();
} else {
// We might have t>1.0 at the end of the animation,
// we want to make sure the line points up at the
// end of the animation.
self.t = 0.0;
}
}
_ => (),
}
}
fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &(), _env: &Env) {}
fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &(), _data: &(), _env: &Env) {}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &(),
_env: &Env,
) -> Size {
bc.constrain((100.0, 100.0))
}
fn paint(&mut self, ctx: &mut PaintCtx, _data: &(), _env: &Env) {
let t = self.t;
let center = Point::new(50.0, 50.0);
ctx.paint_with_z_index(1, move |ctx| {
let ambit = center + 45.0 * Vec2::from_angle((0.75 + t) * 2.0 * PI);
ctx.stroke(Line::new(center, ambit), &Color::WHITE, 1.0);
});
ctx.fill(Circle::new(center, 50.0), &Color::BLACK);
}
}
pub fn main() {
let window = WindowDesc::new(AnimWidget { t: 0.0 }).title(
LocalizedString::new("anim-demo-window-title")
.with_placeholder("You spin me right round..."),
);
AppLauncher::with_window(window)
.log_to_console()
.launch(())
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/layout.rs | druid/examples/layout.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example shows how to construct a basic layout,
//! using columns, rows, and loops, for repeated Widgets.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::{AspectRatioBox, Button, Flex, Label, LineBreaking};
use druid::{AppLauncher, Color, Widget, WidgetExt, WindowDesc};
fn build_app() -> impl Widget<u32> {
// Usually we put all the widgets in one big tree using builder-style
// methods. Sometimes we split them up in declarations to increase
// readability. In this case we also have some recurring elements,
// we add those in a loop later on.
let mut col = Flex::column().with_child(
// The `Flex`'s first child is another Flex! In this case it is
// a row.
Flex::row()
// The row has its own children.
.with_child(
Label::new("One")
.fix_width(60.0)
.background(Color::rgb8(0x77, 0x77, 0))
.border(Color::WHITE, 3.0)
.center(),
)
// Spacing element that will fill all available space in
// between label and a button. Notice that weight is non-zero.
// We could have achieved a similar result with expanding the
// width and setting the main-axis-allignment to SpaceBetween.
.with_flex_spacer(1.0)
.with_child(Button::new("Two").padding(20.))
// After we added all the children, we can set some more
// values using builder-style methods. Since these methods
// dont return the original `Flex` but a SizedBox and Container
// respectively, we have to put these at the end.
.fix_height(100.0)
//turquoise
.background(Color::rgb8(0, 0x77, 0x88)),
);
for i in 0..5 {
// Give a larger weight to one of the buttons for it to
// occupy more space.
let weight = if i == 2 { 3.0 } else { 1.0 };
// call `expand_height` to force the buttons to use all their provided flex
col.add_flex_child(Button::new(format!("Button #{i}")).expand_height(), weight);
}
// aspect ratio box
let aspect_ratio_label = Label::new("This is an aspect-ratio box. Notice how the text will overflow if the box becomes too small.")
.with_text_color(Color::BLACK)
.with_line_break_mode(LineBreaking::WordWrap)
.center();
let aspect_ratio_box = AspectRatioBox::new(aspect_ratio_label, 4.0)
.border(Color::BLACK, 1.0)
.background(Color::WHITE);
col.add_flex_child(aspect_ratio_box.center(), 1.0);
// This method asks Druid to draw colored rectangles around our widgets,
// so we can visually inspect their layout rectangles.
col.debug_paint_layout()
}
pub fn main() {
let window = WindowDesc::new(build_app()).title("Very flexible");
AppLauncher::with_window(window)
.log_to_console()
.launch(0)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/scroll_colors.rs | druid/examples/scroll_colors.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example allows to play with scroll bars over different color tones.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::{Container, Flex, Scroll, SizedBox};
use druid::{AppLauncher, Color, LocalizedString, Widget, WindowDesc};
fn build_app() -> impl Widget<u32> {
let mut col = Flex::column();
let rows = 30;
let cols = 30;
for i in 0..cols {
let mut row = Flex::row();
let col_progress = i as f64 / cols as f64;
for j in 0..rows {
let row_progress = j as f64 / rows as f64;
row.add_child(
Container::new(SizedBox::empty().width(200.0).height(200.0))
.background(Color::rgb(1.0 * col_progress, 1.0 * row_progress, 1.0)),
);
}
col.add_child(row);
}
Scroll::new(col)
}
pub fn main() {
let main_window = WindowDesc::new(build_app()).title(
LocalizedString::new("scroll-colors-demo-window-title").with_placeholder("Rainbows!"),
);
let data = 0_u32;
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/view_switcher.rs | druid/examples/view_switcher.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example demonstrates the `ViewSwitcher` widget
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::{Button, Flex, Label, Split, TextBox, ViewSwitcher};
use druid::{AppLauncher, Data, Env, Lens, LocalizedString, Widget, WidgetExt, WindowDesc};
#[derive(Clone, Data, Lens)]
struct AppState {
current_view: u32,
current_text: String,
}
pub fn main() {
let main_window = WindowDesc::new(make_ui()).title(LocalizedString::new("View Switcher"));
let data = AppState {
current_view: 0,
current_text: "Edit me!".to_string(),
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn make_ui() -> impl Widget<AppState> {
let mut switcher_column = Flex::column();
switcher_column.add_child(
Label::new(|data: &u32, _env: &Env| format!("Current view: {data}"))
.lens(AppState::current_view),
);
for i in 0..6 {
switcher_column.add_spacer(80.);
switcher_column.add_child(
Button::new(format!("View {i}"))
.on_click(move |_event, data: &mut u32, _env| {
*data = i;
})
.lens(AppState::current_view),
);
}
let view_switcher = ViewSwitcher::new(
|data: &AppState, _env| data.current_view,
|selector, _data, _env| match selector {
0 => Box::new(Label::new("Simple Label").center()),
1 => Box::new(
Button::new("Simple Button").on_click(|_event, _data, _env| {
println!("Simple button clicked!");
}),
),
2 => Box::new(
Button::new("Another Simple Button").on_click(|_event, _data, _env| {
println!("Another simple button clicked!");
}),
),
3 => Box::new(
Flex::column()
.with_flex_child(Label::new("Here is a label").center(), 1.0)
.with_flex_child(
Button::new("Button").on_click(|_event, _data, _env| {
println!("Complex button clicked!");
}),
1.0,
)
.with_flex_child(TextBox::new().lens(AppState::current_text), 1.0)
.with_flex_child(
Label::new(|data: &String, _env: &Env| format!("Value entered: {data}"))
.lens(AppState::current_text),
1.0,
),
),
4 => Box::new(
Split::columns(
Label::new("Left split").center(),
Label::new("Right split").center(),
)
.draggable(true),
),
_ => Box::new(Label::new("Unknown").center()),
},
);
Flex::row()
.with_child(switcher_column)
.with_flex_child(view_switcher, 1.0)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/async_event.rs | druid/examples/async_event.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of sending commands from another thread.
//! This is useful when you want to have some kind of
//! generated content (like here), or some task that just
//! takes a long time but don't want to block the main thread
//! (waiting on an http request, some cpu intensive work etc.)
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use instant::Instant;
use std::thread;
use std::time::Duration;
use druid::widget::Painter;
use druid::{AppLauncher, Color, RenderContext, Widget, WidgetExt, WindowDesc};
pub fn main() {
let window = WindowDesc::new(make_ui()).title("External Event Demo");
let launcher = AppLauncher::with_window(window);
// If we want to create commands from another thread `launcher.get_external_handle()`
// should be used. For sending commands from within widgets you can always call
// `ctx.submit_command`
let event_sink = launcher.get_external_handle();
// We create a new thread and generate colours in it.
// This happens on a second thread so that we can run the UI in the
// main thread. Generating some colours nicely follows the pattern for what
// should be done like this: generating something over time
// (like this or reacting to external events), or something that takes a
// long time and shouldn't block main UI updates.
thread::spawn(move || generate_colors(event_sink));
launcher
.log_to_console()
.launch(Color::BLACK)
.expect("launch failed");
}
fn generate_colors(event_sink: druid::ExtEventSink) {
// This function is called in a separate thread, and runs until the program ends.
// We take an `ExtEventSink` as an argument, we can use this event sink to send
// commands to the main thread. Every time we generate a new colour we send it
// to the main thread.
let start_time = Instant::now();
let mut color = Color::WHITE;
loop {
let time_since_start = (Instant::now() - start_time).as_nanos();
let (r, g, b, _) = color.as_rgba8();
// there is no logic here; it's a very silly way of mutating the color.
color = match (time_since_start % 2, time_since_start % 3) {
(0, _) => Color::rgb8(r.wrapping_add(3), g, b),
(_, 0) => Color::rgb8(r, g.wrapping_add(3), b),
(_, _) => Color::rgb8(r, g, b.wrapping_add(3)),
};
// schedule idle callback to change the data
event_sink.add_idle_callback(move |data: &mut Color| {
*data = color;
});
thread::sleep(Duration::from_millis(20));
}
}
fn make_ui() -> impl Widget<Color> {
Painter::new(|ctx, data, _env| {
let rect = ctx.size().to_rounded_rect(5.0);
ctx.fill(rect, data);
})
.fix_width(300.0)
.fix_height(300.0)
.padding(10.0)
.center()
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/input_region.rs | druid/examples/input_region.rs | // Copyright 2023 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! A demo of a few window features, including input region, always on top,
//! and titlebar visibility.
//! The demo is setup so that there are parts of the window that you can click through.
//! There are also buttons for setting always on top and setting the visibility of the
//! titlebar.
//! The window's region is managed by the root custom widget.
use druid::widget::prelude::*;
use druid::widget::{Button, Container, Flex, Label, LineBreaking, Widget};
use druid::{AppLauncher, Color, Lens, Point, Rect, Region, WidgetExt, WidgetPod, WindowDesc};
const EXAMPLE_BORDER_SIZE: f64 = 3.0;
const INFO_TEXT: &str = "Only this text and the borders can be interacted with.
You can click through the other parts
This demo is useful for observing the limitations of each OS.
- Windows is well supported. Observation: When the titlebar is enabled and the input region is set, the border becomes invisible. Always on top is supported.
- macOS has good support, but doesn't allow toggling titlebar after the window is opened. Also, it just makes transparent regions transparent automatically when set to have no titlebar. Always on top is supported.
- Linux support varies by desktop environment and display server. Wayland is much more restrictive, with it not allowing things like setting position and always on top. Fortunately desktop environments often allow you to manually set window decoration and always on top on the Window itself. The offsets can differ between desktop environments, and sometimes you need to open the window with the titlebar, then turn it off, for it to work.";
#[derive(Clone, Data, Lens)]
struct AppState {
limit_input_region: bool,
show_titlebar: bool,
always_on_top: bool,
mouse_pass_through_while_not_in_focus: bool,
mouse_pass_through: bool,
}
struct InputRegionExampleWidget {
info_label: WidgetPod<AppState, Container<AppState>>,
controls: WidgetPod<AppState, Flex<AppState>>,
}
impl InputRegionExampleWidget {
pub fn new() -> Self {
let info_label = Label::new(INFO_TEXT)
.with_line_break_mode(LineBreaking::WordWrap)
.padding(20.0)
.background(Color::rgba(0.2, 0.2, 0.2, 0.5));
let toggle_input_region = Button::new("Toggle Input Region")
.on_click(|ctx, data: &mut bool, _: &Env| {
*data = !*data;
tracing::debug!("Setting input region toggle to: {}", *data);
ctx.request_layout();
})
.lens(AppState::limit_input_region);
let toggle_titlebar = Button::new("Toggle TitleBar")
.on_click(|ctx, data: &mut bool, _: &Env| {
*data = !*data;
tracing::debug!("Setting titlebar visibility to: {}", *data);
ctx.window().show_titlebar(*data);
ctx.request_layout();
})
.lens(AppState::show_titlebar);
let toggle_always_on_top = Button::new("Toggle Always On Top")
.on_click(|ctx, data: &mut bool, _: &Env| {
*data = !*data;
tracing::debug!("Setting always on top to: {}", *data);
ctx.window().set_always_on_top(*data);
})
.lens(AppState::always_on_top);
let toggle_mouse_pass_through_while_not_in_focus = Button::new("Toggle Mouse Pass Through")
.on_click(|_, data: &mut bool, _: &Env| {
*data = !*data;
tracing::debug!(
"Setting mouse pass through while not in focus to: {}",
*data
);
})
.lens(AppState::mouse_pass_through_while_not_in_focus);
let controls_flex = Flex::row()
.with_child(toggle_input_region)
.with_child(toggle_titlebar)
.with_child(toggle_always_on_top)
.with_child(toggle_mouse_pass_through_while_not_in_focus);
Self {
info_label: WidgetPod::new(info_label),
controls: WidgetPod::new(controls_flex),
}
}
}
impl Widget<AppState> for InputRegionExampleWidget {
fn event(
&mut self,
ctx: &mut druid::EventCtx,
event: &druid::Event,
data: &mut AppState,
env: &druid::Env,
) {
self.info_label.event(ctx, event, data, env);
self.controls.event(ctx, event, data, env);
let mouse_pass_through =
data.mouse_pass_through_while_not_in_focus && !ctx.window().is_foreground_window();
if mouse_pass_through != data.mouse_pass_through {
data.mouse_pass_through = mouse_pass_through;
tracing::debug!("Setting mouse pass through to: {}", mouse_pass_through);
ctx.window().set_mouse_pass_through(mouse_pass_through);
}
}
fn lifecycle(
&mut self,
ctx: &mut druid::LifeCycleCtx,
event: &druid::LifeCycle,
data: &AppState,
env: &druid::Env,
) {
self.info_label.lifecycle(ctx, event, data, env);
self.controls.lifecycle(ctx, event, data, env);
}
fn update(
&mut self,
ctx: &mut druid::UpdateCtx,
_old_data: &AppState,
data: &AppState,
env: &druid::Env,
) {
self.info_label.update(ctx, data, env);
self.controls.update(ctx, data, env);
}
fn layout(
&mut self,
ctx: &mut druid::LayoutCtx,
bc: &druid::BoxConstraints,
data: &AppState,
env: &druid::Env,
) -> druid::Size {
let mut interactable_area = Region::EMPTY;
let smaller_bc = BoxConstraints::new(
Size::new(0.0, 0.0),
Size::new(bc.max().width - 100.0, bc.max().height - 100.0),
);
let full_bc = BoxConstraints::new(Size::new(0.0, 0.0), bc.max());
let _label_size = self.info_label.layout(ctx, &smaller_bc, data, env);
let controls_size = self.controls.layout(ctx, &full_bc, data, env);
let text_origin_point = Point::new(50.0, 50.0 + controls_size.height);
self.info_label.set_origin(ctx, text_origin_point);
let controls_origin_point = Point::new(EXAMPLE_BORDER_SIZE, EXAMPLE_BORDER_SIZE);
self.controls.set_origin(ctx, controls_origin_point);
// Add side rects to clarify the dimensions of the window.
let left_rect = Rect::new(0.0, 0.0, EXAMPLE_BORDER_SIZE, bc.max().height);
let right_rect = Rect::new(
bc.max().width - EXAMPLE_BORDER_SIZE,
0.0,
bc.max().width,
bc.max().height,
);
let bottom_rect = Rect::new(
0.0,
bc.max().height - EXAMPLE_BORDER_SIZE,
bc.max().width,
bc.max().height,
);
interactable_area.add_rect(left_rect);
interactable_area.add_rect(right_rect);
interactable_area.add_rect(bottom_rect);
interactable_area.add_rect(self.info_label.layout_rect());
interactable_area.add_rect(self.controls.layout_rect());
if data.limit_input_region {
ctx.window().set_input_region(Some(interactable_area));
} else {
ctx.window().set_input_region(None);
}
bc.max()
}
fn paint(&mut self, ctx: &mut druid::PaintCtx, data: &AppState, env: &druid::Env) {
let window_area = ctx.size();
let left_rect = Rect::new(0.0, 0.0, EXAMPLE_BORDER_SIZE, window_area.height);
let right_rect = Rect::new(
window_area.width - EXAMPLE_BORDER_SIZE,
0.0,
window_area.width,
window_area.height,
);
let bottom_rect = Rect::new(
0.0,
window_area.height - EXAMPLE_BORDER_SIZE,
window_area.width,
window_area.height,
);
ctx.fill(left_rect, &Color::rgba(1.0, 0., 0., 0.7));
ctx.fill(right_rect, &Color::rgba(1.0, 0., 0., 0.7));
ctx.fill(bottom_rect, &Color::rgba(1.0, 0., 0., 0.7));
self.info_label.paint(ctx, data, env);
self.controls.paint(ctx, data, env);
}
}
fn main() {
let main_window = WindowDesc::new(InputRegionExampleWidget::new())
.title("Input Region Demo")
.window_size((750.0, 500.0))
.with_min_size((650.0, 450.0))
// Disable the titlebar since it breaks the desired effect on mac.
// It can be turned on with the button, but not on mac.
// A lot of apps that will use the interaction features will turn this off
// On Windows, if on, this will be invisible, but still there.
.show_titlebar(false)
.transparent(true);
let state = AppState {
limit_input_region: true,
always_on_top: false,
show_titlebar: false,
mouse_pass_through_while_not_in_focus: false,
mouse_pass_through: false,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(state)
.expect("Failed to launch application");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/multiwin.rs | druid/examples/multiwin.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Opening and closing windows and using window and context menus.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{
Align, BackgroundBrush, Button, Controller, ControllerHost, Flex, Label, Padding,
};
use druid::Target::Global;
use druid::{
commands as sys_cmds, AppDelegate, AppLauncher, Application, Color, Command, Data, DelegateCtx,
Handled, LocalizedString, Menu, MenuItem, Target, WindowDesc, WindowHandle, WindowId,
};
use tracing::info;
#[derive(Debug, Clone, Default, Data)]
struct State {
menu_count: usize,
selected: usize,
glow_hot: bool,
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder()).menu(make_menu).title(
LocalizedString::new("multiwin-demo-window-title").with_placeholder("Many windows!"),
);
AppLauncher::with_window(main_window)
.delegate(Delegate {
windows: Vec::new(),
})
.log_to_console()
.launch(State::default())
.expect("launch failed");
}
fn ui_builder() -> impl Widget<State> {
let text = LocalizedString::new("hello-counter")
.with_arg("count", |data: &State, _env| data.menu_count.into());
let label = Label::new(text);
let inc_button =
Button::<State>::new("Add menu item").on_click(|_ctx, data, _env| data.menu_count += 1);
let dec_button = Button::<State>::new("Remove menu item")
.on_click(|_ctx, data, _env| data.menu_count = data.menu_count.saturating_sub(1));
let new_button = Button::<State>::new("New window").on_click(|ctx, _data, _env| {
ctx.submit_command(sys_cmds::NEW_FILE.to(Global));
});
let quit_button = Button::<State>::new("Quit app").on_click(|_ctx, _data, _env| {
Application::global().quit();
});
let mut col = Flex::column();
col.add_flex_child(Align::centered(Padding::new(5.0, label)), 1.0);
let mut row = Flex::row();
row.add_child(Padding::new(5.0, inc_button));
row.add_child(Padding::new(5.0, dec_button));
col.add_flex_child(Align::centered(row), 1.0);
let mut row = Flex::row();
row.add_child(Padding::new(5.0, new_button));
row.add_child(Padding::new(5.0, quit_button));
col.add_flex_child(Align::centered(row), 1.0);
let content = ControllerHost::new(col, ContextMenuController);
Glow::new(content)
}
struct Glow<W> {
inner: W,
}
impl<W> Glow<W> {
pub fn new(inner: W) -> Glow<W> {
Glow { inner }
}
}
impl<W: Widget<State>> Widget<State> for Glow<W> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut State, env: &Env) {
self.inner.event(ctx, event, data, env);
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &State, env: &Env) {
if let LifeCycle::HotChanged(_) = event {
ctx.request_paint();
}
self.inner.lifecycle(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &State, data: &State, env: &Env) {
if old_data.glow_hot != data.glow_hot {
ctx.request_paint();
}
self.inner.update(ctx, old_data, data, env);
}
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &State,
env: &Env,
) -> Size {
self.inner.layout(ctx, bc, data, env)
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &State, env: &Env) {
if data.glow_hot && ctx.is_hot() {
BackgroundBrush::Color(Color::rgb8(200, 55, 55)).paint(ctx, data, env);
}
self.inner.paint(ctx, data, env);
}
}
struct ContextMenuController;
struct Delegate {
windows: Vec<WindowId>,
}
impl<W: Widget<State>> Controller<State, W> for ContextMenuController {
fn event(
&mut self,
child: &mut W,
ctx: &mut EventCtx,
event: &Event,
data: &mut State,
env: &Env,
) {
match event {
Event::MouseDown(ref mouse) if mouse.button.is_right() => {
ctx.show_context_menu(make_context_menu(), mouse.pos);
}
_ => child.event(ctx, event, data, env),
}
}
}
impl AppDelegate<State> for Delegate {
fn command(
&mut self,
ctx: &mut DelegateCtx,
_target: Target,
cmd: &Command,
data: &mut State,
_env: &Env,
) -> Handled {
if cmd.is(sys_cmds::NEW_FILE) {
let new_win = WindowDesc::new(ui_builder())
.menu(make_menu)
.window_size((data.selected as f64 * 100.0 + 300.0, 500.0));
ctx.new_window(new_win);
Handled::Yes
} else {
Handled::No
}
}
fn window_added(
&mut self,
id: WindowId,
_handle: WindowHandle,
_data: &mut State,
_env: &Env,
_ctx: &mut DelegateCtx,
) {
info!("Window added, id: {:?}", id);
self.windows.push(id);
}
fn window_removed(
&mut self,
id: WindowId,
_data: &mut State,
_env: &Env,
_ctx: &mut DelegateCtx,
) {
info!("Window removed, id: {:?}", id);
if let Some(pos) = self.windows.iter().position(|x| *x == id) {
self.windows.remove(pos);
}
}
}
#[allow(unused_assignments)]
fn make_menu(_: Option<WindowId>, state: &State, _: &Env) -> Menu<State> {
let mut base = Menu::empty();
#[cfg(target_os = "macos")]
{
base = druid::platform_menus::mac::menu_bar();
}
#[cfg(any(
target_os = "windows",
target_os = "freebsd",
target_os = "linux",
target_os = "openbsd"
))]
{
base = base.entry(druid::platform_menus::win::file::default());
}
if state.menu_count != 0 {
let mut custom = Menu::new(LocalizedString::new("Custom"));
for i in 1..=state.menu_count {
custom = custom.entry(
MenuItem::new(
LocalizedString::new("hello-counter")
.with_arg("count", move |_: &State, _| i.into()),
)
.on_activate(move |_ctx, data, _env| data.selected = i)
.enabled_if(move |_data, _env| i % 3 != 0)
.selected_if(move |data, _env| i == data.selected),
);
}
base = base.entry(custom);
}
base.rebuild_on(|old_data, data, _env| old_data.menu_count != data.menu_count)
}
fn make_context_menu() -> Menu<State> {
Menu::empty()
.entry(
MenuItem::new(LocalizedString::new("Increment"))
.on_activate(|_ctx, data: &mut State, _env| data.menu_count += 1),
)
.entry(
MenuItem::new(LocalizedString::new("Decrement")).on_activate(
|_ctx, data: &mut State, _env| data.menu_count = data.menu_count.saturating_sub(1),
),
)
.entry(
MenuItem::new(LocalizedString::new("Glow when hot"))
.on_activate(|_ctx, data: &mut State, _env| data.glow_hot = !data.glow_hot),
)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/widget_gallery.rs | druid/examples/widget_gallery.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example showcasing various widgets.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::{
im,
kurbo::{Affine, BezPath, Circle, Point},
piet::{FixedLinearGradient, GradientStop, InterpolationMode},
widget::{
prelude::*, Button, Checkbox, FillStrat, Flex, Image, Label, List, Painter, ProgressBar,
RadioGroup, Scroll, Slider, Spinner, Stepper, Switch, TextBox,
},
AppLauncher, Color, Data, ImageBuf, Lens, Widget, WidgetExt, WidgetPod, WindowDesc,
};
#[cfg(feature = "svg")]
use druid::widget::{Svg, SvgData};
const XI_IMAGE: &[u8] = include_bytes!("assets/xi.image");
#[derive(Clone, Data, Lens)]
struct AppData {
label_data: String,
checkbox_data: bool,
clicked_count: u64,
list_items: im::Vector<String>,
progressbar: f64,
radio: MyRadio,
stepper: f64,
editable_text: String,
}
#[derive(Clone, Data, PartialEq)]
enum MyRadio {
GaGa,
GuGu,
BaaBaa,
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder()).title("Widget Gallery");
// Set our initial data
let data = AppData {
label_data: "test".into(),
checkbox_data: false,
clicked_count: 0,
list_items: im::vector!["1".into(), "2".into(), "3".into()],
progressbar: 0.5,
radio: MyRadio::GaGa,
stepper: 0.0,
editable_text: "edit me!".into(),
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn ui_builder() -> impl Widget<AppData> {
#[cfg(feature = "svg")]
let svg_example = label_widget(
Svg::new(
include_str!("./assets/tiger.svg")
.parse::<SvgData>()
.unwrap(),
),
"Svg",
);
#[cfg(not(feature = "svg"))]
let svg_example = label_widget(Label::new("SVG not supported (yet)").center(), "Svg");
Scroll::new(
SquaresGrid::new()
.with_cell_size(Size::new(200.0, 240.0))
.with_spacing(20.0)
.with_child(label_widget(
Label::new(|data: &AppData, _: &_| data.label_data.clone()),
"Label",
))
.with_child(label_widget(
Flex::column()
.with_child(
Button::new("Click me!")
.on_click(|_, data: &mut AppData, _: &_| data.clicked_count += 1),
)
.with_spacer(4.0)
.with_child(Label::new(|data: &AppData, _: &_| {
format!("Clicked {} times!", data.clicked_count)
})),
"Button",
))
.with_child(label_widget(
Checkbox::new("Check me!").lens(AppData::checkbox_data),
"Checkbox",
))
.with_child(label_widget(
List::new(|| {
Label::new(|data: &String, _: &_| format!("List item: {}", data))
.center()
.background(Color::hlc(230.0, 50.0, 50.0))
.fix_height(40.0)
.expand_width()
})
.lens(AppData::list_items),
"List",
))
.with_child(label_widget(
Flex::column()
.with_child(ProgressBar::new().lens(AppData::progressbar))
.with_spacer(4.0)
.with_child(Label::new(|data: &AppData, _: &_| {
format!("{:.1}%", data.progressbar * 100.0)
}))
.with_spacer(4.0)
.with_child(
Flex::row()
.with_child(Button::new("<<").on_click(|_, data: &mut AppData, _| {
data.progressbar = (data.progressbar - 0.05).max(0.0);
}))
.with_spacer(4.0)
.with_child(Button::new(">>").on_click(|_, data: &mut AppData, _| {
data.progressbar = (data.progressbar + 0.05).min(1.0);
})),
),
"ProgressBar",
))
// The image example here uses hard-coded literal image data included in the binary.
// You may also want to load an image at runtime using a crate like `image`.
.with_child(label_widget(
Painter::new(paint_example).fix_size(32.0, 32.0),
"Painter",
))
.with_child(label_widget(
RadioGroup::column(vec![
("radio gaga", MyRadio::GaGa),
("radio gugu", MyRadio::GuGu),
("radio baabaa", MyRadio::BaaBaa),
])
.lens(AppData::radio),
"RadioGroup",
))
.with_child(label_widget(
Flex::column()
.with_child(
Slider::new()
.with_range(0.05, 0.95)
.with_step(0.10)
.lens(AppData::progressbar),
)
.with_spacer(4.0)
.with_child(Label::new(|data: &AppData, _: &_| {
format!("{:3.2}%", data.progressbar * 100.)
})),
"Slider",
))
.with_child(label_widget(
Flex::row()
.with_child(Stepper::new().lens(AppData::stepper))
.with_spacer(4.0)
.with_child(Label::new(|data: &AppData, _: &_| {
format!("{:.1}", data.stepper)
})),
"Stepper",
))
.with_child(label_widget(
TextBox::new().lens(AppData::editable_text),
"TextBox",
))
.with_child(label_widget(
Switch::new().lens(AppData::checkbox_data),
"Switch",
))
.with_child(label_widget(
Spinner::new().fix_height(40.0).center(),
"Spinner",
))
.with_child(label_widget(
Image::new(
ImageBuf::from_data(include_bytes!("./assets/PicWithAlpha.png")).unwrap(),
)
.fill_mode(FillStrat::Fill)
.interpolation_mode(InterpolationMode::Bilinear),
"Image",
))
.with_child(svg_example),
)
.vertical()
}
fn label_widget<T: Data>(widget: impl Widget<T> + 'static, label: &str) -> impl Widget<T> {
Flex::column()
.must_fill_main_axis(true)
.with_flex_child(widget.center(), 1.0)
.with_child(
Painter::new(|ctx, _: &_, _: &_| {
let size = ctx.size().to_rect();
ctx.fill(size, &Color::WHITE)
})
.fix_height(1.0),
)
.with_child(Label::new(label).center().fix_height(40.0))
.border(Color::WHITE, 1.0)
}
fn load_xi_image<Ctx: druid::RenderContext>(ctx: &mut Ctx) -> Ctx::Image {
ctx.make_image(32, 32, XI_IMAGE, druid::piet::ImageFormat::Rgb)
.unwrap()
}
fn paint_example<T>(ctx: &mut PaintCtx, _: &T, _env: &Env) {
let bounds = ctx.size().to_rect();
let img = load_xi_image(ctx.render_ctx);
ctx.draw_image(
&img,
bounds,
druid::piet::InterpolationMode::NearestNeighbor,
);
ctx.with_save(|ctx| {
ctx.transform(Affine::scale_non_uniform(bounds.width(), bounds.height()));
// Draw the dot of the `i` on top of the image data.
let i_dot = Circle::new((0.775, 0.18), 0.05);
let i_dot_brush = ctx.solid_brush(Color::WHITE);
ctx.fill(i_dot, &i_dot_brush);
// Cross out Xi because it's going dormant :'(
let mut spare = BezPath::new();
spare.move_to((0.1, 0.1));
spare.line_to((0.2, 0.1));
spare.line_to((0.9, 0.9));
spare.line_to((0.8, 0.9));
spare.close_path();
let spare_brush = ctx
.gradient(FixedLinearGradient {
start: (0.0, 0.0).into(),
end: (1.0, 1.0).into(),
stops: vec![
GradientStop {
pos: 0.0,
color: Color::rgb(1.0, 0.0, 0.0),
},
GradientStop {
pos: 1.0,
color: Color::rgb(0.4, 0.0, 0.0),
},
],
})
.unwrap();
ctx.fill(spare, &spare_brush);
});
}
// Grid widget
const DEFAULT_GRID_CELL_SIZE: Size = Size::new(100.0, 100.0);
const DEFAULT_GRID_SPACING: f64 = 10.0;
pub struct SquaresGrid<T> {
widgets: Vec<WidgetPod<T, Box<dyn Widget<T>>>>,
/// The number of widgets we can fit in the grid given the grid size.
drawable_widgets: usize,
cell_size: Size,
spacing: f64,
}
impl<T> SquaresGrid<T> {
pub fn new() -> Self {
SquaresGrid {
widgets: vec![],
drawable_widgets: 0,
cell_size: DEFAULT_GRID_CELL_SIZE,
spacing: DEFAULT_GRID_SPACING,
}
}
pub fn with_spacing(mut self, spacing: f64) -> Self {
self.spacing = spacing;
self
}
pub fn with_cell_size(mut self, cell_size: Size) -> Self {
self.cell_size = cell_size;
self
}
pub fn with_child(mut self, widget: impl Widget<T> + 'static) -> Self {
self.widgets.push(WidgetPod::new(Box::new(widget)));
self
}
}
impl<T> Default for SquaresGrid<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Data> Widget<T> for SquaresGrid<T> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) {
for widget in self.widgets.iter_mut() {
widget.event(ctx, event, data, env);
}
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
for widget in self.widgets.iter_mut() {
widget.lifecycle(ctx, event, data, env);
}
}
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) {
for widget in self.widgets.iter_mut() {
widget.update(ctx, data, env);
}
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
let count = self.widgets.len() as f64;
// The space needed to lay all elements out on a single line.
let ideal_width = (self.cell_size.width + self.spacing + 1.0) * count;
// Constrain the width.
let width = ideal_width.min(bc.max().width).max(bc.min().width);
// Given the width, the space needed to lay out all elements (as many as possible on each
// line).
let cells_in_row =
((width - self.spacing) / (self.cell_size.width + self.spacing)).floor() as usize;
let (height, rows) = if cells_in_row > 0 {
let mut rows = (count / cells_in_row as f64).ceil() as usize;
let height_from_rows =
|rows: usize| (rows as f64) * (self.cell_size.height + self.spacing) + self.spacing;
let ideal_height = height_from_rows(rows);
// Constrain the height
let height = ideal_height.max(bc.min().height).min(bc.max().height);
// Now calculate how many rows we can actually fit in
while height_from_rows(rows) > height && rows > 0 {
rows -= 1;
}
(height, rows)
} else {
(bc.min().height, 0)
};
// Constrain the number of drawn widgets by the number there is space to draw.
self.drawable_widgets = self.widgets.len().min(rows * cells_in_row);
// Now we have the width and height, we can lay out the children.
let mut x_position = self.spacing;
let mut y_position = self.spacing;
for (idx, widget) in self
.widgets
.iter_mut()
.take(self.drawable_widgets)
.enumerate()
{
widget.layout(
ctx,
&BoxConstraints::new(self.cell_size, self.cell_size),
data,
env,
);
widget.set_origin(ctx, Point::new(x_position, y_position));
// Increment position for the next cell
x_position += self.cell_size.width + self.spacing;
// If we can't fit in another cell in this row ...
if (idx + 1) % cells_in_row == 0 {
// ... then start a new row.
x_position = self.spacing;
y_position += self.cell_size.height + self.spacing;
}
}
Size { width, height }
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
for widget in self.widgets.iter_mut().take(self.drawable_widgets) {
widget.paint(ctx, data, env);
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/blocking_function.rs | druid/examples/blocking_function.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of a blocking function running in another thread. We give
//! the other thread some data and then we also pass some data back
//! to the main thread using commands.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use std::{thread, time};
use druid::widget::prelude::*;
use druid::widget::{Button, Either, Flex, Label, Spinner};
use druid::{
AppDelegate, AppLauncher, Command, Data, DelegateCtx, ExtEventSink, Handled, Lens,
LocalizedString, Selector, Target, WidgetExt, WindowDesc,
};
const FINISH_SLOW_FUNCTION: Selector<u32> = Selector::new("finish_slow_function");
#[derive(Clone, Default, Data, Lens)]
struct AppState {
processing: bool,
value: u32,
}
fn ui_builder() -> impl Widget<AppState> {
let button = Button::new("Start slow increment")
.on_click(|ctx, data: &mut AppState, _env| {
data.processing = true;
// In order to make sure that the other thread can communicate with the main thread we
// have to pass an external handle to the second thread.
// Using this handle we can send commands back to the main thread.
wrapped_slow_function(ctx.get_external_handle(), data.value);
})
.padding(5.0);
let button_placeholder = Flex::column()
.with_child(Label::new(LocalizedString::new("Processing...")).padding(5.0))
.with_child(Spinner::new());
// Hello-counter is defined in the built-in localisation file. This maps to "Current value is {count}"
// localised in english, french, or german. Every time the value is updated it shows the new value.
let text = LocalizedString::new("hello-counter")
.with_arg("count", |data: &AppState, _env| (data.value).into());
let label = Label::new(text).padding(5.0).center();
let either = Either::new(|data, _env| data.processing, button_placeholder, button);
Flex::column().with_child(label).with_child(either)
}
fn wrapped_slow_function(sink: ExtEventSink, number: u32) {
thread::spawn(move || {
let number = slow_function(number);
// Once the slow function is done we can use the event sink (the external handle).
// This sends the `FINISH_SLOW_FUNCTION` command to the main thread and attach
// the number as payload.
sink.submit_command(FINISH_SLOW_FUNCTION, number, Target::Auto)
.expect("command failed to submit");
});
}
// Pretend this is downloading a file, or doing heavy calculations...
fn slow_function(number: u32) -> u32 {
let a_while = time::Duration::from_millis(2000);
thread::sleep(a_while);
number + 1
}
struct Delegate;
impl AppDelegate<AppState> for Delegate {
fn command(
&mut self,
_ctx: &mut DelegateCtx,
_target: Target,
cmd: &Command,
data: &mut AppState,
_env: &Env,
) -> Handled {
if let Some(number) = cmd.get(FINISH_SLOW_FUNCTION) {
// If the command we received is `FINISH_SLOW_FUNCTION` handle the payload.
data.processing = false;
data.value = *number;
Handled::Yes
} else {
Handled::No
}
}
}
fn main() {
let main_window =
WindowDesc::new(ui_builder()).title(LocalizedString::new("Blocking functions"));
AppLauncher::with_window(main_window)
.delegate(Delegate {})
.log_to_console()
.launch(AppState::default())
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/identity.rs | druid/examples/identity.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An example of sending commands to specific widgets.
//!
//! This example is fairly contrived; the basic idea is that there are two counters,
//! and two buttons. If you press button one, counter one goes up. If you press button
//! two counter two goes up.
//!
//! The key insight is that the data is not mutated by the button directly;
//! instead the button sends a command to a separate controller widget
//! that performs the actual mutation.
//!
//! If you were designing a real app you might choose a different mechanism
//! (such as just just changing the `Data` in the on_click); however there are
//! other circumstances where widgets may need to communicate with specific
//! other widgets, and identity is a useful mechanism in those cases.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Button, Controller, Flex, Label, WidgetId};
use druid::{AppLauncher, Data, Lens, Selector, WidgetExt, WindowDesc};
const INCREMENT: Selector = Selector::new("identity-example.increment");
#[derive(Clone, Data, Lens)]
struct OurData {
counter_one: u64,
counter_two: u64,
}
pub fn main() {
let window = WindowDesc::new(make_ui()).title("identity example");
let data = OurData {
counter_one: 0,
counter_two: 0,
};
AppLauncher::with_window(window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
/// A constant `WidgetId`. This may be passed around and can be reused when
/// rebuilding a widget graph; however it should only ever be associated with
/// a single widget at a time.
const ID_ONE: WidgetId = WidgetId::reserved(1);
fn make_ui() -> impl Widget<OurData> {
// We can also generate these dynamically whenever we need it.
let id_two = WidgetId::next();
// We have a column with 2 labels and 2 buttons.
// Each of the 2 labels only has access to its own counter and is given a `WidgetId`.
// Both labels have a controller, this handles commands send to children.
// The 2 buttons send a command when clicked. Both send the exact same command.
// The key diference is that they both give a different `WidgetId` as target.
// This means that only the corresponding controller gets the command, and increments their counter.
Flex::column()
.with_child(
Label::dynamic(|data, _| format!("One: {data}"))
.controller(LabelControler)
.with_id(ID_ONE)
.lens(OurData::counter_one)
.padding(2.0),
)
.with_child(
Label::dynamic(|data, _| format!("Two: {data}"))
.controller(LabelControler)
.with_id(id_two)
.lens(OurData::counter_two)
.padding(2.0),
)
.with_child(
Button::<OurData>::new("Increment one")
.on_click(|ctx, _data, _env| ctx.submit_command(INCREMENT.to(ID_ONE)))
.padding(2.0),
)
.with_child(
Button::<OurData>::new("Increment two")
.on_click(move |ctx, _data, _env| ctx.submit_command(INCREMENT.to(id_two)))
.padding(2.0),
)
.padding(10.0)
}
struct LabelControler;
impl Controller<u64, Label<u64>> for LabelControler {
fn event(
&mut self,
child: &mut Label<u64>,
ctx: &mut EventCtx,
event: &Event,
data: &mut u64,
env: &Env,
) {
match event {
Event::Command(cmd) if cmd.is(INCREMENT) => *data += 1,
_ => child.event(ctx, event, data, env),
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/event_viewer.rs | druid/examples/event_viewer.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! An application that accepts keyboard and mouse input, and displays
//! information about received events.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::prelude::*;
use druid::widget::{Controller, CrossAxisAlignment, Flex, Label, List, Scroll, SizedBox, TextBox};
use druid::{
theme, AppLauncher, Color, Data, FontDescriptor, KeyEvent, Lens, Location, Modifiers,
MouseButton, MouseEvent, WidgetExt, WindowDesc,
};
use std::sync::Arc;
const CURSOR_BACKGROUND_COLOR: Color = Color::grey8(0x55);
const HEADER_BACKGROUND: Color = Color::grey8(0xCC);
const INTERACTIVE_AREA_DIM: f64 = 160.0;
const INTERACTIVE_AREA_BORDER: Color = Color::grey8(0xCC);
const TEXT_COLOR: Color = Color::grey8(0x11);
const PROPERTIES: &[(&str, f64)] = &[
("#", 40.0),
("Event", 80.0),
("Point", 90.0),
("Wheel", 80.0),
("Button", 60.0),
("Count", 50.0),
("Repeat", 50.0),
("Key", 60.0),
("Code", 60.0),
("Modifiers", 80.0),
("Location", 60.0),
];
#[allow(clippy::rc_buffer)]
#[derive(Clone, Data, Lens)]
struct AppState {
/// The text in the text field
text_input: String,
events: Arc<Vec<LoggedEvent>>,
}
struct EventLogger<F: Fn(&Event) -> bool> {
filter: F,
}
impl<W: Widget<AppState>, F: Fn(&Event) -> bool> Controller<AppState, W> for EventLogger<F> {
fn event(
&mut self,
child: &mut W,
ctx: &mut EventCtx,
event: &Event,
data: &mut AppState,
env: &Env,
) {
// Every time this controller receives an event we check `f()`.
// If `f()` returns true it means that we can add it to the log,
// if not then we can skip it.
if (self.filter)(event) {
if let Some(to_log) = LoggedEvent::try_from_event(event, data.events.len()) {
Arc::make_mut(&mut data.events).push(to_log);
}
}
// Always pass on the event!
child.event(ctx, event, data, env)
}
}
/// The types of events we display
#[derive(Clone, Copy, Data, PartialEq)]
enum EventType {
KeyDown,
KeyUp,
MouseDown,
MouseUp,
Wheel,
}
/// A type that represents any logged event shown in the list
#[derive(Clone, Data)]
struct LoggedEvent {
typ: EventType,
number: usize,
// To see what #[data(ignore)] does look at the docs.rs page on `Data`:
// https://docs.rs/druid/latest/druid/trait.Data.html
#[data(ignore)]
mouse: Option<MouseEvent>,
#[data(ignore)]
key: Option<KeyEvent>,
}
/// Here we implement all the display elements of the log entry.
/// We have one method for every attribute we want to show.
/// This is not very interesting it is mostly just getting the data
/// from the events and handling `None` values.
impl LoggedEvent {
fn try_from_event(event: &Event, number: usize) -> Option<Self> {
let to_log = match event {
Event::MouseUp(mouse) => Some((EventType::MouseUp, Some(mouse.clone()), None)),
Event::MouseDown(mouse) => Some((EventType::MouseDown, Some(mouse.clone()), None)),
Event::Wheel(mouse) => Some((EventType::Wheel, Some(mouse.clone()), None)),
Event::KeyUp(key) => Some((EventType::KeyUp, None, Some(key.clone()))),
Event::KeyDown(key) => Some((EventType::KeyDown, None, Some(key.clone()))),
_ => None,
};
to_log.map(|(typ, mouse, key)| LoggedEvent {
typ,
number,
mouse,
key,
})
}
fn number(&self) -> String {
self.number.to_string()
}
fn name(&self) -> String {
match self.typ {
EventType::KeyDown => "KeyDown",
EventType::KeyUp => "KeyUp",
EventType::MouseDown => "MouseDown",
EventType::MouseUp => "MouseUp",
EventType::Wheel => "Wheel",
}
.into()
}
fn mouse_pos(&self) -> String {
self.mouse
.as_ref()
.map(|m| format!("{:.2}", m.pos))
.unwrap_or_default()
}
fn wheel_delta(&self) -> String {
self.mouse
.as_ref()
.filter(|_| self.typ == EventType::Wheel)
.map(|m| format!("({:.1}, {:.1})", m.wheel_delta.x, m.wheel_delta.y))
.unwrap_or_default()
}
fn mouse_button(&self) -> String {
self.mouse
.as_ref()
.map(|m| {
match m.button {
MouseButton::Left => "Left",
MouseButton::Right => "Right",
MouseButton::X1 => "X1",
MouseButton::X2 => "X2",
MouseButton::None => "",
MouseButton::Middle => "Middle",
}
.into()
})
.unwrap_or_default()
}
fn click_count(&self) -> String {
self.mouse
.as_ref()
.map(|m| m.count.to_string())
.unwrap_or_default()
}
fn key(&self) -> String {
self.key
.as_ref()
.map(|k| k.key.to_string())
.unwrap_or_default()
}
fn code(&self) -> String {
self.key
.as_ref()
.map(|k| k.code.to_string())
.unwrap_or_default()
}
fn modifiers(&self) -> String {
self.key
.as_ref()
.map(|k| modifiers_string(k.mods))
.or_else(|| self.mouse.as_ref().map(|m| modifiers_string(m.mods)))
.unwrap_or_default()
}
fn location(&self) -> String {
match self.key.as_ref().map(|k| k.location) {
None => "",
Some(Location::Standard) => "Standard",
Some(Location::Left) => "Left",
Some(Location::Right) => "Right",
Some(Location::Numpad) => "Numpad",
}
.into()
}
fn is_repeat(&self) -> String {
if self.key.as_ref().map(|k| k.repeat).unwrap_or(false) {
"True".to_string()
} else {
"False".to_string()
}
}
}
fn build_root_widget() -> impl Widget<AppState> {
Flex::column()
.with_child(interactive_area())
.with_flex_child(event_list(), 1.0)
}
/// The top part of the application, that accepts keyboard and mouse input.
fn interactive_area() -> impl Widget<AppState> {
let text_box = TextBox::multiline()
.with_text_color(Color::rgb8(0xf0, 0xf0, 0xea))
.fix_size(INTERACTIVE_AREA_DIM, INTERACTIVE_AREA_DIM)
.lens(AppState::text_input)
.controller(EventLogger {
filter: |event| matches!(event, Event::KeyDown(_) | Event::KeyUp(_)),
});
let mouse_box = SizedBox::empty()
.fix_size(INTERACTIVE_AREA_DIM, INTERACTIVE_AREA_DIM)
.background(CURSOR_BACKGROUND_COLOR)
.rounded(5.0)
.border(INTERACTIVE_AREA_BORDER, 1.0)
.controller(EventLogger {
filter: |event| {
matches!(
event,
Event::MouseDown(_) | Event::MouseUp(_) | Event::Wheel(_)
)
},
});
Flex::row()
.with_flex_spacer(1.0)
.with_child(text_box)
.with_flex_spacer(1.0)
.with_child(mouse_box)
.with_flex_spacer(1.0)
.padding(10.0)
}
/// The bottom part of the application, a list of received events.
fn event_list() -> impl Widget<AppState> {
// Because this would be a HUGE block of repeated code with constants
// we just use a loop to generate the header.
let mut header = Flex::row().with_child(
Label::new(PROPERTIES[0].0)
.fix_width(PROPERTIES[0].1)
.background(HEADER_BACKGROUND),
);
for (name, size) in PROPERTIES.iter().skip(1) {
// Keep in mind that later on, in the main function,
// we set the default spacer values. Without explicitly
// setting them the default spacer is bigger, and is
// probably not desirable for your purposes.
header.add_default_spacer();
header.add_child(
Label::new(*name)
.fix_width(*size)
.background(HEADER_BACKGROUND),
);
}
Scroll::new(
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(header)
.with_default_spacer()
.with_flex_child(
// `List::new` generates a list entry for every element in the `Vec`.
// In this case it shows a log entry for every element in `AppState::events`.
// `make_list_item` generates this new log entry.
Scroll::new(List::new(make_list_item).lens(AppState::events)).vertical(),
1.0,
)
.background(Color::WHITE),
)
.horizontal()
.padding(10.0)
}
/// A single event row.
fn make_list_item() -> impl Widget<LoggedEvent> {
Flex::row()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.number()).fix_width(PROPERTIES[0].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.name()).fix_width(PROPERTIES[1].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.mouse_pos()).fix_width(PROPERTIES[2].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.wheel_delta()).fix_width(PROPERTIES[3].1))
.with_default_spacer()
.with_child(
Label::dynamic(|d: &LoggedEvent, _| d.mouse_button()).fix_width(PROPERTIES[4].1),
)
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.click_count()).fix_width(PROPERTIES[5].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.is_repeat()).fix_width(PROPERTIES[6].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.key()).fix_width(PROPERTIES[7].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.code()).fix_width(PROPERTIES[8].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.modifiers()).fix_width(PROPERTIES[9].1))
.with_default_spacer()
.with_child(Label::dynamic(|d: &LoggedEvent, _| d.location()).fix_width(PROPERTIES[10].1))
}
pub fn main() {
//describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("Event Viewer")
.window_size((760.0, 680.0));
//start the application
AppLauncher::with_window(main_window)
.log_to_console()
.configure_env(|env, _| {
env.set(theme::UI_FONT, FontDescriptor::default().with_size(12.0));
env.set(theme::TEXT_COLOR, TEXT_COLOR);
env.set(theme::WIDGET_PADDING_HORIZONTAL, 2.0);
env.set(theme::WIDGET_PADDING_VERTICAL, 2.0);
})
.launch(AppState {
text_input: String::new(),
events: Arc::new(Vec::new()),
})
.expect("Failed to launch application");
}
fn modifiers_string(mods: Modifiers) -> String {
let mut result = String::new();
if mods.shift() {
result.push_str("Shift ");
}
if mods.ctrl() {
result.push_str("Ctrl ");
}
if mods.alt() {
result.push_str("Alt ");
}
if mods.meta() {
result.push_str("Meta ");
}
if result.is_empty() {
result.push_str("None");
}
result
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/lens.rs | druid/examples/lens.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! This example shows basic usage of Lens
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::Slider;
use druid::widget::{CrossAxisAlignment, Flex, Label, TextBox};
use druid::{AppLauncher, Data, Env, Lens, LocalizedString, Widget, WidgetExt, WindowDesc};
pub fn main() {
let main_window = WindowDesc::new(ui_builder())
.title(LocalizedString::new("lens-demo-window-title").with_placeholder("Lens Demo"));
let data = MyComplexState {
term: "hello".into(),
scale: 0.0,
};
AppLauncher::with_window(main_window)
.launch(data)
.expect("launch failed");
}
#[derive(Clone, Debug, Data, Lens)]
struct MyComplexState {
#[lens(name = "term_lens")]
term: String,
scale: f64,
}
fn ui_builder() -> impl Widget<MyComplexState> {
// `TextBox` is of type `Widget<String>`
// via `.lens` we get it to be of type `Widget<MyComplexState>`
let searchbar = TextBox::new().lens(MyComplexState::term_lens);
// `Slider` is of type `Widget<f64>`
// via `.lens` we get it to be of type `Widget<MyComplexState>`
let slider = Slider::new().lens(MyComplexState::scale);
let label = Label::new(|d: &MyComplexState, _: &Env| format!("{}: {:.2}", d.term, d.scale));
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_child(label)
.with_default_spacer()
.with_child(
Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_child(searchbar)
.with_default_spacer()
.with_child(slider),
)
.center()
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/open_save.rs | druid/examples/open_save.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Usage of file open and saving.
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
use druid::widget::{Align, Button, Flex, TextBox};
use druid::{
commands, AppDelegate, AppLauncher, Command, DelegateCtx, Env, FileDialogOptions, FileSpec,
Handled, LocalizedString, Target, Widget, WindowDesc,
};
struct Delegate;
pub fn main() {
let main_window = WindowDesc::new(ui_builder())
.title(LocalizedString::new("open-save-demo").with_placeholder("Opening/Saving Demo"));
let data = "Type here.".to_owned();
AppLauncher::with_window(main_window)
.delegate(Delegate)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn ui_builder() -> impl Widget<String> {
let rs = FileSpec::new("Rust source", &["rs"]);
let txt = FileSpec::new("Text file", &["txt"]);
let other = FileSpec::new("Bogus file", &["foo", "bar", "baz"]);
// The options can also be generated at runtime,
// so to show that off we create a String for the default save name.
let default_save_name = String::from("MyFile.txt");
let save_dialog_options = FileDialogOptions::new()
.allowed_types(vec![rs, txt, other])
.default_type(txt)
.default_name(default_save_name)
.name_label("Target")
.title("Choose a target for this lovely file")
.button_text("Export");
let open_dialog_options = save_dialog_options
.clone()
.default_name("MySavedFile.txt")
.name_label("Source")
.title("Where did you put that file?")
.button_text("Import");
let input = TextBox::new();
let save = Button::new("Save").on_click(move |ctx, _, _| {
ctx.submit_command(druid::commands::SHOW_SAVE_PANEL.with(save_dialog_options.clone()))
});
let open = Button::new("Open").on_click(move |ctx, _, _| {
ctx.submit_command(druid::commands::SHOW_OPEN_PANEL.with(open_dialog_options.clone()))
});
let mut col = Flex::column();
col.add_child(input);
col.add_spacer(8.0);
col.add_child(save);
col.add_child(open);
Align::centered(col)
}
impl AppDelegate<String> for Delegate {
fn command(
&mut self,
_ctx: &mut DelegateCtx,
_target: Target,
cmd: &Command,
data: &mut String,
_env: &Env,
) -> Handled {
if let Some(file_info) = cmd.get(commands::SAVE_FILE_AS) {
if let Err(e) = std::fs::write(file_info.path(), &data[..]) {
println!("Error writing file: {e}");
}
return Handled::Yes;
}
if let Some(file_info) = cmd.get(commands::OPEN_FILE) {
match std::fs::read_to_string(file_info.path()) {
Ok(s) => {
let first_line = s.lines().next().unwrap_or("");
*data = first_line.to_owned();
}
Err(e) => {
println!("Error opening file: {e}");
}
}
return Handled::Yes;
}
Handled::No
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/switches.rs | druid/examples/switches.rs | // Copyright 2019 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Example of switches
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
#[allow(deprecated)]
use druid::widget::Parse;
use druid::widget::{
Checkbox, Flex, Label, LensWrap, MainAxisAlignment, Padding, Stepper, Switch, TextBox,
WidgetExt,
};
use druid::{AppLauncher, Data, Lens, LensExt, LocalizedString, Widget, WindowDesc};
#[derive(Clone, Data, Lens)]
struct DemoState {
value: bool,
stepper_value: f64,
}
fn build_widget() -> impl Widget<DemoState> {
let mut col = Flex::column();
let mut row = Flex::row();
let switch = LensWrap::new(Switch::new(), DemoState::value);
let check_box = LensWrap::new(Checkbox::new(""), DemoState::value);
let switch_label = Label::new("Setting label");
row.add_child(Padding::new(5.0, switch_label));
row.add_child(Padding::new(5.0, switch));
row.add_child(Padding::new(5.0, check_box));
let stepper = LensWrap::new(
Stepper::new()
.with_range(0.0, 10.0)
.with_step(0.5)
.with_wraparound(false),
DemoState::stepper_value,
);
let mut textbox_row = Flex::row();
// TODO: Replace Parse usage with TextBox::with_formatter
#[allow(deprecated)]
let textbox = LensWrap::new(
Parse::new(TextBox::new()),
DemoState::stepper_value.map(|x| Some(*x), |x, y| *x = y.unwrap_or(0.0)),
);
textbox_row.add_child(Padding::new(5.0, textbox));
textbox_row.add_child(Padding::new(5.0, stepper.center()));
let mut label_row = Flex::row();
let label = Label::new(|data: &DemoState, _env: &_| {
format!("Stepper value: {0:.2}", data.stepper_value)
});
label_row.add_child(Padding::new(5.0, label));
col.set_main_axis_alignment(MainAxisAlignment::Center);
col.add_child(Padding::new(5.0, row));
col.add_child(Padding::new(5.0, textbox_row));
col.add_child(Padding::new(5.0, label_row));
col.center()
}
pub fn main() {
let window = WindowDesc::new(build_widget())
.title(LocalizedString::new("switch-demo-window-title").with_placeholder("Switch Demo"));
AppLauncher::with_window(window)
.log_to_console()
.launch(DemoState {
value: true,
stepper_value: 1.0,
})
.expect("launch failed");
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/value_formatting/src/formatters.rs | druid/examples/value_formatting/src/formatters.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Implementations of the [`druid::text::Formatter`] trait.
use druid::text::{Formatter, Selection, Validation, ValidationError};
use druid::Data;
/// A formatter that can display currency values.
pub struct NaiveCurrencyFormatter {
currency_symbol: char,
thousands_separator: char,
decimal_separator: char,
}
/// Errors returned by [`NaiveCurrencyFormatter`].
#[derive(Debug, Clone)]
pub enum CurrencyValidationError {
Parse(std::num::ParseFloatError),
InvalidChar(char),
TooManyCharsAfterDecimal,
}
/// A `Formatter` for postal codes, which are the format A0A 0A0 where 'A' is
/// any uppercase ascii character, and '0' is any numeral.
///
/// This formatter will accept lowercase characters as input, but will replace
/// them with uppercase characters.
pub struct CanadianPostalCodeFormatter;
/// A Canadian postal code, in the format 'A0A0A0'.
#[derive(Debug, Clone, Copy, Data)]
pub struct PostalCode {
chars: [u8; 6],
}
/// Error returned by [`CanadianPostalCodeFormatter`].
#[derive(Debug, Clone)]
pub enum PostalCodeValidationError {
WrongNumberOfCharacters,
IncorrectFormat,
}
/// A formatter that sets the selection to the first occurrence of the word 'cat'
/// in an input string, if it is found.
pub struct CatSelectingFormatter;
impl NaiveCurrencyFormatter {
/// A formatter for USD.
pub const DOLLARS: NaiveCurrencyFormatter = NaiveCurrencyFormatter {
currency_symbol: '$',
thousands_separator: ',',
decimal_separator: '.',
};
/// A formatter for euros.
pub const EUROS: NaiveCurrencyFormatter = NaiveCurrencyFormatter {
currency_symbol: '€',
thousands_separator: '.',
decimal_separator: ',',
};
/// A formatter for british pounds.
pub const GBP: NaiveCurrencyFormatter = NaiveCurrencyFormatter {
currency_symbol: '£',
thousands_separator: '.',
decimal_separator: ',',
};
}
impl Formatter<f64> for NaiveCurrencyFormatter {
fn format(&self, value: &f64) -> String {
if !value.is_normal() {
return format!("{}0{}00", self.currency_symbol, self.decimal_separator);
}
let mut components = Vec::new();
let mut major_part = value.abs().trunc() as usize;
let minor_part = (value.abs().fract() * 100.0).round() as usize;
let bonus_rounding_dollar = minor_part / 100;
components.push(format!("{}{:02}", self.decimal_separator, minor_part % 100));
if major_part == 0 {
components.push('0'.to_string());
}
while major_part > 0 {
let remain = major_part % 1000;
major_part /= 1000;
if major_part > 0 {
components.push(format!("{}{:03}", self.thousands_separator, remain));
} else {
components.push((remain + bonus_rounding_dollar).to_string());
}
}
if value.is_sign_negative() {
components.push(format!("-{}", self.currency_symbol));
} else {
components.push(self.currency_symbol.to_string());
}
components.iter().rev().flat_map(|s| s.chars()).collect()
}
fn format_for_editing(&self, value: &f64) -> String {
self.format(value)
.chars()
.filter(|c| *c != self.currency_symbol)
.collect()
}
fn value(&self, input: &str) -> Result<f64, ValidationError> {
// we need to convert from our naive localized representation back into
// rust's float representation
let decimal_pos = input
.bytes()
.rposition(|b| b as char == self.decimal_separator);
let (major, minor) = input.split_at(decimal_pos.unwrap_or(input.len()));
let canonical: String = major
.chars()
.filter(|c| *c != self.thousands_separator)
.chain(Some('.'))
.chain(minor.chars().skip(1))
.collect();
canonical
.parse()
.map_err(|err| ValidationError::new(CurrencyValidationError::Parse(err)))
}
fn validate_partial_input(&self, input: &str, _sel: &Selection) -> Validation {
if input.is_empty() {
return Validation::success();
}
let mut char_iter = input.chars();
if let Some(c) = char_iter.next() {
if !(c.is_ascii_digit() || c == '-') {
return Validation::failure(CurrencyValidationError::InvalidChar(c));
}
}
let mut char_iter =
char_iter.skip_while(|c| c.is_ascii_digit() || *c == self.thousands_separator);
match char_iter.next() {
None => return Validation::success(),
Some(c) if c == self.decimal_separator => (),
Some(c) => return Validation::failure(CurrencyValidationError::InvalidChar(c)),
};
// we're after the decimal, allow up to 2 digits
let (d1, d2, d3) = (char_iter.next(), char_iter.next(), char_iter.next());
match (d1, d2, d3) {
(_, _, Some(_)) => {
Validation::failure(CurrencyValidationError::TooManyCharsAfterDecimal)
}
(Some(c), None, _) if c.is_ascii_digit() => Validation::success(),
(Some(c), None, _) => Validation::failure(CurrencyValidationError::InvalidChar(c)),
(None, None, _) => Validation::success(),
(Some(c1), Some(c2), _) if c1.is_ascii_digit() && c2.is_ascii_digit() => {
Validation::success()
}
(Some(c1), Some(other), _) => {
let bad_char = if c1.is_ascii_digit() { other } else { c1 };
Validation::failure(CurrencyValidationError::InvalidChar(bad_char))
}
other => panic!("unexpected: {:?}", other),
}
}
}
//TODO: never write parsing code like this again
impl Formatter<PostalCode> for CanadianPostalCodeFormatter {
fn format(&self, value: &PostalCode) -> String {
value.to_string()
}
fn validate_partial_input(&self, input: &str, sel: &Selection) -> Validation {
let mut chars = input.chars();
let mut valid = true;
let mut has_space = false;
if matches!(chars.next(), Some(c) if !c.is_ascii_alphabetic()) {
valid = false;
}
if matches!(chars.next(), Some(c) if !c.is_ascii_digit()) {
valid = false;
}
if matches!(chars.next(), Some(c) if !c.is_ascii_alphabetic()) {
valid = false;
}
match chars.next() {
Some(' ') => {
has_space = true;
if matches!(chars.next(), Some(c) if !c.is_ascii_digit()) {
valid = false;
}
}
Some(other) if !other.is_ascii_digit() => valid = false,
_ => (),
}
if matches!(chars.next(), Some(c) if !c.is_ascii_alphabetic()) {
valid = false;
}
if matches!(chars.next(), Some(c) if !c.is_ascii_digit()) {
valid = false;
}
if chars.next().is_some() {
valid = false;
}
if valid {
// if valid we convert to canonical format; h1h2h2 becomes H!H 2H2
let (replacement_text, sel) = if input.len() < 4 || has_space {
(input.to_uppercase(), None)
} else {
//let split_at = 3.min(input.len().saturating_sub(1));
let (first, second) = input.split_at(3);
let insert_space = if second.bytes().next() == Some(b' ') {
None
} else {
Some(' ')
};
let sel = if insert_space.is_some() && sel.is_caret() {
Some(Selection::caret(sel.min() + 1))
} else {
None
};
(
first
.chars()
.map(|c| c.to_ascii_uppercase())
.chain(insert_space)
.chain(second.chars().map(|c| c.to_ascii_uppercase()))
.collect(),
sel,
)
};
if let Some(replacement_sel) = sel {
Validation::success()
.change_text(replacement_text)
.change_selection(replacement_sel)
} else {
Validation::success().change_text(replacement_text)
}
} else {
Validation::failure(ValidationError::new(
PostalCodeValidationError::IncorrectFormat,
))
}
}
#[allow(clippy::many_single_char_names, clippy::match_ref_pats)]
fn value(&self, input: &str) -> Result<PostalCode, ValidationError> {
match input.as_bytes() {
&[a, b, c, d, e, f] => PostalCode::from_bytes([a, b, c, d, e, f]),
&[a, b, c, b' ', d, e, f] => PostalCode::from_bytes([a, b, c, d, e, f]),
_ => Err(PostalCodeValidationError::WrongNumberOfCharacters),
}
.map_err(ValidationError::new)
}
}
impl PostalCode {
pub fn new(s: &str) -> Result<Self, PostalCodeValidationError> {
if s.as_bytes().len() != 6 {
Err(PostalCodeValidationError::WrongNumberOfCharacters)
} else {
let b = s.as_bytes();
Self::from_bytes([b[0], b[1], b[2], b[3], b[4], b[5]])
}
}
fn from_bytes(bytes: [u8; 6]) -> Result<Self, PostalCodeValidationError> {
if [bytes[0], bytes[2], bytes[4]]
.iter()
.all(|b| (*b as char).is_ascii_uppercase())
&& [bytes[1], bytes[3], bytes[5]]
.iter()
.all(|b| (*b as char).is_ascii_digit())
{
Ok(PostalCode { chars: bytes })
} else {
Err(PostalCodeValidationError::IncorrectFormat)
}
}
}
#[allow(clippy::many_single_char_names)]
impl std::fmt::Display for PostalCode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let [a, b, c, d, e, g] = self.chars;
write!(
f,
"{}{}{} {}{}{}",
a as char, b as char, c as char, d as char, e as char, g as char
)
}
}
impl Formatter<String> for CatSelectingFormatter {
fn format(&self, value: &String) -> String {
value.to_owned()
}
fn value(&self, input: &str) -> Result<String, ValidationError> {
Ok(input.to_owned())
}
fn validate_partial_input(&self, input: &str, _sel: &Selection) -> Validation {
if let Some(idx) = input.find("cat") {
Validation::success().change_selection(Selection::new(idx, idx + 3))
} else {
Validation::success()
}
}
}
impl std::fmt::Display for CurrencyValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
CurrencyValidationError::InvalidChar(c) => write!(f, "Invalid character '{}'", c),
CurrencyValidationError::Parse(err) => write!(f, "Parse failed: {}", err),
CurrencyValidationError::TooManyCharsAfterDecimal => {
write!(f, "Too many characters after decimal")
}
}
}
}
impl std::error::Error for CurrencyValidationError {}
impl std::fmt::Display for PostalCodeValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
PostalCodeValidationError::WrongNumberOfCharacters => {
write!(f, "Incorrect number of characters.")
}
PostalCodeValidationError::IncorrectFormat => {
write!(f, "Postal code must be of format A2A2A2")
}
}
}
}
impl std::error::Error for PostalCodeValidationError {}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/value_formatting/src/widgets.rs | druid/examples/value_formatting/src/widgets.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
//! Widgets, widget components, and functions for creating widgets
use druid::text::ValidationError;
use druid::widget::{
prelude::*, Controller, Either, Label, SizedBox, TextBoxEvent, ValidationDelegate,
};
use druid::{Color, Data, Point, Selector, WidgetExt, WidgetId, WidgetPod};
use super::AppData;
pub const DOLLAR_ERROR_WIDGET: WidgetId = WidgetId::reserved(2);
pub const EURO_ERROR_WIDGET: WidgetId = WidgetId::reserved(3);
pub const POUND_ERROR_WIDGET: WidgetId = WidgetId::reserved(4);
pub const POSTAL_ERROR_WIDGET: WidgetId = WidgetId::reserved(5);
pub const CAT_ERROR_WIDGET: WidgetId = WidgetId::reserved(6);
/// Sent by the [`TextBoxErrorDelegate`] when an error should be displayed.
const SHOW_ERROR: Selector<ValidationError> = Selector::new("druid-example.show-error");
/// Sent by the [`TextBoxErrorDelegate`] when an error should be cleared.
const CLEAR_ERROR: Selector = Selector::new("druid-example.clear-error");
/// Sent by the [`TextBoxErrorDelegate`] when editing began.
///
/// This is used to set the contents of the help text.
const EDIT_BEGAN: Selector<WidgetId> = Selector::new("druid-example.edit-began");
/// Sent by the [`TextBoxErrorDelegate`] when editing finishes.
///
/// This is used to set the contents of the help text.
const EDIT_FINISHED: Selector<WidgetId> = Selector::new("druid-example.edit-finished");
static DEFAULT_EXPLAINER: &str = "This example shows various ways you can use a \
TextBox with a Formatter to control the display \
and validation of text.";
static DOLLAR_EXPLAINER: &str = "This text field accepts any input, and performs \
validation when the user attempts to complete \
editing.";
static EURO_EXPLAINER: &str = "This text field performs validation during editing, \
rejecting invalid edits.";
static POUND_EXPLAINER: &str = "This text field updates the application data \
during editing, whenever the current input is \
valid.";
static POSTAL_EXPLAINER: &str = "This text field edits the contents to ensure \
all letters are capitalized, and the two triplets \
are space-separated.";
static CAT_EXPLAINER: &str = "This text field does no formatting, but selects any \
instance of the string 'cat'.";
const ERROR_TEXT_COLOR: Color = Color::rgb8(0xB6, 0x00, 0x04);
/// Create a widget that will display errors.
///
/// The `id` param is the `WidgetId` that this widget should use; that id
/// will be sent messages when it should display or clear an error.
pub fn error_display_widget<T: Data>(id: WidgetId) -> impl Widget<T> {
ErrorController::new(
Either::new(
|d: &Option<ValidationError>, _| d.is_some(),
Label::dynamic(|d: &Option<ValidationError>, _| {
d.as_ref().map(|d| d.to_string()).unwrap_or_default()
})
.with_text_color(ERROR_TEXT_COLOR)
.with_text_size(12.0),
SizedBox::empty(),
)
.with_id(id),
)
}
/// Create the 'explainer' widget.
pub fn explainer() -> impl Widget<AppData> {
Label::dynamic(|d: &Option<&'static str>, _| d.unwrap_or(DEFAULT_EXPLAINER).to_string())
.with_line_break_mode(druid::widget::LineBreaking::WordWrap)
.with_text_color(druid::theme::FOREGROUND_DARK)
.with_font(druid::theme::UI_FONT_ITALIC)
.lens(AppData::active_message)
}
/// Create the 'active value' widget
pub fn active_value() -> impl Widget<AppData> {
Label::dynamic(|d: &AppData, _| match d.active_textbox {
None => "No textfield is active".to_string(),
Some(id) => match id {
DOLLAR_ERROR_WIDGET => format!("Active value: {:2}", d.dollars),
EURO_ERROR_WIDGET => format!("Active value: {:2}", d.euros),
POUND_ERROR_WIDGET => format!("Active value: {:2}", d.pounds),
POSTAL_ERROR_WIDGET => format!("Active value: {}", d.postal_code),
CAT_ERROR_WIDGET => format!("Active value: {}", d.dont_type_cat),
_ => unreachable!(),
},
})
.with_text_color(druid::theme::FOREGROUND_DARK)
.with_font(druid::theme::UI_FONT_ITALIC)
}
/// A widget that manages a child which can display an error.
///
/// This is not a blessed pattern, but works around certain limitations of Druid,
/// using Commands.
///
/// The basic idea is that this widget owns an `Option<Error>`, and it either
/// clears or sets this error based on `Command`s sent to it from some other
/// widget.
///
/// Its child's data is this `Option<Error>`; the incoming data is ignored
/// completely.
pub struct ErrorController<W> {
child: WidgetPod<Option<ValidationError>, W>,
error: Option<ValidationError>,
}
/// A controller that sits at the root of our widget tree and updates the
/// helper text in response to messages about the currently focused widget.
pub struct RootController;
pub struct TextBoxErrorDelegate {
target: WidgetId,
sends_partial_errors: bool,
}
impl<W: Widget<Option<ValidationError>>> ErrorController<W> {
pub fn new(child: W) -> ErrorController<W> {
ErrorController {
child: WidgetPod::new(child),
error: None,
}
}
}
impl<T, W: Widget<Option<ValidationError>>> Widget<T> for ErrorController<W> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut T, env: &Env) {
match event {
Event::Command(cmd) if cmd.is(SHOW_ERROR) => {
self.error = Some(cmd.get_unchecked(SHOW_ERROR).to_owned());
ctx.request_update();
}
Event::Command(cmd) if cmd.is(CLEAR_ERROR) => {
self.error = None;
ctx.request_update();
}
_ => self.child.event(ctx, event, &mut self.error, env),
}
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _: &T, env: &Env) {
self.child.lifecycle(ctx, event, &self.error, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, _: &T, _: &T, env: &Env) {
self.child.update(ctx, &self.error, env)
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _: &T, env: &Env) -> Size {
let size = self.child.layout(ctx, bc, &self.error, env);
self.child.set_origin(ctx, Point::ZERO);
size
}
fn paint(&mut self, ctx: &mut PaintCtx, _: &T, env: &Env) {
self.child.paint(ctx, &self.error, env);
}
fn id(&self) -> Option<WidgetId> {
Some(self.child.id())
}
}
impl<W: Widget<AppData>> Controller<AppData, W> for RootController {
fn event(
&mut self,
child: &mut W,
ctx: &mut EventCtx,
event: &Event,
data: &mut AppData,
env: &Env,
) {
match event {
Event::Command(cmd) if cmd.is(EDIT_BEGAN) => {
let widget_id = *cmd.get_unchecked(EDIT_BEGAN);
data.active_message = match widget_id {
DOLLAR_ERROR_WIDGET => Some(DOLLAR_EXPLAINER),
EURO_ERROR_WIDGET => Some(EURO_EXPLAINER),
POUND_ERROR_WIDGET => Some(POUND_EXPLAINER),
POSTAL_ERROR_WIDGET => Some(POSTAL_EXPLAINER),
CAT_ERROR_WIDGET => Some(CAT_EXPLAINER),
_ => unreachable!(),
};
data.active_textbox = Some(widget_id);
}
Event::Command(cmd) if cmd.is(EDIT_FINISHED) => {
let finished_id = *cmd.get_unchecked(EDIT_FINISHED);
if data.active_textbox == Some(finished_id) {
data.active_textbox = None;
data.active_message = None;
}
}
_ => child.event(ctx, event, data, env),
}
}
}
impl TextBoxErrorDelegate {
pub fn new(target: WidgetId) -> TextBoxErrorDelegate {
TextBoxErrorDelegate {
target,
sends_partial_errors: false,
}
}
pub fn sends_partial_errors(mut self, flag: bool) -> Self {
self.sends_partial_errors = flag;
self
}
}
impl ValidationDelegate for TextBoxErrorDelegate {
fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, _current_text: &str) {
match event {
TextBoxEvent::Began => {
ctx.submit_command(CLEAR_ERROR.to(self.target));
ctx.submit_command(EDIT_BEGAN.with(self.target));
}
TextBoxEvent::Changed if self.sends_partial_errors => {
ctx.submit_command(CLEAR_ERROR.to(self.target));
}
TextBoxEvent::PartiallyInvalid(err) if self.sends_partial_errors => {
ctx.submit_command(SHOW_ERROR.with(err).to(self.target));
}
TextBoxEvent::Invalid(err) => {
ctx.submit_command(SHOW_ERROR.with(err).to(self.target));
}
TextBoxEvent::Cancel | TextBoxEvent::Complete => {
ctx.submit_command(CLEAR_ERROR.to(self.target));
ctx.submit_command(EDIT_FINISHED.with(self.target));
}
_ => (),
}
}
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/value_formatting/src/main.rs | druid/examples/value_formatting/src/main.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
// On Windows platform, don't show a console when opening the app.
#![windows_subsystem = "windows"]
mod formatters;
mod widgets;
use druid::widget::{prelude::*, Flex, Label, TextBox};
use druid::{AppLauncher, Data, Lens, WidgetExt, WidgetId, WindowDesc};
use formatters::{
CanadianPostalCodeFormatter, CatSelectingFormatter, NaiveCurrencyFormatter, PostalCode,
};
use widgets::{RootController, TextBoxErrorDelegate};
/// Various values that we are going to use with formatters.
#[derive(Debug, Clone, Data, Lens)]
pub struct AppData {
dollars: f64,
euros: f64,
pounds: f64,
postal_code: PostalCode,
dont_type_cat: String,
#[data(ignore)]
active_textbox: Option<WidgetId>,
active_message: Option<&'static str>,
}
pub fn main() {
let main_window = WindowDesc::new(ui_builder()).title("Formatting and Validation");
let data = AppData {
dollars: 12.2,
euros: -20.0,
pounds: 1337.,
postal_code: PostalCode::new("H0H0H0").unwrap(),
dont_type_cat: String::new(),
active_textbox: None,
active_message: None,
};
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
.expect("launch failed");
}
fn dollar_validation_scope() -> impl Widget<AppData> {
let textbox = TextBox::new()
.with_formatter(NaiveCurrencyFormatter::DOLLARS)
.validate_while_editing(false)
.delegate(
TextBoxErrorDelegate::new(widgets::DOLLAR_ERROR_WIDGET).sends_partial_errors(true),
);
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(
Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Baseline)
.with_child(Label::new("Dollars:"))
.with_default_spacer()
.with_child(textbox),
)
.with_child(widgets::error_display_widget(widgets::DOLLAR_ERROR_WIDGET))
.lens(AppData::dollars)
}
fn euro_validation_scope() -> impl Widget<AppData> {
let textbox = TextBox::new()
.with_formatter(NaiveCurrencyFormatter::EUROS)
.delegate(TextBoxErrorDelegate::new(widgets::EURO_ERROR_WIDGET).sends_partial_errors(true));
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(
Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Baseline)
.with_child(Label::new("Euros, often:"))
.with_default_spacer()
.with_child(textbox),
)
.with_child(widgets::error_display_widget(widgets::EURO_ERROR_WIDGET))
.lens(AppData::euros)
}
fn pound_validation_scope() -> impl Widget<AppData> {
let textbox = TextBox::new()
.with_formatter(NaiveCurrencyFormatter::GBP)
.update_data_while_editing(true)
.delegate(
TextBoxErrorDelegate::new(widgets::POUND_ERROR_WIDGET).sends_partial_errors(true),
);
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(
Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Baseline)
.with_child(Label::new("Sterling Quidpence:"))
.with_default_spacer()
.with_child(textbox),
)
.with_child(widgets::error_display_widget(widgets::POUND_ERROR_WIDGET))
.lens(AppData::pounds)
}
fn postal_validation_scope() -> impl Widget<AppData> {
let textbox = TextBox::new()
.with_formatter(CanadianPostalCodeFormatter)
.delegate(
TextBoxErrorDelegate::new(widgets::POSTAL_ERROR_WIDGET).sends_partial_errors(true),
);
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(
Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Baseline)
.with_child(Label::new("Postal code:"))
.with_default_spacer()
.with_child(textbox),
)
.with_child(widgets::error_display_widget(widgets::POSTAL_ERROR_WIDGET))
.lens(AppData::postal_code)
}
fn cat_validation_scope() -> impl Widget<AppData> {
let textbox = TextBox::new()
.with_placeholder("^(`.`)^")
.with_formatter(CatSelectingFormatter)
.delegate(TextBoxErrorDelegate::new(widgets::CAT_ERROR_WIDGET));
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(
Flex::row()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::Baseline)
.with_child(Label::new("Cat selector:"))
.with_default_spacer()
.with_child(textbox),
)
.lens(AppData::dont_type_cat)
}
fn ui_builder() -> impl Widget<AppData> {
Flex::column()
.with_child(
widgets::explainer()
.padding(10.0)
.border(druid::theme::BORDER_DARK, 4.0)
.rounded(10.0)
.padding(10.0),
)
.with_default_spacer()
.with_child(
Flex::column()
.cross_axis_alignment(druid::widget::CrossAxisAlignment::End)
.with_child(dollar_validation_scope())
.with_default_spacer()
.with_child(euro_validation_scope())
.with_default_spacer()
.with_child(pound_validation_scope())
.with_default_spacer()
.with_child(postal_validation_scope())
.with_default_spacer()
.with_child(cat_validation_scope())
.center(),
)
.with_default_spacer()
.with_child(
widgets::active_value()
.padding(10.0)
.border(druid::theme::BORDER_DARK, 4.0)
.rounded(10.0)
.padding(10.0),
)
.controller(RootController)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/hello_web/src/lib.rs | druid/examples/hello_web/src/lib.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use druid::widget::{Align, Flex, Label, TextBox};
use druid::{AppLauncher, Data, Env, Lens, Widget, WidgetExt, WindowDesc};
use wasm_bindgen::prelude::*;
const VERTICAL_WIDGET_SPACING: f64 = 20.0;
const TEXT_BOX_WIDTH: f64 = 200.0;
#[derive(Clone, Data, Lens)]
struct HelloState {
name: String,
}
// This wrapper function is the primary modification we're making to the vanilla
// hello.rs example.
#[wasm_bindgen]
pub fn wasm_main() {
// This hook is necessary to get panic messages in the console
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
main()
}
pub fn main() {
// describe the main window
//
// Window title is set in index.html and window size is ignored on the web,
// so can we leave those off.
let main_window = WindowDesc::new(build_root_widget());
// create the initial app state
let initial_state = HelloState {
name: "World".into(),
};
// start the application
AppLauncher::with_window(main_window)
.launch(initial_state)
.expect("Failed to launch application");
}
fn build_root_widget() -> impl Widget<HelloState> {
// a label that will determine its text based on the current app data.
let label = Label::new(|data: &HelloState, _env: &Env| format!("Hello {}!", data.name));
// a textbox that modifies `name`.
let textbox = TextBox::new()
.with_placeholder("Who are we greeting?")
.fix_width(TEXT_BOX_WIDTH)
.lens(HelloState::name);
// arrange the two widgets vertically, with some padding
let layout = Flex::column()
.with_child(label)
.with_spacer(VERTICAL_WIDGET_SPACING)
.with_child(textbox);
// center the two widgets in the available space
Align::centered(layout)
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/web/build.rs | druid/examples/web/build.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use std::io::{ErrorKind, Result};
use std::path::{Path, PathBuf};
use std::{env, fs};
/// Examples known to not work with the web backend are skipped.
/// Ideally this list will eventually be empty.
const EXCEPTIONS: &[&str] = &[
"markdown_preview", // rich text not implemented in piet-web
"svg", // usvg doesn't currently build as Wasm.
"async_event", // the web backend doesn't currently support spawning threads.
"blocking_function", // the web backend doesn't currently support spawning threads.
"sub_window", // Sub-windows dont apply to web
"input_region", // None of the demonstrated window features apply to web
];
/// Create a platform specific link from `src` to the `dst` directory.
#[inline]
fn link_dir(src: &Path, dst: &Path) {
#[cfg(unix)]
link_dir_unix(src, dst);
#[cfg(windows)]
link_dir_windows(src, dst);
}
#[cfg(unix)]
fn link_dir_unix(src: &Path, dst: &Path) {
let err = std::os::unix::fs::symlink(src, dst).err();
match err {
None => (),
Some(err) if err.kind() == ErrorKind::AlreadyExists => (),
Some(err) => panic!("Failed to create symlink: {}", err),
}
}
#[cfg(windows)]
fn link_dir_windows(src: &Path, dst: &Path) {
// First we have to delete any previous link,
// especially because a junction is an absolute path reference
// that becomes invalid if one of our ancestor directories gets renamed/moved.
let err = fs::remove_dir(dst).err(); // Safe as it errors when directory isn't empty
match err {
None => (),
Some(err) if err.kind() == ErrorKind::NotFound => (),
Some(err) => panic!("Failed to remove directory: {}", err),
}
// Attempt to create a symlink, which will work with either
// * Administrator privileges
// * New enough Windows with developer mode enabled
if std::os::windows::fs::symlink_dir(src, dst).is_ok() {
return;
}
// Otherwise fall back to creating a junction instead,
// by using Command Prompt's inbuilt 'mklink' command.
std::process::Command::new("cmd")
.arg("/C") // Run a command and exit
.arg("mklink")
.arg("/J") // Junction
.arg(dst.as_os_str())
.arg(src.as_os_str())
.output()
.expect("failed to execute process");
// Make sure the directory exists now
if !dst.exists() {
panic!("Failed to create a link");
}
}
fn main() -> Result<()> {
let crate_dir = PathBuf::from(&env::var("CARGO_MANIFEST_DIR").unwrap());
let src_dir = crate_dir.join("src");
let examples_dir = src_dir.join("examples");
let parent_dir = crate_dir.parent().unwrap();
// Create a platform specific link to the examples directory.
link_dir(parent_dir, &examples_dir);
// Generate example module and the necessary html documents.
// Declare the newly found example modules in examples.in
let mut examples_in = r#"
// This file is automatically generated and must not be committed.
/// This is a module collecting all valid examples in the parent examples directory.
mod examples {
"#
.to_string();
let mut index_html = r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Druid web examples</title>
</head>
<body>
<h1>Druid web examples</h1>
<ul>
"#
.to_string();
for entry in examples_dir.read_dir()? {
let path = entry?.path();
if let Some(r) = path.extension() {
if r != "rs" {
continue;
}
} else {
continue;
}
if let Some(example) = path.file_stem() {
let example_str = example.to_string_lossy();
// Skip examples that are known to not work.
if EXCEPTIONS.contains(&example_str.as_ref()) {
continue;
}
// Record the valid example module we found to add to the generated examples.in
examples_in.push_str(&format!(" pub mod {};\n", example_str));
// Add an entry to the index.html file.
let index_entry = format!(
"<li><a href=\"./html/{name}.html\">{name}</a></li>",
name = example_str
);
index_html.push_str(&index_entry);
// Create an html document for each example.
let html = format!(
r#"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Druid web examples - {name}</title>
<style>
html, body, canvas {{
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
overflow: hidden;
}}
</style>
</head>
<body>
<noscript>This page contains WebAssembly and JavaScript content, please enable JavaScript in your browser.</noscript>
<canvas id="canvas"></canvas>
<script type="module">
import init, {{ {name} }} from '../pkg/druid_web_examples.js';
async function run() {{
await init();
{name}();
}}
run();
</script>
</body>
</html>"#,
name = example_str.to_string()
);
// Write out the html file into a designated html directory located in crate root.
let html_dir = crate_dir.join("html");
if !html_dir.exists() {
fs::create_dir(&html_dir).unwrap_or_else(|_| {
panic!("Failed to create output html directory: {:?}", &html_dir)
});
}
fs::write(html_dir.join(example).with_extension("html"), html)
.unwrap_or_else(|_| panic!("Failed to create {}.html", example_str));
}
}
examples_in.push('}');
index_html.push_str("</ul></body></html>");
// Write out the contents of the examples.in module.
fs::write(src_dir.join("examples.in"), examples_in)?;
// Write out the index.html file
fs::write(crate_dir.join("index.html"), index_html)?;
Ok(())
}
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
linebender/druid | https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/examples/web/src/lib.rs | druid/examples/web/src/lib.rs | // Copyright 2020 the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use wasm_bindgen::prelude::*;
// This line includes an automatically generated (in build.rs) examples module.
// This particular mechanism is chosen to avoid any kinds of modifications to committed files at
// build time, keeping the source tree clean from build artifacts.
include!("examples.in");
// This macro constructs a `wasm_bindgen` entry point to the given example from the examples
// directory.
//
// There are three ways to call this macro:
//
// 1. impl_example!(<example_name>);
// Creates the binding for an example whose main fn returns nothing (or unit).
//
// 2. impl_example!(<example_name>.unwrap());
// Creates the binding for an example whose main fn returns a Result which is immediately
// unwrapped.
//
// 3. impl_example!(<wasm_fn_name>, <path_to_example_main_fn>());
// Creates a wasm binding named <wasm_fn_name>, which calls into the Rust example fn given by
// <path_to_example_main_fn>. This can be used to make a different wasm binding name than the
// name of the original example itself (e.g. it was used for the `switch` example to avoid name
// collisions with the JavaScript `switch` statement).
macro_rules! impl_example {
($wasm_fn:ident, $expr:expr) => {
#[wasm_bindgen]
pub fn $wasm_fn() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
$expr;
}
};
($fn:ident) => {
impl_example!($fn, examples::$fn::main());
};
($fn:ident.unwrap()) => {
impl_example!($fn, examples::$fn::main().unwrap());
};
}
// Below is a list of examples that can be built for the web.
// Please add the examples that cannot be built to the EXCEPTIONS list in build.rs.
impl_example!(anim);
impl_example!(calc);
impl_example!(cursor);
impl_example!(custom_widget);
impl_example!(disabled);
impl_example!(either);
impl_example!(event_viewer);
impl_example!(flex);
impl_example!(game_of_life);
impl_example!(hello);
impl_example!(identity);
impl_example!(image);
impl_example!(invalidation);
impl_example!(layout);
impl_example!(lens);
impl_example!(list);
impl_example!(multiwin);
impl_example!(open_save);
impl_example!(panels.unwrap());
impl_example!(scroll_colors);
impl_example!(scroll);
impl_example!(slider);
impl_example!(split_demo);
impl_example!(styled_text.unwrap());
impl_example!(switches);
impl_example!(timer);
impl_example!(tabs);
impl_example!(textbox);
impl_example!(transparency);
impl_example!(view_switcher);
impl_example!(widget_gallery);
impl_example!(text);
| rust | Apache-2.0 | b27ea6a618c32f9ea0e8a56822f9487d23401c0d | 2026-01-04T15:44:39.941670Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/build.rs | build.rs | #[cfg(windows)]
extern crate winres;
use std::borrow::Cow;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;
include!("./src/networking/types/service_query.rs");
include!("./src/networking/types/protocol.rs");
const WINDOWS_ICON_PATH: &str = "./resources/packaging/windows/graphics/sniffnet.ico";
const SERVICES_LIST_PATH: &str = "./services.txt";
fn main() {
println!("cargo:rerun-if-changed={WINDOWS_ICON_PATH}");
println!("cargo:rerun-if-changed={SERVICES_LIST_PATH}");
set_icon();
build_services_phf();
}
fn set_icon() {
#[cfg(windows)]
{
let mut res = winres::WindowsResource::new();
res.set_icon(WINDOWS_ICON_PATH);
res.compile().unwrap();
}
}
fn build_services_phf() {
let out_path = Path::new(&env::var("OUT_DIR").unwrap()).join("services.rs");
let mut output = BufWriter::new(File::create(out_path).unwrap());
let mut services_map = phf_codegen::Map::new();
let input = BufReader::new(File::open(SERVICES_LIST_PATH).unwrap());
let mut num_entries = 0;
for line_res in input.lines() {
// we want to panic if one of the lines is err...
let line = line_res.unwrap();
let mut parts = line.split('\t');
// we want to panic if one of the service names is invalid
let val = Cow::Owned(get_valid_service_fmt_const(parts.next().unwrap()));
// we want to panic if port is not a u16, or protocol is not TCP or UDP
let key = get_valid_service_query(parts.next().unwrap());
assert!(parts.next().is_none());
services_map.entry(key, val);
num_entries += 1;
}
assert_eq!(num_entries, 12084);
writeln!(
&mut output,
"#[allow(clippy::unreadable_literal)]\n\
static SERVICES: phf::Map<ServiceQuery, Service> = {};",
services_map.build()
)
.unwrap();
}
fn get_valid_service_fmt_const(s: &str) -> String {
match s.trim() {
invalid
if ["", "unknown", "-"].contains(&invalid)
|| !invalid.is_ascii()
|| invalid.starts_with('#')
|| invalid.contains(' ')
|| invalid.contains('?') =>
{
panic!("Invalid service name found: {invalid}")
}
#[cfg(debug_assertions)]
inappropriate
if rustrict::Censor::from_str(inappropriate)
.with_trie(&SAFE_WORDS_FOR_SERVICE_NAME)
.analyze()
.is(rustrict::Type::INAPPROPRIATE) =>
{
panic!("Inappropriate service name found: {inappropriate}")
}
name => format!("Service::Name(\"{name}\")"),
}
}
fn get_valid_service_query(s: &str) -> ServiceQuery {
let mut parts = s.split('/');
let port = parts.next().unwrap().parse::<u16>().unwrap();
let protocol_str = parts.next().unwrap();
let protocol = match protocol_str {
"tcp" => Protocol::TCP,
"udp" => Protocol::UDP,
invalid => panic!("Invalid protocol found: {invalid}"),
};
assert!(parts.next().is_none());
ServiceQuery(port, protocol)
}
#[cfg(debug_assertions)]
static SAFE_WORDS_FOR_SERVICE_NAME: std::sync::LazyLock<rustrict::Trie> =
std::sync::LazyLock::new(|| {
let mut safe_words = rustrict::Trie::default();
for word in [
"npp",
"emfis-cntl",
"ardus-cntl",
"pmip6-cntl",
"mpp",
"ipp",
"vpp",
"epp",
"kink",
"kvm-via-ip",
"dpp",
"slinkysearch",
"alta-ana-lm",
"vpps-qua",
"vpps-via",
"ibm-pps",
"ppsms",
"ppsuitemsg",
"icpps",
"rap-listen",
"cadabra-lm",
"pay-per-view",
"sixtrak",
"cvmon",
"houdini-lm",
"dic-aida",
"p2pq",
"bigbrother",
"bintec-admin",
"zymed-zpp",
"cvmmon",
"btpp2sectrans",
"conclave-cpp",
"btpp2audctr1",
"tclprodebugger",
"bintec-capi",
"bintec-tapi",
"dicom-iscl",
"dicom-tls",
"nmsigport",
"ppp",
"tl1-telnet",
"opcon-xps",
"netwatcher-mon",
"netwatcher-db",
"xnm-ssl",
"edm-mgr-cntrl",
"isoft-p2p",
"must-p2p",
"p2pgroup",
"quasar-server",
"int-rcv-cntrl",
"faxstfx-port",
"sunlps-http",
"fagordnc",
"p2pcommunity",
"minger",
"assuria-slm",
"wcpp",
"plcy-net-svcs",
"assyst-dr",
"mobile-p2p",
"assuria-ins",
"taep-as-svc",
"nlg-data",
"dj-ice",
"x500ms",
"X11:7",
"p2p-sip",
"p4p-portal",
"bmc-perf-agent",
"ntz-p2p-storage",
"citrixupp",
"freezexservice",
"p2pevolvenet",
"papachi-p2p-srv",
"espeasy-p2p",
"pim-port",
"vp2p",
"dicom",
"icpp",
"sauterdongle",
"vocaltec-hos",
"BackOrifice",
"dhanalakshmi",
"3gpp-w1ap",
"pmsm-webrctl",
"bif-p2p",
"as-servermap",
"nm-asses-admin",
"ias-session",
"smar-se-port1",
"smar-se-port2",
"canon-cpp-disc",
"3gpp-monp",
"emc-pp-mgmtsvc",
"3gpp-cbsp",
] {
safe_words.set(word, rustrict::Type::SAFE);
}
safe_words
});
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/main.rs | src/main.rs | //! Module containing the entry point of application execution.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::borrow::Cow;
use chart::types::traffic_chart::TrafficChart;
use cli::handle_cli_args;
use gui::pages::types::running_page::RunningPage;
use gui::sniffer::Sniffer;
use gui::styles::style_constants::FONT_SIZE_BODY;
use gui::styles::types::style_type::StyleType;
use iced::window::Position;
#[cfg(target_os = "linux")]
use iced::window::settings::PlatformSpecific;
use iced::{Font, Pixels, application, window};
use networking::types::data_representation::ByteMultiple;
use networking::types::info_traffic::InfoTraffic;
use networking::types::protocol::Protocol;
use networking::types::service::Service;
use translations::types::language::Language;
use utils::formatted_strings::print_cli_welcome_message;
use crate::gui::sniffer::FONT_FAMILY_NAME;
use crate::gui::styles::style_constants::{ICONS_BYTES, SARASA_MONO_BYTES};
use crate::gui::types::conf::CONF;
mod chart;
mod cli;
mod countries;
mod gui;
mod mmdb;
mod networking;
mod notifications;
mod report;
mod translations;
mod utils;
pub const SNIFFNET_LOWERCASE: &str = "sniffnet";
pub const SNIFFNET_TITLECASE: &str = "Sniffnet";
const WINDOW_ICON: &[u8] = include_bytes!("../resources/logos/raw/icon.png");
/// Entry point of application execution
///
/// It initializes variables and loads configuration parameters
pub fn main() -> iced::Result {
#[cfg(all(windows, not(debug_assertions)))]
let _gag1: gag::Redirect<std::fs::File>;
#[cfg(all(windows, not(debug_assertions)))]
let _gag2: gag::Redirect<std::fs::File>;
#[cfg(all(windows, not(debug_assertions)))]
if let Some((gag1, gag2)) = utils::formatted_strings::redirect_stdout_stderr_to_file() {
_gag1 = gag1;
_gag2 = gag2;
}
let conf = CONF.clone();
#[cfg(debug_assertions)]
{
// kill the main thread as soon as a secondary thread panics
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
std::process::exit(1);
}));
}
print_cli_welcome_message();
let size = conf.window.size();
let position = Position::Specific(conf.window.position());
// TODO: parse CLI args before launching GUI
application(
move || (Sniffer::new(conf.clone()), handle_cli_args()),
Sniffer::update,
Sniffer::view,
)
.title(SNIFFNET_TITLECASE)
.settings(iced::Settings {
// id needed for Linux Wayland; should match StartupWMClass in .desktop file; see issue #292
id: Some(String::from(SNIFFNET_LOWERCASE)),
fonts: vec![Cow::Borrowed(SARASA_MONO_BYTES), Cow::Borrowed(ICONS_BYTES)],
default_font: Font::with_name(FONT_FAMILY_NAME),
default_text_size: Pixels(FONT_SIZE_BODY),
antialiasing: true,
vsync: true,
})
.window(window::Settings {
size, // start size
position,
min_size: None, // Some(ConfigWindow::MIN_SIZE.to_size()), // min size allowed
max_size: None,
visible: true,
resizable: true,
decorations: true,
transparent: false,
icon: window::icon::from_file_data(WINDOW_ICON, None).ok(),
#[cfg(target_os = "linux")]
platform_specific: PlatformSpecific {
application_id: String::from(SNIFFNET_LOWERCASE),
..PlatformSpecific::default()
},
exit_on_close_request: false,
..Default::default()
})
.subscription(Sniffer::subscription)
.theme(Sniffer::theme)
.scale_factor(Sniffer::scale_factor)
.run()
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/country.rs | src/mmdb/country.rs | use crate::countries::types::country::Country;
use crate::mmdb::types::mmdb_country_entry::MmdbCountryEntry;
use crate::mmdb::types::mmdb_reader::MmdbReader;
use std::net::IpAddr;
pub const COUNTRY_MMDB: &[u8] = include_bytes!("../../resources/DB/GeoLite2-Country.mmdb");
#[allow(clippy::module_name_repetitions)]
pub fn get_country(address: &IpAddr, country_db_reader: &MmdbReader) -> Country {
if let Some(res) = country_db_reader.lookup::<MmdbCountryEntry>(*address) {
return res.get_country();
}
Country::ZZ // unknown
}
#[cfg(test)]
mod tests {
use crate::countries::types::country::Country;
use crate::mmdb::country::{COUNTRY_MMDB, get_country};
use crate::mmdb::types::mmdb_reader::MmdbReader;
use std::net::IpAddr;
use std::str::FromStr;
#[test]
fn test_get_country_with_default_reader() {
let reader_1 = MmdbReader::from(&String::from("unknown path"), COUNTRY_MMDB);
assert!(matches!(reader_1, MmdbReader::Default(_)));
let reader_2 = MmdbReader::from(&String::new(), COUNTRY_MMDB);
assert!(matches!(reader_2, MmdbReader::Default(_)));
let reader_3 = MmdbReader::from(&String::from("resources/repository/hr.png"), COUNTRY_MMDB);
assert!(matches!(reader_3, MmdbReader::Default(_)));
let reader_4 = MmdbReader::from(
&String::from("resources/DB/GeoLite2-Country.mmdb"),
COUNTRY_MMDB,
);
assert!(matches!(reader_4, MmdbReader::Custom(_)));
let reader_5 = MmdbReader::from(&String::from("resources/DB/GeoLite2-Country.mmdb"), &[]);
assert!(matches!(reader_5, MmdbReader::Custom(_)));
for reader in vec![reader_1, reader_2, reader_3, reader_4, reader_5] {
// known IP
let res = get_country(&IpAddr::from([8, 8, 8, 8]), &reader);
assert_eq!(res, Country::US);
// another known IP
let res = get_country(&IpAddr::from([78, 35, 248, 93]), &reader);
assert_eq!(res, Country::DE);
// known IPv6
let res = get_country(&IpAddr::from_str("2806:230:2057::").unwrap(), &reader);
assert_eq!(res, Country::MX);
// unknown IP
let res = get_country(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res, Country::ZZ);
// unknown IPv6
let res = get_country(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res, Country::ZZ);
}
}
#[test]
fn test_get_country_with_custom_ipinfo_single_reader() {
let reader_1 = MmdbReader::from(
&String::from("resources/test/ipinfo_location_sample.mmdb"),
COUNTRY_MMDB,
);
let reader_2 = MmdbReader::from(
&String::from("resources/test/ipinfo_location_sample.mmdb"),
&[],
);
for reader in vec![reader_1, reader_2] {
assert!(matches!(reader, MmdbReader::Custom(_)));
// known IP
let res = get_country(&IpAddr::from([1, 0, 6, 99]), &reader);
assert_eq!(res, Country::AU);
// another known IP
let res = get_country(&IpAddr::from([1, 0, 8, 0]), &reader);
assert_eq!(res, Country::CN);
// known IPv6
// let res = get_country(&IpAddr::from_str("2a0e:1d80::").unwrap(), &reader);
// assert_eq!(res, Country::RO);
// unknown IP
let res = get_country(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res, Country::ZZ);
// unknown IPv6
let res = get_country(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res, Country::ZZ);
}
}
#[test]
fn test_get_country_with_custom_ipinfo_combined_reader() {
let reader_1 = MmdbReader::from(
&String::from("resources/test/ipinfo_lite_sample.mmdb"),
COUNTRY_MMDB,
);
let reader_2 =
MmdbReader::from(&String::from("resources/test/ipinfo_lite_sample.mmdb"), &[]);
for reader in vec![reader_1, reader_2] {
assert!(matches!(reader, MmdbReader::Custom(_)));
// known IP
let res = get_country(&IpAddr::from([1, 0, 65, 1]), &reader);
assert_eq!(res, Country::JP);
// another known IP
let res = get_country(&IpAddr::from([1, 6, 230, 0]), &reader);
assert_eq!(res, Country::IN);
// known IPv6
// let res = get_country(&IpAddr::from_str("2a02:6ea0:f001::").unwrap(), &reader);
// assert_eq!(res, Country::AR);
// unknown IP
let res = get_country(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res, Country::ZZ);
// unknown IPv6
let res = get_country(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res, Country::ZZ);
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/mod.rs | src/mmdb/mod.rs | pub mod asn;
pub mod country;
pub mod types;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/asn.rs | src/mmdb/asn.rs | use crate::mmdb::types::mmdb_asn_entry::MmdbAsnEntry;
use crate::mmdb::types::mmdb_reader::MmdbReader;
use crate::networking::types::asn::Asn;
use std::net::IpAddr;
pub const ASN_MMDB: &[u8] = include_bytes!("../../resources/DB/GeoLite2-ASN.mmdb");
#[allow(clippy::module_name_repetitions)]
pub fn get_asn(address: &IpAddr, asn_db_reader: &MmdbReader) -> Asn {
if let Some(res) = asn_db_reader.lookup::<MmdbAsnEntry>(*address) {
return res.get_asn();
}
Asn::default()
}
#[cfg(test)]
mod tests {
use crate::mmdb::asn::{ASN_MMDB, get_asn};
use crate::mmdb::types::mmdb_reader::MmdbReader;
use std::net::IpAddr;
use std::str::FromStr;
#[test]
fn test_get_asn_with_default_reader() {
let reader_1 = MmdbReader::from(&String::from("unknown path"), ASN_MMDB);
assert!(matches!(reader_1, MmdbReader::Default(_)));
let reader_2 = MmdbReader::from(&String::new(), ASN_MMDB);
assert!(matches!(reader_2, MmdbReader::Default(_)));
let reader_3 = MmdbReader::from(&String::from("resources/repository/hr.png"), ASN_MMDB);
assert!(matches!(reader_3, MmdbReader::Default(_)));
let reader_4 = MmdbReader::from(&String::from("resources/DB/GeoLite2-ASN.mmdb"), ASN_MMDB);
assert!(matches!(reader_4, MmdbReader::Custom(_)));
let reader_5 = MmdbReader::from(&String::from("resources/DB/GeoLite2-ASN.mmdb"), &[]);
assert!(matches!(reader_5, MmdbReader::Custom(_)));
for reader in vec![reader_1, reader_2, reader_3, reader_4, reader_5] {
// known IP
let res = get_asn(&IpAddr::from([8, 8, 8, 8]), &reader);
assert_eq!(res.code, "15169");
assert_eq!(res.name, "GOOGLE");
// another known IP
let res = get_asn(&IpAddr::from([78, 35, 248, 93]), &reader);
assert_eq!(res.code, "8422");
assert_eq!(
res.name,
"NetCologne Gesellschaft fur Telekommunikation mbH"
);
// known IPv6
let res = get_asn(&IpAddr::from_str("2806:230:2057::").unwrap(), &reader);
assert_eq!(res.code, "11888");
assert_eq!(res.name, "Television Internacional, S.A. de C.V.");
// unknown IP
let res = get_asn(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
// unknown IPv6
let res = get_asn(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
}
}
#[test]
fn test_get_asn_with_custom_ipinfo_single_reader() {
let reader_1 = MmdbReader::from(
&String::from("resources/test/ipinfo_asn_sample.mmdb"),
ASN_MMDB,
);
let reader_2 =
MmdbReader::from(&String::from("resources/test/ipinfo_asn_sample.mmdb"), &[]);
for reader in vec![reader_1, reader_2] {
assert!(matches!(reader, MmdbReader::Custom(_)));
// known IP
let res = get_asn(&IpAddr::from([185, 72, 2, 28]), &reader);
assert_eq!(res.code, "AS202583");
assert_eq!(res.name, "AVATEL TELECOM, SA");
// another known IP
let res = get_asn(&IpAddr::from([89, 187, 198, 0]), &reader);
assert_eq!(res.code, "AS210367");
assert_eq!(res.name, "Krajska zdravotni, a.s.");
// known IPv6
let res = get_asn(&IpAddr::from_str("2408:8957:6280::").unwrap(), &reader);
assert_eq!(res.code, "AS17622");
assert_eq!(res.name, "China Unicom Guangzhou network");
// unknown IP
let res = get_asn(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
// unknown IPv6
let res = get_asn(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
}
}
#[test]
fn test_get_asn_with_custom_ipinfo_combined_reader() {
let reader_1 = MmdbReader::from(
&String::from("resources/test/ipinfo_lite_sample.mmdb"),
ASN_MMDB,
);
let reader_2 =
MmdbReader::from(&String::from("resources/test/ipinfo_lite_sample.mmdb"), &[]);
for reader in vec![reader_1, reader_2] {
assert!(matches!(reader, MmdbReader::Custom(_)));
// known IP
let res = get_asn(&IpAddr::from([1, 0, 65, 1]), &reader);
assert_eq!(res.code, "AS18144");
assert_eq!(res.name, "Enecom,Inc.");
// another known IP
let res = get_asn(&IpAddr::from([1, 6, 230, 0]), &reader);
assert_eq!(res.code, "AS4755");
assert_eq!(res.name, "TATA Communications formerly VSNL is Leading ISP");
// known IPv6
// let res = get_asn(&IpAddr::from_str("2a02:6ea0:f001::").unwrap(), &reader);
// assert_eq!(res.code, "AS60068");
// assert_eq!(res.name, "Datacamp Limited");
// unknown IP
let res = get_asn(&IpAddr::from([127, 0, 0, 1]), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
// unknown IPv6
let res = get_asn(&IpAddr::from_str("::1").unwrap(), &reader);
assert_eq!(res.code, "");
assert_eq!(res.name, "");
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/types/mmdb_asn_entry.rs | src/mmdb/types/mmdb_asn_entry.rs | use serde::Deserialize;
use crate::networking::types::asn::Asn;
#[derive(Deserialize)]
pub struct MmdbAsnEntry<'a> {
#[serde(alias = "autonomous_system_number", alias = "asn")]
code: MmdbAsnCode<'a>,
#[serde(alias = "autonomous_system_organization", alias = "as_name")]
name: Option<&'a str>,
}
impl MmdbAsnEntry<'_> {
pub fn get_asn(&self) -> Asn {
Asn {
code: self.code.get_code(),
name: self.name.unwrap_or_default().to_string(),
}
}
}
#[derive(Deserialize)]
#[serde(untagged)]
enum MmdbAsnCode<'a> {
Int(Option<u32>),
Str(Option<&'a str>),
}
impl MmdbAsnCode<'_> {
fn get_code(&self) -> String {
match self {
Self::Int(Some(code)) => code.to_string(),
Self::Str(Some(code)) => (*code).to_string(),
_ => String::new(),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/types/mmdb_country_entry.rs | src/mmdb/types/mmdb_country_entry.rs | use serde::Deserialize;
use crate::countries::types::country::Country;
#[derive(Deserialize)]
#[serde(transparent)]
pub struct MmdbCountryEntry<'a> {
#[serde(borrow)]
inner: MmdbCountryEntryInner<'a>,
}
impl MmdbCountryEntry<'_> {
pub fn get_country(&self) -> Country {
self.inner.get_country()
}
}
#[derive(Deserialize)]
#[serde(untagged)]
enum MmdbCountryEntryInner<'a> {
#[serde(borrow)]
Standard(StandardCountryEntry<'a>),
#[serde(borrow)]
Ipinfo(IpinfoCountryEntry<'a>),
}
impl MmdbCountryEntryInner<'_> {
fn get_country(&self) -> Country {
match self {
Self::Standard(StandardCountryEntry {
country: Some(StandardCountryEntryInner { iso_code: Some(c) }),
})
| Self::Ipinfo(IpinfoCountryEntry {
country_code: Some(c),
}) => Country::from_str(c),
_ => Country::ZZ,
}
}
}
#[derive(Deserialize)]
struct StandardCountryEntry<'a> {
#[serde(borrow)]
country: Option<StandardCountryEntryInner<'a>>,
}
#[derive(Deserialize)]
struct StandardCountryEntryInner<'a> {
iso_code: Option<&'a str>,
}
#[derive(Deserialize)]
struct IpinfoCountryEntry<'a> {
country_code: Option<&'a str>,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/types/mmdb_reader.rs | src/mmdb/types/mmdb_reader.rs | use std::net::IpAddr;
use std::sync::Arc;
use crate::location;
use crate::utils::error_logger::{ErrorLogger, Location};
use maxminddb::Reader;
use serde::Deserialize;
#[derive(Clone)]
pub struct MmdbReaders {
pub country: Arc<MmdbReader>,
pub asn: Arc<MmdbReader>,
}
pub enum MmdbReader {
Default(Reader<&'static [u8]>),
Custom(Reader<Vec<u8>>),
Empty,
}
impl MmdbReader {
pub fn from(mmdb_path: &String, default_mmdb: &'static [u8]) -> MmdbReader {
if let Ok(custom_reader) = maxminddb::Reader::open_readfile(mmdb_path) {
return MmdbReader::Custom(custom_reader);
}
match maxminddb::Reader::from_source(default_mmdb) {
Ok(default_reader) => MmdbReader::Default(default_reader),
err_res => {
let _ = err_res.log_err(location!());
MmdbReader::Empty
}
}
}
pub fn lookup<'a, T: Deserialize<'a>>(&'a self, ip: IpAddr) -> Option<T> {
match self {
MmdbReader::Default(reader) => reader.lookup(ip).and_then(|lr| lr.decode()).ok()?,
MmdbReader::Custom(reader) => reader.lookup(ip).and_then(|lr| lr.decode()).ok()?,
MmdbReader::Empty => None,
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/mmdb/types/mod.rs | src/mmdb/types/mod.rs | pub mod mmdb_asn_entry;
pub mod mmdb_country_entry;
pub mod mmdb_reader;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/translations.rs | src/translations/translations.rs | // EXTRA NEEDED CHARACTERS: Б
use iced::widget::Text;
use crate::StyleType;
use crate::translations::types::language::Language;
// pub fn choose_adapters_translation<'a>(language: Language) -> Text<'a, StyleType> {
// Text::new(match language {
// Language::EN => "Select network adapter to inspect",
// Language::CS => "Výběr síťového adaptéru ke kontrole",
// Language::IT => "Seleziona la scheda di rete da ispezionare",
// Language::FR => "Sélectionnez une carte réseau à inspecter",
// Language::ES => "Seleccione el adaptador de red que desea inspeccionar",
// Language::PL => "Wybierz adapter sieciowy do inspekcji",
// Language::DE => "Wähle einen Netzwerkadapter zum überwachen aus",
// Language::UK => "Виберіть мережевий адаптер для перевірки",
// Language::ZH => "选择需要监控的网络适配器",
// Language::ZH_TW => "選取要檢視的網路介面卡",
// Language::RO => "Selectați adaptor de rețea pentru a inspecta",
// Language::KO => "검사할 네트워크 어댑터 선택",
// Language::TR => "İncelemek için bir ağ adaptörü seçiniz",
// Language::RU => "Выберите сетевой адаптер для инспекции",
// Language::PT => "Selecione o adaptador de rede a inspecionar",
// Language::EL => "Επιλέξτε τον προσαρμογέα δικτύου για επιθεώρηση",
// // Language::FA => "مبدل شبکه را برای بازرسی انتخاب کنید",
// Language::SV => "Välj nätverksadapter att inspektera",
// Language::FI => "Valitse tarkasteltava verkkosovitin",
// Language::JA => "使用するネットワーク アダプターを選択してください",
// Language::UZ => "Tekshirish uchun tarmoq adapterini tanlang",
// Language::VI => "Hãy chọn network adapter để quan sát",
// Language::ID => "Pilih Adapter Jaringan yang ingin dicek",
// Language::NL => "Selecteer netwerkadapter om te inspecteren",
// })
// }
// pub fn application_protocol_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Application protocol",
// Language::CS => "Aplikační protokol",
// Language::IT => "Protocollo applicativo",
// Language::FR => "Protocole applicatif",
// Language::ES => "Protocolo de aplicación",
// Language::PL => "Protokół aplikacji",
// Language::DE => "Anwendungs-Protokoll",
// Language::UK => "Протокол застосування",
// Language::ZH => "目标应用层协议",
// Language::ZH_TW => "應用程式通訊協定",
// Language::RO => "Protocol aplicație",
// Language::KO => "어플리케이션 프로토콜",
// Language::TR => "Uygulama protokolü",
// Language::RU => "Прикладной протокол",
// Language::PT => "Protocolo de aplicação",
// Language::EL => "Πρωτόκολλο εφαρμογής",
// // Language::FA => "پیوندنامهٔ درخواست",
// Language::SV => "Applikationsprotokoll",
// Language::FI => "Sovellusprotokolla",
// Language::JA => "アプリケーション プロトコル",
// Language::UZ => "Ilova protokoli",
// Language::ID => "Protokol Aplikasi",
// Language::NL => "Toepassingsprotocol",
// }
// }
// pub fn select_filters_translation<'a>(language: Language) -> Text<'a, StyleType> {
// Text::new(match language {
// Language::EN => "Select filters to be applied on network traffic",
// Language::CS => "Výběr filtrů které budou použity na síťový provoz",
// Language::IT => "Seleziona i filtri da applicare al traffico di rete",
// Language::FR => "Sélectionnez les filtres à appliquer sur le traffic réseau",
// Language::ES => "Seleccionar los filtros que se aplicarán al tráfico de red",
// Language::PL => "Wybierz filtry, które mają być zastosowane na ruchu sieciowym",
// Language::DE => "Wähle die Filter, die auf den Netzwerkverkehr angewendet werden sollen",
// Language::UK => "Виберіть фільтри, які мають бути застосовані до мережевого руху",
// Language::ZH => "选择需要监控的目标",
// Language::ZH_TW => "選取要套用於網路流量的篩選器",
// Language::RO => "Selectați filtre pentru traficul de rețea",
// Language::KO => "네트워크 트레픽에 적용할 필터 선택",
// Language::TR => "Ağ trafiğine uygulanacak filtreleri seçiniz",
// Language::RU => "Выберите фильтры для применения к сетевому трафику",
// Language::PT => "Selecione os filtros a serem aplicados no tráfego de rede",
// Language::EL => "Επιλέξτε τα φίλτρα που θα εφαρμοστούν στην κίνηση του δικτύου",
// // Language::FA => "صافی ها را جهت اعمال بر آمد و شد شبکه انتخاب کنید",
// Language::SV => "Välj filtren som ska appliceras på nätverkstrafiken",
// Language::FI => "Valitse suodattimet verkkoliikenteelle",
// Language::JA => "トラフィックに適用するフィルターを選択してください",
// Language::UZ => "Tarmoq trafigiga qo'llaniladigan filtrlarni tanlang",
// Language::VI => "Hãy chọn bộ lọc cho lưu lượng mạng",
// Language::ID => "Pilih filter yang ingin dipasang dilalulintas jaringan",
// Language::NL => "Selecteer filters om toe te passen op netwerkverkeer",
// })
// }
pub fn start_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::DE | Language::RO | Language::KO | Language::NL | Language::CS => {
"Start!"
}
Language::IT => "Avvia!",
Language::FR => "Commencer!",
Language::ES => "¡Empieza!",
Language::PL => "Rozpocznij!",
Language::UK => "Почати!",
Language::ZH => "开始!",
Language::TR => "Başla!",
Language::RU => "Начать!",
Language::PT => "Começar!",
Language::EL => "Ξεκίνα!",
// Language::FA => "شروع!",
Language::SV => "Starta!",
Language::FI => "Aloita!",
Language::JA | Language::ZH_TW => "開始!",
Language::UZ => "Boshlash!",
Language::VI => "Bắt đầu!",
Language::ID => "Mulai!",
}
}
pub fn address_translation(language: Language) -> &'static str {
match language {
Language::EN => "Address",
Language::CS => "Adresa",
Language::IT => "Indirizzo",
Language::FR | Language::DE => "Adresse",
Language::ES => "Dirección",
Language::PL | Language::TR | Language::NL => "Adres",
Language::UK => "Адреса",
Language::ZH => "网络地址",
Language::ZH_TW => "網路位址",
Language::RO => "Adresă",
Language::KO => "주소",
Language::RU => "Адрес",
Language::PT => "Endereço",
Language::EL => "Διεύθυνση",
// Language::FA => "نشانی",
Language::SV => "Adress",
Language::FI => "Osoite",
Language::JA => "アドレス",
Language::UZ => "Manzil",
Language::VI => "Địa chỉ",
Language::ID => "Alamat",
}
}
// pub fn addresses_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Addresses",
// Language::IT => "Indirizzi",
// Language::FR => "Adresses",
// Language::ES => "Direcciones",
// Language::PL | Language::CS => "Adresy",
// Language::DE | Language::NL => "Adressen",
// Language::UK => "Адреси",
// Language::ZH => "网络地址",
// Language::ZH_TW => "網路位址",
// Language::RO => "Adrese",
// Language::KO => "주소",
// Language::TR => "Adresler",
// Language::RU => "Адреса",
// Language::PT => "Endereços",
// Language::EL => "Διευθύνσεις",
// // Language::FA => "نشانی ها",
// Language::SV => "Adresser",
// Language::FI => "Osoitteet",
// Language::JA => "アドレス",
// Language::UZ => "Manzillar",
// Language::VI => "Danh sách địa chỉ",
// Language::ID => "Alamat",
// }
// }
// pub fn ip_version_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "IP version",
// Language::CS => "Verze IP",
// Language::IT => "Versione IP",
// Language::FR => "Version IP",
// Language::ES => "Versión IP",
// Language::PL => "Wersja IP",
// Language::DE => "IP Version",
// Language::UK => "Версія IP",
// Language::ZH => "目标IP协议版本",
// Language::ZH_TW => "IP 版本",
// Language::RO => "Versiune IP",
// Language::KO => "IP 버전",
// Language::TR => "IP versiyonu",
// Language::RU => "Версия IP",
// Language::PT => "Versão de IP",
// Language::EL => "Έκδοση IP",
// // Language::FA => "نسخهٔ IP",
// Language::SV => "IP-version",
// Language::FI => "IP-versio",
// Language::JA => "IP バージョン",
// Language::UZ => "IP versiyasi",
// Language::VI => "Phiên bản IP",
// Language::ID => "Versi IP",
// Language::NL => "IP versie",
// }
// }
// pub fn transport_protocol_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Transport protocol",
// Language::CS => "Transportní protokol",
// Language::IT => "Protocollo di trasporto",
// Language::FR => "Protocole de transport",
// Language::ES | Language::PT => "Protocolo de transporte",
// Language::PL => "Protokół transportowy",
// Language::DE => "Netzwerkprotokoll",
// Language::UK => "Транспортний протокол",
// Language::ZH => "目标传输协议",
// Language::ZH_TW => "傳輸通訊協定",
// Language::RO => "Protocol de transport",
// Language::KO => "전송 프로토콜",
// Language::TR => "İletişim protokolü",
// Language::RU => "Транспортный протокол",
// Language::EL => "Πρωτόκολλο μεταφοράς",
// // Language::FA => "پیوندنامهٔ ترابرد",
// Language::SV => "Transportprotokoll",
// Language::FI => "Kuljetusprotokolla",
// Language::JA => "トランスポート プロトコル",
// Language::UZ => "Transport protokoli",
// Language::ID => "Protokol berjalan",
// Language::NL => "Transportprotocol",
// }
// }
pub fn protocol_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::RO | Language::NL => "Protocol",
Language::IT => "Protocollo",
Language::FR => "Protocole",
Language::ES | Language::PT => "Protocolo",
Language::PL => "Protokół",
Language::DE | Language::SV => "Protokoll",
Language::UK | Language::RU => "Протокол",
Language::ZH => "协议",
Language::ZH_TW => "通訊協定",
Language::KO => "프로토콜",
Language::TR => "Protokolü",
Language::EL => "Πρωτόκολλο",
// Language::FA => "پیوندنامهٔ",
Language::FI => "Protokolla",
Language::JA => "プロトコル",
Language::UZ => "Protokoli",
Language::VI => "Phương thức",
Language::ID | Language::CS => "Protokol",
}
}
pub fn traffic_rate_translation<'a>(language: Language) -> Text<'a, StyleType> {
Text::new(match language {
Language::EN => "Traffic rate",
Language::CS => "Intenzita provozu",
Language::IT => "Intensità del traffico",
Language::FR => "Fréquence du traffic",
Language::ES => "Tasa de tráfico",
Language::PL => "Prędkość ruchu",
Language::DE => "Daten Frequenz",
Language::UK => "Швидкість руху",
Language::ZH => "网络速率图",
Language::ZH_TW => "流量速率",
Language::RO => "Rata de trafic",
Language::KO => "트레픽 속도",
Language::TR => "Trafik oranı",
Language::RU => "Cкорость трафика",
Language::PT => "Taxa de tráfego",
Language::EL => "Ρυθμός κίνησης",
// Language::FA => "نرخ آمد و شد",
Language::SV => "Datafrekvens",
Language::FI => "Liikennemäärä",
Language::JA => "トラフィック レート",
Language::UZ => "Trafik tezligi",
Language::VI => "Lưu lượng truy cập",
Language::ID => "Tingkat lalulintas",
Language::NL => "Verkeerssnelheid",
})
}
// pub fn relevant_connections_translation(language: Language) -> Text<StyleType> {
// Text::new(match language {
// Language::EN => "Relevant connections:",
// Language::CS => "Relevantní spojení:",
// Language::IT => "Connessioni rilevanti:",
// Language::FR => "Connexions pertinentes:",
// Language::ES => "Conexiones Relevantes:",
// Language::PL => "Istotne połączenia:",
// Language::DE => "Relevante Verbindungen:",
// Language::UK => "Важливі підключення:",
// Language::ZH => "连接详情:",
// Language::ZH_TW => "相關連線:",
// Language::RO => "Conexiuni relevante:",
// Language::KO => "관련 연결:",
// Language::TR => "İlgili bağlantılar:",
// Language::RU => "Важные подключения:",
// Language::PT => "Conexões relevantes:",
// Language::EL => "Σχετικές συνδέσεις:",
// Language::FA => "پیوند های خویشاوند:",
// Language::SE => "Relevanta anslutningar:",
// Language::UZ => "Tegishli ulanishlar:",
// Language::ID => "Koneksi yang berkaitan",
// Language::NL => "Relevante verbindingen:",
// })
// }
pub fn settings_translation(language: Language) -> &'static str {
match language {
Language::EN => "Settings",
Language::CS => "Nastavení",
Language::IT => "Impostazioni",
Language::FR => "Paramètres",
Language::ES => "Ajustes",
Language::PL => "Ustawienia",
Language::DE => "Einstellungen",
Language::UK => "Налаштування",
Language::ZH => "设置",
Language::RO => "Setări",
Language::KO => "설정",
Language::TR => "Ayarlar",
Language::RU => "Настройки",
Language::PT => "Configurações",
Language::EL => "Ρυθμίσεις",
// Language::FA => "پیکربندی",
Language::SV => "Inställningar",
Language::FI => "Asetukset",
Language::JA | Language::ZH_TW => "設定",
Language::UZ => "Sozlamalar",
Language::VI => "Cài đặt",
Language::ID => "Pengaturan",
Language::NL => "Instellingen",
}
}
pub fn yes_translation<'a>(language: Language) -> Text<'a, StyleType> {
Text::new(match language {
Language::EN => "Yes",
Language::CS => "Ano",
Language::IT => "Sì",
Language::FR => "Oui",
Language::ES => "Sí",
Language::PL => "Tak",
Language::DE | Language::SV | Language::NL => "Ja",
Language::UK => "Так",
Language::ZH | Language::ZH_TW => "是",
Language::RO => "Da",
Language::KO => "네",
Language::TR => "Evet",
Language::RU => "Да",
Language::PT => "Sim",
Language::EL => "Ναι",
// Language::FA => "بله",
Language::FI => "Kyllä",
Language::JA => "はい",
Language::UZ => "Ha",
Language::VI => "Chấp nhận",
Language::ID => "Ya",
})
}
pub fn ask_quit_translation<'a>(language: Language) -> Text<'a, StyleType> {
Text::new(match language {
Language::EN => "Are you sure you want to quit this analysis?",
Language::CS => "Opravdu ukončit tuto analýzu?",
Language::IT => "Sei sicuro di voler interrompere questa analisi?",
Language::FR => "Êtes-vous sûr de vouloir quitter l'application ?",
Language::ES => "¿Estás seguro de que quieres dejar este análisis?",
Language::PL => "Jesteś pewien, że chcesz zakończyć analizę?",
Language::DE => "Bist du sicher, dass du diese Analyse beenden willst?",
Language::UK => "Чи справді хочете закінчити аналіз?",
Language::ZH => "您确定退出当前监控吗?",
Language::ZH_TW => "您確定要結束目前的分析嗎?",
Language::RO => "Sunteți sigur că doriți să renunțați la această analiză?",
Language::KO => "정말로 분석을 종료하겠습니까?",
Language::TR => "Bu analizden çıkmak istediğine emin misin?",
Language::RU => "Вы уверены, что хотите выйти из текущего анализа?",
Language::PT => "Tem a certeza que deseja sair desta análise?",
Language::EL => "Είστε βέβαιοι ότι θέλετε να τερματίσετε την ανάλυση;",
// Language::FA => "آیا مطمئن هستید می خواهید از این تحلیل خارج شوید؟",
Language::SV => "Är du säker på att du vill avsluta analysen?",
Language::FI => "Haluatko varmasti lopettaa analyysin?",
Language::JA => "分析を終了しますか?",
Language::UZ => "Tahlildan chiqishga ishonchingiz komilmi?",
Language::VI => "Bạn có chắc là muốn thoát phiên phân tích này?",
Language::ID => "Apa kamu yakin untuk berhenti analisa?",
Language::NL => "Weet je zeker dat je deze analyse wilt afsluiten?",
})
}
pub fn quit_analysis_translation(language: Language) -> &'static str {
match language {
Language::EN => "Quit analysis",
Language::CS => "Ukončit analýzu",
Language::IT => "Interrompi analisi",
Language::FR => "Quitter l'analyse",
Language::ES => "Quitar el análisis",
Language::PL => "Zakończ analize",
Language::DE => "Analyse beenden",
Language::UK => "Закінчити аналіз",
Language::ZH => "退出监控",
Language::ZH_TW => "結束分析",
Language::RO => "Renunță la analiză",
Language::KO => "분석종료",
Language::TR => "Analizden çık",
Language::RU => "Закончить анализ",
Language::PT => "Sair da análise",
Language::EL => "Έξοδος ανάλυσης",
// Language::FA => "خروج از تحلیل",
Language::SV => "Avsluta analys",
Language::FI => "Lopeta analyysi",
Language::JA => "分析の終了",
Language::UZ => "Tahlildan chiqish",
Language::VI => "Thoát phiên phân tích",
Language::ID => "Berhenti analisa",
Language::NL => "Analyse afsluiten",
}
}
pub fn ask_clear_all_translation<'a>(language: Language) -> Text<'a, StyleType> {
Text::new(match language {
Language::EN => "Are you sure you want to clear notifications?",
Language::CS => "Opravdu chcete vyčistit notifikace?",
Language::IT => "Sei sicuro di voler eliminare le notifiche?",
Language::FR => "Êtes-vous sûr de vouloir effacer les notifications ?",
Language::ES => "¿Seguro que quieres borrar las notificaciones?",
Language::PL => "Czy na pewno chcesz wyczyścić powiadomienia?",
Language::DE => "Bist du sicher, dass du alle Benachrichtigungen löschen willst?",
Language::UK => "Чи справді хочете видалити всі повідомлення?",
Language::ZH => "确定清除所有通知?",
Language::ZH_TW => "您確定要清除所有通知嗎?",
Language::RO => "Sigur doriți să ștergeți notificările?",
Language::KO => "알림을 삭제하시겠습니까?",
Language::TR => "Bildirimleri temizlemek istediğine emin misin?",
Language::RU => "Вы уверены, что хотите удлить все уведомления?",
Language::PT => "Tem a certeza que deseja eliminar as notificações?",
Language::EL => "Είστε βέβαιοι ότι θέλετε να εκκαθαρίσετε τις ειδοποιήσεις;",
// Language::FA => "آیا مطمئن هستید می خواهید اعلان ها را پاک کنید؟",
Language::SV => "Är du säker på att du vill radera notifikationerna?",
Language::FI => "Haluatko varmasti tyhjentää ilmoitukset?",
Language::JA => "すべての通知を削除します。よろしいですか?",
Language::UZ => "Haqiqatan ham bildirishnomalarni tozalamoqchimisiz?",
Language::VI => "Bạn có chắc là muốn xóa các thông báo?",
Language::ID => "Apa kamu yakin untuk membersihkan notifikasi?",
Language::NL => "Weet je zeker dat je alle meldingen wilt wissen?",
})
}
pub fn clear_all_translation(language: Language) -> &'static str {
match language {
Language::EN => "Clear all",
Language::CS => "Vyčistit vše",
Language::IT => "Elimina tutto",
Language::FR => "Tout effacer",
Language::ES => "Borrar todo",
Language::PL => "Wyczyść wszystko",
Language::DE => "Alle löschen",
Language::UK => "Видалити все",
Language::ZH | Language::ZH_TW => "清除所有",
Language::RO => "Ștergeți tot",
Language::KO => "모두 지우기",
Language::TR => "Hepsini temizle",
Language::RU => "Очистить всё",
Language::PT => "Limpar tudo",
Language::EL => "Εκκαθάριση όλων",
// Language::FA => "پاک کردن همه",
Language::SV => "Radera alla",
Language::FI => "Tyhjennä kaikki",
Language::JA => "すべて削除",
Language::UZ => "Barchasini tozalash",
Language::VI => "Xóa tất cả",
Language::ID => "Bersihkan semua",
Language::NL => "Alles wissen",
}
}
pub fn hide_translation(language: Language) -> &'static str {
match language {
Language::EN => "Hide",
Language::CS => "Skrýt",
Language::IT => "Nascondi",
Language::FR => "Masquer",
Language::ES => "Ocultar",
Language::PL => "Ukryj",
Language::DE => "Verstecken",
Language::UK => "Заховати",
Language::ZH => "隐藏",
Language::ZH_TW => "隱藏",
Language::RO => "Ascundeți",
Language::KO => "숨기기",
Language::TR => "Gizle",
Language::RU => "Скрыть",
Language::PT => "Esconder",
Language::EL => "Κλείσιμο",
// Language::FA => "پنهان کردن",
Language::SV => "Göm",
Language::FI => "Piilota",
Language::JA => "隠す",
Language::UZ => "Yashirish",
Language::VI => "Ẩn",
Language::ID => "Sembunyikan",
Language::NL => "Verbergen",
}
}
pub fn network_adapter_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::VI => "Network adapter",
Language::CS => "Síťový adaptér",
Language::IT => "Adattatore di rete",
Language::FR => "Carte réseau",
Language::ES => "Adaptador de red",
Language::PL => "Adapter sieciowy",
Language::DE => "Netzwerkadapter",
Language::UK => "Мережевий адаптер",
Language::ZH => "网络适配器",
Language::ZH_TW => "網路介面卡",
Language::RO => "Adaptor de rețea",
Language::KO => "네트워크 어뎁터",
Language::TR => "Ağ adaptörü",
Language::RU => "Сетевой интерфейс",
Language::PT => "Adaptador de rede",
Language::EL => "Προσαρμογέας δικτύου",
// Language::FA => "مبدل شبکه",
Language::SV => "Nätverksadapter",
Language::FI => "Verkkosovitin",
Language::JA => "ネットワーク アダプター",
Language::UZ => "Tarmoq adapteri",
Language::ID => "Adapter jaringan",
Language::NL => "Netwerkadapter",
}
}
#[allow(clippy::too_many_lines)]
pub fn no_addresses_translation(language: Language) -> &'static str {
match language {
Language::EN => {
"No traffic can be observed because the adapter you selected has no active addresses...\n\n\
If you are sure you are connected to the internet, try choosing a different adapter."
}
Language::CS => {
"Nelze sledovat žádný provoz, protože vybraný adaptér nemá žádné aktivní adresy...\n\n\
Pokud jste si jisti, že jste připojeni k internetu, zkuste vybrat jiný adaptér."
}
Language::IT => {
"Non è osservabile alcun traffico perché l'adattatore di rete selezionato non ha indirizzi attivi...\n\n\
Se sei sicuro di essere connesso ad internet, prova a scegliere un adattatore diverso."
}
Language::FR => {
"Aucun trafic ne peut être observé, car la carte réseau que vous avez saisie n'a pas d'adresse...\n\n\
Si vous êtes sûr d'être connecté à internet, essayez une autre carte."
}
Language::ES => {
"No se puede observar ningún tráfico porque el adaptador seleccionado no tiene direcciones activas...\n\n\
Si estás seguro de que estás conectado a Internet, prueba a elegir otro adaptador."
}
Language::PL => {
"Nie można zaobserwować żadnego ruchu, ponieważ wybrany adapter nie ma aktywnych adresów...\n\n\
Jeśli jesteś pewien, że jesteś podłączony do internetu, spróbuj wybrać inny adapter."
}
Language::DE => {
"Es kann kein Netzwerkverkehr beobachtet werden, weil der Adapter keine aktiven Adressen hat...\n\n\
Wenn du dir sicher bist, dass du mit dem Internet verbunden bist, probier einen anderen Adapter auszuwählen."
}
Language::UK => {
"Не зафіксовано жодного мережевого руху, тому що вибраний адаптер не має активних адрес... \n\n\
Якщо ви впевнені, що підключені до інтернету, спробуйте вибрати інший адаптер."
}
Language::ZH => {
"您选择的网络适配器当前无活动网络...\n\n\
如果您确信您已成功连接互联网, 请尝试选择其他网络适配器."
}
Language::ZH_TW => {
"無法觀察到任何流量,因為您選取的網路介面卡沒有有效的位址...\n\n\
如果您確定已連線至網際網路,請嘗試選取其他網路介面卡。"
}
Language::RO => {
"Niciun trafic nu poate fi observat deoarece adaptorul selectat nu are adrese active...\n\n\
Dacă sunteți sigur că sunteți conectat la internet, încercați să alegeți un alt adaptor."
}
Language::KO => {
"선택한 어댑터에 유효한 주소가 없기 때문에 트래픽을 확인할 수 없습니다...\n\n\
인터넷이 연결되어있다면 다른 어댑터로 시도해보세요."
}
Language::TR => {
"Seçtiğiniz adaptör aktif bir adrese sahip olmadığı için hiç bir trafik izlenemez...\n\n\
Eğer gerçekten internete bağlı olduğunuza eminseniz, başka bir adaptör seçmeyi deneyiniz."
}
Language::RU => {
"Наблюдение за трафиком не возможно, потому что Вы выбрали интерфейс без активного адреса...\n\n\
Если Вы уверены, что подключены к Интернету, попробуйте выбрать другой интерфейс."
}
Language::PT => {
"Não é possível observar tráfego porque o adaptador que selecionou não tem endereços ativos...\n\n\
Se tiver a certeza que está ligado à internet, tente escolher um adaptador diferente."
}
Language::EL => {
"Δεν μπορεί να ανιχνευθεί κίνηση επειδή ο προσαρμογέας που επέλεξες δεν έχει ενεργές διευθύνσεις...\n\n\
Αν είσαι σίγουρος ότι είσαι συνδεδεμένος στο διαδίκτυο, δοκίμασε αν επιλέξεις έναν διαφορετικό προσαρμογέα."
}
// Language::FA => format!("هیچ آمد و شدی قابل مشاهده نیست چون مبدلی که انتخاب کرده اید هیچ نشانی فعالی ندارد...\n\n\
// مبدل شبکه: {adapter}\n\n\
// اگر مطمئن هستید به اینترنت وصل هستید، سعی کنید مبدل متفاوتی را انتخاب کنید."),
Language::SV => {
"Det går inte att observa någon trafik eftersom den valda adaptern inte har några aktiva adresser ...\n\n\
Om du är säker att du är ansluten till internet, testa att välja en annan adapter."
}
Language::FI => {
"Liikennettä ei voitu havainnoida, koska valitulla sovittimella ei ole aktiivista osoitetta...\n\n\
Jos olet varma että sinulla on internet-yhteys, kokeile valita toinen verkkosovitin."
}
Language::JA => {
"選択されたアダプターが有効なアドレスを持っていないため、トラフィックを観測できていません...\n\n\
インターネットに接続しているか確認し、別のネットワーク アダプターを試してください。"
}
Language::UZ => {
"Trafik kuzatilmaydi, chunki siz tanlagan adapterda faol manzillar yo'q...\n\n\
Internetga ulanganingizga ishonchingiz komil bo'lsa, boshqa adapterni tanlashga harakat qiling"
}
Language::VI => {
"Không thể quan sát lưu lượng nào vì adapter mà bạn chọn không địa chỉ hoạt động...\n\n\
Nếu bạn đã chắc chắn kết nối với internet, hãy thử chọn network adapter khác."
}
Language::ID => {
"Tidak ada sinyal yang bisa dilihat karena adapter yang kamu pilih tidak memiliki alamat yang aktif...\n\n\
Jika kamu yakin kamu terhubung ke internet, coba untuk memilih adapter lainnya."
}
Language::NL => {
"Er kan geen verkeer worden waargenomen omdat de geselecteerde adapter geen actieve adressen heeft...\n\n\
Als je zeker weet dat je verbonden bent met het internet, probeer dan een andere adapter te kiezen."
}
}
}
#[allow(clippy::too_many_lines)]
pub fn waiting_translation(language: Language) -> &'static str {
match language {
Language::EN => {
"No traffic has been observed yet. Waiting for network packets...\n\n\
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | true |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/translations_3.rs | src/translations/translations_3.rs | #![allow(clippy::match_same_arms, clippy::match_wildcard_for_single_variants)]
use crate::Language;
// This is referred to settings (General settings)
pub fn general_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::RO => "General",
Language::CS => "Hlavní",
// Language::FA => "عمومی",
Language::ES => "Generales",
Language::IT => "Generali",
Language::FR => "Général",
Language::DE => "Allgemein",
Language::PL => "Ogólne",
Language::RU => "Общие",
Language::JA => "一般",
Language::UZ => "Asosiy",
Language::SV => "Allmänt",
Language::VI => "Tổng quan",
Language::ZH => "通用",
Language::ZH_TW => "一般",
Language::KO => "일반",
Language::TR => "Genel",
Language::PT => "Geral",
Language::UK => "Загальні",
Language::ID => "Umum",
Language::NL => "Algemeen",
Language::EL => "Γενικά",
_ => "General",
}
}
pub fn zoom_translation(language: Language) -> &'static str {
match language {
Language::EN
| Language::IT
| Language::ES
| Language::FR
| Language::DE
| Language::RO
| Language::PT
| Language::NL
| Language::SV => "Zoom",
Language::CS => "Přiblížení",
// Language::FA => "بزرگنمایی",
Language::PL => "Powiększenie",
Language::RU => "Масштаб интерфейса",
Language::JA => "ズーム",
Language::UZ => "Kattalashtirish",
Language::VI => "Phóng to",
Language::ZH => "缩放",
Language::ZH_TW => "縮放",
Language::KO => "확대",
Language::TR => "Yakınlaştırma",
Language::UK => "Масштабування",
Language::ID => "Perbesar",
Language::EL => "Εστίαση",
_ => "Zoom",
}
}
pub fn mmdb_files_translation(language: Language) -> &'static str {
match language {
Language::EN => "Database files",
Language::CS => "Databázové soubory",
// Language::FA => "پرونده های پایگاه داده",
Language::ES => "Archivos de la base de datos",
Language::IT => "File di database",
Language::FR => "Fichiers de la base de données",
Language::DE => "Datenbank Dateien",
Language::PL => "Pliki bazy danych",
Language::RU => "Файлы базы данных",
Language::RO => "Fișiere bază de date",
Language::JA => "データベース ファイル",
Language::UZ => "Ma'lumotlar bazasi fayllari",
Language::SV => "Databasfiler",
Language::VI => "Tập tin cơ sở dữ liệu",
Language::ZH => "数据库文件",
Language::ZH_TW => "資料庫檔案",
Language::KO => "데이터베이스 파일",
Language::TR => "Veri tabanı dosyaları",
Language::PT => "Arquivos da base de dados",
Language::UK => "Файли бази даних",
Language::ID => "Berkas database",
Language::NL => "Database bestanden",
Language::EL => "Αρχεία βάσης δεδομένων",
_ => "Database files",
}
}
pub fn params_not_editable_translation(language: Language) -> &'static str {
match language {
Language::EN => "The following parameters can't be modified during the analysis",
Language::CS => "Následující parametry nelze během analýzy měnit",
// Language::FA => "مولفه های روبرو هنگام تحلیل قابل تغییر نیستند",
Language::ES => "Los siguientes parámetros no pueden modificarse durante el análisis",
Language::IT => "I seguenti parametri non sono modificabili durante l'analisi",
Language::FR => "Les paramètres suivants ne peuvent pas être modifiés durant l'analyse",
Language::DE => "Die folgenden Parameter können während der Analyse nicht verändert werden",
Language::PL => "Następujące parametry nie mogą być modyfikowane podczas analizy",
Language::RU => "Следующие параметры не могут быть изменены во время анализа трафика",
Language::RO => "Următorii parametri nu sunt modificabili în timpul analizei",
Language::JA => "以下のパラメーターは分析中は変更できません",
Language::UZ => "Tahlil vaqtida quyidagi parametrlarni o'zgartirib bo'lmaydi",
Language::SV => "Följande parametrar kan inte ändras under analysen",
Language::VI => "Các tham số sau không thể bị thay đổi khi đang phân tích",
Language::ZH => "以下参数在分析过程中不能修改",
Language::ZH_TW => "以下參數在分析期間無法修改",
Language::KO => "분석 중 다음의 매개변수들은 수정할 수 없습니다",
Language::TR => "Analiz sırasında bu parametrelere müdahale edilemez",
Language::PT => "Os seguintes parâmetros não podem ser modificados durante a análise",
Language::UK => "Наступні параметри не можна змінювати під час аналізу трафіку",
Language::ID => "Parameter berikut tidak bisa diubah saat dianalisa",
Language::NL => "De volgende parameters kunnen niet worden aangepast tijdens de analyse",
Language::EL => {
"Οι ακόλουθες παράμετροι δεν μπορούν να τροποποιηθούν κατά τη διάρκεια της ανάλυσης"
}
_ => "The following parameters can't be modified during the analysis",
}
}
pub fn custom_style_translation(language: Language) -> &'static str {
match language {
Language::EN => "Custom style",
Language::CS => "Vlastní styl",
// Language::FA => "شیوه سفارشی",
Language::ES | Language::PT => "Estilo personalizado",
Language::IT => "Stile personalizzato",
Language::FR => "Style personnalisé",
Language::DE => "Benutzerdefinierter Stil",
Language::PL => "Niestandardowy styl",
Language::RU => "Свой стиль",
Language::RO => "Temă personalizată",
Language::JA => "カスタム スタイル",
Language::UZ => "Moslashtirilgan uslub",
Language::SV => "Anpassad stil",
Language::VI => "Tùy chỉnh chủ đề",
Language::ZH => "自定义样式",
Language::ZH_TW => "自訂佈景主題",
Language::KO => "사용자 지정 스타일",
Language::TR => "Kişisel görünüm",
Language::UK => "Власний стиль",
Language::ID => "Ubah Model",
Language::NL => "Aangepaste stijl",
Language::EL => "Προσαρμοσμένο στυλ",
_ => "Custom style",
}
}
pub fn copy_translation(language: Language) -> &'static str {
match language {
Language::EN => "Copy",
Language::CS => "Kopírovat",
// Language::FA => "رونوشت",
Language::IT | Language::ES => "Copia",
Language::FR | Language::RO => "Copie",
Language::DE => "Kopieren",
Language::PL => "Kopiuj",
Language::RU => "Скопировать",
Language::JA => "コピー",
Language::UZ => "Nusxalash",
Language::SV => "Kopia",
Language::VI => "Sao chép",
Language::ZH => "复制",
Language::ZH_TW => "複製",
Language::KO => "복사",
Language::TR => "Kopyala",
Language::PT => "Copiar",
Language::UK => "Копіювати",
Language::ID => "Salin",
Language::NL => "Kopiëren",
Language::EL => "Αντιγραφή",
_ => "Copy",
}
}
pub fn port_translation(language: Language) -> &'static str {
match language {
Language::EN
| Language::CS
| Language::FR
| Language::DE
| Language::PL
| Language::RO
| Language::UZ
| Language::SV
| Language::TR => "Port",
// Language::FA => "درگاه",
Language::ES => "Puerto",
Language::IT | Language::PT => "Porta",
Language::RU => "Порт",
Language::JA => "ポート",
Language::VI => "Cổng",
Language::ZH => "端口",
Language::ZH_TW => "連接埠",
Language::KO => "포트",
Language::UK => "Порт",
Language::ID => "Port",
Language::NL => "Poort",
Language::EL => "Θύρα",
_ => "Port",
}
}
// pub fn invalid_filters_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Invalid filters",
// Language::CS => "Neplatné filtry",
// // Language::FA => "صافی نامعتبر",
// Language::ES | Language::PT => "Filtros inválidos",
// Language::IT => "Filtri non validi",
// Language::FR => "Filtres invalides",
// Language::DE => "Ungültige Filter",
// Language::PL => "Nieprawidłowe filtry",
// Language::RU => "Неверный формат фильтров",
// Language::RO => "Filtre invalide",
// Language::JA => "無効なフィルター",
// Language::UZ => "Noto'g'ri filterlar",
// Language::SV => "Ogiltiga filter",
// Language::VI => "Bộ lọc không khả dụng",
// Language::ZH => "无效的过滤器",
// Language::ZH_TW => "無效的篩選器",
// Language::KO => "잘못된 필터",
// Language::TR => "Geçersiz filtreler",
// Language::UK => "Неправильний формат фільтрів",
// Language::ID => "Filter salah",
// Language::NL => "Ongeldige filters",
// Language::EL => "Μη έγκυρα φίλτρα",
// _ => "Invalid filters",
// }
// }
pub fn messages_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::FR => "Messages",
Language::CS => "Zprávy",
// Language::FA => "پیام ها",
Language::ES => "Mensajes",
Language::IT => "Messaggi",
Language::DE => "Nachrichten",
Language::PL => "Wiadomości",
Language::RU => "Сообщения",
Language::RO => "Mesaje",
Language::JA => "メッセージ",
Language::UZ => "Xabarlar",
Language::SV => "Meddelanden",
Language::VI => "Tin nhắn",
Language::ZH => "信息",
Language::ZH_TW => "訊息",
Language::KO => "메시지",
Language::TR => "Mesajlar",
Language::PT => "Mensagens",
Language::UK => "Повідомлення",
Language::ID => "Pesan",
Language::NL => "Berichten",
Language::EL => "Μηνύματα",
_ => "Messages",
}
}
pub fn link_type_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::NL => "Link type",
Language::CS => "Typ linky",
// Language::FA => "نوع پیوند",
Language::ES => "Tipo de conexión",
Language::IT => "Tipo di collegamento",
Language::FR => "Type de connexion",
Language::DE => "Verbindungsart",
Language::PL => "Rodzaj połączenia", // "Typ łącza"?
Language::RU => "Тип соединения",
Language::RO => "Tipul conexiunii",
Language::JA => "リンク タイプ",
Language::UZ => "Havola turi",
Language::SV => "Länktyp",
Language::VI => "Loại liên kết",
Language::ZH => "链接类型",
Language::ZH_TW => "連線類型",
Language::KO => "링크 유형",
Language::TR => "Link türü",
Language::PT => "Tipo de conexão",
Language::UK => "Різновид зʼєднання",
Language::ID => "Tipe koneksi",
Language::EL => "Τύπος σύνδεσης",
_ => "Link type",
}
}
pub fn unsupported_link_type_translation(language: Language) -> &'static str {
match language {
Language::EN => {
"The link type associated with this adapter is not supported by Sniffnet yet..."
}
Language::CS => {
"Typ linky přidružený k tomuto adaptéru zatím není Sniffnetem podporován...."
}
// Language::FA => "نوع پیوند مرتبط با این مبدل هنوز توسط Sniffnet پشتیبانی نمی شود...",
Language::ES => {
"La conexión asociada a este adaptador aún no está soportada por Sniffnet..."
}
Language::IT => {
"Il tipo di collegamento associato a questo adattatore di rete non è ancora supportato da Sniffnet..."
}
Language::FR => {
"Le type de connexion associé à cet adaptateur n'est pas encore supporté par Sniffnet..."
}
Language::DE => {
"Die Verbindungsart dieses Adapters wird noch nicht von Sniffnet unterstützt..."
}
Language::PL => {
"Rodzaj połączenia powiązany z tym adapterem nie jest jeszcze obsługiwany przez Sniffnet..."
}
Language::RU => {
"Тип соединения, связанный с этим адаптером, пока не поддерживается Sniffnet..."
}
Language::RO => {
"Tipul conexiunii asociate acestui adaptor de rețea nu este încă suportat de Sniffnet..."
}
Language::JA => {
"このアダプターのリンク タイプは Sniffnet ではまだサポートされていません..."
}
Language::UZ => {
"Ushbu adapter bilan bog'langan havola turi hozircha Sniffnet tomonidan qo'llab quvvatlanmaydi..."
}
Language::SV => "Länktypen associerad med denna adapter stöds inte av Sniffnet än...",
Language::VI => "Loại liên kết được gắn với adapter này chưa được Sniffnet hỗ trợ...",
Language::ZH => "Sniffnet 尚不支持与此适配器关联的链接类型...",
Language::ZH_TW => "Sniffnet 目前尚不支援與此網路介面卡相關的連線類型...",
Language::KO => "이 어댑터와 연결된 링크 유형은 Sniffnet에서 아직 지원되지 않습니다...",
Language::TR => {
"Bu adaptör ile ilişkilendirilmiş link türü henüz Sniffnet tarafından desteklenmiyor..."
}
Language::PT => {
"O tipo de conexão associado com este adaptador não é suportado pelo Sniffnet ainda..."
}
Language::UK => {
"Різновид зʼєднання, повʼязаний з даним адаптером, ще не підтримується Sniffnet-ом..."
}
Language::ID => {
"Tipe koneksi yang terhubung dengan adaptor ini belum didukung oleh Sniffnet"
}
Language::NL => {
"Het linktype dat is gekoppeld aan deze adapter wordt nog niet ondersteund door Sniffnet..."
}
Language::EL => {
"Ο τύπος σύνδεσης που σχετίζεται με αυτόν τον προσαρμογέα δεν υποστηρίζεται ακόμη από το Sniffnet..."
}
_ => "The link type associated with this adapter is not supported by Sniffnet yet...",
}
}
pub fn style_from_file_translation(language: Language) -> &'static str {
match language {
Language::EN => "Select style from a file",
Language::CS => "Výběr stylu ze souboru",
// Language::FA => "انتخاب شیوه از یک پرونده",
Language::ES => "Selecciona el estilo desde un archivo",
Language::IT => "Seleziona lo stile da un file",
Language::FR => "Sélectionner un style à partir d'un fichier",
Language::DE => "Stil aus einer Datei wählen",
Language::PL => "Wybierz styl z pliku",
Language::RU => "Выберите тему из файла",
Language::RO => "Selectează tema dintr-un fișier",
Language::JA => "ファイルからスタイルを選択してください",
Language::UZ => "Fayldan uslubni tanlang",
Language::SV => "Välj stil från en fil",
Language::VI => "Chọn chủ đề từ file của bạn",
Language::ZH => "从文件中选择样式",
Language::ZH_TW => "從檔案中選擇佈景主題",
Language::KO => "파일에서 스타일을 선택하세요",
Language::TR => "Dosyadan bir görünüm seç",
Language::PT => "Selecionar estilo a partir de um arquivo",
Language::UK => "Виберіть стиль з файлу",
Language::ID => "Pilih model / gaya dari berkas",
Language::NL => "Selecteer stijl vanuit een bestand",
Language::EL => "Επιλογή στυλ από αρχείο",
_ => "Select style from a file",
}
}
pub fn database_from_file_translation(language: Language) -> &'static str {
match language {
Language::EN => "Select database file",
Language::CS => "Výběr souboru databáze",
// Language::FA => "پرونده پایگاه داده را انتخاب کنید",
Language::ES => "Selecciona un archivo de base de datos",
Language::IT => "Seleziona file di database",
Language::FR => "Sélection d'un fichier de base de données",
Language::DE => "Datenbank Datei auswählen",
Language::PL => "Wybierz plik bazy danych",
Language::RU => "Выберите файл базы данных",
Language::RO => "Selectează fișier bază de date",
Language::JA => "データベース ファイルを選択してください",
Language::UZ => "Ma'lumotlar bazasi faylini tanlang",
Language::SV => "Välj databasfil",
Language::VI => "Chọn tập tin cơ sở dữ liệu",
Language::ZH => "选择数据库文件",
Language::ZH_TW => "選擇資料庫檔案",
Language::KO => "데이터베이스 파일 선택",
Language::TR => "Veri tabanı dosyası seç",
Language::PT => "Selecione um arquivo de base de dados",
Language::UK => "Виберіть файл бази даних",
Language::ID => "Pilih berkas database",
Language::NL => "Selecteer database bestand",
Language::EL => "Επιλογή αρχείου βάσης δεδομένων",
_ => "Select database file",
}
}
pub fn filter_by_host_translation(language: Language) -> &'static str {
match language {
Language::EN => "Filter by network host",
Language::CS => "Filtrovat podle síťového hostitele",
// Language::FA => "صافی بر اساس میزبان شبکه",
Language::ES => "Filtra por host de red",
Language::IT => "Filtra per host di rete",
Language::FR => "Filtrer par réseau hôte",
Language::DE => "Nach Netzwerk-Host filtern",
Language::PL => "Filtruj według hosta sieciowego",
Language::RU => "Фильтр по сетевому хосту",
Language::RO => "Filtrează după host-ul de rețea",
Language::JA => "ネットワーク ホストでフィルター",
Language::UZ => "Tarmoq xosti bo'yicha filtrlash",
Language::SV => "Filtrera efter nätverksvärd",
Language::VI => "Lọc bởi máy chủ mạng",
Language::ZH => "按网络主机筛选",
Language::ZH_TW => "依網路主機篩選",
Language::KO => "네트워크 호스트로 필터링",
Language::TR => "Ağ sunucusuna göre filtrele",
Language::PT => "Filtrar por host de rede",
Language::UK => "Фільтр за хостом мережі",
Language::ID => "Filter berdasarkan jaringan asal",
Language::NL => "Filteren op netwerk host",
Language::EL => "Φίλτρο ανά διακομιστή δικτύου",
_ => "Filter by network host",
}
}
pub fn service_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::FR | Language::DE | Language::SV => "Service",
Language::CS => "Služba",
// Language::FA => "خدمت",
Language::ES => "Servicio",
Language::IT => "Servizio",
Language::PL => "Usługa",
Language::RU => "Сервис",
Language::RO => "Serviciu",
Language::JA => "サービス",
Language::UZ => "Xizmat",
Language::VI => "Dịch vụ",
Language::ZH => "服务",
Language::ZH_TW => "服務",
Language::KO => "서비스",
Language::TR => "Servis",
Language::PT => "Serviço",
Language::UK => "Сервіс",
Language::ID => "Layanan",
Language::NL => "Dienst",
Language::EL => "Υπηρεσία",
_ => "Service",
}
}
pub fn export_capture_translation(language: Language) -> &'static str {
match language {
Language::EN => "Export capture file",
Language::CS => "Export souboru zachycení",
// Language::FA => "خروجی گرفتن پرونده تسخیری",
Language::IT => "Esporta file di cattura",
Language::FR => "Exporter le fichier de capture",
Language::DE => "Aufzeichnungsdatei exportieren",
Language::PL => "Eksportuj plik przechwytywania",
Language::RU => "Экспорт файла захвата",
Language::RO => "Export fișier captură",
Language::JA => "キャプチャ ファイルをエクスポート",
Language::UZ => "Cap faylni eksport qilish",
Language::SV => "Exportera inspelningsfil",
Language::VI => "Xuất tập tin đã bắt",
Language::ZH => "导出捕获文件",
Language::ZH_TW => "匯出擷取的檔案",
Language::KO => "캡처 파일 내보내기",
Language::TR => "Yakalanan dosyayı dışa aktar",
Language::PT => "Exportar arquivo capturado",
Language::UK => "Експорт файлу захоплення",
Language::ID => "Ekspor data tangkapan",
Language::ES => "Exportar archivo de captura",
Language::NL => "Exporteer capture bestand",
Language::EL => "Εξαγωγή αρχείου καταγραφής",
_ => "Export capture file",
}
}
// (a filesystem directory)
pub fn directory_translation(language: Language) -> &'static str {
match language {
Language::EN => "Directory",
Language::CS => "Složka",
// Language::FA => "پوشه",
Language::IT => "Cartella",
Language::FR => "Répertoire",
Language::DE => "Ordner",
Language::PL | Language::UZ | Language::SV => "Katalog",
Language::RU => "Директория",
Language::RO => "Director",
Language::JA => "ディレクトリー",
Language::VI => "Thư mục",
Language::ZH => "目录",
Language::ZH_TW => "目錄",
Language::KO => "디렉토리",
Language::TR => "Klasör",
Language::PT => "Diretório",
Language::UK => "Тека",
Language::ID => "Direktori",
Language::ES => "Directorio",
Language::NL => "Map",
Language::EL => "Κατάλογος",
_ => "Directory",
}
}
pub fn select_directory_translation(language: Language) -> &'static str {
match language {
Language::EN => "Select destination directory",
Language::CS => "Výběr cílové složky",
// Language::FA => "انتخاب پوشه مقصد",
Language::IT => "Seleziona cartella di destinazione",
Language::FR => "Sélectionner le répertoire de destination",
Language::DE => "Zielordner wählen",
Language::PL => "Wybierz katalog docelowy", // "Wybierz folder docelowy"?
Language::RU => "Выберите директорию назначения",
Language::RO => "Selectează directorul destinație",
Language::JA => "宛先のディレクトリーを選択する",
Language::UZ => "Manzil katalogni tanlang",
Language::SV => "Välj målkatalog",
Language::VI => "Chọn thư mục đích đến",
Language::ZH => "选择目标目录",
Language::ZH_TW => "選擇目的目錄",
Language::KO => "대상 디렉토리 선택",
Language::TR => "Hedef klasörü seç",
Language::PT => "Selecionar diretório de destino",
Language::UK => "Виберіть теку призначення",
Language::ID => "Pilih direktori tujuan",
Language::ES => "Selecciona el directorio de destino",
Language::NL => "Selecteer doelmap",
Language::EL => "Επιλογή καταλόγου προορισμού",
_ => "Select destination directory",
}
}
pub fn file_name_translation(language: Language) -> &'static str {
match language {
Language::EN => "File name",
Language::CS => "Jméno souboru",
// Language::FA => "نام پرونده",
Language::IT => "Nome del file",
Language::FR => "Nom du fichier",
Language::DE => "Dateiname",
Language::PL => "Nazwa pliku",
Language::RU => "Имя файла",
Language::RO => "Nume fișier",
Language::JA => "ファイル ネーム",
Language::UZ => "Fayl nomi",
Language::SV => "Filnamn",
Language::VI => "Tên file",
Language::ZH => "文件名",
Language::ZH_TW => "檔案名稱",
Language::KO => "파일 이름",
Language::TR => "Dosya adı",
Language::PT => "Nome do arquivo",
Language::UK => "Назва файлу",
Language::ID => "Nama berkas",
Language::ES => "Nombre del archivo",
Language::NL => "Bestandsnaam",
Language::EL => "Όνομα αρχείου",
_ => "File name",
}
}
pub fn thumbnail_mode_translation(language: Language) -> &'static str {
match language {
Language::EN => "Thumbnail mode",
Language::CS => "Režim miniatury",
// Language::FA => "حالت تصویر بندانگشتی",
Language::IT => "Modalità miniatura",
Language::FR => "Mode miniature",
Language::DE => "Bild-in-Bild Modus",
Language::PL => "Tryb miniatury",
Language::RU => "Режим миниатюры",
Language::RO => "Mod thumbnail",
Language::JA => "サムネイル モード",
Language::UZ => "Kichik rasm rejimi",
Language::SV => "Miniatyrläge",
Language::VI => "Chế độ thu nhỏ",
Language::ZH => "缩略图模式",
Language::ZH_TW => "縮圖模式",
Language::KO => "썸네일 모드",
Language::TR => "Küçük resim modu",
Language::PT | Language::ES => "Modo miniatura",
Language::UK => "Режим мініатюри",
Language::ID => "Mode gambar kecil",
Language::NL => "Miniatuur modus",
Language::EL => "Λειτουργία μικρογραφιών",
_ => "Thumbnail mode",
}
}
// pub fn learn_more_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Do you want to learn more?",
// Language::CS => "Chcete se dozvědět více?",
// // Language::FA => "آیا می خواهید بیشتر یاد بگیرید؟",
// Language::IT => "Vuoi saperne di più?",
// Language::FR => "Voulez-vous en savoir davantage?",
// Language::DE => "Mehr erfahren",
// Language::PL => "Chcesz dowiedzieć się więcej?",
// Language::RU => "Хотите узнать больше?",
// Language::RO => "Vrei să înveți mai multe?",
// Language::JA => "もっと知りたいですか?",
// Language::UZ => "Ko'proq bilishni hohlaysizmi?",
// Language::SV => "Vill du veta mer?",
// Language::VI => "Bạn có muốn tìm hiểu thêm?",
// Language::ZH => "想知道更多吗?",
// Language::ZH_TW => "想了解更多嗎?",
// Language::KO => "더 자세히 알고 싶으십니까?",
// Language::TR => "Daha fazlasını öğrenmek ister misin?",
// Language::PT => "Quer aprender mais?",
// Language::UK => "Бажаєте дізнатись більше?",
// Language::ID => "Apakah kamu mau belajar lebih lanjut?",
// Language::ES => "¿Quieres aprender más?",
// Language::NL => "Wil je meer leren?",
// _ => "Do you want to learn more?",
// }
// }
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/translations_2.rs | src/translations/translations_2.rs | use crate::Language;
pub fn new_version_available_translation(language: Language) -> &'static str {
match language {
Language::EN => "A newer version is available!",
Language::CS => "Je k dispozici novější verze!",
Language::IT => "Una versione più recente è disponibile!",
Language::RU => "Новая версия доступна!",
Language::EL => "Μια νεότερη έκδοση είναι διαθέσιμη!",
// Language::FA => "یک نسخه جدیدتر روی GitHub موجود است",
Language::SV => "En nyare version finns tillgänglig!",
Language::FI => "Uudempi versio saatavilla!",
Language::DE => "Eine neue Version ist verfügbar!",
Language::TR => "Daha yeni bir versiyon mevcut!",
Language::ES => "Hay una nueva versión disponible!",
Language::KO => "새로운 버전이 출시되었습니다!",
Language::ZH => "新版本已在 Github 发布!",
Language::ZH_TW => "有可用的新版本!",
Language::UK => "Нова версія доступна!",
Language::RO => "O versiune nouă este disponibilă!",
Language::PL => "Nowsza wersja jest dostępna!",
Language::FR => "Une nouvelle version est disponible!",
Language::JA => "新しいバージョンが利用可能になりました!",
Language::UZ => "Yangi versiya mavjud!",
Language::PT => "Uma nova versão está disponível!",
Language::VI => "Phiên bản mới đã sẵn sàng!",
Language::ID => "Versi baru tersedia!",
Language::NL => "Een nieuwere versie is beschikbaar!",
}
}
pub fn inspect_translation(language: Language) -> &'static str {
match language {
Language::EN => "Inspect",
Language::CS => "Kontrola",
Language::IT => "Ispeziona",
Language::FR => "Inspecter",
Language::ES => "Inspeccionar",
Language::PL => "Sprawdź",
Language::DE => "Inspizieren",
Language::RU => "Инспектировать",
Language::SV => "Inspektera",
Language::FI => "Tarkastele",
Language::TR => "İncele",
// Language::FA => "بازرسی",
Language::KO => "검사",
Language::ZH => "检查",
Language::ZH_TW => "檢查",
Language::UK => "Перевірити",
Language::RO => "Inspectați",
Language::JA => "検査",
Language::UZ => "Tekshirish",
Language::PT => "Inspecionar",
Language::VI => "Quan sát",
Language::ID => "Memeriksa",
Language::NL => "Inspecteren",
Language::EL => "Επιθεώρηση",
}
}
pub fn connection_details_translation(language: Language) -> &'static str {
match language {
Language::EN => "Connection details",
Language::CS => "Podrobnosti spojení",
Language::IT => "Dettagli della connessione",
Language::RU => "Подробнее о соединении",
Language::SV => "Anslutningsdetaljer",
Language::FI => "Yhteyden tiedot",
Language::DE => "Verbindungsdetails",
Language::TR => "Bağlantı detayları",
// Language::FA => "مشخصات اتصال",
Language::ES => "Detalles de la conexión",
Language::KO => "연결 상세",
Language::ZH => "连接详情",
Language::ZH_TW => "連線詳細資訊",
Language::UK => "Деталі зʼєднання",
Language::RO => "Detalii conexiune",
Language::PL => "Szczegóły połączenia",
Language::FR => "Détails de la connexion",
Language::JA => "接続の詳細",
Language::UZ => "Ulanish ma'lumotlari",
Language::PT => "Detalhes da conexão",
Language::VI => "Thông tin kết nối",
Language::ID => "Rincian koneksi",
Language::NL => "Verbindingsdetails",
Language::EL => "Λεπτομέρειες σύνδεσης",
}
}
// refers to bytes or packets dropped because they weren't processed fast enough
pub fn dropped_translation(language: Language) -> &'static str {
match language {
Language::EN => "Dropped",
Language::CS => "Zahozené",
Language::IT => "Persi",
Language::RU => "Потеряно",
Language::SV => "Tappade",
Language::FI => "Pudotetut",
Language::DE | Language::NL => "Verloren",
Language::TR => "Düşen",
// Language::FA => "رها شده",
Language::ES | Language::PT => "Perdidos",
Language::KO => "손실",
Language::ZH => "丢计",
Language::ZH_TW => "丟棄",
Language::UK => "Пропущені",
Language::RO => "Pierdute",
Language::PL => "Utracone",
Language::FR => "Perdus",
Language::JA => "ドロップした",
Language::UZ => "Yig'ilgan",
Language::VI => "Mất",
Language::ID => "Dihapus",
Language::EL => "Απορριμμένα",
}
}
pub fn data_representation_translation(language: Language) -> &'static str {
match language {
Language::EN => "Data representation",
Language::CS => "Prezentace dat",
Language::IT => "Rappresentazione dei dati",
Language::RU => "Показывать в виде", // there is selector below: "байтов" or "пакетов"
Language::SV => "Datarepresentation",
Language::FI => "Tietojen esitys",
Language::DE => "Daten Darstellung",
Language::TR => "Veri gösterimi",
// Language::FA => "بازنمایی داده ها",
Language::ES => "Representación de los datos",
Language::KO => "데이터 단위",
Language::ZH => "图表数据",
Language::ZH_TW => "資料呈現方式",
Language::UK => "Відображення даних",
Language::RO => "Reprezentarea datelor",
Language::PL => "Reprezentacja danych",
Language::FR => "Représentation de données",
Language::JA => "データ表示",
Language::UZ => "Ma'lumotlarni taqdim etish",
Language::PT => "Representação dos dados",
Language::VI => "Miêu tả dữ liệu",
Language::ID => "Penyajian ulang data",
Language::NL => "Gegevensweergave",
Language::EL => "Αναπαράσταση δεδομένων",
}
}
pub fn host_translation(language: Language) -> &'static str {
match language {
Language::EN => "Network host",
Language::CS => "Síťová adresa",
Language::IT => "Host di rete",
Language::RU => "Сетевой хост",
Language::SV => "Nätverksvärd",
Language::FI => "Verkkoisäntä",
Language::DE => "Netzwerk-Host",
Language::TR => "Ağ sunucusu",
// Language::FA => "میزبان شبکه",
Language::ES => "Host de red",
Language::KO => "네트워크 호스트",
Language::ZH => "主机",
Language::ZH_TW => "網路主機",
Language::UK => "Мережевий хост",
Language::RO => "Host rețea",
Language::PL => "Host sieciowy",
Language::FR => "Host réseaux",
Language::JA => "ネットワーク ホスト",
Language::UZ => "Tarmoq serveri",
Language::PT => "Host da rede",
Language::VI => "Máy chủ",
Language::ID => "Jaringan asal",
Language::NL => "Netwerk host",
Language::EL => "Κόμβος δικτύου",
}
}
pub fn only_top_30_items_translation(language: Language) -> &'static str {
match language {
Language::EN => "Only the top 30 items are displayed here",
Language::CS => "Zde je zobrazeno pouze prvních 30 položek",
Language::IT => "Solo i 30 maggiori elementi sono mostrati qui",
Language::RU => "Показываются только первые 30 элементов",
Language::SV => "Endast de 30 främsta föremål visas här",
Language::FI => "Vain 30 parasta kohteita näytetään tässä",
Language::DE => "Nur die obersten 30 Elemente werden hier angezeigt",
Language::TR => "Sadece ilk 30 öğeler burda gösterilmektedir",
// Language::FA => "تنها ۳۰ موارد برتر در اینجا نمایش داده شده اند",
Language::ES => "Aquí sólo se muestran los 30 primeros elementos",
Language::KO => "상위 30개의 아이템만 노출됩니다",
Language::ZH => "仅展示前 30 个项目",
Language::ZH_TW => "此處僅顯示前 30 個項目",
Language::UK => "Тут відображаються лише перші 30 елементів",
Language::RO => "Doar primele 30 de articole sunt afișate aici",
Language::PL => "Tylko 30 pierwszych rzeczy jest wyświetlanych",
Language::FR => "Seuls les 30 premiers articles sont affichés ici",
Language::JA => "上位 30 件のアイテムのみが表示されます",
Language::UZ => "Bu erda faqat dastlabki 30 ta buyumlar ko'rsatiladi",
Language::PT => "Apenas os 30 melhores unid são expostos aqui",
Language::VI => "Chỉ có 30 mục gần nhất được hiển thị ở đây",
Language::ID => "Hanya 30 teratas yang ditampilkan disini",
Language::NL => "Alleen de bovenste 30 items worden hier weergegeven",
Language::EL => "Εμφανίζονται μόνο τα κορυφαία 30 στοιχεία",
}
}
// pub fn sort_by_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Sort by",
// Language::CS => "Seřazeno podle",
// Language::IT => "Ordina per",
// Language::RU => "Сортировка",
// Language::SV => "Sortera efter",
// Language::FI => "Järjestä",
// Language::DE => "Sortieren nach",
// Language::TR => "Şuna göre sırala",
// // Language::FA => "مرتب سازی بر اساس",
// Language::ES | Language::PT => "Ordenar por",
// Language::KO => "정렬",
// Language::ZH => "排序",
// Language::ZH_TW => "排序依據",
// Language::UK => "Сортувати за",
// Language::RO => "Filtrează după",
// Language::PL => "Sortuj według",
// Language::FR => "Trier par",
// Language::JA => "ソート",
// Language::UZ => "Saralash turi",
// Language::ID => "Urut berdasarkan",
// Language::NL => "Sorteren op",
// _ => "Sort by",
// }
// }
pub fn local_translation(language: Language) -> &'static str {
match language {
Language::EN => "Local network",
Language::CS => "Místní síť",
Language::IT => "Rete locale",
Language::RU => "Локальная сеть",
Language::SV => "Lokalt nätverk",
Language::FI => "Paikallinen verkko",
Language::DE => "Lokales Netzwerk",
Language::TR => "Yerel ağ",
// Language::FA => "شبکه محلی",
Language::ES => "Red local",
Language::KO => "로컬 네트워크",
Language::ZH => "局域网",
Language::ZH_TW => "區域網路",
Language::UK => "Локальна мережа",
Language::RO => "Rețea locală",
Language::PL => "Sieć lokalna",
Language::FR => "Réseau local",
Language::JA => "ローカル ネットワーク",
Language::UZ => "Mahalliy tarmoq",
Language::PT => "Rede local",
Language::VI => "Mạng nội bộ",
Language::ID => "Jaringan lokal",
Language::NL => "Lokaal netwerk",
Language::EL => "Τοπικό δίκτυο",
}
}
pub fn unknown_translation(language: Language) -> &'static str {
match language {
Language::EN => "Unknown location",
Language::CS => "Neznámá lokalita",
Language::IT => "Localizzazione sconosciuta",
Language::RU => "Неизвестный регион",
Language::SV => "Okänd plats",
Language::FI => "Tuntematon sijanti",
Language::DE => "Unbekannter Ort",
Language::TR => "Bilinmeyen yer",
// Language::FA => "محل نامعلوم",
Language::ES => "Ubicación desconocida",
Language::KO => "알 수 없는 위치",
Language::ZH => "未知",
Language::ZH_TW => "未知位置",
Language::UK => "Невідоме місцезнаходження",
Language::RO => "Locație necunoscută",
Language::PL => "Nieznana lokalizacja",
Language::FR => "Localisation inconnue",
Language::JA => "不明なロケーション",
Language::UZ => "Noma'lum joylashuv",
Language::PT => "Localização desconhecida",
Language::VI => "Không rõ địa điểm",
Language::ID => "Lokasi tidak diketahui",
Language::NL => "Onbekende locatie",
Language::EL => "Άγνωστη τοποθεσία",
}
}
pub fn your_network_adapter_translation(language: Language) -> &'static str {
match language {
Language::EN => "Your network adapter",
Language::CS => "Síťový adaptér",
Language::IT => "La tua scheda di rete",
Language::RU => "Ваш сетевой адаптер",
Language::SV => "Din nätverksadapter",
Language::FI => "Sinun verkkosovitin",
Language::DE => "Dein Netzwerk-Adapter",
Language::TR => "Ağ adaptörün",
// Language::FA => "مبدل شبکه شما",
Language::ES => "Su adaptador de red",
Language::KO => "네트워크 어댑터",
Language::ZH => "你的网络适配器",
Language::ZH_TW => "您的網路介面卡",
Language::UK => "Ваш мережевий адаптер",
Language::RO => "Adaptorul dvs. de rețea",
Language::PL => "Twój adapter sieciowy",
Language::FR => "Votre carte réseau",
Language::JA => "自身のネットワーク アダプター",
Language::UZ => "Sizning tarmoq adapteringiz",
Language::PT => "Seu adaptador de rede",
Language::VI => "Network adapter của bạn",
Language::ID => "Adaptor jaringan kamu",
Language::NL => "Uw netwerkadapter",
Language::EL => "Ο προσαρμογέας δικτύου σας",
}
}
pub fn socket_address_translation(language: Language) -> &'static str {
match language {
Language::EN => "Socket address",
Language::CS => "Adresa soketu",
Language::IT => "Indirizzo del socket",
Language::RU => "Адрес сокета",
Language::SV => "Socketadress",
Language::FI => "Socket osoite",
Language::DE => "Socket Adresse",
Language::TR => "Soket adresi",
// Language::FA => "پریز شبکه",
Language::ES => "Dirección del socket",
Language::KO => "소켓 어드레스",
Language::ZH => "套接字地址",
Language::ZH_TW => "Socket 位址",
Language::UK => "Адреса сокета",
Language::RO => "Adresa socket-ului",
Language::PL => "Adres gniazda",
Language::FR => "Adresse du socket",
Language::JA => "ソケット アドレス",
Language::UZ => "Soket manzili",
Language::PT => "Endereço da socket",
Language::VI => "Địa chỉ socket",
Language::ID => "Alamat sambungan",
Language::NL => "Socket adres",
Language::EL => "Διεύθυνση υποδοχής",
}
}
pub fn mac_address_translation(language: Language) -> &'static str {
match language {
Language::EN => "MAC address",
Language::CS => "MAC adresa",
Language::IT => "Indirizzo MAC",
Language::RU => "MAC адрес",
Language::SV => "MAC-adress",
Language::FI => "MAC-osoite",
Language::DE => "MAC Adresse",
Language::TR => "MAC adresi",
// Language::FA => "آدرس MAC",
Language::ES => "Dirección MAC",
Language::KO => "맥 어드레스",
Language::ZH => "MAC 地址",
Language::ZH_TW => "MAC 位址",
Language::UK => "MAC-адреса",
Language::RO => "Adresa MAC",
Language::PL => "Adres MAC",
Language::FR => "Adresse MAC",
Language::JA => "MAC アドレス",
Language::UZ => "MAC manzili",
Language::PT => "Endereço MAC",
Language::VI => "Địa chỉ MAC",
Language::ID => "Alamat MAC",
Language::NL => "MAC-adres",
Language::EL => "Διεύθυνση MAC",
}
}
pub fn source_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::FR => "Source",
Language::CS => "Zdroj",
Language::IT => "Sorgente",
Language::RU => "Источник",
Language::SV => "Källa",
Language::FI => "Lähde",
Language::DE => "Quelle",
Language::TR => "Kaynak",
// Language::FA => "منبع",
Language::ES => "Origen",
Language::KO => "소스",
Language::ZH => "源",
Language::ZH_TW => "來源",
Language::UK => "Джерело",
Language::RO => "Sursă",
Language::PL => "Źródło",
Language::JA => "送信元",
Language::UZ => "Manba",
Language::PT => "Fonte",
Language::VI => "Nguồn",
Language::ID => "Asal",
Language::NL => "Bron",
Language::EL => "Πηγή",
}
}
pub fn destination_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::SV | Language::FR => "Destination",
Language::CS => "Cíl",
Language::IT => "Destinazione",
Language::RU => "Получатель",
Language::FI => "Määränpää",
Language::DE => "Ziel",
Language::TR => "Hedef",
// Language::FA => "مقصد",
Language::ES | Language::PT => "Destino",
Language::KO => "목적지",
Language::ZH => "目标",
Language::ZH_TW => "目的地",
Language::UK => "Призначення",
Language::RO => "Destinație",
Language::PL => "Miejsce docelowe",
Language::JA => "送信先",
Language::UZ => "Qabul qiluvchi",
Language::VI => "Đích",
Language::ID => "Tujuan",
Language::NL => "Bestemming",
Language::EL => "Προορισμός",
}
}
pub fn fqdn_translation(language: Language) -> &'static str {
match language {
Language::EN => "Fully qualified domain name",
Language::CS => "Plně kvalifikované doménové jméno",
Language::IT => "Nome di dominio completo",
Language::RU => "Полное доменное имя",
Language::SV => "Fullständigt domännamn",
Language::FI => "Täysin määritelty verkkotunnus",
Language::DE => "Vollständig qualifizierter Domain Name",
Language::TR => "Tam nitelikli alan adı",
// Language::FA => "نام دامنه جامع الشرایط",
Language::ES => "Nombre de dominio completo",
Language::KO => "절대 도메인 네임",
Language::ZH | Language::JA | Language::ZH_TW => "FQDN",
Language::UK => "Повністю визначене доменне ім'я",
Language::RO => "Nume de domeniu complet calificat",
Language::PL => "Pełna nazwa domeny",
Language::FR => "Nom de domaine complètement qualifié",
Language::UZ => "To'liq domen nomi",
Language::PT => "Nome de domínio completo",
Language::VI => "Tên miền đầy đủ",
Language::ID => "Nama domain yang memenuhi syarat",
Language::NL => "Volledig gekwalificeerde domeinnaam",
Language::EL => "Πλήρως προσδιορισμένο όνομα τομέα",
}
}
pub fn administrative_entity_translation(language: Language) -> &'static str {
match language {
Language::EN => "Autonomous System name",
Language::CS => "Jméno autonomního systému",
Language::IT => "Nome del sistema autonomo",
Language::RU => "Имя автономной системы",
Language::SV => "Administrativ enhet",
Language::FI => "Autonomisen järjestelmän nimi",
Language::DE => "Name des autonomen Systems",
Language::TR => "Yönetim varlığı",
// Language::FA => "واحد اداری",
Language::ES => "Nombre del sistema autónomo",
Language::KO => "관리 엔티티",
Language::ZH => "ASN 信息",
Language::ZH_TW => "ASN 資訊",
Language::UK => "Адміністративна одиниця",
Language::RO => "Numele sistemului autonom",
Language::PL => "Nazwa autonomicznego systemu",
Language::FR => "Nom du système autonome",
Language::JA => "AS 名",
Language::UZ => "Avtonom tizim nomi",
Language::PT => "Entidade administrativa",
Language::VI => "Tên Autonomous System",
Language::ID => "Nama System Otomatis",
Language::NL => "Naam van het autonome systeem",
Language::EL => "Όνομα αυτόνομου συστήματος",
}
}
pub fn transmitted_data_translation(language: Language) -> &'static str {
match language {
Language::EN => "Transmitted data",
Language::CS => "Přenesená data",
Language::IT => "Dati trasmessi",
Language::RU => "Передано данных",
Language::SV => "Överförd data",
Language::FI => "Lähetetty data",
Language::DE => "Übermittelte Daten",
Language::TR => "Aktarılan veri",
// Language::FA => "دادهٔ منتقل شده",
Language::ES => "Datos transmitidos",
Language::KO => "수신된 데이터",
Language::ZH => "数据传输",
Language::ZH_TW => "已傳輸的資料",
Language::UK => "Передані дані",
Language::RO => "Date transmise",
Language::PL => "Przesłane dane",
Language::FR => "Données transmises",
Language::JA => "転送データ",
Language::UZ => "Uzatilgan ma'lumotlar",
Language::PT => "Dados transmitidos",
Language::VI => "Dữ liệu được truyền",
Language::ID => "Data terkirim",
Language::NL => "Verzonden gegevens",
Language::EL => "Μεταδιδόμενα δεδομένα",
}
}
pub fn country_translation(language: Language) -> &'static str {
match language {
Language::EN => "Country",
Language::CS => "Země",
Language::IT => "Paese",
Language::RU => "Страна",
Language::SV | Language::DE | Language::NL => "Land",
Language::FI => "Maa",
Language::TR => "Ülke",
// Language::FA => "کشور",
Language::ES | Language::PT => "País",
Language::KO => "국가",
Language::ZH => "国家",
Language::ZH_TW => "國家",
Language::UK => "Країна",
Language::RO => "Țară",
Language::PL => "Kraj",
Language::FR => "Pays",
Language::JA => "国",
Language::UZ => "Davlat",
Language::VI => "Quốc gia",
Language::ID => "Negara",
Language::EL => "Χώρα",
}
}
pub fn domain_name_translation(language: Language) -> &'static str {
match language {
Language::EN => "Domain name",
Language::CS => "Doménové jméno",
Language::IT => "Nome di dominio",
Language::RU => "Доменное имя",
Language::SV => "Domännamn",
Language::FI => "Verkkotunnus",
Language::DE => "Domain Name",
Language::TR => "Alan adı",
// Language::FA => "نام دامنه",
Language::ES => "Nombre de dominio",
Language::KO => "도메인 네임",
Language::ZH => "域名",
Language::ZH_TW => "網域名稱",
Language::UK => "Доменне ім'я",
Language::RO => "Nume domeniu",
Language::PL => "Nazwa domeny",
Language::FR => "Nom de domaine",
Language::JA => "ドメイン名",
Language::UZ => "Domen nomi",
Language::PT => "Nome do domínio",
Language::VI => "Tên miền",
Language::ID => "Nama Domain",
Language::NL => "Domeinnaam",
Language::EL => "Όνομα τομέα",
}
}
pub fn only_show_favorites_translation(language: Language) -> &'static str {
match language {
Language::EN => "Only show favorites",
Language::CS => "Zobrazit pouze oblíbené",
Language::IT => "Mostra solo i preferiti",
Language::RU => "Показывать только избранные",
Language::SV => "Visa endast favoriter",
Language::FI => "Näytä vain suosikit",
Language::DE => "Zeige nur die Favoriten",
Language::TR => "Sadece favorileri göster",
// Language::FA => "فقط پسندیده ها را نمایش بده",
Language::ES => "Mostrar solo los favoritos",
Language::KO => "즐겨찾기만 보기",
Language::ZH => "仅显示收藏",
Language::ZH_TW => "僅顯示我的最愛",
Language::UK => "Показувати лише улюблені",
Language::RO => "Arată doar favorite",
Language::PL => "Pokaż tylko ulubione",
Language::FR => "Afficher uniquement les favoris",
Language::JA => "お気に入りのみを表示する",
Language::UZ => "Faqat sevimlilarni ko'rsatish",
Language::PT => "Apenas mostrar os favoritos",
Language::VI => "Chỉ hiển thị mục ưa thích",
Language::ID => "Hanya tunjukkan favorit",
Language::NL => "Toon alleen favorieten",
Language::EL => "Εμφάνιση μόνο αγαπημένων",
}
}
// pub fn search_filters_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Search filters",
// Language::CS => "Vyhledávací filtry",
// Language::IT => "Filtri di ricerca",
// Language::RU => "Фильтры для поиска",
// Language::SV => "Sökfilter",
// Language::FI => "Hakusuodattimet",
// Language::DE => "Filter suchen",
// Language::TR => "Arama filtresi",
// // Language::FA => "صافی های جستجو",
// Language::ES => "Filtros de búsqueda",
// Language::KO => "검색 필터",
// Language::ZH => "搜索条件",
// Language::ZH_TW => "搜尋篩選器",
// Language::UK => "Фільтри пошуку",
// Language::RO => "Filtre de căutare",
// Language::PL => "Filtry wyszukiwania",
// Language::FR => "Filtres de recherche",
// Language::JA => "検索フィルター",
// Language::UZ => "Qidiruv filtrlari",
// Language::PT => "Filtros de busca",
// Language::ID => "Filter Pencarian",
// Language::NL => "Zoekfilters",
// _ => "Search filters",
// }
// }
pub fn no_search_results_translation(language: Language) -> &'static str {
match language {
Language::EN => "No result available according to the specified search filters",
Language::CS => "Podle zadaných vyhledávacích filtrů není k dispozici žádný výsledek",
Language::IT => "Nessun risultato disponibile secondo i filtri di ricerca specificati",
Language::RU => "Ничего не найдено после применения выбранных фильтров",
Language::SV => "Inga resultat tillgängliga utifrån de angivna sökfilterna",
Language::FI => "Ei tuloksia saatavilla määritellyille hakusuodattimille",
Language::DE => "Keine Resultate für die gewählten Filter verfügbar",
Language::TR => "Belirtilen arama filtrelerine göre herhangi bir sonuç bulunmamaktadır",
// Language::FA => "هیچ نتیجه ای بر اساس صافی های جستجوی تعیین شده وجود ندارد",
Language::ES => "Los filtros de búsqueda especificados no generan ningún resultado",
Language::KO => "해당 검색 필터로 검색된 결과가 없습니다.",
Language::ZH => "没有符合条件的条目",
Language::ZH_TW => "根據指定的篩選條件,找不到任何結果",
Language::UK => "Немає результатів згідно з обраними фільтрами пошуку",
Language::RO => "Niciun rezultat disponibil conform filtrelor de căutare specificate",
Language::PL => "Brak wyników zgodnych z określonymi filtrami wyszukiwania",
Language::FR => "Aucun résultat disponible selon les filtres de recherche spécifiés",
Language::JA => "指定されたフィルター条件で表示できる結果はありません",
Language::UZ => "Belgilangan qidiruv filtrlari bo'yicha hech qanday natija mavjud emas",
Language::PT => "Nenhum resultado disponível de acordo com os filtros selecionados",
Language::VI => "Không có kết quả nào theo các bộ lọc được chỉ định",
Language::ID => "Tidak ada hasil berdasarkan filter pencarian spesifik",
Language::NL => "Geen resultaten beschikbaar volgens de opgegeven zoekfilters",
Language::EL => {
"Δεν υπάρχουν διαθέσιμα αποτελέσματα σύμφωνα με τα καθορισμένα φίλτρα αναζήτησης"
}
}
}
pub fn showing_results_translation(
language: Language,
start: usize,
end: usize,
total: usize,
) -> String {
match language {
Language::EN => format!("Showing {start}-{end} of {total} total results"),
Language::CS => format!("Zobrazení {start}-{end} z celkových {total} výsledků"),
Language::IT => format!("Sono mostrati {start}-{end} di {total} risultati totali"),
Language::RU => format!("Показываются {start}-{end} из {total} общего числа результатов"),
Language::SV => format!("Visar {start}-{end} av {total} totala resultat"),
Language::FI => format!("Näytetään {start}-{end} tulosta, kaikista tuloksista {total}"),
Language::DE => format!("{start}-{end} von insgesamt {total} Resultaten werden angezeigt"),
Language::TR => format!("{total} sonuç içinde {start}-{end}"),
// Language::FA => format!("نمایش {start}-{end} از تمامی {total} نتیجه"),
Language::ES => format!("Mostrando {start}-{end} de {total} resultados totales"),
Language::KO => format!("총 {total}개의 결과 중 {start}-{end}을(를) 보여줍니다"),
Language::ZH => format!("显示累计 {total} 条目中第 {start}-{end} 个"),
Language::ZH_TW => format!("顯示總共 {total} 個結果中的第 {start}-{end} 個"),
Language::UK => format!("Показано {start}-{end} з {total} загальних результатів"),
Language::RO => format!("Se afișează {start}-{end} din {total} rezultate"),
Language::PL => format!("Wyświetlanie {start}-{end} z {total} wyników"),
Language::FR => format!("Affichage de {start}-{end} de {total} résultats totaux"),
Language::JA => format!("{total} 件中の {start}-{end} 件を表示"),
Language::UZ => format!("Jami {total} natijadan {start}-{end} ko'rsatilyapti"),
Language::PT => format!("Mostrando {start}-{end} de {total} resultados totais"),
Language::VI => format!("Đang hiển thị {start}-{end} của {total} tổng số kết quả"),
Language::ID => format!("Menampilkan {start}-{end} dari {total} semua hasil"),
Language::NL => {
format!("{start}-{end} van de {total} totale resultaten worden weergegeven")
}
Language::EL => format!("Εμφάνιση {start}-{end} από {total} συνολικά αποτελέσματα"),
}
}
pub fn color_gradients_translation(language: Language) -> &'static str {
match language {
Language::EN => "Apply color gradients",
Language::CS => "Použít barevné přechody",
Language::IT => "Applica sfumature di colore",
Language::RU => "Применить цветовой градиент", // recheck
Language::SV => "Applicera färggradient",
Language::FI => "Käytä värigradientteja",
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | true |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/mod.rs | src/translations/mod.rs | #![allow(clippy::module_inception, clippy::module_name_repetitions)]
pub mod translations;
pub mod translations_2;
pub mod translations_3;
pub mod translations_4;
pub mod translations_5;
pub mod types;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/translations_4.rs | src/translations/translations_4.rs | #![allow(clippy::match_same_arms)]
use crate::translations::types::language::Language;
pub fn reserved_address_translation(language: Language, info: &str) -> String {
match language {
Language::EN => format!("Reserved address ({info})"),
Language::CS => format!("Rezervovaná adresa ({info})"),
Language::IT => format!("Indirizzo riservato ({info})"),
Language::JA => format!("予約済みアドレス ({info})"),
Language::PT => format!("Endereço reservado ({info})"),
Language::UK => format!("Зарезервована адреса ({info})"),
Language::ZH => format!("预留地址 ({info})"),
Language::ZH_TW => format!("保留的網路位址 ({info})"),
Language::FR => format!("Adresse réservée ({info})"),
Language::NL => format!("Gereserveerd adres ({info})"),
Language::ES => format!("Dirección reservada ({info})"),
Language::RO => format!("Adresă rezervată ({info})"),
Language::DE => format!("Reservierte Adresse ({info})"),
Language::UZ => format!("Rezervlangan manzil ({info})"),
Language::ID => format!("Alamat disimpan ({info})"),
Language::EL => format!("Δεσμευμένη διεύθυνση ({info})"),
Language::VI => format!("Địa chỉ dự trữ ({info})"),
_ => format!("Reserved address ({info})"),
}
}
pub fn share_feedback_translation(language: Language) -> &'static str {
match language {
Language::EN => "Share your feedback",
Language::CS => "Sdílejte své hodnocení",
Language::IT => "Condividi il tuo feedback",
Language::JA => "フィードバックを共有",
Language::ZH => "分享您的反馈",
Language::ZH_TW => "分享您的意見回饋",
Language::FR => "Partagez vos commentaires",
Language::NL => "Deel uw feedback",
Language::ES => "Comparte tus comentarios",
Language::RO => "Împărtășiți feedback-ul dvs",
Language::DE => "Feedback geben",
Language::UZ => "Fikr-mulohazalaringizni ulashing",
Language::ID => "Berikan masukanmu",
Language::EL => "Μοιραστείτε τα σχόλιά σας",
Language::VI => "Chia sẻ phản hồi của bạn",
_ => "Share your feedback",
}
}
// refers to bytes or packets excluded because of the filters
// pub fn excluded_translation(language: Language) -> &'static str {
// match language {
// Language::EN => "Excluded",
// Language::CS => "Vyloučeno",
// Language::IT => "Esclusi",
// Language::JA => "除外",
// Language::ZH => "已被过滤",
// Language::UZ => "Chiqarib tashlangan",
// Language::ZH_TW => "已排除",
// Language::FR => "Exclus",
// Language::NL => "Uitgesloten",
// Language::DE => "Herausgefiltert",
// Language::EL => "Εξαιρούμενα",
// Language::RO => "Excluși",
// Language::ID => "Kecuali",
// Language::ES => "Excluidos",
// Language::VI => "Loại trừ",
// _ => "Excluded",
// }
// }
pub fn capture_file_translation(language: Language) -> &'static str {
match language {
Language::EN => "Capture file",
Language::CS => "Soubor zachycení",
Language::IT => "File di cattura",
Language::FR => "Fichier de capture",
Language::JA => "キャプチャファイル",
Language::ZH => "捕获文件",
Language::NL => "Capture bestand",
Language::DE => "Aufzeichnungsdatei",
Language::UZ => "Tahlil faylini",
Language::EL => "Αρχείου καταγραφής",
Language::RO => "Fișierul de captură",
Language::ZH_TW => "擷取文件",
Language::ID => "File tangkapan",
Language::ES => "Archivo de captura",
Language::VI => "Bắt tệp tin",
_ => "Capture file",
}
}
pub fn select_capture_translation(language: Language) -> &'static str {
match language {
Language::EN => "Select capture file",
Language::CS => "Výběr souboru se záznamem",
Language::IT => "Seleziona file di cattura",
Language::FR => "Sélectionner un fichier de capture",
Language::JA => "キャプチャファイルを選択",
Language::ZH => "选择捕获文件",
Language::NL => "Selecteer capture bestand",
Language::ES => "Seleccionar archivo de captura",
Language::RO => "Selectează fișierul de captură",
Language::DE => "Aufzeichnungsdatei auswählen",
Language::UZ => "Tahlil faylini tanlang",
Language::ID => "Pilih file tangkapan",
Language::ZH_TW => "選擇擷取文件",
Language::EL => "Επιλογή αρχείου καταγραφής",
Language::VI => "Chọn tệp tin được bắt",
_ => "Select capture file",
}
}
pub fn reading_from_pcap_translation(language: Language) -> &'static str {
match language {
Language::EN => {
"Reading packets from file...\n\n\
Are you sure the file you selected isn't empty?"
}
Language::CS => {
"Čtení paketů ze souuboru...\n\n\
Jste si jistý že vybraný soubor není prázdný?"
}
Language::IT => {
"Lettura pacchetti da file...\n\n\
Sei sicuro che il file che hai selezionato non sia vuoto?"
}
Language::FR => {
"Lecture des paquets depuis le fichier...\n\n\
Êtes-vous sûr que le fichier sélectionné n'est pas vide?"
}
Language::JA => {
"ファイルからパケットを読み込み中...\n\n\
選択したファイルが空でないことを確認しましたか?"
}
Language::ZH => {
"从文件中读取数据包...\n\n\
您确定选中的文件不是空的吗?"
}
Language::NL => {
"Pakketten lezen uit bestand...\n\n\
Weet je zeker dat het geselecteerde bestand niet leeg is?"
}
Language::ES => {
"Leyendo paquetes desde el archivo...\n\n\
¿Seguro que el archivo seleccionado no está vacío?"
}
Language::RO => {
"Citirea pachetelor din fișier...\n\n\
Ești sigur că fișierul selectat nu este gol?"
}
Language::DE => {
"Pakete aus Datei laden... \n\n\
Bist du sicher, dass die gewählte Datei nicht leer ist?"
}
Language::UZ => {
"Faylni o'qish...\n\n\
Fayl bo'sh emasligiga aminmisiz?"
}
Language::ID => {
"Membaca paket dari berkas...\n\n\
Apa kamu yakin berkasnya tidak kosong?"
}
Language::ZH_TW => {
"從檔案讀取資料包...\n\n\
您確定您選擇的檔案不是空的嗎?"
}
Language::EL => {
"Ανάγνωση πακέτων από αρχείο...\n\n\
Είστε βέβαιοι ότι το επιλεγμένο αρχείο δεν είναι κενό;"
}
Language::VI => {
"Đang đọc gói tin từ tệp...\n\n\
Bạn có chắc tệp tin đã chọn không bị trống?"
}
_ => {
"Reading packets from file...\n\n\
Are you sure the file you selected isn't empty?"
}
}
}
pub fn data_exceeded_translation(language: Language) -> &'static str {
match language {
Language::EN => "Data threshold exceeded",
Language::CS => "Překročen limit dat",
Language::IT => "Soglia di dati superata",
Language::FR => "Seuil de données dépassé",
Language::JA => "データの閾値を超えました",
Language::ZH | Language::ZH_TW => "已超出数据阈值",
Language::NL => "Gegevenslimiet overschreden",
Language::ES => "Umbral de datos superado",
Language::RO => "Limita de date depășită",
Language::DE => "Datenschwelle überschritten",
Language::UZ => "Ma'lumotlar chegarasidan oshib ketdi",
Language::ID => "Ambang batas data terlampaui",
Language::EL => "Υπέρβαση ορίου δεδομένων",
Language::VI => "Đã vượt ngưỡng dữ liệu",
_ => "Data threshold exceeded",
}
}
pub fn bits_exceeded_translation(language: Language) -> &'static str {
match language {
Language::EN => "Bits threshold exceeded",
Language::CS => "Překročen limit bitů",
Language::IT => "Soglia di bit superata",
Language::FR => "Seuil de bits dépassé",
Language::JA => "ビットの閾値を超えました",
Language::ZH => "已超出比特阈值",
Language::NL => "Bits limiet overschreden",
Language::ES => "Umbral de bits superado",
Language::RO => "Limita de biți depășită",
Language::DE => "Bitschwelle überschritten",
Language::UZ => "Bitlar chegarasidan oshib ketdi",
Language::ID => "Ambang batas bit terlampaui",
Language::ZH_TW => "超出數據界限",
Language::EL => "Υπέρβαση ορίου δυφίων",
Language::VI => "Đã vượt ngưỡng bit",
_ => "Bits threshold exceeded",
}
}
pub fn bits_translation(language: Language) -> &'static str {
match language {
Language::EN
| Language::IT
| Language::NL
| Language::DE
| Language::FR
| Language::ID
| Language::ES => "bits",
Language::CS => "bity",
Language::JA => "ビット",
Language::ZH => "比特",
Language::UZ => "bitlar",
Language::EL => "Δυφία",
Language::RO => "biți",
Language::ZH_TW => "位元",
Language::VI => "bit",
_ => "bits",
}
}
#[allow(dead_code)]
pub fn pause_translation(language: Language) -> &'static str {
match language {
Language::EN | Language::DE | Language::FR => "Pause",
Language::CS => "Pauza",
Language::IT | Language::ES => "Pausa",
Language::JA => "一時停止",
Language::ZH => "暂停",
Language::NL => "Pauzeren",
Language::RO => "Pauză",
Language::UZ => "To'xtatish",
Language::ID => "Dijeda",
Language::ZH_TW => "暫停",
Language::EL => "Παύση",
Language::VI => "Tạm dừng",
_ => "Pause",
}
}
#[allow(dead_code)]
pub fn resume_translation(language: Language) -> &'static str {
match language {
Language::EN => "Resume",
Language::CS => "Obnovit",
Language::IT => "Riprendi",
Language::FR => "Reprendre",
Language::JA => "再開",
Language::ZH => "恢复",
Language::NL => "Hervatten",
Language::ES => "Reanudar",
Language::RO => "Continuă",
Language::DE => "Fortsetzen",
Language::UZ => "Davom ettirish",
Language::ID => "Dilanjut",
Language::ZH_TW => "繼續",
Language::EL => "Συνέχεια",
Language::VI => "Tiếp tục",
_ => "Resume",
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/translations_5.rs | src/translations/translations_5.rs | #![allow(clippy::match_same_arms)]
use crate::translations::types::language::Language;
pub fn filter_traffic_translation(language: Language) -> String {
match language {
Language::EN => "Filter traffic",
Language::CS => "Filtr provozu",
Language::IT => "Filtra il traffico",
_ => "Filter traffic",
}
.to_string()
}
// the source from which Sniffnet reads network traffic (i.e., a capture file or a network adapter)
pub fn traffic_source_translation(language: Language) -> &'static str {
match language {
Language::EN => "Traffic source",
Language::CS => "Zdroj provozu",
Language::IT => "Fonte del traffico",
_ => "Traffic source",
}
}
pub fn remote_notifications_translation(language: Language) -> &'static str {
match language {
Language::EN => "Remote notifications",
Language::IT => "Notifiche remote",
_ => "Remote notifications",
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/types/language.rs | src/translations/types/language.rs | use std::fmt;
use iced::widget::Svg;
use iced::widget::svg::Handle;
use serde::{Deserialize, Serialize};
use crate::StyleType;
use crate::countries::flags_pictures::{
CN, CZ, DE, ES, FI, FLAGS_WIDTH_BIG, FR, GB, GR, ID, IT, JP, KR, NL, PL, PT, RO, RU, SE, TR,
TW, UA, UZ, VN,
};
/// This enum defines the available languages.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize, Hash, Default)]
pub enum Language {
/// English.
#[default]
EN,
/// Italian.
IT,
/// French.
FR,
/// Spanish.
ES,
/// Polish.
PL,
/// German,
DE,
/// Ukrainian
UK,
/// Simplified Chinese
ZH,
/// Traditional Chinese
#[allow(non_camel_case_types)]
ZH_TW,
/// Romanian
RO,
/// Korean
KO,
/// Portuguese
PT,
/// Turkish
TR,
/// Russian
RU,
/// Greek
EL,
// /// Persian
// FA,
/// Swedish
SV,
/// Finnish
FI,
/// Japanese
JA,
/// Uzbek
UZ,
/// Vietnamese
VI,
/// Indonesian
ID,
/// Dutch
NL,
/// Czech
CS,
}
impl Language {
pub const ALL: [Language; 23] = [
Language::EN,
Language::CS,
Language::DE,
Language::EL,
Language::ES,
Language::FI,
Language::FR,
Language::ID,
Language::IT,
Language::JA,
Language::KO,
Language::NL,
Language::PL,
Language::PT,
Language::RO,
Language::RU,
Language::SV,
Language::TR,
Language::UK,
Language::UZ,
Language::VI,
Language::ZH,
Language::ZH_TW,
];
pub fn get_flag<'a>(self) -> Svg<'a, StyleType> {
Svg::new(Handle::from_memory(Vec::from(match self {
Language::ZH => CN,
Language::ZH_TW => TW,
Language::DE => DE,
Language::ES => ES,
Language::FR => FR,
Language::EN => GB,
Language::IT => IT,
Language::KO => KR,
Language::PL => PL,
Language::PT => PT,
Language::RO => RO,
Language::RU => RU,
Language::TR => TR,
Language::UK => UA,
Language::EL => GR,
// Language::FA => IR,
Language::SV => SE,
Language::FI => FI,
Language::JA => JP,
Language::UZ => UZ,
Language::VI => VN,
Language::ID => ID,
Language::NL => NL,
Language::CS => CZ,
})))
.width(FLAGS_WIDTH_BIG)
}
pub fn is_up_to_date(self) -> bool {
matches!(
self,
Language::EN
| Language::IT
| Language::NL
| Language::DE
| Language::UZ
| Language::ZH
| Language::JA
| Language::FR
| Language::EL
| Language::RO
| Language::ZH_TW
| Language::ID
| Language::ES
| Language::CS
| Language::VI
)
}
}
impl fmt::Display for Language {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let lang_str = match self {
Language::EN => "English",
Language::IT => "Italiano",
Language::FR => "Français",
Language::ES => "Español",
Language::PL => "Polski",
Language::DE => "Deutsch",
Language::UK => "Українська",
Language::ZH => "简体中文",
Language::ZH_TW => "繁體中文",
Language::RO => "Română",
Language::KO => "한국어",
Language::TR => "Türkçe",
Language::RU => "Русский",
Language::PT => "Português",
Language::EL => "Ελληνικά",
// Language::FA => "فارسی",
Language::SV => "Svenska",
Language::FI => "Suomi",
Language::JA => "日本語",
Language::UZ => "O'zbekcha",
Language::VI => "Tiếng Việt",
Language::ID => "Bahasa Indonesia",
Language::NL => "Nederlands",
Language::CS => "Čeština",
};
write!(f, "{self:?} - {lang_str}")
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/translations/types/mod.rs | src/translations/types/mod.rs | pub mod language;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/error_logger.rs | src/utils/error_logger.rs | use std::fmt::Display;
/// Trait for logging errors in a unified way
pub trait ErrorLogger<T, E> {
/// Log the error and its location
#[allow(clippy::missing_errors_doc)]
fn log_err(self, loc: Location) -> Result<T, E>;
}
impl<T, E: Display> ErrorLogger<T, E> for Result<T, E> {
fn log_err(self, location: Location) -> Result<T, E> {
if let Err(e) = &self {
let file = location.file;
let line = location.line;
eprintln!("Sniffnet error at [{file}:{line}]: {e}");
// in debug mode, panic on error
#[cfg(debug_assertions)]
panic!();
}
self
}
}
/// Struct to store the location in the code (file and line)
pub struct Location {
pub file: &'static str,
pub line: u32,
}
#[macro_export]
/// Macro to get the current location in the code (file and line)
macro_rules! location {
() => {
Location {
file: file!(),
line: line!(),
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(debug_assertions)]
#[should_panic]
fn test_error_logger_panics_on_err_in_debug_mode() {
let err_result: Result<usize, &str> = Err("test_error");
let _err_handled = err_result.log_err(location!());
}
#[test]
#[cfg(not(debug_assertions))]
fn test_error_logger_no_panic_on_err_in_release_mode() {
let err_result: Result<usize, &str> = Err("test_error");
let err_handled = err_result.log_err(location!());
assert_eq!(err_handled, err_result);
}
#[test]
fn test_error_logger_ok() {
let ok_result: Result<usize, &str> = Ok(2);
let ok_handled = ok_result.log_err(location!());
assert_eq!(ok_handled, ok_result);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/mod.rs | src/utils/mod.rs | pub mod check_updates;
pub mod error_logger;
pub mod formatted_strings;
pub mod types;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/check_updates.rs | src/utils/check_updates.rs | use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::formatted_strings::APP_VERSION;
use crate::{SNIFFNET_LOWERCASE, location};
use semver::Version;
use serde::Deserialize;
use std::time::Duration;
#[derive(Deserialize, Debug)]
struct AppVersion {
name: String,
}
/// Calls a method to check if a newer release of Sniffnet is available on GitHub
/// and updates application status accordingly
pub async fn set_newer_release_status() -> Option<bool> {
is_newer_release_available(6, 30).await
}
/// Checks if a newer release of Sniffnet is available on GitHub
async fn is_newer_release_available(max_retries: u8, seconds_between_retries: u8) -> Option<bool> {
let client = reqwest::Client::builder()
.user_agent(format!("{SNIFFNET_LOWERCASE}-{APP_VERSION}"))
.build()
.log_err(location!())
.ok()?;
let response = client
.get("https://api.github.com/repos/GyulyVGC/sniffnet/releases/latest")
.header("User-agent", format!("{SNIFFNET_LOWERCASE}-{APP_VERSION}"))
.header("Accept", "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28")
.send()
.await;
if let Ok(result) = response {
let result_json = result.json::<AppVersion>().await;
#[cfg(test)]
if result_json.is_err() {
let response2 = client
.get("https://api.github.com/repos/GyulyVGC/sniffnet/releases/latest")
.header("User-agent", format!("{SNIFFNET_LOWERCASE}-{APP_VERSION}"))
.header("Accept", "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28")
.send()
.await;
println!("\nResponse text: {:?}", response2.unwrap());
println!("JSON result: {result_json:?}\n");
}
let mut latest_version = result_json
.unwrap_or_else(|_| AppVersion {
name: String::from(":-("),
})
.name;
latest_version = latest_version.trim().to_string();
// release name sample: v1.2.3
let stripped = latest_version.trim_start_matches('v');
if let (Ok(latest_semver), Ok(current_semver)) =
(Version::parse(stripped), Version::parse(APP_VERSION))
{
return Some(latest_semver > current_semver);
}
}
let retries_left = max_retries - 1;
if retries_left > 0 {
// sleep seconds_between_retries and retries the request
tokio::time::sleep(Duration::from_secs(u64::from(seconds_between_retries))).await;
Box::pin(is_newer_release_available(
retries_left,
seconds_between_retries,
))
.await
} else {
None
}
}
#[cfg(all(test, not(target_os = "macos")))]
mod tests {
use super::*;
#[tokio::test]
async fn fetch_latest_release_from_github() {
let result = is_newer_release_available(6, 2).await;
result.expect("Latest release request from GitHub error");
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/formatted_strings.rs | src/utils/formatted_strings.rs | use std::cmp::min;
use std::net::IpAddr;
use crate::utils::types::timestamp::Timestamp;
use chrono::{Local, TimeZone};
/// Application version number (to be displayed in gui footer)
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
// /// Computes the String representing the percentage of filtered bytes/packets
// pub fn get_percentage_string(observed: u128, filtered: u128) -> String {
// #[allow(clippy::cast_precision_loss)]
// let filtered_float = filtered as f32;
// #[allow(clippy::cast_precision_loss)]
// let observed_float = observed as f32;
// if format!("{:.1}", 100.0 * filtered_float / observed_float).eq("0.0") {
// "<0.1%".to_string()
// } else {
// format!("{:.1}%", 100.0 * filtered_float / observed_float)
// }
// }
pub fn print_cli_welcome_message() {
let ver = APP_VERSION;
print!(
"\n\
╭────────────────────────────────────────────────────────────────────╮\n\
│ │\n\
│ Sniffnet {ver} │\n\
│ │\n\
│ → Website: https://sniffnet.net │\n\
│ → GitHub: https://github.com/GyulyVGC/sniffnet │\n\
│ │\n\
╰────────────────────────────────────────────────────────────────────╯\n\n"
);
}
pub fn get_domain_from_r_dns(r_dns: String) -> String {
if r_dns.parse::<IpAddr>().is_ok() || r_dns.is_empty() {
// rDNS is equal to the corresponding IP address (can't be empty but checking it to be safe)
r_dns
} else {
let parts: Vec<&str> = r_dns.split('.').collect();
let len = parts.len();
if len >= 2 {
let last = parts.get(len - 1).unwrap_or(&"");
let second_last = parts.get(len - 2).unwrap_or(&"");
if last.len() > 3 || second_last.len() > 3 {
format!("{second_last}.{last}")
} else {
let third_last_opt = len.checked_sub(3).and_then(|i| parts.get(i));
match third_last_opt {
Some(third_last) => format!("{third_last}.{second_last}.{last}"),
None => format!("{second_last}.{last}"),
}
}
} else {
r_dns
}
}
}
pub fn get_socket_address(address: &IpAddr, port: Option<u16>) -> String {
if let Some(res) = port {
if address.is_ipv6() {
// IPv6
format!("[{address}]:{res}")
} else {
// IPv4
format!("{address}:{res}")
}
} else {
address.to_string()
}
}
pub fn get_path_termination_string(full_path: &str, i: usize) -> String {
let chars = full_path.chars().collect::<Vec<char>>();
if chars.is_empty() {
return String::new();
}
let tot_len = chars.len();
let slice_len = min(i, tot_len);
let suspensions = if tot_len > i { "…" } else { "" };
[
suspensions,
&chars[tot_len - slice_len..].iter().collect::<String>(),
" ",
]
.concat()
}
pub fn get_formatted_num_seconds(num_seconds: u128) -> String {
match num_seconds {
0..3600 => format!("{:02}:{:02}", num_seconds / 60, num_seconds % 60),
_ => format!(
"{:02}:{:02}:{:02}",
num_seconds / 3600,
(num_seconds % 3600) / 60,
num_seconds % 60
),
}
}
pub fn get_formatted_timestamp(t: Timestamp) -> String {
let date_opt = t
.to_usecs()
.and_then(|usecs| Local.timestamp_micros(usecs).latest());
if let Some(date) = date_opt {
date.format("%Y/%m/%d %H:%M:%S").to_string()
} else {
"?".to_string()
}
}
#[allow(dead_code)]
#[cfg(windows)]
pub fn get_logs_file_path() -> Option<String> {
let mut conf = confy::get_configuration_file_path(crate::SNIFFNET_LOWERCASE, "logs").ok()?;
conf.set_extension("txt");
Some(conf.to_str()?.to_string())
}
#[cfg(all(windows, not(debug_assertions)))]
pub fn redirect_stdout_stderr_to_file()
-> Option<(gag::Redirect<std::fs::File>, gag::Redirect<std::fs::File>)> {
if let Ok(logs_file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(get_logs_file_path()?)
{
return Some((
gag::Redirect::stdout(logs_file.try_clone().ok()?).ok()?,
gag::Redirect::stderr(logs_file).ok()?,
));
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_formatted_num_seconds() {
assert_eq!(get_formatted_num_seconds(0), "00:00");
assert_eq!(get_formatted_num_seconds(1), "00:01");
assert_eq!(get_formatted_num_seconds(28), "00:28");
assert_eq!(get_formatted_num_seconds(59), "00:59");
assert_eq!(get_formatted_num_seconds(60), "01:00");
assert_eq!(get_formatted_num_seconds(61), "01:01");
assert_eq!(get_formatted_num_seconds(119), "01:59");
assert_eq!(get_formatted_num_seconds(120), "02:00");
assert_eq!(get_formatted_num_seconds(121), "02:01");
assert_eq!(get_formatted_num_seconds(3500), "58:20");
assert_eq!(get_formatted_num_seconds(3599), "59:59");
assert_eq!(get_formatted_num_seconds(3600), "01:00:00");
assert_eq!(get_formatted_num_seconds(3601), "01:00:01");
assert_eq!(get_formatted_num_seconds(3661), "01:01:01");
assert_eq!(get_formatted_num_seconds(7139), "01:58:59");
assert_eq!(get_formatted_num_seconds(7147), "01:59:07");
assert_eq!(get_formatted_num_seconds(7199), "01:59:59");
assert_eq!(get_formatted_num_seconds(7200), "02:00:00");
assert_eq!(get_formatted_num_seconds(9999), "02:46:39");
assert_eq!(get_formatted_num_seconds(36000), "10:00:00");
assert_eq!(get_formatted_num_seconds(36001), "10:00:01");
assert_eq!(get_formatted_num_seconds(36061), "10:01:01");
assert_eq!(get_formatted_num_seconds(86400), "24:00:00");
assert_eq!(get_formatted_num_seconds(123456789), "34293:33:09");
assert_eq!(
get_formatted_num_seconds(u128::MAX),
"94522879700260684295381835397713392:04:15"
);
}
#[cfg(windows)]
#[test]
fn test_logs_file_path() {
let file_path = std::path::PathBuf::from(get_logs_file_path().unwrap());
assert!(file_path.is_absolute());
assert_eq!(file_path.file_name().unwrap(), "logs.txt");
}
#[test]
fn test_get_domain_from_r_dns() {
let f = |s: &str| get_domain_from_r_dns(s.to_string());
assert_eq!(f(""), "");
assert_eq!(f("8.8.8.8"), "8.8.8.8");
assert_eq!(f("a.b.c.d"), "b.c.d");
assert_eq!(f("ciao.xyz"), "ciao.xyz");
assert_eq!(f("bye.ciao.xyz"), "ciao.xyz");
assert_eq!(f("ciao.bye.xyz"), "ciao.bye.xyz");
assert_eq!(f("hola.ciao.bye.xyz"), "ciao.bye.xyz");
assert_eq!(f(".bye.xyz"), ".bye.xyz");
assert_eq!(f("bye.xyz"), "bye.xyz");
assert_eq!(f("hola.ciao.b"), "ciao.b");
assert_eq!(f("hola.b.ciao"), "b.ciao");
assert_eq!(f("ciao."), "ciao.");
assert_eq!(f("ciao.."), "ciao..");
assert_eq!(f(".ciao."), "ciao.");
assert_eq!(f("ciao.bye."), "ciao.bye.");
assert_eq!(f("ciao..."), "..");
assert_eq!(f("..bye"), "..bye");
assert_eq!(f("ciao..bye"), "ciao..bye");
assert_eq!(f("..ciao"), ".ciao");
assert_eq!(f("bye..ciao"), ".ciao");
assert_eq!(f("."), ".");
assert_eq!(f(".."), "..");
assert_eq!(f("..."), "..");
assert_eq!(f("no_dots_in_this"), "no_dots_in_this");
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/types/icon.rs | src/utils/types/icon.rs | use iced::widget::Text;
use crate::StyleType;
use crate::gui::styles::style_constants::ICONS;
pub enum Icon {
ArrowBack,
ArrowLeft,
ArrowRight,
ArrowsDown,
AudioHigh,
AudioMute,
Bin,
Book,
BytesThreshold,
Clock,
// Collapse,
Copy,
Generals,
Error,
// Expand,
Feedback,
File,
Forbidden,
Funnel,
GitHub,
// Globe,
HalfSun,
Hourglass1,
Hourglass2,
Hourglass3,
Inspect,
Lightning,
Moon,
NewerVersion,
News,
Notification,
OpenLink,
Overview,
PacketsThreshold,
// Restore,
Roadmap,
// Rocket,
Settings,
Sniffnet,
Sniffnet1,
Sniffnet2,
Sniffnet3,
Sniffnet4,
SortAscending,
SortDescending,
SortNeutral,
Star,
Sun,
ThumbnailOpen,
ThumbnailClose,
// Update1,
// Update2,
// Update3,
Warning,
Waves,
Pause,
Resume,
}
impl Icon {
pub fn codepoint(&self) -> char {
match self {
Icon::ArrowBack => 'C',
Icon::ArrowLeft => 'i',
Icon::ArrowRight => 'j',
Icon::ArrowsDown => ':',
Icon::AudioHigh => 'Z',
Icon::AudioMute => 'Y',
Icon::Bin => 'h',
Icon::BytesThreshold => '[',
Icon::Clock => '9',
Icon::Generals => 'Q',
Icon::Error => 'U',
Icon::Feedback => '=',
Icon::File => '8',
Icon::Forbidden => 'x',
Icon::Funnel => 'V',
Icon::GitHub => 'H',
// Icon::Globe => 'c',
Icon::HalfSun => 'K',
Icon::Hourglass1 => '1',
Icon::Hourglass2 => '2',
Icon::Hourglass3 => '3',
Icon::Inspect => '5',
Icon::Lightning => 'z',
Icon::Moon => 'G',
Icon::Notification => '7',
Icon::Overview => 'd',
Icon::PacketsThreshold => '\\',
// Icon::Restore => 'k',
// Icon::Rocket => 'S',
Icon::Settings => 'a',
Icon::Sniffnet => 'A',
Icon::Sniffnet1 => '!',
Icon::Sniffnet2 => '"',
Icon::Sniffnet3 => '#',
Icon::Sniffnet4 => '$',
Icon::Star => 'g',
Icon::Warning => 'T',
Icon::Waves => 'y',
Icon::Copy => 'u',
Icon::SortAscending => 'm',
Icon::SortDescending => 'l',
Icon::SortNeutral => 'n',
Icon::Sun => 'F',
Icon::OpenLink => 'o',
Icon::ThumbnailOpen => 's',
Icon::ThumbnailClose => 'r',
Icon::Book => 'B',
Icon::Roadmap => '?',
Icon::News => '>',
Icon::NewerVersion => '(',
// Icon::Update1 => '\'',
// Icon::Update2 => '%',
// Icon::Update3 => '&',
// Icon::Expand => 'p',
// Icon::Collapse => 'q',
Icon::Pause => '-',
Icon::Resume => '+',
}
}
pub fn to_text<'a>(&self) -> Text<'a, StyleType> {
Text::new(self.codepoint().to_string()).font(ICONS)
}
pub fn get_hourglass<'a>(num: usize) -> Text<'a, StyleType> {
match num {
2 => Icon::Hourglass2.to_text(),
3 => Icon::Hourglass3.to_text(),
_ => Icon::Hourglass1.to_text(),
}
}
// pub fn get_update<'a>(num: usize) -> Text<'a, StyleType> {
// match num {
// 2 => Icon::Update2.to_text(),
// 3 => Icon::Update3.to_text(),
// _ => Icon::Update1.to_text(),
// }
// }
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/types/file_info.rs | src/utils/types/file_info.rs | use crate::translations::translations_3::{
database_from_file_translation, select_directory_translation, style_from_file_translation,
};
use crate::translations::translations_4::select_capture_translation;
use crate::translations::types::language::Language;
#[derive(Debug, Clone, PartialEq)]
pub enum FileInfo {
Style,
Database,
Directory,
PcapImport,
}
impl FileInfo {
pub fn get_extensions(&self) -> Vec<&'static str> {
match self {
FileInfo::Style => vec!["toml"],
FileInfo::Database => vec!["mmdb"],
FileInfo::Directory => vec![],
FileInfo::PcapImport => vec!["pcap", "pcapng", "cap"],
}
}
pub fn action_info(&self, language: Language) -> &'static str {
match self {
FileInfo::Style => style_from_file_translation(language),
FileInfo::Database => database_from_file_translation(language),
FileInfo::Directory => select_directory_translation(language),
FileInfo::PcapImport => select_capture_translation(language),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/types/timestamp.rs | src/utils/types/timestamp.rs | #[derive(Clone, Default, Debug, Copy, Eq, PartialEq)]
pub struct Timestamp {
secs: i64,
usecs: i64,
}
impl Timestamp {
pub fn new(secs: i64, usecs: i64) -> Self {
Self { secs, usecs }
}
pub fn secs(&self) -> i64 {
self.secs
}
pub fn to_usecs(self) -> Option<i64> {
self.secs
.checked_mul(1_000_000)
.and_then(|x| x.checked_add(self.usecs))
}
pub fn add_secs(&mut self, secs: i64) {
self.secs += secs;
}
}
impl Ord for Timestamp {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.to_usecs().cmp(&other.to_usecs())
}
}
impl PartialOrd for Timestamp {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_timestamp_cmp() {
let t0 = Timestamp::new(-1, 700);
let t1 = Timestamp::new(1, 500);
let t2 = Timestamp::new(1, 600);
let t3 = Timestamp::new(2, 0);
assert_eq!(t0.cmp(&t1), std::cmp::Ordering::Less);
assert_eq!(t1.cmp(&t0), std::cmp::Ordering::Greater);
assert_eq!(t0.cmp(&t2), std::cmp::Ordering::Less);
assert_eq!(t2.cmp(&t0), std::cmp::Ordering::Greater);
assert_eq!(t0.cmp(&t3), std::cmp::Ordering::Less);
assert_eq!(t3.cmp(&t0), std::cmp::Ordering::Greater);
assert_eq!(t1.cmp(&t2), std::cmp::Ordering::Less);
assert_eq!(t2.cmp(&t1), std::cmp::Ordering::Greater);
assert_eq!(t1.cmp(&t3), std::cmp::Ordering::Less);
assert_eq!(t3.cmp(&t1), std::cmp::Ordering::Greater);
assert_eq!(t2.cmp(&t3), std::cmp::Ordering::Less);
assert_eq!(t3.cmp(&t2), std::cmp::Ordering::Greater);
assert_eq!(t0.cmp(&t0), std::cmp::Ordering::Equal);
assert_eq!(t1.cmp(&t1), std::cmp::Ordering::Equal);
}
#[test]
fn test_timestamp_to_usecs() {
let t = Timestamp::new(-1, -700);
assert_eq!(t.to_usecs(), Some(-1_000_700));
let t = Timestamp::new(137, 500);
assert_eq!(t.to_usecs(), Some(137_000_500));
let t = Timestamp::new(0, i64::MAX);
assert_eq!(t.to_usecs(), Some(i64::MAX));
let t = Timestamp::new(0, i64::MIN);
assert_eq!(t.to_usecs(), Some(i64::MIN));
let t = Timestamp::new(i64::MAX, 0);
assert_eq!(t.to_usecs(), None);
let t = Timestamp::new(i64::MIN, 0);
assert_eq!(t.to_usecs(), None);
let t = Timestamp::new(1, i64::MAX);
assert_eq!(t.to_usecs(), None);
let t = Timestamp::new(-1, i64::MIN);
assert_eq!(t.to_usecs(), None);
let t = Timestamp::new(1, i64::MIN);
assert!(t.to_usecs().is_some());
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/types/web_page.rs | src/utils/types/web_page.rs | /// This enum defines the possible web pages to be opened.
#[derive(Debug, Clone)]
pub enum WebPage {
/// Sniffnet's GitHub repository.
Repo,
// /// Sniffnet's website main page.
// Website,
/// Sniffnet's website/download page.
WebsiteDownload,
/// Sniffnet's website/news page.
WebsiteNews,
/// Sniffnet's website/sponsor page.
WebsiteSponsor,
/// Sniffnet Roadmap
Roadmap,
/// Sniffnet issues on GitHub
Issues,
/// Sniffnet issue #60 on GitHub
IssueLanguages,
/// Sniffnet Wiki
Wiki,
/// My GitHub profile
MyGitHub,
}
impl WebPage {
pub fn get_url(&self) -> &str {
match self {
WebPage::Repo => "https://github.com/GyulyVGC/sniffnet",
// WebPage::Website => "https://www.sniffnet.net",
WebPage::WebsiteSponsor => "https://www.sniffnet.net/sponsor",
WebPage::WebsiteDownload => "https://www.sniffnet.net/download",
WebPage::WebsiteNews => "https://www.sniffnet.net/news",
WebPage::Roadmap => "https://whimsical.com/sniffnet-roadmap-Damodrdfx22V9jGnpHSCGo",
WebPage::Issues => "https://github.com/GyulyVGC/sniffnet/issues",
WebPage::IssueLanguages => "https://github.com/GyulyVGC/sniffnet/issues/60",
WebPage::Wiki => "https://github.com/GyulyVGC/sniffnet/wiki",
WebPage::MyGitHub => "https://github.com/GyulyVGC",
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/utils/types/mod.rs | src/utils/types/mod.rs | pub mod file_info;
pub mod icon;
pub mod timestamp;
pub mod web_page;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/manage_packets.rs | src/networking/manage_packets.rs | use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use etherparse::{
ArpHardwareId, EtherType, LaxPacketHeaders, LinkHeader, NetHeaders, TransportHeader,
};
use pcap::Address;
use crate::Protocol;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::arp_type::ArpType;
use crate::networking::types::bogon::is_bogon;
use crate::networking::types::capture_context::CaptureSource;
use crate::networking::types::icmp_type::{IcmpType, IcmpTypeV4, IcmpTypeV6};
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::networking::types::info_traffic::InfoTraffic;
use crate::networking::types::service::Service;
use crate::networking::types::service_query::ServiceQuery;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::networking::types::traffic_type::TrafficType;
use std::fmt::Write;
include!(concat!(env!("OUT_DIR"), "/services.rs"));
/// Calls methods to analyze link, network, and transport headers.
/// Returns the relevant collected information.
pub fn analyze_headers(
headers: LaxPacketHeaders,
mac_addresses: &mut (Option<String>, Option<String>),
exchanged_bytes: &mut u128,
icmp_type: &mut IcmpType,
arp_type: &mut ArpType,
) -> Option<AddressPortPair> {
let mut retval = AddressPortPair::default();
analyze_link_header(
headers.link,
&mut mac_addresses.0,
&mut mac_addresses.1,
exchanged_bytes,
);
let is_arp = matches!(&headers.net, Some(NetHeaders::Arp(_)));
if !analyze_network_header(
headers.net,
exchanged_bytes,
&mut retval.source,
&mut retval.dest,
arp_type,
) {
return None;
}
if !is_arp
&& !analyze_transport_header(
headers.transport,
&mut retval.sport,
&mut retval.dport,
&mut retval.protocol,
icmp_type,
)
{
return None;
}
Some(retval)
}
/// This function analyzes the data link layer header passed as parameter and updates variables
/// passed by reference on the basis of the packet header content.
/// Returns false if packet has to be skipped.
fn analyze_link_header(
link_header: Option<LinkHeader>,
mac_address1: &mut Option<String>,
mac_address2: &mut Option<String>,
exchanged_bytes: &mut u128,
) {
match link_header {
Some(LinkHeader::Ethernet2(header)) => {
*exchanged_bytes += 14;
*mac_address1 = Some(mac_from_dec_to_hex(header.source));
*mac_address2 = Some(mac_from_dec_to_hex(header.destination));
}
Some(LinkHeader::LinuxSll(header)) => {
*exchanged_bytes += 16;
*mac_address1 = if header.sender_address_valid_length == 6
&& header.arp_hrd_type == ArpHardwareId::ETHERNET
&& let Ok(sender) = header.sender_address[0..6].try_into()
{
Some(mac_from_dec_to_hex(sender))
} else {
None
};
*mac_address2 = None;
}
None => {
*mac_address1 = None;
*mac_address2 = None;
}
}
}
/// This function analyzes the network layer header passed as parameter and updates variables
/// passed by reference on the basis of the packet header content.
/// Returns false if packet has to be skipped.
fn analyze_network_header(
network_header: Option<NetHeaders>,
exchanged_bytes: &mut u128,
address1: &mut IpAddr,
address2: &mut IpAddr,
arp_type: &mut ArpType,
) -> bool {
match network_header {
Some(NetHeaders::Ipv4(ipv4header, _)) => {
*address1 = IpAddr::from(ipv4header.source);
*address2 = IpAddr::from(ipv4header.destination);
*exchanged_bytes += u128::from(ipv4header.total_len);
true
}
Some(NetHeaders::Ipv6(ipv6header, _)) => {
*address1 = IpAddr::from(ipv6header.source);
*address2 = IpAddr::from(ipv6header.destination);
*exchanged_bytes += u128::from(40 + ipv6header.payload_length);
true
}
Some(NetHeaders::Arp(arp_packet)) => {
match arp_packet.proto_addr_type {
EtherType::IPV4 => {
*address1 =
match TryInto::<[u8; 4]>::try_into(arp_packet.sender_protocol_addr()) {
Ok(source) => IpAddr::from(source),
Err(_) => return false,
};
*address2 =
match TryInto::<[u8; 4]>::try_into(arp_packet.target_protocol_addr()) {
Ok(destination) => IpAddr::from(destination),
Err(_) => return false,
};
}
EtherType::IPV6 => {
*address1 =
match TryInto::<[u8; 16]>::try_into(arp_packet.sender_protocol_addr()) {
Ok(source) => IpAddr::from(source),
Err(_) => return false,
};
*address2 =
match TryInto::<[u8; 16]>::try_into(arp_packet.target_protocol_addr()) {
Ok(destination) => IpAddr::from(destination),
Err(_) => return false,
};
}
_ => return false,
}
*exchanged_bytes += arp_packet.packet_len() as u128;
*arp_type = ArpType::from_etherparse(arp_packet.operation);
true
}
None => false,
}
}
/// This function analyzes the transport layer header passed as parameter and updates variables
/// passed by reference on the basis of the packet header content.
/// Returns false if packet has to be skipped.
fn analyze_transport_header(
transport_header: Option<TransportHeader>,
port1: &mut Option<u16>,
port2: &mut Option<u16>,
protocol: &mut Protocol,
icmp_type: &mut IcmpType,
) -> bool {
match transport_header {
Some(TransportHeader::Udp(udp_header)) => {
*port1 = Some(udp_header.source_port);
*port2 = Some(udp_header.destination_port);
*protocol = Protocol::UDP;
true
}
Some(TransportHeader::Tcp(tcp_header)) => {
*port1 = Some(tcp_header.source_port);
*port2 = Some(tcp_header.destination_port);
*protocol = Protocol::TCP;
true
}
Some(TransportHeader::Icmpv4(icmpv4_header)) => {
*port1 = None;
*port2 = None;
*protocol = Protocol::ICMP;
*icmp_type = IcmpTypeV4::from_etherparse(&icmpv4_header.icmp_type);
true
}
Some(TransportHeader::Icmpv6(icmpv6_header)) => {
*port1 = None;
*port2 = None;
*protocol = Protocol::ICMP;
*icmp_type = IcmpTypeV6::from_etherparse(&icmpv6_header.icmp_type);
true
}
None => false,
}
}
pub fn get_service(
key: &AddressPortPair,
traffic_direction: TrafficDirection,
my_interface_addresses: &[Address],
) -> Service {
if key.protocol == Protocol::ICMP || key.protocol == Protocol::ARP {
return Service::NotApplicable;
}
let Some(port1) = key.sport else {
return Service::NotApplicable;
};
let Some(port2) = key.dport else {
return Service::NotApplicable;
};
// to return the service associated with the highest score:
// score = service_is_some * (port_is_well_known + bonus_direction)
// service_is_some: 1 if some, 0 if unknown
// port_is_well_known: 3 if well known, 1 if not
// bonus_direction: +1 assigned to remote port, or to destination port in case of multicast
let compute_service_score = |service: &Service, port: u16, bonus_direction: bool| {
let service_is_some = u8::from(matches!(service, Service::Name(_)));
let port_is_well_known = if port < 1024 { 3 } else { 1 };
let bonus_direction = u8::from(bonus_direction);
service_is_some * (port_is_well_known + bonus_direction)
};
let unknown = Service::Unknown;
let service1 = SERVICES
.get(&ServiceQuery(port1, key.protocol))
.unwrap_or(&unknown);
let service2 = SERVICES
.get(&ServiceQuery(port2, key.protocol))
.unwrap_or(&unknown);
let dest_ip = key.dest;
let bonus_dest = traffic_direction.eq(&TrafficDirection::Outgoing)
|| dest_ip.is_multicast()
|| is_broadcast_address(&dest_ip, my_interface_addresses);
let score1 = compute_service_score(service1, port1, !bonus_dest);
let score2 = compute_service_score(service2, port2, bonus_dest);
if score1 > score2 {
*service1
} else {
*service2
}
}
/// Function to insert the source and destination of a packet into the map containing the analyzed traffic
pub fn modify_or_insert_in_map(
info_traffic_msg: &mut InfoTraffic,
key: &AddressPortPair,
cs: &CaptureSource,
mac_addresses: (Option<String>, Option<String>),
icmp_type: IcmpType,
arp_type: ArpType,
exchanged_bytes: u128,
) -> (TrafficDirection, Service) {
let mut traffic_direction = TrafficDirection::default();
let mut service = Service::Unknown;
if !info_traffic_msg.map.contains_key(key) {
// first occurrence of key (in this time interval)
let my_interface_addresses = cs.get_addresses();
// determine traffic direction
let source_ip = &key.source;
let destination_ip = &key.dest;
traffic_direction = get_traffic_direction(
source_ip,
destination_ip,
key.sport,
key.dport,
my_interface_addresses,
);
// determine upper layer service
service = get_service(key, traffic_direction, my_interface_addresses);
}
let timestamp = info_traffic_msg.last_packet_timestamp;
let new_info = info_traffic_msg
.map
.entry(*key)
.and_modify(|info| {
info.transmitted_bytes += exchanged_bytes;
info.transmitted_packets += 1;
info.final_timestamp = timestamp;
if key.protocol.eq(&Protocol::ICMP) {
info.icmp_types
.entry(icmp_type)
.and_modify(|n| *n += 1)
.or_insert(1);
}
if key.protocol.eq(&Protocol::ARP) {
info.arp_types
.entry(arp_type)
.and_modify(|n| *n += 1)
.or_insert(1);
}
})
.or_insert_with(|| InfoAddressPortPair {
mac_address1: mac_addresses.0,
mac_address2: mac_addresses.1,
transmitted_bytes: exchanged_bytes,
transmitted_packets: 1,
initial_timestamp: timestamp,
final_timestamp: timestamp,
service,
traffic_direction,
icmp_types: if key.protocol.eq(&Protocol::ICMP) {
HashMap::from([(icmp_type, 1)])
} else {
HashMap::new()
},
arp_types: if key.protocol.eq(&Protocol::ARP) {
HashMap::from([(arp_type, 1)])
} else {
HashMap::new()
},
});
(new_info.traffic_direction, new_info.service)
}
/// Returns the traffic direction observed (incoming or outgoing)
fn get_traffic_direction(
source_ip: &IpAddr,
destination_ip: &IpAddr,
source_port: Option<u16>,
dest_port: Option<u16>,
my_interface_addresses: &[Address],
) -> TrafficDirection {
let my_interface_addresses_ip: Vec<IpAddr> = my_interface_addresses
.iter()
.map(|address| address.addr)
.collect();
// first let's handle TCP and UDP loopback
if source_ip.is_loopback()
&& destination_ip.is_loopback()
&& let (Some(sport), Some(dport)) = (source_port, dest_port)
{
return if sport > dport {
TrafficDirection::Outgoing
} else {
TrafficDirection::Incoming
};
}
// if interface_addresses is empty, check if the IP is a bogon (useful when importing pcap files)
let is_local = |interface_addresses: &Vec<IpAddr>, ip: &IpAddr| -> bool {
if interface_addresses.is_empty() {
is_bogon(ip).is_some()
} else {
interface_addresses.contains(ip)
}
};
if is_local(&my_interface_addresses_ip, source_ip) {
// source is local
TrafficDirection::Outgoing
} else if source_ip.ne(&IpAddr::V4(Ipv4Addr::UNSPECIFIED))
&& source_ip.ne(&IpAddr::V6(Ipv6Addr::UNSPECIFIED))
{
// source not local and different from 0.0.0.0 and different from ::
TrafficDirection::Incoming
} else if !is_local(&my_interface_addresses_ip, destination_ip) {
// source is 0.0.0.0 or :: (local not yet assigned an IP) and destination is not local
TrafficDirection::Outgoing
} else {
TrafficDirection::Incoming
}
}
/// Returns the traffic type observed (unicast, multicast or broadcast)
/// It refers to the remote host
pub fn get_traffic_type(
destination_ip: &IpAddr,
my_interface_addresses: &[Address],
traffic_direction: TrafficDirection,
) -> TrafficType {
if traffic_direction.eq(&TrafficDirection::Outgoing) {
if destination_ip.is_multicast() {
TrafficType::Multicast
} else if is_broadcast_address(destination_ip, my_interface_addresses) {
TrafficType::Broadcast
} else {
TrafficType::Unicast
}
} else {
TrafficType::Unicast
}
}
/// Determines if the input address is a broadcast address or not.
///
/// # Arguments
///
/// * `address` - string representing an IPv4 or IPv6 network address.
fn is_broadcast_address(address: &IpAddr, my_interface_addresses: &[Address]) -> bool {
if address.eq(&IpAddr::from([255, 255, 255, 255])) {
return true;
}
// check if directed broadcast
let my_broadcast_addresses: Vec<IpAddr> = my_interface_addresses
.iter()
.map(|address| {
address
.broadcast_addr
.unwrap_or_else(|| IpAddr::from([255, 255, 255, 255]))
})
.collect();
if my_broadcast_addresses.contains(address) {
return true;
}
false
}
/// Determines if the connection is local
pub fn is_local_connection(
address_to_lookup: &IpAddr,
my_interface_addresses: &Vec<Address>,
) -> bool {
let mut ret_val = false;
for address in my_interface_addresses {
match address.addr {
IpAddr::V4(local_addr) => {
if let IpAddr::V4(address_to_lookup_v4) = address_to_lookup {
// remote is link local?
if address_to_lookup_v4.is_link_local() {
ret_val = true;
}
// is the same subnet?
else if let Some(IpAddr::V4(netmask)) = address.netmask {
let mut local_subnet = Vec::new();
let mut remote_subnet = Vec::new();
let netmask_digits = netmask.octets();
let local_addr_digits = local_addr.octets();
let remote_addr_digits = address_to_lookup_v4.octets();
for (i, netmask_digit) in netmask_digits.iter().enumerate() {
local_subnet.push(netmask_digit & local_addr_digits[i]);
remote_subnet.push(netmask_digit & remote_addr_digits[i]);
}
if local_subnet == remote_subnet {
ret_val = true;
}
}
}
}
IpAddr::V6(local_addr) => {
if let IpAddr::V6(address_to_lookup_v6) = address_to_lookup {
// remote is link local?
if address_to_lookup_v6.is_unicast_link_local() {
ret_val = true;
}
// is the same subnet?
else if let Some(IpAddr::V6(netmask)) = address.netmask {
let mut local_subnet = Vec::new();
let mut remote_subnet = Vec::new();
let netmask_digits = netmask.octets();
let local_addr_digits = local_addr.octets();
let remote_addr_digits = address_to_lookup_v6.octets();
for (i, netmask_digit) in netmask_digits.iter().enumerate() {
local_subnet.push(netmask_digit & local_addr_digits[i]);
remote_subnet.push(netmask_digit & remote_addr_digits[i]);
}
if local_subnet == remote_subnet {
ret_val = true;
}
}
}
}
}
}
ret_val
}
/// Determines if the address passed as parameter belong to the chosen adapter
pub fn is_my_address(local_address: &IpAddr, my_interface_addresses: &Vec<Address>) -> bool {
for address in my_interface_addresses {
if address.addr.eq(local_address) {
return true;
}
}
local_address.is_loopback()
}
/// Converts a MAC address in its hexadecimal form
fn mac_from_dec_to_hex(mac_dec: [u8; 6]) -> String {
let mut mac_hex = String::new();
for n in &mac_dec {
let _ = write!(mac_hex, "{n:02x}:");
}
mac_hex.pop();
mac_hex
}
pub fn get_address_to_lookup(key: &AddressPortPair, traffic_direction: TrafficDirection) -> IpAddr {
match traffic_direction {
TrafficDirection::Outgoing => key.dest,
TrafficDirection::Incoming => key.source,
}
}
#[cfg(test)]
mod tests {
use pcap::Address;
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use crate::Protocol;
use crate::Service;
use crate::networking::manage_packets::{
get_service, get_traffic_direction, get_traffic_type, is_local_connection,
mac_from_dec_to_hex,
};
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::service_query::ServiceQuery;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::networking::types::traffic_type::TrafficType;
include!(concat!(env!("OUT_DIR"), "/services.rs"));
#[test]
fn mac_simple_test() {
let result = mac_from_dec_to_hex([255, 255, 10, 177, 9, 15]);
assert_eq!(result, "ff:ff:0a:b1:09:0f".to_string());
}
#[test]
fn mac_all_zero_test() {
let result = mac_from_dec_to_hex([0, 0, 0, 0, 0, 0]);
assert_eq!(result, "00:00:00:00:00:00".to_string());
}
#[test]
fn ipv6_simple_test() {
let result = IpAddr::from([
255, 10, 10, 255, 255, 10, 10, 255, 255, 10, 10, 255, 255, 10, 10, 255,
]);
assert_eq!(
result.to_string(),
"ff0a:aff:ff0a:aff:ff0a:aff:ff0a:aff".to_string()
);
}
#[test]
fn ipv6_zeros_in_the_middle() {
let result =
IpAddr::from([255, 10, 10, 255, 0, 0, 0, 0, 28, 4, 4, 28, 255, 1, 0, 0]).to_string();
assert_eq!(result, "ff0a:aff::1c04:41c:ff01:0".to_string());
}
#[test]
fn ipv6_leading_zeros() {
let result =
IpAddr::from([0, 0, 0, 0, 0, 0, 0, 0, 28, 4, 4, 28, 255, 1, 0, 10]).to_string();
assert_eq!(result, "::1c04:41c:ff01:a".to_string());
}
#[test]
fn ipv6_tail_one_after_zeros() {
let result =
IpAddr::from([28, 4, 4, 28, 255, 1, 0, 10, 0, 0, 0, 0, 0, 0, 0, 1]).to_string();
assert_eq!(result, "1c04:41c:ff01:a::1".to_string());
}
#[test]
fn ipv6_tail_zeros() {
let result =
IpAddr::from([28, 4, 4, 28, 255, 1, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0]).to_string();
assert_eq!(result, "1c04:41c:ff01:a::".to_string());
}
#[test]
fn ipv6_multiple_zero_sequences_first_longer() {
let result = IpAddr::from([32, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1]).to_string();
assert_eq!(result, "2000::101:0:0:1".to_string());
}
#[test]
fn ipv6_multiple_zero_sequences_first_longer_head() {
let result = IpAddr::from([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1]).to_string();
assert_eq!(result, "::101:0:0:1".to_string());
}
#[test]
fn ipv6_multiple_zero_sequences_second_longer() {
let result = IpAddr::from([1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 118]).to_string();
assert_eq!(result, "100:0:0:1::376".to_string());
}
#[test]
fn ipv6_multiple_zero_sequences_second_longer_tail() {
let result = IpAddr::from([32, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]).to_string();
assert_eq!(result, "2000:0:0:1:101::".to_string());
}
#[test]
fn ipv6_multiple_zero_sequences_equal_length() {
let result = IpAddr::from([118, 3, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1]).to_string();
assert_eq!(result, "7603::1:101:0:0:1".to_string());
}
#[test]
fn ipv6_all_zeros() {
let result = IpAddr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).to_string();
assert_eq!(result, "::".to_string());
}
#[test]
fn ipv6_x_all_zeros() {
let result = IpAddr::from([161, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).to_string();
assert_eq!(result, "a100::".to_string());
}
#[test]
fn ipv6_all_zeros_x() {
let result = IpAddr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 176]).to_string();
assert_eq!(result, "::b0".to_string());
}
#[test]
fn ipv6_many_zeros_but_no_compression() {
let result = IpAddr::from([0, 16, 16, 0, 0, 1, 7, 0, 0, 2, 216, 0, 1, 0, 0, 1]).to_string();
assert_eq!(result, "10:1000:1:700:2:d800:100:1".to_string());
}
#[test]
fn traffic_direction_ipv4_test() {
let mut address_vec: Vec<Address> = Vec::new();
let my_address_v4 = Address {
addr: IpAddr::V4("172.20.10.9".parse().unwrap()),
netmask: Some(IpAddr::V4("255.255.255.240".parse().unwrap())),
broadcast_addr: Some(IpAddr::V4("172.20.10.15".parse().unwrap())),
dst_addr: None,
};
let my_address_v6 = Address {
addr: IpAddr::V6("fe80::8b1:1234:5678:d065".parse().unwrap()),
netmask: Some(IpAddr::V6("ffff:ffff:ffff:ffff::".parse().unwrap())),
broadcast_addr: None,
dst_addr: None,
};
address_vec.push(my_address_v4);
address_vec.push(my_address_v6);
let result1 = get_traffic_direction(
&IpAddr::from([172, 20, 10, 9]),
&IpAddr::from([99, 88, 77, 0]),
Some(99),
Some(99),
&address_vec,
);
assert_eq!(result1, TrafficDirection::Outgoing);
let result2 = get_traffic_direction(
&IpAddr::from([172, 20, 10, 10]),
&IpAddr::from([172, 20, 10, 9]),
Some(99),
Some(99),
&address_vec,
);
assert_eq!(result2, TrafficDirection::Incoming);
let result3 = get_traffic_direction(
&IpAddr::from([172, 20, 10, 9]),
&IpAddr::V4(Ipv4Addr::UNSPECIFIED),
Some(99),
Some(99),
&address_vec,
);
assert_eq!(result3, TrafficDirection::Outgoing);
let result4 = get_traffic_direction(
&IpAddr::V4(Ipv4Addr::UNSPECIFIED),
&IpAddr::from([172, 20, 10, 9]),
Some(99),
Some(99),
&address_vec,
);
assert_eq!(result4, TrafficDirection::Incoming);
let result4 = get_traffic_direction(
&IpAddr::V4(Ipv4Addr::UNSPECIFIED),
&IpAddr::from([172, 20, 10, 10]),
Some(99),
Some(99),
&address_vec,
);
assert_eq!(result4, TrafficDirection::Outgoing);
}
#[test]
fn traffic_type_multicast_ipv4_test() {
let result1 = get_traffic_type(
&IpAddr::from([227, 255, 255, 0]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Multicast);
let result2 = get_traffic_type(
&IpAddr::from([239, 255, 255, 255]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result2, TrafficType::Multicast);
let result3 = get_traffic_type(
&IpAddr::from([224, 0, 0, 0]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result3, TrafficType::Multicast);
let result4 = get_traffic_type(
&IpAddr::from([223, 255, 255, 255]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result4, TrafficType::Unicast);
let result5 = get_traffic_type(
&IpAddr::from([240, 0, 0, 0]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result5, TrafficType::Unicast);
let result6 = get_traffic_type(
&IpAddr::from([227, 255, 255, 0]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result6, TrafficType::Unicast);
let result7 = get_traffic_type(
&IpAddr::from([239, 255, 255, 255]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result7, TrafficType::Unicast);
let result8 = get_traffic_type(
&IpAddr::from([224, 0, 0, 0]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result8, TrafficType::Unicast);
let result9 = get_traffic_type(
&IpAddr::from([223, 255, 255, 255]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result9, TrafficType::Unicast);
let result10 = get_traffic_type(
&IpAddr::from([240, 0, 0, 0]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result10, TrafficType::Unicast);
}
#[test]
fn traffic_type_multicast_ipv6_test() {
let result1 = get_traffic_type(
&IpAddr::from_str("ff00::").unwrap(),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Multicast);
let result2 = get_traffic_type(
&IpAddr::from_str("fe80:1234::").unwrap(),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result2, TrafficType::Unicast);
let result3 = get_traffic_type(
&IpAddr::from_str("ffff:ffff:ffff::").unwrap(),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result3, TrafficType::Multicast);
let result4 = get_traffic_type(
&IpAddr::from_str("ff00::").unwrap(),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result4, TrafficType::Unicast);
let result5 = get_traffic_type(
&IpAddr::from_str("fe80:1234::").unwrap(),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result5, TrafficType::Unicast);
let result6 = get_traffic_type(
&IpAddr::from_str("ffff:ffff:ffff::").unwrap(),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result6, TrafficType::Unicast);
}
#[test]
fn traffic_type_host_local_broadcast_test() {
let result1 = get_traffic_type(
&IpAddr::from([255, 255, 255, 255]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Broadcast);
let result2 = get_traffic_type(
&IpAddr::from([255, 255, 255, 255]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result2, TrafficType::Unicast);
let result3 = get_traffic_type(
&IpAddr::from([255, 255, 255, 254]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result3, TrafficType::Unicast);
let mut address_vec: Vec<Address> = Vec::new();
let my_address = Address {
addr: IpAddr::V4("172.20.10.9".parse().unwrap()),
netmask: Some(IpAddr::V4("255.255.255.240".parse().unwrap())),
broadcast_addr: Some(IpAddr::V4("172.20.10.15".parse().unwrap())),
dst_addr: None,
};
address_vec.push(my_address);
let result1 = get_traffic_type(
&IpAddr::from([255, 255, 255, 255]),
&address_vec,
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Broadcast);
let result2 = get_traffic_type(
&IpAddr::from([255, 255, 255, 255]),
&address_vec,
TrafficDirection::Incoming,
);
assert_eq!(result2, TrafficType::Unicast);
}
#[test]
fn traffic_type_host_directed_broadcast_test() {
let result1 = get_traffic_type(
&IpAddr::from([172, 20, 10, 15]),
&[],
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Unicast);
let result2 = get_traffic_type(
&IpAddr::from([172, 20, 10, 15]),
&[],
TrafficDirection::Incoming,
);
assert_eq!(result2, TrafficType::Unicast);
let mut address_vec: Vec<Address> = Vec::new();
let my_address = Address {
addr: IpAddr::V4("172.20.10.9".parse().unwrap()),
netmask: Some(IpAddr::V4("255.255.255.240".parse().unwrap())),
broadcast_addr: Some(IpAddr::V4("172.20.10.15".parse().unwrap())),
dst_addr: None,
};
address_vec.push(my_address);
let result1 = get_traffic_type(
&IpAddr::from([172, 20, 10, 15]),
&address_vec,
TrafficDirection::Outgoing,
);
assert_eq!(result1, TrafficType::Broadcast);
let result2 = get_traffic_type(
&IpAddr::from([172, 20, 10, 15]),
&address_vec,
TrafficDirection::Incoming,
);
assert_eq!(result2, TrafficType::Unicast);
}
#[test]
fn is_local_connection_ipv4_test() {
let mut address_vec: Vec<Address> = Vec::new();
let my_address_v4 = Address {
addr: IpAddr::V4("172.20.10.9".parse().unwrap()),
netmask: Some(IpAddr::V4("255.255.255.240".parse().unwrap())),
broadcast_addr: Some(IpAddr::V4("172.20.10.15".parse().unwrap())),
dst_addr: None,
};
let my_address_v6 = Address {
addr: IpAddr::V6("fe80::8b1:1234:5678:d065".parse().unwrap()),
netmask: Some(IpAddr::V6("ffff:ffff:ffff:ffff::".parse().unwrap())),
broadcast_addr: None,
dst_addr: None,
};
address_vec.push(my_address_v4);
address_vec.push(my_address_v6);
let result1 = is_local_connection(&IpAddr::from([104, 18, 43, 158]), &address_vec);
assert_eq!(result1, false);
let result2 = is_local_connection(&IpAddr::from([172, 20, 10, 15]), &address_vec);
assert_eq!(result2, true);
let result3 = is_local_connection(&IpAddr::from([172, 20, 10, 16]), &address_vec);
assert_eq!(result3, false);
let result4 = is_local_connection(&IpAddr::from([172, 20, 10, 0]), &address_vec);
assert_eq!(result4, true);
let result5 = is_local_connection(&IpAddr::from([172, 20, 10, 7]), &address_vec);
assert_eq!(result5, true);
let result6 = is_local_connection(&IpAddr::from([172, 20, 10, 99]), &address_vec);
assert_eq!(result6, false);
}
#[test]
fn is_local_connection_ipv6_test() {
let mut address_vec: Vec<Address> = Vec::new();
let my_address_v4 = Address {
addr: IpAddr::V4("172.20.10.9".parse().unwrap()),
netmask: Some(IpAddr::V4("255.255.255.240".parse().unwrap())),
broadcast_addr: Some(IpAddr::V4("172.20.10.15".parse().unwrap())),
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | true |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/parse_packets.rs | src/networking/parse_packets.rs | //! Module containing functions executed by the thread in charge of parsing sniffed packets
use crate::gui::types::filters::Filters;
use crate::location;
use crate::mmdb::asn::get_asn;
use crate::mmdb::country::get_country;
use crate::mmdb::types::mmdb_reader::MmdbReaders;
use crate::networking::manage_packets::{
analyze_headers, get_address_to_lookup, get_traffic_type, is_local_connection,
modify_or_insert_in_map,
};
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::arp_type::ArpType;
use crate::networking::types::bogon::is_bogon;
use crate::networking::types::capture_context::{CaptureContext, CaptureSource, CaptureType};
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::host::{Host, HostMessage};
use crate::networking::types::icmp_type::IcmpType;
use crate::networking::types::info_traffic::InfoTraffic;
use crate::networking::types::my_link_type::MyLinkType;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::formatted_strings::get_domain_from_r_dns;
use crate::utils::types::timestamp::Timestamp;
use async_channel::Sender;
use dns_lookup::lookup_addr;
use etherparse::{EtherType, LaxPacketHeaders};
use pcap::{Address, Packet, PacketHeader};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tokio::sync::broadcast::Receiver;
/// The calling thread enters a loop in which it waits for network packets
#[allow(clippy::too_many_lines)]
pub fn parse_packets(
cap_id: usize,
mut cs: CaptureSource,
mmdb_readers: &MmdbReaders,
capture_context: CaptureContext,
filters: Filters,
tx: &Sender<BackendTrafficMessage>,
freeze_rxs: (Receiver<()>, Receiver<()>),
) {
let (mut freeze_rx, mut freeze_rx_2) = freeze_rxs;
let my_link_type = capture_context.my_link_type();
if !my_link_type.is_supported() {
return;
}
let (Some(cap), mut savefile) = capture_context.consume() else {
return;
};
let mut info_traffic_msg = InfoTraffic::default();
let resolutions_state = Arc::new(Mutex::new(AddressesResolutionState::default()));
// list of newly resolved hosts to be sent (batched to avoid UI updates too often)
let new_hosts_to_send = Arc::new(Mutex::new(Vec::new()));
// instant of the first parsed packet plus multiples of 1 second (only used in live captures)
let mut first_packet_ticks = None;
let (pcap_tx, pcap_rx) = std::sync::mpsc::sync_channel(10_000);
let _ = thread::Builder::new()
.name("thread_packet_stream".to_string())
.spawn(move || packet_stream(cap, &pcap_tx, &mut freeze_rx_2, &filters))
.log_err(location!());
loop {
// check if we need to freeze the parsing
if freeze_rx.try_recv().is_ok() {
// wait until unfreeze
let _ = freeze_rx.blocking_recv();
// reset the first packet ticks
first_packet_ticks = Some(Instant::now());
}
let (packet_res, cap_stats) = pcap_rx
.recv_timeout(Duration::from_millis(150))
.unwrap_or((Err(pcap::Error::TimeoutExpired), None));
if tx.is_closed() {
return;
}
if matches!(cs, CaptureSource::Device(_)) {
maybe_send_tick_run_live(
cap_id,
&mut info_traffic_msg,
&new_hosts_to_send,
&mut cs,
&mut first_packet_ticks,
tx,
);
}
match packet_res {
Err(e) => {
if e == pcap::Error::NoMorePackets {
// send a message including data from the last interval (only happens in offline captures)
let _ = tx.send_blocking(BackendTrafficMessage::TickRun(
cap_id,
info_traffic_msg,
new_hosts_to_send.lock().unwrap().drain(..).collect(),
true,
));
// wait until there is still some thread doing rdns
while tx.sender_count() > 1 {
thread::sleep(Duration::from_millis(1000));
}
// send one last message including all pending hosts
let _ = tx.send_blocking(BackendTrafficMessage::PendingHosts(
cap_id,
new_hosts_to_send.lock().unwrap().drain(..).collect(),
));
return;
}
}
Ok(packet) => {
if let Some(headers) = get_sniffable_headers(&packet.data, my_link_type) {
#[allow(clippy::useless_conversion)]
let secs = i64::from(packet.header.ts.tv_sec);
#[allow(clippy::useless_conversion)]
let usecs = i64::from(packet.header.ts.tv_usec);
let next_packet_timestamp = Timestamp::new(secs, usecs);
if matches!(cs, CaptureSource::File(_)) {
maybe_send_tick_run_offline(
cap_id,
&mut info_traffic_msg,
&new_hosts_to_send,
next_packet_timestamp,
tx,
);
} else if first_packet_ticks.is_none() {
first_packet_ticks = Some(Instant::now());
}
info_traffic_msg.last_packet_timestamp = next_packet_timestamp;
let mut exchanged_bytes = 0;
let mut mac_addresses = (None, None);
let mut icmp_type = IcmpType::default();
let mut arp_type = ArpType::default();
let key_option = analyze_headers(
headers,
&mut mac_addresses,
&mut exchanged_bytes,
&mut icmp_type,
&mut arp_type,
);
let Some(key) = key_option else {
continue;
};
// save this packet to PCAP file
if let Some(file) = savefile.as_mut() {
file.write(&Packet {
header: &packet.header,
data: &packet.data,
});
}
// update the map
let (traffic_direction, service) = modify_or_insert_in_map(
&mut info_traffic_msg,
&key,
&cs,
mac_addresses,
icmp_type,
arp_type,
exchanged_bytes,
);
info_traffic_msg
.tot_data_info
.add_packet(exchanged_bytes, traffic_direction);
// check the rDNS status of this address and act accordingly
let address_to_lookup = get_address_to_lookup(&key, traffic_direction);
let mut r_dns_waiting_resolution = false;
let mut resolutions_lock = resolutions_state.lock().unwrap();
let r_dns_already_resolved = resolutions_lock
.addresses_resolved
.contains_key(&address_to_lookup);
if !r_dns_already_resolved {
r_dns_waiting_resolution = resolutions_lock
.addresses_waiting_resolution
.contains_key(&address_to_lookup);
}
match (r_dns_waiting_resolution, r_dns_already_resolved) {
(false, false) => {
// rDNS not requested yet (first occurrence of this address to lookup)
// Add this address to the map of addresses waiting for a resolution
// Useful to NOT perform again a rDNS lookup for this entry
resolutions_lock.addresses_waiting_resolution.insert(
address_to_lookup,
DataInfo::new_with_first_packet(exchanged_bytes, traffic_direction),
);
drop(resolutions_lock);
// launch new thread to resolve host name
let key2 = key;
let resolutions_state2 = resolutions_state.clone();
let new_hosts_to_send2 = new_hosts_to_send.clone();
let interface_addresses = cs.get_addresses().clone();
let mmdb_readers_2 = mmdb_readers.clone();
let tx2 = tx.clone();
let _ = thread::Builder::new()
.name("thread_reverse_dns_lookup".to_string())
.spawn(move || {
reverse_dns_lookup(
&resolutions_state2,
&new_hosts_to_send2,
&key2,
traffic_direction,
&interface_addresses,
&mmdb_readers_2,
&tx2,
);
})
.log_err(location!());
}
(true, false) => {
// waiting for a previously requested rDNS resolution
// update the corresponding waiting address data
resolutions_lock
.addresses_waiting_resolution
.entry(address_to_lookup)
.and_modify(|data_info| {
data_info.add_packet(exchanged_bytes, traffic_direction);
});
drop(resolutions_lock);
}
(_, true) => {
// rDNS already resolved
// update the corresponding host's data info
let host = resolutions_lock
.addresses_resolved
.get(&address_to_lookup)
.unwrap_or(&Host::default())
.clone();
drop(resolutions_lock);
info_traffic_msg
.hosts
.entry(host)
.and_modify(|data_info_host| {
data_info_host
.data_info
.add_packet(exchanged_bytes, traffic_direction);
})
.or_insert_with(|| {
let my_interface_addresses = cs.get_addresses();
let traffic_type = get_traffic_type(
&address_to_lookup,
my_interface_addresses,
traffic_direction,
);
let is_loopback = address_to_lookup.is_loopback();
let is_local = is_local_connection(
&address_to_lookup,
my_interface_addresses,
);
let is_bogon = is_bogon(&address_to_lookup);
DataInfoHost {
data_info: DataInfo::new_with_first_packet(
exchanged_bytes,
traffic_direction,
),
is_favorite: false,
is_loopback,
is_local,
is_bogon,
traffic_type,
}
});
}
}
//increment the packet count for the sniffed service
info_traffic_msg
.services
.entry(service)
.and_modify(|data_info| {
data_info.add_packet(exchanged_bytes, traffic_direction);
})
.or_insert_with(|| {
DataInfo::new_with_first_packet(exchanged_bytes, traffic_direction)
});
// update dropped packets number
if let Some(stats) = cap_stats {
info_traffic_msg.dropped_packets = stats.dropped;
}
}
}
}
}
}
pub(super) fn get_sniffable_headers(
packet: &[u8],
my_link_type: MyLinkType,
) -> Option<LaxPacketHeaders<'_>> {
match my_link_type {
MyLinkType::Ethernet(_) | MyLinkType::Unsupported(_) | MyLinkType::NotYetAssigned => {
LaxPacketHeaders::from_ethernet(packet).ok()
}
MyLinkType::RawIp(_) | MyLinkType::IPv4(_) | MyLinkType::IPv6(_) => {
LaxPacketHeaders::from_ip(packet).ok()
}
MyLinkType::LinuxSll(_) => from_linux_sll(packet, true),
MyLinkType::LinuxSll2(_) => from_linux_sll(packet, false),
MyLinkType::Null(_) | MyLinkType::Loop(_) => from_null(packet),
}
}
fn from_null(packet: &[u8]) -> Option<LaxPacketHeaders<'_>> {
if packet.len() <= 4 {
return None;
}
let is_valid_af_inet = {
// based on https://wiki.wireshark.org/NullLoopback.md (2023-12-31)
fn matches(value: u32) -> bool {
match value {
// 2 = IPv4 on all platforms
// 24, 28, or 30 = IPv6 depending on platform
2 | 24 | 28 | 30 => true,
_ => false,
}
}
let h = &packet[..4];
let b = [h[0], h[1], h[2], h[3]];
// check both big endian and little endian representations
// as some OS'es use native endianness and others use big endian
matches(u32::from_le_bytes(b)) || matches(u32::from_be_bytes(b))
};
if is_valid_af_inet {
LaxPacketHeaders::from_ip(&packet[4..]).ok()
} else {
None
}
}
fn from_linux_sll(packet: &[u8], is_v1: bool) -> Option<LaxPacketHeaders<'_>> {
let header_len = if is_v1 { 16 } else { 20 };
if packet.len() <= header_len {
return None;
}
let protocol_type = u16::from_be_bytes(if is_v1 {
[packet[14], packet[15]]
} else {
[packet[0], packet[1]]
});
let payload = &packet[header_len..];
Some(LaxPacketHeaders::from_ether_type(
EtherType(protocol_type),
payload,
))
}
fn reverse_dns_lookup(
resolutions_state: &Arc<Mutex<AddressesResolutionState>>,
new_hosts_to_send: &Arc<Mutex<Vec<HostMessage>>>,
key: &AddressPortPair,
traffic_direction: TrafficDirection,
interface_addresses: &Vec<Address>,
mmdb_readers: &MmdbReaders,
// needed to know that this thread is still running!
_tx: &Sender<BackendTrafficMessage>,
) {
let address_to_lookup = get_address_to_lookup(key, traffic_direction);
// perform rDNS lookup
let lookup_result = lookup_addr(&address_to_lookup);
// get new host info and build the new host
let traffic_type = get_traffic_type(&address_to_lookup, interface_addresses, traffic_direction);
let is_loopback = address_to_lookup.is_loopback();
let is_local = is_local_connection(&address_to_lookup, interface_addresses);
let is_bogon = is_bogon(&address_to_lookup);
let country = get_country(&address_to_lookup, &mmdb_readers.country);
let asn = get_asn(&address_to_lookup, &mmdb_readers.asn);
let rdns = if let Ok(result) = lookup_result {
if result.is_empty() {
address_to_lookup.to_string()
} else {
result
}
} else {
address_to_lookup.to_string()
};
let new_host = Host {
domain: get_domain_from_r_dns(rdns.clone()),
asn,
country,
};
// collect the data exchanged from the same address so far and remove the address from the collection of addresses waiting a rDNS
let mut resolutions_lock = resolutions_state.lock().unwrap();
let other_data = resolutions_lock
.addresses_waiting_resolution
.remove(&address_to_lookup)
.unwrap_or_default();
// insert the newly resolved host in the collections, with the data it exchanged so far
resolutions_lock
.addresses_resolved
.insert(address_to_lookup, new_host.clone());
drop(resolutions_lock);
let data_info_host = DataInfoHost {
data_info: other_data,
is_favorite: false,
is_local,
is_bogon,
is_loopback,
traffic_type,
};
let msg_data = HostMessage {
host: new_host,
data_info_host,
address_to_lookup,
rdns,
};
// add the new host to the list of hosts to be sent
new_hosts_to_send.lock().unwrap().push(msg_data);
}
#[derive(Default)]
pub struct AddressesResolutionState {
/// Map of the addresses waiting for a rDNS resolution; used to NOT send multiple rDNS for the same address
addresses_waiting_resolution: HashMap<IpAddr, DataInfo>,
/// Map of the resolved addresses with the corresponding host
pub addresses_resolved: HashMap<IpAddr, Host>,
}
#[allow(clippy::large_enum_variant)]
pub enum BackendTrafficMessage {
TickRun(usize, InfoTraffic, Vec<HostMessage>, bool),
PendingHosts(usize, Vec<HostMessage>),
OfflineGap(usize, u32),
}
fn maybe_send_tick_run_live(
cap_id: usize,
info_traffic_msg: &mut InfoTraffic,
new_hosts_to_send: &Arc<Mutex<Vec<HostMessage>>>,
cs: &mut CaptureSource,
first_packet_ticks: &mut Option<Instant>,
tx: &Sender<BackendTrafficMessage>,
) {
if first_packet_ticks.is_some_and(|i| i.elapsed() >= Duration::from_millis(1000)) {
*first_packet_ticks =
first_packet_ticks.and_then(|i| i.checked_add(Duration::from_millis(1000)));
let _ = tx.send_blocking(BackendTrafficMessage::TickRun(
cap_id,
info_traffic_msg.take_but_leave_something(),
new_hosts_to_send.lock().unwrap().drain(..).collect(),
false,
));
cs.set_addresses();
}
}
fn maybe_send_tick_run_offline(
cap_id: usize,
info_traffic_msg: &mut InfoTraffic,
new_hosts_to_send: &Arc<Mutex<Vec<HostMessage>>>,
next_packet_timestamp: Timestamp,
tx: &Sender<BackendTrafficMessage>,
) {
if info_traffic_msg.last_packet_timestamp == Timestamp::default() {
info_traffic_msg.last_packet_timestamp = next_packet_timestamp;
}
if info_traffic_msg.last_packet_timestamp.secs() < next_packet_timestamp.secs() {
let diff_secs =
next_packet_timestamp.secs() - info_traffic_msg.last_packet_timestamp.secs();
let _ = tx.send_blocking(BackendTrafficMessage::TickRun(
cap_id,
info_traffic_msg.take_but_leave_something(),
new_hosts_to_send.lock().unwrap().drain(..).collect(),
false,
));
if diff_secs > 1 {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let _ = tx.send_blocking(BackendTrafficMessage::OfflineGap(
cap_id,
diff_secs as u32 - 1,
));
}
}
}
fn packet_stream(
mut cap: CaptureType,
tx: &std::sync::mpsc::SyncSender<(Result<PacketOwned, pcap::Error>, Option<pcap::Stat>)>,
freeze_rx: &mut Receiver<()>,
filters: &Filters,
) {
loop {
// check if we need to freeze the parsing
if freeze_rx.try_recv().is_ok() {
// pause the capture
cap.pause();
// wait until unfreeze
let _ = freeze_rx.blocking_recv();
// resume the capture
cap.resume(filters);
}
let packet_res = cap.next_packet();
let packet_owned = packet_res.map(|p| PacketOwned {
header: *p.header,
data: p.data.into(),
});
if tx.send((packet_owned, cap.stats().ok())).is_err() {
return;
}
}
}
struct PacketOwned {
header: PacketHeader,
data: Box<[u8]>,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/mod.rs | src/networking/mod.rs | pub mod manage_packets;
pub mod parse_packets;
pub mod traffic_preview;
pub mod types;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/traffic_preview.rs | src/networking/traffic_preview.rs | use crate::gui::types::filters::Filters;
use crate::location;
use crate::networking::manage_packets::analyze_headers;
use crate::networking::parse_packets::get_sniffable_headers;
use crate::networking::types::arp_type::ArpType;
use crate::networking::types::capture_context::{CaptureContext, CaptureSource, CaptureType};
use crate::networking::types::icmp_type::IcmpType;
use crate::networking::types::my_device::MyDevice;
use crate::networking::types::my_link_type::MyLinkType;
use crate::utils::error_logger::{ErrorLogger, Location};
use async_channel::Sender;
use pcap::{Device, Stat};
use std::collections::HashMap;
use std::thread;
use std::time::{Duration, Instant};
#[derive(Default, Clone, Debug)]
pub struct TrafficPreview {
pub data: Vec<(MyDevice, u128)>,
}
pub fn traffic_preview(tx: &Sender<TrafficPreview>) {
let mut ticks = Instant::now();
let (pcap_tx, pcap_rx) = std::sync::mpsc::sync_channel(10_000);
let mut data = HashMap::new();
handle_devices_and_previews(&mut data, tx, &pcap_tx);
loop {
let (packet_res, _) = pcap_rx
.recv_timeout(Duration::from_millis(150))
.unwrap_or((Err(pcap::Error::TimeoutExpired), None));
if tx.is_closed() {
return;
}
if ticks.elapsed() >= Duration::from_millis(1000) {
ticks = ticks
.checked_add(Duration::from_millis(1000))
.unwrap_or(Instant::now());
handle_devices_and_previews(&mut data, tx, &pcap_tx);
}
if let Ok(packet) = packet_res {
let dev_info = packet.dev_info;
let my_link_type = dev_info.my_link_type;
if let Some(headers) = get_sniffable_headers(&packet.data, my_link_type)
&& analyze_headers(
headers,
&mut (None, None),
&mut 0,
&mut IcmpType::default(),
&mut ArpType::default(),
)
.is_some()
{
data.entry(dev_info.name)
.and_modify(|p| *p += 1)
.or_insert(1);
}
}
}
}
fn handle_devices_and_previews(
data: &mut HashMap<String, u128>,
tx: &Sender<TrafficPreview>,
pcap_tx: &std::sync::mpsc::SyncSender<(Result<PacketOwned, pcap::Error>, Option<Stat>)>,
) {
let mut traffic_preview = TrafficPreview::default();
for dev in Device::list().unwrap_or_default() {
let dev_name = dev.name.clone();
let my_dev = MyDevice::from_pcap_device(dev);
if let Some(n) = data.get(&dev_name) {
traffic_preview.data.push((my_dev, *n));
continue;
}
data.insert(dev_name.clone(), 0);
traffic_preview.data.push((my_dev.clone(), 0));
let capture_source = CaptureSource::Device(my_dev);
let capture_context = CaptureContext::new(&capture_source, None, &Filters::default());
let my_link_type = capture_context.my_link_type();
if !my_link_type.is_supported() {
continue;
}
let pcap_tx = pcap_tx.clone();
let thread_name = format!("thread_traffic_preview_{dev_name}");
let dev_info = DevInfo {
name: dev_name,
my_link_type,
};
let (Some(cap), _) = capture_context.consume() else {
continue;
};
let _ = thread::Builder::new()
.name(thread_name)
.spawn(move || {
packet_stream(cap, &pcap_tx, &dev_info);
})
.log_err(location!());
}
let _ = tx.send_blocking(traffic_preview);
for v in data.values_mut() {
*v = 0;
}
}
fn packet_stream(
mut cap: CaptureType,
tx: &std::sync::mpsc::SyncSender<(Result<PacketOwned, pcap::Error>, Option<pcap::Stat>)>,
dev_info: &DevInfo,
) {
loop {
let packet_res = cap.next_packet();
let packet_owned = packet_res.map(|p| PacketOwned {
data: p.data.into(),
dev_info: dev_info.clone(),
});
if tx.send((packet_owned, cap.stats().ok())).is_err() {
return;
}
}
}
#[derive(Clone)]
struct DevInfo {
name: String,
my_link_type: MyLinkType,
}
struct PacketOwned {
data: Box<[u8]>,
dev_info: DevInfo,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/ip_collection.rs | src/networking/types/ip_collection.rs | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::ops::RangeInclusive;
use std::str::FromStr;
#[derive(Debug, Eq, PartialEq, Clone)]
pub(crate) struct IpCollection {
ips: Vec<IpAddr>,
ranges: Vec<RangeInclusive<IpAddr>>,
}
impl IpCollection {
const SEPARATOR: char = ',';
const RANGE_SEPARATOR: char = '-';
pub(crate) fn new(str: &str) -> Option<Self> {
let str = str.replace(' ', "");
if str.is_empty() {
return Some(Self::default());
}
let mut ips = Vec::new();
let mut ranges = Vec::new();
let objects: Vec<&str> = str.split(Self::SEPARATOR).collect();
for object in objects {
if object.contains(Self::RANGE_SEPARATOR) {
// IP range
let mut subparts = object.split(Self::RANGE_SEPARATOR);
if subparts.clone().count() != 2 {
return None;
}
let (lower_str, upper_str) =
(subparts.next().unwrap_or(""), subparts.next().unwrap_or(""));
let lower_ip = IpAddr::from_str(lower_str).ok()?;
let upper_ip = IpAddr::from_str(upper_str).ok()?;
let range = RangeInclusive::new(lower_ip, upper_ip);
if range.is_empty() || lower_ip.is_ipv4() != upper_ip.is_ipv4() {
return None;
}
ranges.push(range);
} else {
// individual IP
let ip = IpAddr::from_str(object).ok()?;
ips.push(ip);
}
}
Some(Self { ips, ranges })
}
pub(crate) fn contains(&self, ip: &IpAddr) -> bool {
for range in &self.ranges {
if range.contains(ip) {
return true;
}
}
self.ips.contains(ip)
}
}
impl Default for IpCollection {
fn default() -> Self {
IpCollection {
ips: vec![],
ranges: vec![
RangeInclusive::new(
IpAddr::V4(Ipv4Addr::UNSPECIFIED),
IpAddr::from([255, 255, 255, 255]),
),
RangeInclusive::new(
IpAddr::V6(Ipv6Addr::UNSPECIFIED),
IpAddr::from([
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,
]),
),
],
}
}
}
#[cfg(test)]
mod tests {
use std::net::IpAddr;
use std::ops::RangeInclusive;
use std::str::FromStr;
use crate::networking::types::ip_collection::IpCollection;
#[test]
fn test_default_collection_contains_everything() {
let collection = IpCollection::default();
assert!(collection.contains(&IpAddr::from_str("1.1.1.1").unwrap()));
assert!(collection.contains(&IpAddr::from_str("0.0.0.0").unwrap()));
assert!(collection.contains(&IpAddr::from_str("255.255.255.255").unwrap()));
assert!(collection.contains(&IpAddr::from_str("192.168.1.1").unwrap()));
assert!(
collection
.contains(&IpAddr::from_str("0000:0000:0000:0000:0000:0000:0000:0000").unwrap())
);
assert!(
collection
.contains(&IpAddr::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap())
);
assert!(collection.contains(&IpAddr::from_str("88::02").unwrap()));
assert!(
collection
.contains(&IpAddr::from_str("2001:db8:1234:ffff:ffff:ffff:ffff:eeee").unwrap())
);
}
#[test]
fn test_new_collections_1() {
assert_eq!(
IpCollection::new("1.1.1.1,2.2.2.2").unwrap(),
IpCollection {
ips: vec![
IpAddr::from_str("1.1.1.1").unwrap(),
IpAddr::from_str("2.2.2.2").unwrap()
],
ranges: vec![]
}
);
assert_eq!(
IpCollection::new("1.1.1.1, 2.2.2.2, 3.3.3.3 - 5.5.5.5, 10.0.0.1-10.0.0.255,9.9.9.9",)
.unwrap(),
IpCollection {
ips: vec![
IpAddr::from_str("1.1.1.1").unwrap(),
IpAddr::from_str("2.2.2.2").unwrap(),
IpAddr::from_str("9.9.9.9").unwrap()
],
ranges: vec![
RangeInclusive::new(
IpAddr::from_str("3.3.3.3").unwrap(),
IpAddr::from_str("5.5.5.5").unwrap()
),
RangeInclusive::new(
IpAddr::from_str("10.0.0.1").unwrap(),
IpAddr::from_str("10.0.0.255").unwrap()
)
]
}
);
assert_eq!(
IpCollection::new(" aaaa::ffff,bbbb::1-cccc::2").unwrap(),
IpCollection {
ips: vec![IpAddr::from_str("aaaa::ffff").unwrap(),],
ranges: vec![RangeInclusive::new(
IpAddr::from_str("bbbb::1").unwrap(),
IpAddr::from_str("cccc::2").unwrap()
)]
}
);
}
#[test]
fn test_new_collections_2() {
assert_eq!(
IpCollection::new("1.1.1.1,2.2.2.2, 8.8.8.8 ").unwrap(),
IpCollection {
ips: vec![
IpAddr::from_str("1.1.1.1").unwrap(),
IpAddr::from_str("2.2.2.2").unwrap(),
IpAddr::from_str("8.8.8.8").unwrap()
],
ranges: vec![]
}
);
assert_eq!(
IpCollection::new(" 1.1.1.1 -1.1.1.1").unwrap(),
IpCollection {
ips: vec![],
ranges: vec![RangeInclusive::new(
IpAddr::from_str("1.1.1.1").unwrap(),
IpAddr::from_str("1.1.1.1").unwrap()
),]
}
);
assert_eq!(
IpCollection::new("1.1.1.1,2.2.2.2,3.3.3.3-5.5.5.5,10.0.0.1-10.0.0.255,9.9.9.9",)
.unwrap(),
IpCollection {
ips: vec![
IpAddr::from_str("1.1.1.1").unwrap(),
IpAddr::from_str("2.2.2.2").unwrap(),
IpAddr::from_str("9.9.9.9").unwrap()
],
ranges: vec![
RangeInclusive::new(
IpAddr::from_str("3.3.3.3").unwrap(),
IpAddr::from_str("5.5.5.5").unwrap()
),
RangeInclusive::new(
IpAddr::from_str("10.0.0.1").unwrap(),
IpAddr::from_str("10.0.0.255").unwrap()
)
]
}
);
assert_eq!(
IpCollection::new("aaaa::ffff,bbbb::1-cccc::2,ff::dd").unwrap(),
IpCollection {
ips: vec![
IpAddr::from_str("aaaa::ffff").unwrap(),
IpAddr::from_str("ff::dd").unwrap()
],
ranges: vec![RangeInclusive::new(
IpAddr::from_str("bbbb::1").unwrap(),
IpAddr::from_str("cccc::2").unwrap()
)]
}
);
}
#[test]
fn test_new_collections_invalid() {
assert_eq!(
IpCollection::new("1.1.1.1,2.2.2.2,3.3.3.3-5.5.5.5,10.0.0.1-10.0.0.255,9.9.9"),
None
);
assert_eq!(
IpCollection::new("1.1.1.1,2.2.2.2,3.3.3.3-5.5.5.5,10.0.0.1:10.0.0.255,9.9.9.9"),
None
);
assert_eq!(IpCollection::new("1.1.1.1-aa::ff"), None);
assert_eq!(IpCollection::new("aa::ff-1.1.1.1"), None);
assert_eq!(IpCollection::new("aa::ff-aa::ee"), None);
assert_eq!(IpCollection::new("1.1.1.1-1.1.0.1"), None);
assert_eq!(IpCollection::new("1.1.1.1-2.2.2.2-3.3.3.3"), None);
assert_eq!(IpCollection::new("1.1.1.1-2.2.2.2-"), None);
}
#[test]
fn test_ip_collection_contains() {
let collection =
IpCollection::new("1.1.1.1,2.2.2.2,3.3.3.3-5.5.5.5,10.0.0.1-10.0.0.255,9.9.9.9")
.unwrap();
assert!(collection.contains(&IpAddr::from_str("1.1.1.1").unwrap()));
assert!(collection.contains(&IpAddr::from_str("2.2.2.2").unwrap()));
assert!(collection.contains(&IpAddr::from_str("3.3.3.3").unwrap()));
assert!(collection.contains(&IpAddr::from_str("4.0.0.0").unwrap()));
assert!(collection.contains(&IpAddr::from_str("5.5.5.5").unwrap()));
assert!(collection.contains(&IpAddr::from_str("9.9.9.9").unwrap()));
assert!(collection.contains(&IpAddr::from_str("10.0.0.1").unwrap()));
assert!(collection.contains(&IpAddr::from_str("10.0.0.128").unwrap()));
assert!(collection.contains(&IpAddr::from_str("10.0.0.255").unwrap()));
assert!(!collection.contains(&IpAddr::from_str("10.0.0.0").unwrap()));
assert!(!collection.contains(&IpAddr::from_str("2.2.2.1").unwrap()));
assert!(!collection.contains(&IpAddr::from_str("9.9.9.10").unwrap()));
assert!(!collection.contains(&IpAddr::from_str("3.3.3.2").unwrap()));
let collection_2 = IpCollection::new("1.1.1.0-1.1.9.0").unwrap();
assert!(!collection_2.contains(&IpAddr::from_str("1.1.100.5").unwrap()));
assert!(collection_2.contains(&IpAddr::from_str("1.1.3.255").unwrap()));
// check that ipv4 range doesn't contain ipv6
let collection_3 = IpCollection::new("0.0.0.0-255.255.255.255").unwrap();
assert!(!collection_3.contains(&IpAddr::from_str("::").unwrap()));
assert!(!collection_3.contains(&IpAddr::from_str("1111::2222").unwrap()));
}
#[test]
fn test_ip_collection_contains_ipv6() {
let collection =
IpCollection::new( "2001:db8:1234:0000:0000:0000:0000:0000-2001:db8:1234:ffff:ffff:ffff:ffff:ffff,daa::aad,caa::aac").unwrap();
assert!(
collection
.contains(&IpAddr::from_str("2001:db8:1234:0000:0000:0000:0000:0000").unwrap())
);
assert!(
collection
.contains(&IpAddr::from_str("2001:db8:1234:ffff:ffff:ffff:ffff:ffff").unwrap())
);
assert!(
collection
.contains(&IpAddr::from_str("2001:db8:1234:ffff:ffff:ffff:ffff:eeee").unwrap())
);
assert!(
collection
.contains(&IpAddr::from_str("2001:db8:1234:aaaa:ffff:ffff:ffff:eeee").unwrap())
);
assert!(collection.contains(&IpAddr::from_str("daa::aad").unwrap()));
assert!(collection.contains(&IpAddr::from_str("caa::aac").unwrap()));
assert!(
!collection
.contains(&IpAddr::from_str("2000:db8:1234:0000:0000:0000:0000:0000").unwrap())
);
assert!(
!collection
.contains(&IpAddr::from_str("2001:db8:1235:ffff:ffff:ffff:ffff:ffff").unwrap())
);
assert!(
!collection
.contains(&IpAddr::from_str("2001:eb8:1234:ffff:ffff:ffff:ffff:eeee").unwrap())
);
assert!(!collection.contains(&IpAddr::from_str("da::aad").unwrap()));
assert!(!collection.contains(&IpAddr::from_str("caa::aab").unwrap()));
let collection_2 = IpCollection::new("aa::bb-aa:1::00").unwrap();
assert!(!collection_2.contains(&IpAddr::from_str("aa:11::0").unwrap()));
assert!(collection_2.contains(&IpAddr::from_str("aa::bc").unwrap()));
assert!(collection_2.contains(&IpAddr::from_str("aa::bbcc").unwrap()));
assert!(collection_2.contains(&IpAddr::from_str("00aa:0001::00").unwrap()));
// check that ipv6 range doesn't contain ipv4
let collection_3 = IpCollection::new("0000::0000-ffff::8888").unwrap();
assert!(!collection_3.contains(&IpAddr::from_str("192.168.1.1").unwrap()));
assert!(!collection_3.contains(&IpAddr::from_str("0.0.0.0").unwrap()));
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/data_info_host.rs | src/networking/types/data_info_host.rs | //! Module defining the `DataInfoHost` struct related to hosts.
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::traffic_type::TrafficType;
/// Host-related information.
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Hash)]
pub struct DataInfoHost {
/// Incoming and outgoing packets and bytes
pub data_info: DataInfo,
/// Determine if this host is one of the favorites
pub is_favorite: bool,
/// Determine if the connection is loopback (the "remote" is loopback)
pub is_loopback: bool,
/// Determine if the connection with this host is local
pub is_local: bool,
/// Determine if the connection is with a bogon address
pub is_bogon: Option<&'static str>,
/// Determine if the connection with this host is unicast, multicast, or broadcast
pub traffic_type: TrafficType,
}
impl DataInfoHost {
pub fn refresh(&mut self, other: &Self) {
self.data_info.refresh(other.data_info);
self.is_loopback = other.is_loopback;
self.is_local = other.is_local;
self.is_bogon = other.is_bogon;
self.traffic_type = other.traffic_type;
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/host_data_states.rs | src/networking/types/host_data_states.rs | use std::collections::BTreeSet;
use std::net::IpAddr;
use iced::widget::combo_box;
use crate::countries::types::country::Country;
use crate::networking::types::host::Host;
use crate::report::types::search_parameters::SearchParameters;
/// Struct to contain all the sets of data related to network hosts
///
/// It also stores combobox states for the host-related filters
#[derive(Default)]
pub struct HostDataStates {
pub data: HostData,
pub states: HostStates,
}
impl HostDataStates {
pub fn update_states(&mut self, search: &SearchParameters) {
let states = &mut self.states;
let data = &mut self.data;
if data.domains.1 {
states.domains = combo_box::State::with_selection(
data.domains.0.iter().cloned().collect(),
Some(&search.domain),
);
data.domains.1 = false;
}
if data.asns.1 {
states.asns = combo_box::State::with_selection(
data.asns.0.iter().cloned().collect(),
Some(&search.as_name),
);
data.asns.1 = false;
}
if data.countries.1 {
states.countries = combo_box::State::with_selection(
data.countries.0.iter().cloned().collect(),
Some(&search.country),
);
data.countries.1 = false;
}
}
}
#[derive(Default)]
pub struct HostData {
pub domains: (BTreeSet<String>, bool),
pub asns: (BTreeSet<String>, bool),
pub countries: (BTreeSet<String>, bool),
}
impl HostData {
pub fn update(&mut self, host: &Host) {
if !host.domain.is_empty() && host.domain.parse::<IpAddr>().is_err() {
self.domains.1 = self.domains.0.insert(host.domain.clone()) || self.domains.1;
}
if !host.asn.name.is_empty() {
self.asns.1 = self.asns.0.insert(host.asn.name.clone()) || self.asns.1;
}
if host.country != Country::ZZ {
self.countries.1 =
self.countries.0.insert(host.country.to_string()) || self.countries.1;
}
}
}
#[derive(Default)]
pub struct HostStates {
pub domains: combo_box::State<String>,
pub asns: combo_box::State<String>,
pub countries: combo_box::State<String>,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/info_address_port_pair.rs | src/networking/types/info_address_port_pair.rs | //! Module defining the `InfoAddressPortPair` struct, useful to format the output report file and
//! to keep track of statistics about the sniffed traffic.
use std::cmp::Ordering;
use std::collections::HashMap;
use crate::Service;
use crate::networking::types::arp_type::ArpType;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::icmp_type::IcmpType;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::report::types::sort_type::SortType;
use crate::utils::types::timestamp::Timestamp;
/// Struct useful to format the output report file and to keep track of statistics about the sniffed traffic.
///
/// Each `InfoAddressPortPair` struct is associated to a single address:port pair.
#[derive(Clone, Default, Debug)]
pub struct InfoAddressPortPair {
/// Source MAC address
pub mac_address1: Option<String>,
/// Destination MAC address
pub mac_address2: Option<String>,
/// Amount of bytes transmitted between the pair.
pub transmitted_bytes: u128,
/// Amount of packets transmitted between the pair.
pub transmitted_packets: u128,
/// First occurrence of information exchange featuring the associate address:port pair as a source or destination.
pub initial_timestamp: Timestamp,
/// Last occurrence of information exchange featuring the associate address:port pair as a source or destination.
pub final_timestamp: Timestamp,
/// Upper layer service carried by the associated address:port pair.
pub service: Service,
/// Determines if the connection is incoming or outgoing
pub traffic_direction: TrafficDirection,
/// Types of the ICMP messages exchanged, with the relative count (this is empty if not ICMP)
pub icmp_types: HashMap<IcmpType, usize>,
/// Types of the ARP operations, with the relative count (this is empty if not ARP)
pub arp_types: HashMap<ArpType, usize>,
}
impl InfoAddressPortPair {
pub fn refresh(&mut self, other: &Self) {
self.transmitted_bytes += other.transmitted_bytes;
self.transmitted_packets += other.transmitted_packets;
self.final_timestamp = other.final_timestamp;
self.service = other.service;
self.traffic_direction = other.traffic_direction;
for (icmp_type, count) in &other.icmp_types {
self.icmp_types
.entry(*icmp_type)
.and_modify(|v| *v += count)
.or_insert(*count);
}
for (arp_type, count) in &other.arp_types {
self.arp_types
.entry(*arp_type)
.and_modify(|v| *v += count)
.or_insert(*count);
}
}
pub fn transmitted_data(&self, data_repr: DataRepr) -> u128 {
match data_repr {
DataRepr::Packets => self.transmitted_packets,
DataRepr::Bytes => self.transmitted_bytes,
DataRepr::Bits => self.transmitted_bytes * 8,
}
}
pub fn compare(&self, other: &Self, sort_type: SortType, data_repr: DataRepr) -> Ordering {
match sort_type {
SortType::Ascending => self
.transmitted_data(data_repr)
.cmp(&other.transmitted_data(data_repr)),
SortType::Descending => other
.transmitted_data(data_repr)
.cmp(&self.transmitted_data(data_repr)),
SortType::Neutral => other.final_timestamp.cmp(&self.final_timestamp),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::networking::types::data_representation::DataRepr;
use crate::report::types::sort_type::SortType;
#[test]
fn test_info_address_port_pair_data() {
let pair1 = InfoAddressPortPair {
transmitted_bytes: 1000,
transmitted_packets: 10,
final_timestamp: Timestamp::new(8, 1300),
..Default::default()
};
let pair2 = InfoAddressPortPair {
transmitted_bytes: 1100,
transmitted_packets: 8,
final_timestamp: Timestamp::new(15, 0),
..Default::default()
};
assert_eq!(pair1.transmitted_data(DataRepr::Bytes), 1000);
assert_eq!(pair1.transmitted_data(DataRepr::Packets), 10);
assert_eq!(pair1.transmitted_data(DataRepr::Bits), 8000);
assert_eq!(pair2.transmitted_data(DataRepr::Bytes), 1100);
assert_eq!(pair2.transmitted_data(DataRepr::Packets), 8);
assert_eq!(pair2.transmitted_data(DataRepr::Bits), 8800);
assert_eq!(
pair1.compare(&pair2, SortType::Ascending, DataRepr::Bytes),
Ordering::Less
);
assert_eq!(
pair1.compare(&pair2, SortType::Descending, DataRepr::Bytes),
Ordering::Greater
);
assert_eq!(
pair1.compare(&pair2, SortType::Neutral, DataRepr::Bytes),
Ordering::Greater
);
assert_eq!(
pair1.compare(&pair2, SortType::Ascending, DataRepr::Packets),
Ordering::Greater
);
assert_eq!(
pair1.compare(&pair2, SortType::Descending, DataRepr::Packets),
Ordering::Less
);
assert_eq!(
pair1.compare(&pair2, SortType::Neutral, DataRepr::Packets),
Ordering::Greater
);
assert_eq!(
pair1.compare(&pair2, SortType::Ascending, DataRepr::Bits),
Ordering::Less
);
assert_eq!(
pair1.compare(&pair2, SortType::Descending, DataRepr::Bits),
Ordering::Greater
);
assert_eq!(
pair1.compare(&pair2, SortType::Neutral, DataRepr::Bits),
Ordering::Greater
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/bogon.rs | src/networking/types/bogon.rs | use crate::networking::types::ip_collection::IpCollection;
use std::net::IpAddr;
pub struct Bogon {
pub range: IpCollection,
pub description: &'static str,
}
// IPv4 bogons
static THIS_NETWORK: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("0.0.0.0-0.255.255.255").unwrap(),
description: "\"this\" network",
});
static PRIVATE_USE: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new(
"10.0.0.0-10.255.255.255, 172.16.0.0-172.31.255.255, 192.168.0.0-192.168.255.255",
)
.unwrap(),
description: "private-use",
});
static CARRIER_GRADE: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("100.64.0.0-100.127.255.255").unwrap(),
description: "carrier-grade NAT",
});
static LOOPBACK: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("127.0.0.0-127.255.255.255").unwrap(),
description: "loopback",
});
static LINK_LOCAL: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("169.254.0.0-169.254.255.255").unwrap(),
description: "link local",
});
static IETF_PROTOCOL: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("192.0.0.0-192.0.0.255").unwrap(),
description: "IETF protocol assignments",
});
static TEST_NET_1: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("192.0.2.0-192.0.2.255").unwrap(),
description: "TEST-NET-1",
});
static NETWORK_INTERCONNECT: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("198.18.0.0-198.19.255.255").unwrap(),
description: "network interconnect device benchmark testing",
});
static TEST_NET_2: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("198.51.100.0-198.51.100.255").unwrap(),
description: "TEST-NET-2",
});
static TEST_NET_3: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("203.0.113.0-203.0.113.255").unwrap(),
description: "TEST-NET-3",
});
static MULTICAST: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("224.0.0.0-239.255.255.255").unwrap(),
description: "multicast",
});
static FUTURE_USE: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("240.0.0.0-255.255.255.255").unwrap(),
description: "future use",
});
// IPv6 bogons
static NODE_SCOPE_UNSPECIFIED: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("::").unwrap(),
description: "node-scope unicast unspecified",
});
static NODE_SCOPE_LOOPBACK: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("::1").unwrap(),
description: "node-scope unicast loopback",
});
static IPV4_MAPPED: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("::ffff:0.0.0.0-::ffff:255.255.255.255").unwrap(),
description: "IPv4-mapped",
});
static IPV4_COMPATIBLE: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("::-::255.255.255.255").unwrap(),
description: "IPv4-compatible",
});
static REMOTELY_TRIGGERED: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("100::-100::ffff:ffff:ffff:ffff").unwrap(),
description: "remotely triggered black hole",
});
static ORCHID: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("2001:10::-2001:1f:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(),
description: "ORCHID",
});
static DOCUMENTATION_PREFIX: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| {
Bogon {
range: IpCollection::new("2001:db8::-2001:db8:ffff:ffff:ffff:ffff:ffff:ffff, 3fff::-3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff")
.unwrap(),
description: "documentation prefix",
}
});
static ULA: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(),
description: "ULA",
});
static LINK_LOCAL_UNICAST: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(),
description: "link-local unicast",
});
static SITE_LOCAL_UNICAST: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("fec0::-feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(),
description: "site-local unicast",
});
static MULTICAST_V6: std::sync::LazyLock<Bogon> = std::sync::LazyLock::new(|| Bogon {
range: IpCollection::new("ff00::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").unwrap(),
description: "multicast v6",
});
// all bogons
static BOGONS: std::sync::LazyLock<Vec<&'static Bogon>> = std::sync::LazyLock::new(|| {
vec![
&THIS_NETWORK,
&PRIVATE_USE,
&CARRIER_GRADE,
&LOOPBACK,
&LINK_LOCAL,
&IETF_PROTOCOL,
&TEST_NET_1,
&NETWORK_INTERCONNECT,
&TEST_NET_2,
&TEST_NET_3,
&MULTICAST,
&FUTURE_USE,
&NODE_SCOPE_UNSPECIFIED,
&NODE_SCOPE_LOOPBACK,
&IPV4_MAPPED,
&IPV4_COMPATIBLE,
&REMOTELY_TRIGGERED,
&ORCHID,
&DOCUMENTATION_PREFIX,
&ULA,
&LINK_LOCAL_UNICAST,
&SITE_LOCAL_UNICAST,
&MULTICAST_V6,
]
});
pub fn is_bogon(address: &IpAddr) -> Option<&'static str> {
for bogon in BOGONS.iter() {
if bogon.range.contains(address) {
return Some(bogon.description);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn test_is_bogon_no() {
assert_eq!(is_bogon(&IpAddr::from_str("8.8.8.8").unwrap()), None);
assert_eq!(
is_bogon(&IpAddr::from_str("2001:4860:4860::8888").unwrap()),
None
);
}
#[test]
fn test_is_bogon_this_network() {
assert_eq!(
is_bogon(&IpAddr::from_str("0.1.2.3").unwrap()),
Some("\"this\" network")
);
}
#[test]
fn test_is_bogon_private_use_networks() {
assert_eq!(
is_bogon(&IpAddr::from_str("10.1.2.3").unwrap()),
Some("private-use")
);
assert_eq!(
is_bogon(&IpAddr::from_str("172.22.2.3").unwrap()),
Some("private-use")
);
assert_eq!(
is_bogon(&IpAddr::from_str("192.168.255.3").unwrap()),
Some("private-use")
);
}
#[test]
fn test_is_bogon_carrier_grade() {
assert_eq!(
is_bogon(&IpAddr::from_str("100.99.2.1").unwrap()),
Some("carrier-grade NAT")
);
}
#[test]
fn test_is_bogon_loopback() {
assert_eq!(
is_bogon(&IpAddr::from_str("127.99.2.1").unwrap()),
Some("loopback")
);
}
#[test]
fn test_is_bogon_link_local() {
assert_eq!(
is_bogon(&IpAddr::from_str("169.254.0.0").unwrap()),
Some("link local")
);
}
#[test]
fn test_is_bogon_ietf() {
assert_eq!(
is_bogon(&IpAddr::from_str("192.0.0.255").unwrap()),
Some("IETF protocol assignments")
);
}
#[test]
fn test_is_bogon_test_net_1() {
assert_eq!(
is_bogon(&IpAddr::from_str("192.0.2.128").unwrap()),
Some("TEST-NET-1")
);
}
#[test]
fn test_is_bogon_network_interconnect() {
assert_eq!(
is_bogon(&IpAddr::from_str("198.18.2.128").unwrap()),
Some("network interconnect device benchmark testing")
);
}
#[test]
fn test_is_bogon_test_net_2() {
assert_eq!(
is_bogon(&IpAddr::from_str("198.51.100.128").unwrap()),
Some("TEST-NET-2")
);
}
#[test]
fn test_is_bogon_test_net_3() {
assert_eq!(
is_bogon(&IpAddr::from_str("203.0.113.128").unwrap()),
Some("TEST-NET-3")
);
}
#[test]
fn test_is_bogon_multicast() {
assert_eq!(
is_bogon(&IpAddr::from_str("224.12.13.255").unwrap()),
Some("multicast")
);
}
#[test]
fn test_is_bogon_future_use() {
assert_eq!(
is_bogon(&IpAddr::from_str("240.0.0.0").unwrap()),
Some("future use")
);
}
#[test]
fn test_node_scope_unspecified() {
assert_eq!(
is_bogon(&IpAddr::from_str("::").unwrap()),
Some("node-scope unicast unspecified")
);
}
#[test]
fn test_node_scope_loopback() {
assert_eq!(
is_bogon(&IpAddr::from_str("::1").unwrap()),
Some("node-scope unicast loopback")
);
}
#[test]
fn test_ipv4_mapped() {
assert_eq!(
is_bogon(&IpAddr::from_str("::ffff:8.8.8.8").unwrap()),
Some("IPv4-mapped")
);
}
#[test]
fn test_ipv4_compatible() {
assert_eq!(
is_bogon(&IpAddr::from_str("::8.8.8.8").unwrap()),
Some("IPv4-compatible")
);
}
#[test]
fn test_remotely_triggered() {
assert_eq!(
is_bogon(&IpAddr::from_str("100::beef").unwrap()),
Some("remotely triggered black hole")
);
}
#[test]
fn test_orchid() {
assert_eq!(
is_bogon(&IpAddr::from_str("2001:10::feed").unwrap()),
Some("ORCHID")
);
}
#[test]
fn test_documentation_prefix() {
assert_eq!(
is_bogon(&IpAddr::from_str("2001:db8::fe90").unwrap()),
Some("documentation prefix")
);
assert_eq!(
is_bogon(&IpAddr::from_str("3fff::").unwrap()),
Some("documentation prefix")
);
}
#[test]
fn test_ula() {
assert_eq!(is_bogon(&IpAddr::from_str("fdff::").unwrap()), Some("ULA"));
}
#[test]
fn test_link_local_unicast() {
assert_eq!(
is_bogon(&IpAddr::from_str("feaf::").unwrap()),
Some("link-local unicast")
);
}
#[test]
fn test_site_local_unicast() {
assert_eq!(
is_bogon(&IpAddr::from_str("feea::1").unwrap()),
Some("site-local unicast")
);
}
#[test]
fn test_is_bogon_multicast_v6() {
assert_eq!(
is_bogon(&IpAddr::from_str("ff02::1").unwrap()),
Some("multicast v6")
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.