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 |
|---|---|---|---|---|---|---|---|---|
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/address_port_pair.rs | src/networking/types/address_port_pair.rs | //! Module defining the `AddressPortPair` struct, which represents a network address:port pair.
use crate::Protocol;
use std::net::{IpAddr, Ipv4Addr};
/// Struct representing a network address:port pair.
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct AddressPortPair {
/// Network layer IPv4 or IPv6 source address.
pub source: IpAddr,
/// Transport layer source port number (in the range 0..=65535).
pub sport: Option<u16>,
/// Network layer IPv4 or IPv6 destination address.
pub dest: IpAddr,
/// Transport layer destination port number (in the range 0..=65535).
pub dport: Option<u16>,
/// Transport layer protocol carried through the associate address:port pair (TCP or UPD).
pub protocol: Protocol,
}
#[cfg(test)]
impl AddressPortPair {
pub fn new(
source: IpAddr,
sport: Option<u16>,
dest: IpAddr,
dport: Option<u16>,
protocol: Protocol,
) -> Self {
AddressPortPair {
source,
sport,
dest,
dport,
protocol,
}
}
}
impl Default for AddressPortPair {
fn default() -> Self {
AddressPortPair {
source: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
dest: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
sport: None,
dport: None,
protocol: Protocol::ARP,
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/config_device.rs | src/networking/types/config_device.rs | use crate::gui::types::conf::deserialize_or_default;
use crate::networking::types::my_device::MyDevice;
use pcap::{Device, DeviceFlags};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[serde(default)]
pub struct ConfigDevice {
#[serde(deserialize_with = "deserialize_or_default")]
pub device_name: String,
}
impl Default for ConfigDevice {
fn default() -> Self {
Self {
device_name: Device::lookup()
.unwrap_or(None)
.unwrap_or_else(|| Device {
name: String::new(),
desc: None,
addresses: vec![],
flags: DeviceFlags::empty(),
})
.name,
}
}
}
impl ConfigDevice {
pub fn to_my_device(&self) -> MyDevice {
for device in Device::list().unwrap_or_default() {
if device.name.eq(&self.device_name) {
return MyDevice::from_pcap_device(device);
}
}
let standard_device = Device::lookup().unwrap_or(None).unwrap_or_else(|| Device {
name: String::new(),
desc: None,
addresses: vec![],
flags: DeviceFlags::empty(),
});
MyDevice::from_pcap_device(standard_device)
}
}
| 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.rs | src/networking/types/data_info.rs | //! Module defining the `DataInfo` struct, which represents incoming and outgoing packets and bytes.
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::report::types::sort_type::SortType;
use std::cmp::Ordering;
use std::time::Instant;
/// Amount of exchanged data (packets and bytes) incoming and outgoing, with the timestamp of the latest occurrence
// data fields are private to make them only editable via the provided methods: needed to correctly refresh timestamps
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct DataInfo {
/// Incoming packets
incoming_packets: u128,
/// Outgoing packets
outgoing_packets: u128,
/// Incoming bytes
incoming_bytes: u128,
/// Outgoing bytes
outgoing_bytes: u128,
/// Latest instant of occurrence
final_instant: Instant,
}
impl DataInfo {
pub fn incoming_data(&self, data_repr: DataRepr) -> u128 {
match data_repr {
DataRepr::Packets => self.incoming_packets,
DataRepr::Bytes => self.incoming_bytes,
DataRepr::Bits => self.incoming_bytes * 8,
}
}
pub fn outgoing_data(&self, data_repr: DataRepr) -> u128 {
match data_repr {
DataRepr::Packets => self.outgoing_packets,
DataRepr::Bytes => self.outgoing_bytes,
DataRepr::Bits => self.outgoing_bytes * 8,
}
}
pub fn tot_data(&self, data_repr: DataRepr) -> u128 {
self.incoming_data(data_repr) + self.outgoing_data(data_repr)
}
pub fn add_packet(&mut self, bytes: u128, traffic_direction: TrafficDirection) {
if traffic_direction.eq(&TrafficDirection::Outgoing) {
self.outgoing_packets += 1;
self.outgoing_bytes += bytes;
} else {
self.incoming_packets += 1;
self.incoming_bytes += bytes;
}
self.final_instant = Instant::now();
}
pub fn add_packets(&mut self, packets: u128, bytes: u128, traffic_direction: TrafficDirection) {
if traffic_direction.eq(&TrafficDirection::Outgoing) {
self.outgoing_packets += packets;
self.outgoing_bytes += bytes;
} else {
self.incoming_packets += packets;
self.incoming_bytes += bytes;
}
}
pub fn new_with_first_packet(bytes: u128, traffic_direction: TrafficDirection) -> Self {
if traffic_direction.eq(&TrafficDirection::Outgoing) {
Self {
incoming_packets: 0,
outgoing_packets: 1,
incoming_bytes: 0,
outgoing_bytes: bytes,
final_instant: Instant::now(),
}
} else {
Self {
incoming_packets: 1,
outgoing_packets: 0,
incoming_bytes: bytes,
outgoing_bytes: 0,
final_instant: Instant::now(),
}
}
}
pub fn refresh(&mut self, rhs: Self) {
self.incoming_packets += rhs.incoming_packets;
self.outgoing_packets += rhs.outgoing_packets;
self.incoming_bytes += rhs.incoming_bytes;
self.outgoing_bytes += rhs.outgoing_bytes;
self.final_instant = rhs.final_instant;
}
pub fn compare(&self, other: &Self, sort_type: SortType, data_repr: DataRepr) -> Ordering {
match sort_type {
SortType::Ascending => self.tot_data(data_repr).cmp(&other.tot_data(data_repr)),
SortType::Descending => other.tot_data(data_repr).cmp(&self.tot_data(data_repr)),
SortType::Neutral => other.final_instant.cmp(&self.final_instant),
}
}
#[cfg(test)]
pub fn new_for_tests(
incoming_packets: u128,
outgoing_packets: u128,
incoming_bytes: u128,
outgoing_bytes: u128,
) -> Self {
Self {
incoming_packets,
outgoing_packets,
incoming_bytes,
outgoing_bytes,
final_instant: Instant::now(),
}
}
}
impl Default for DataInfo {
fn default() -> Self {
Self {
incoming_packets: 0,
outgoing_packets: 0,
incoming_bytes: 0,
outgoing_bytes: 0,
final_instant: Instant::now(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::networking::types::traffic_direction::TrafficDirection;
#[test]
fn test_data_info() {
// in_packets: 0, out_packets: 0, in_bytes: 0, out_bytes: 0
let mut data_info_1 = DataInfo::new_with_first_packet(123, TrafficDirection::Incoming);
// 1, 0, 123, 0
data_info_1.add_packet(100, TrafficDirection::Incoming);
// 2, 0, 223, 0
data_info_1.add_packet(200, TrafficDirection::Outgoing);
// 2, 1, 223, 200
data_info_1.add_packets(11, 1200, TrafficDirection::Outgoing);
// 2, 12, 223, 1400
data_info_1.add_packets(5, 500, TrafficDirection::Incoming);
// 7, 12, 723, 1400
assert_eq!(data_info_1.incoming_packets, 7);
assert_eq!(data_info_1.outgoing_packets, 12);
assert_eq!(data_info_1.incoming_bytes, 723);
assert_eq!(data_info_1.outgoing_bytes, 1400);
assert_eq!(data_info_1.tot_data(DataRepr::Packets), 19);
assert_eq!(data_info_1.tot_data(DataRepr::Bytes), 2123);
assert_eq!(data_info_1.tot_data(DataRepr::Bits), 16984);
assert_eq!(data_info_1.incoming_data(DataRepr::Packets), 7);
assert_eq!(data_info_1.incoming_data(DataRepr::Bytes), 723);
assert_eq!(data_info_1.incoming_data(DataRepr::Bits), 5784);
assert_eq!(data_info_1.outgoing_data(DataRepr::Packets), 12);
assert_eq!(data_info_1.outgoing_data(DataRepr::Bytes), 1400);
assert_eq!(data_info_1.outgoing_data(DataRepr::Bits), 11200);
// sleep a little to have a different final_instant
std::thread::sleep(std::time::Duration::from_millis(10));
let mut data_info_2 = DataInfo::new_with_first_packet(100, TrafficDirection::Outgoing);
// 0, 1, 0, 100
data_info_2.add_packets(19, 300, TrafficDirection::Outgoing);
// 0, 20, 0, 400
assert_eq!(data_info_2.incoming_packets, 0);
assert_eq!(data_info_2.outgoing_packets, 20);
assert_eq!(data_info_2.incoming_bytes, 0);
assert_eq!(data_info_2.outgoing_bytes, 400);
assert_eq!(data_info_2.tot_data(DataRepr::Packets), 20);
assert_eq!(data_info_2.tot_data(DataRepr::Bytes), 400);
assert_eq!(data_info_2.tot_data(DataRepr::Bits), 3200);
assert_eq!(data_info_2.incoming_data(DataRepr::Packets), 0);
assert_eq!(data_info_2.incoming_data(DataRepr::Bytes), 0);
assert_eq!(data_info_2.incoming_data(DataRepr::Bits), 0);
assert_eq!(data_info_2.outgoing_data(DataRepr::Packets), 20);
assert_eq!(data_info_2.outgoing_data(DataRepr::Bytes), 400);
assert_eq!(data_info_2.outgoing_data(DataRepr::Bits), 3200);
// compare data_info_1 and data_info_2
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Ascending, DataRepr::Packets),
Ordering::Less
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Descending, DataRepr::Packets),
Ordering::Greater
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Neutral, DataRepr::Packets),
Ordering::Greater
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Ascending, DataRepr::Bytes),
Ordering::Greater
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Descending, DataRepr::Bytes),
Ordering::Less
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Neutral, DataRepr::Bytes),
Ordering::Greater
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Ascending, DataRepr::Bits),
Ordering::Greater
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Descending, DataRepr::Bits),
Ordering::Less
);
assert_eq!(
data_info_1.compare(&data_info_2, SortType::Neutral, DataRepr::Bits),
Ordering::Greater
);
// refresh data_info_1 with data_info_2
assert!(data_info_1.final_instant < data_info_2.final_instant);
data_info_1.refresh(data_info_2);
// data_info_1 should now contain the sum of both data_info_1 and data_info_2
assert_eq!(data_info_1.incoming_packets, 7);
assert_eq!(data_info_1.outgoing_packets, 32);
assert_eq!(data_info_1.incoming_bytes, 723);
assert_eq!(data_info_1.outgoing_bytes, 1800);
assert_eq!(data_info_1.final_instant, data_info_2.final_instant);
}
}
| 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_traffic.rs | src/networking/types/info_traffic.rs | use crate::Service;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::utils::types::timestamp::Timestamp;
use std::collections::HashMap;
/// Struct containing overall traffic statistics and data.
#[derive(Debug, Default, Clone)]
pub struct InfoTraffic {
/// Total amount of exchanged data
pub tot_data_info: DataInfo,
/// Number of dropped packets
pub dropped_packets: u32,
/// Timestamp of the latest parsed packet
pub last_packet_timestamp: Timestamp,
/// Map of the traffic
pub map: HashMap<AddressPortPair, InfoAddressPortPair>,
/// Map of the upper layer services with their data info
pub services: HashMap<Service, DataInfo>,
/// Map of the hosts with their data info
pub hosts: HashMap<Host, DataInfoHost>,
}
impl InfoTraffic {
pub fn refresh(&mut self, msg: &mut Self) {
self.tot_data_info.refresh(msg.tot_data_info);
self.dropped_packets = msg.dropped_packets;
// it can happen they're equal due to dis-alignments in the PCAP timestamp
if self.last_packet_timestamp.secs() == msg.last_packet_timestamp.secs() {
msg.last_packet_timestamp.add_secs(1);
}
self.last_packet_timestamp = msg.last_packet_timestamp;
for (key, value) in &msg.map {
self.map
.entry(*key)
.and_modify(|x| x.refresh(value))
.or_insert_with(|| value.clone());
}
for (key, value) in &msg.services {
self.services
.entry(*key)
.and_modify(|x| x.refresh(*value))
.or_insert(*value);
}
for (key, value) in &msg.hosts {
self.hosts
.entry(key.clone())
.and_modify(|x| x.refresh(value))
.or_insert(*value);
}
}
pub fn get_thumbnail_data(&self, data_repr: DataRepr) -> (u128, u128, u128) {
let incoming = self.tot_data_info.incoming_data(data_repr);
let outgoing = self.tot_data_info.outgoing_data(data_repr);
let all = incoming + outgoing;
let all_packets = self.tot_data_info.tot_data(DataRepr::Packets);
let dropped = match data_repr {
DataRepr::Packets => u128::from(self.dropped_packets),
DataRepr::Bytes | DataRepr::Bits => {
// assume that the dropped packets have the same size as the average packet
u128::from(self.dropped_packets) * all / all_packets
}
};
(incoming, outgoing, dropped)
}
pub fn take_but_leave_something(&mut self) -> Self {
let info_traffic = Self {
last_packet_timestamp: self.last_packet_timestamp,
dropped_packets: self.dropped_packets,
..Self::default()
};
std::mem::replace(self, info_traffic)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/service.rs | src/networking/types/service.rs | /// Upper layer services.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Service {
/// One of the known services.
Name(&'static str),
/// Not identified
#[default]
Unknown,
/// Not applicable
NotApplicable,
}
impl Service {
pub fn to_string_with_equal_prefix(self) -> String {
match self {
Service::Name(_) | Service::NotApplicable => ["=", &self.to_string()].concat(),
Service::Unknown => self.to_string(),
}
}
}
impl std::fmt::Display for Service {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Service::Name(name) => write!(f, "{name}"),
Service::Unknown => write!(f, "?"),
Service::NotApplicable => write!(f, "-"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_service_display_unknown() {
assert_eq!(Service::Unknown.to_string(), "?");
}
#[test]
fn test_service_display_not_applicable() {
assert_eq!(Service::NotApplicable.to_string(), "-");
}
#[test]
fn test_service_display_known() {
assert_eq!(Service::Name("https").to_string(), "https");
assert_eq!(Service::Name("mpp").to_string(), "mpp");
}
#[test]
fn test_service_to_string_with_equal_prefix() {
assert_eq!(Service::Name("mdns").to_string_with_equal_prefix(), "=mdns");
assert_eq!(Service::Name("upnp").to_string_with_equal_prefix(), "=upnp");
assert_eq!(Service::NotApplicable.to_string_with_equal_prefix(), "=-");
// unknown should not have the prefix
assert_eq!(Service::Unknown.to_string_with_equal_prefix(), "?");
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/traffic_direction.rs | src/networking/types/traffic_direction.rs | /// Enum representing the possible traffic direction (incoming or outgoing).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum TrafficDirection {
/// Incoming traffic (from remote address to local interface)
#[default]
Incoming,
/// Outgoing traffic (from local interface to remote address)
Outgoing,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/my_link_type.rs | src/networking/types/my_link_type.rs | use pcap::Linktype;
use crate::Language;
use crate::translations::translations_3::link_type_translation;
/// Currently supported link types
#[derive(Copy, Clone, Default, Debug)]
pub enum MyLinkType {
Null(Linktype),
Ethernet(Linktype),
RawIp(Linktype),
Loop(Linktype),
IPv4(Linktype),
IPv6(Linktype),
LinuxSll(Linktype),
LinuxSll2(Linktype),
Unsupported(Linktype),
#[default]
NotYetAssigned,
}
impl MyLinkType {
pub fn is_supported(self) -> bool {
!matches!(self, Self::Unsupported(_) | Self::NotYetAssigned)
}
pub fn from_pcap_link_type(link_type: Linktype) -> Self {
match link_type {
Linktype::NULL => Self::Null(link_type),
Linktype::ETHERNET => Self::Ethernet(link_type),
Linktype(12) => Self::RawIp(link_type),
Linktype::LOOP => Self::Loop(link_type),
Linktype::IPV4 => Self::IPv4(link_type),
Linktype::IPV6 => Self::IPv6(link_type),
Linktype::LINUX_SLL => Self::LinuxSll(link_type),
Linktype::LINUX_SLL2 => Self::LinuxSll2(link_type),
_ => Self::Unsupported(link_type),
}
}
pub fn full_print_on_one_line(self, language: Language) -> String {
match self {
Self::Null(l)
| Self::Ethernet(l)
| Self::RawIp(l)
| Self::Loop(l)
| Self::IPv4(l)
| Self::IPv6(l)
| Self::LinuxSll(l)
| Self::LinuxSll2(l)
| Self::Unsupported(l) => {
format!(
"{}: {}{}",
link_type_translation(language),
l.get_name().unwrap_or_else(|_| l.0.to_string()),
if let Ok(desc) = l.get_description() {
format!(" ({desc})")
} else {
String::new()
}
)
}
Self::NotYetAssigned => {
format!("{}: -", link_type_translation(language),)
}
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/traffic_type.rs | src/networking/types/traffic_type.rs | /// Enum representing the possible traffic type (unicast, multicast or broadcast).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Default)]
pub enum TrafficType {
/// Unicast traffic
#[default]
Unicast,
/// Multicast traffic (destination is a multicast address)
Multicast,
/// Broadcast traffic (destination is a broadcast address)
Broadcast,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/mod.rs | src/networking/types/mod.rs | pub mod address_port_pair;
pub mod arp_type;
pub mod asn;
pub mod bogon;
pub mod capture_context;
pub mod config_device;
pub mod data_info;
pub mod data_info_host;
pub mod data_representation;
pub mod host;
pub mod host_data_states;
pub mod icmp_type;
pub mod info_address_port_pair;
pub mod info_traffic;
pub mod ip_collection;
pub mod my_device;
pub mod my_link_type;
pub mod protocol;
pub mod service;
pub mod service_query;
pub mod traffic_direction;
pub mod 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/asn.rs | src/networking/types/asn.rs | /// Struct to represent an Autonomous System
#[derive(Default, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Asn {
/// Autonomous System number
pub code: String,
/// Autonomous System name
pub name: 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/protocol.rs | src/networking/types/protocol.rs | // WARNING: this file is imported in build.rs
/// Enum representing the possible observed values of protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(clippy::upper_case_acronyms)]
pub enum Protocol {
/// Transmission Control Protocol
TCP,
/// User Datagram Protocol
UDP,
/// Internet Control Message Protocol
ICMP,
/// Address Resolution Protocol
ARP,
}
impl std::fmt::Display for Protocol {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
| 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.rs | src/networking/types/host.rs | use crate::countries::types::country::Country;
use crate::networking::types::asn::Asn;
use crate::networking::types::data_info_host::DataInfoHost;
use std::net::IpAddr;
/// Struct to represent a network host
#[derive(Default, PartialEq, Eq, Hash, Clone, Debug)]
pub struct Host {
/// Hostname (domain). Obtained from the reverse DNS.
pub domain: String,
/// Autonomous System which operates the host
pub asn: Asn,
/// Country
pub country: Country,
}
/// Struct to represent a network host for representation in the thumbnail
///
/// This is necessary to remove possible duplicates in the thumbnail host list
#[allow(clippy::module_name_repetitions)]
#[derive(PartialEq)]
pub struct ThumbnailHost {
/// Country
pub country: Country,
/// Text describing the host in the thumbnail
pub text: String,
}
#[derive(Clone, Debug)]
pub struct HostMessage {
pub host: Host,
pub data_info_host: DataInfoHost,
pub address_to_lookup: IpAddr,
pub rdns: 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/data_representation.rs | src/networking/types/data_representation.rs | use crate::translations::translations::{
bytes_exceeded_translation, bytes_translation, packets_exceeded_translation,
packets_translation,
};
use crate::translations::translations_4::{bits_exceeded_translation, bits_translation};
use crate::translations::types::language::Language;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum DataRepr {
Packets,
#[default]
Bytes,
Bits,
}
impl DataRepr {
pub(crate) const ALL: [DataRepr; 3] = [DataRepr::Bits, DataRepr::Bytes, DataRepr::Packets];
pub fn get_label(&self, language: Language) -> &str {
match self {
DataRepr::Packets => packets_translation(language),
DataRepr::Bytes => bytes_translation(language),
DataRepr::Bits => bits_translation(language),
}
}
/// Returns a String representing a quantity of traffic (packets / bytes / bits) with the proper multiple if applicable
pub fn formatted_string(self, amount: u128) -> String {
if self == DataRepr::Packets {
return amount.to_string();
}
#[allow(clippy::cast_precision_loss)]
let mut n = amount as f32;
let byte_multiple = ByteMultiple::from_amount(amount);
#[allow(clippy::cast_precision_loss)]
let multiplier = byte_multiple.multiplier() as f32;
n /= multiplier;
if n > 999.0 && byte_multiple != ByteMultiple::PB {
// this allows representing e.g. 999_999 as 999 KB instead of 1000 KB
n = 999.0;
}
let precision = usize::from(byte_multiple != ByteMultiple::B && n <= 9.95);
format!("{n:.precision$} {}", byte_multiple.pretty_print(self))
.trim()
.to_string()
}
pub fn data_exceeded_translation(&self, language: Language) -> &str {
match self {
DataRepr::Packets => packets_exceeded_translation(language),
DataRepr::Bytes => bytes_exceeded_translation(language),
DataRepr::Bits => bits_exceeded_translation(language),
}
}
}
/// Represents a Byte or bit multiple for displaying values in a human-readable format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ByteMultiple {
/// A Byte
#[default]
B,
/// 10^3 Bytes
KB,
/// 10^6 Bytes
MB,
/// 10^9 Bytes
GB,
/// 10^12 Bytes
TB,
/// 10^15 Bytes
PB,
}
impl ByteMultiple {
pub fn multiplier(self) -> u64 {
match self {
ByteMultiple::B => 1,
ByteMultiple::KB => 1_000,
ByteMultiple::MB => 1_000_000,
ByteMultiple::GB => 1_000_000_000,
ByteMultiple::TB => 1_000_000_000_000,
ByteMultiple::PB => 1_000_000_000_000_000,
}
}
fn from_amount(bytes: u128) -> Self {
match bytes {
x if (u128::MIN..u128::from(ByteMultiple::KB.multiplier())).contains(&x) => {
ByteMultiple::B
}
x if (u128::from(ByteMultiple::KB.multiplier())
..u128::from(ByteMultiple::MB.multiplier()))
.contains(&x) =>
{
ByteMultiple::KB
}
x if (u128::from(ByteMultiple::MB.multiplier())
..u128::from(ByteMultiple::GB.multiplier()))
.contains(&x) =>
{
ByteMultiple::MB
}
x if (u128::from(ByteMultiple::GB.multiplier())
..u128::from(ByteMultiple::TB.multiplier()))
.contains(&x) =>
{
ByteMultiple::GB
}
x if (u128::from(ByteMultiple::TB.multiplier())
..u128::from(ByteMultiple::PB.multiplier()))
.contains(&x) =>
{
ByteMultiple::TB
}
_ => ByteMultiple::PB,
}
}
pub fn get_char(self) -> String {
match self {
Self::B => String::new(),
Self::KB => "K".to_string(),
Self::MB => "M".to_string(),
Self::GB => "G".to_string(),
Self::TB => "T".to_string(),
Self::PB => "P".to_string(),
}
}
pub fn from_char(ch: char) -> Self {
match ch.to_ascii_uppercase() {
'K' => ByteMultiple::KB,
'M' => ByteMultiple::MB,
'G' => ByteMultiple::GB,
'T' => ByteMultiple::TB,
'P' => ByteMultiple::PB,
_ => ByteMultiple::B,
}
}
fn pretty_print(self, repr: DataRepr) -> String {
match repr {
DataRepr::Packets => String::new(),
DataRepr::Bytes => format!("{}B", self.get_char()),
DataRepr::Bits => format!("{}b", self.get_char()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_interpret_suffix_correctly() {
assert_eq!(ByteMultiple::from_char('B'), ByteMultiple::B);
assert_eq!(ByteMultiple::from_char('k'), ByteMultiple::KB);
assert_eq!(ByteMultiple::from_char('M'), ByteMultiple::MB);
assert_eq!(ByteMultiple::from_char('g'), ByteMultiple::GB);
assert_eq!(ByteMultiple::from_char('t'), ByteMultiple::TB);
assert_eq!(ByteMultiple::from_char('P'), ByteMultiple::PB);
}
#[test]
fn test_interpret_unknown_suffix_correctly() {
assert_eq!(ByteMultiple::from_char('E'), ByteMultiple::B);
assert_eq!(ByteMultiple::from_char('y'), ByteMultiple::B);
}
#[test]
fn test_byte_multiple_display() {
assert_eq!(
format!("{}", ByteMultiple::B.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::B.pretty_print(DataRepr::Bytes)),
"B"
);
assert_eq!(
format!("{}", ByteMultiple::B.pretty_print(DataRepr::Bits)),
"b"
);
assert_eq!(
format!("{}", ByteMultiple::KB.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::KB.pretty_print(DataRepr::Bytes)),
"KB"
);
assert_eq!(
format!("{}", ByteMultiple::KB.pretty_print(DataRepr::Bits)),
"Kb"
);
assert_eq!(
format!("{}", ByteMultiple::MB.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::MB.pretty_print(DataRepr::Bytes)),
"MB"
);
assert_eq!(
format!("{}", ByteMultiple::MB.pretty_print(DataRepr::Bits)),
"Mb"
);
assert_eq!(
format!("{}", ByteMultiple::GB.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::GB.pretty_print(DataRepr::Bytes)),
"GB"
);
assert_eq!(
format!("{}", ByteMultiple::GB.pretty_print(DataRepr::Bits)),
"Gb"
);
assert_eq!(
format!("{}", ByteMultiple::TB.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::TB.pretty_print(DataRepr::Bytes)),
"TB"
);
assert_eq!(
format!("{}", ByteMultiple::TB.pretty_print(DataRepr::Bits)),
"Tb"
);
assert_eq!(
format!("{}", ByteMultiple::PB.pretty_print(DataRepr::Packets)),
""
);
assert_eq!(
format!("{}", ByteMultiple::PB.pretty_print(DataRepr::Bytes)),
"PB"
);
assert_eq!(
format!("{}", ByteMultiple::PB.pretty_print(DataRepr::Bits)),
"Pb"
);
}
#[test]
fn test_byte_multiple_get_char() {
assert_eq!(ByteMultiple::B.get_char(), "");
assert_eq!(ByteMultiple::KB.get_char(), "K");
assert_eq!(ByteMultiple::MB.get_char(), "M");
assert_eq!(ByteMultiple::GB.get_char(), "G");
assert_eq!(ByteMultiple::TB.get_char(), "T");
assert_eq!(ByteMultiple::PB.get_char(), "P");
}
#[test]
fn test_byte_multiple_multiplier() {
assert_eq!(ByteMultiple::B.multiplier(), 1);
assert_eq!(ByteMultiple::KB.multiplier(), 1_000);
assert_eq!(ByteMultiple::MB.multiplier(), 1_000_000);
assert_eq!(ByteMultiple::GB.multiplier(), 1_000_000_000);
assert_eq!(ByteMultiple::TB.multiplier(), 1_000_000_000_000);
assert_eq!(ByteMultiple::PB.multiplier(), 1_000_000_000_000_000);
}
#[test]
fn test_byte_multiple_formatted_string() {
assert_eq!(DataRepr::Packets.formatted_string(u128::MIN), "0");
assert_eq!(DataRepr::Bytes.formatted_string(u128::MIN), "0 B");
assert_eq!(DataRepr::Bits.formatted_string(u128::MIN), "0 b");
assert_eq!(DataRepr::Packets.formatted_string(1), "1");
assert_eq!(DataRepr::Bytes.formatted_string(1), "1 B");
assert_eq!(DataRepr::Bits.formatted_string(1), "1 b");
assert_eq!(DataRepr::Packets.formatted_string(82), "82");
assert_eq!(DataRepr::Bytes.formatted_string(82), "82 B");
assert_eq!(DataRepr::Bits.formatted_string(82), "82 b");
assert_eq!(DataRepr::Packets.formatted_string(999), "999");
assert_eq!(DataRepr::Bytes.formatted_string(999), "999 B");
assert_eq!(DataRepr::Bits.formatted_string(999), "999 b");
assert_eq!(DataRepr::Packets.formatted_string(1_000), "1000");
assert_eq!(DataRepr::Bytes.formatted_string(1_000), "1.0 KB");
assert_eq!(DataRepr::Bits.formatted_string(1_000), "1.0 Kb");
assert_eq!(DataRepr::Packets.formatted_string(1_090), "1090");
assert_eq!(DataRepr::Bytes.formatted_string(1_090), "1.1 KB");
assert_eq!(DataRepr::Bits.formatted_string(1_090), "1.1 Kb");
assert_eq!(DataRepr::Packets.formatted_string(1_990), "1990");
assert_eq!(DataRepr::Bytes.formatted_string(1_990), "2.0 KB");
assert_eq!(DataRepr::Bits.formatted_string(1_990), "2.0 Kb");
assert_eq!(DataRepr::Packets.formatted_string(9_090), "9090");
assert_eq!(DataRepr::Bytes.formatted_string(9_090), "9.1 KB");
assert_eq!(DataRepr::Bits.formatted_string(9_090), "9.1 Kb");
assert_eq!(DataRepr::Packets.formatted_string(9_950), "9950");
assert_eq!(DataRepr::Bytes.formatted_string(9_950), "9.9 KB");
assert_eq!(DataRepr::Bits.formatted_string(9_950), "9.9 Kb");
assert_eq!(DataRepr::Packets.formatted_string(9_951), "9951");
assert_eq!(DataRepr::Bytes.formatted_string(9_951), "10 KB");
assert_eq!(DataRepr::Bits.formatted_string(9_951), "10 Kb");
assert_eq!(DataRepr::Packets.formatted_string(71_324), "71324");
assert_eq!(DataRepr::Bytes.formatted_string(71_324), "71 KB");
assert_eq!(DataRepr::Bits.formatted_string(71_324), "71 Kb");
assert_eq!(DataRepr::Packets.formatted_string(821_789), "821789");
assert_eq!(DataRepr::Bytes.formatted_string(821_789), "822 KB");
assert_eq!(DataRepr::Bits.formatted_string(821_789), "822 Kb");
assert_eq!(DataRepr::Packets.formatted_string(999_499), "999499");
assert_eq!(DataRepr::Bytes.formatted_string(999_499), "999 KB");
assert_eq!(DataRepr::Bits.formatted_string(999_499), "999 Kb");
assert_eq!(DataRepr::Packets.formatted_string(999_999), "999999");
assert_eq!(DataRepr::Bytes.formatted_string(999_999), "999 KB");
assert_eq!(DataRepr::Bits.formatted_string(999_999), "999 Kb");
assert_eq!(DataRepr::Packets.formatted_string(1_000_000), "1000000");
assert_eq!(DataRepr::Bytes.formatted_string(1_000_000), "1.0 MB");
assert_eq!(DataRepr::Bits.formatted_string(1_000_000), "1.0 Mb");
assert_eq!(DataRepr::Packets.formatted_string(3_790_000), "3790000");
assert_eq!(DataRepr::Bytes.formatted_string(3_790_000), "3.8 MB");
assert_eq!(DataRepr::Bits.formatted_string(3_790_000), "3.8 Mb");
assert_eq!(DataRepr::Packets.formatted_string(9_950_000), "9950000");
assert_eq!(DataRepr::Bytes.formatted_string(9_950_000), "9.9 MB");
assert_eq!(DataRepr::Bits.formatted_string(9_950_000), "9.9 Mb");
assert_eq!(DataRepr::Packets.formatted_string(9_951_000), "9951000");
assert_eq!(DataRepr::Bytes.formatted_string(9_951_000), "10 MB");
assert_eq!(DataRepr::Bits.formatted_string(9_951_000), "10 Mb");
assert_eq!(DataRepr::Packets.formatted_string(49_499_000), "49499000");
assert_eq!(DataRepr::Bytes.formatted_string(49_499_000), "49 MB");
assert_eq!(DataRepr::Bits.formatted_string(49_499_000), "49 Mb");
assert_eq!(DataRepr::Packets.formatted_string(49_500_000), "49500000");
assert_eq!(DataRepr::Bytes.formatted_string(49_500_000), "50 MB");
assert_eq!(DataRepr::Bits.formatted_string(49_500_000), "50 Mb");
assert_eq!(DataRepr::Packets.formatted_string(670_900_000), "670900000");
assert_eq!(DataRepr::Bytes.formatted_string(670_900_000), "671 MB");
assert_eq!(DataRepr::Bits.formatted_string(670_900_000), "671 Mb");
assert_eq!(DataRepr::Packets.formatted_string(998_199_999), "998199999");
assert_eq!(DataRepr::Bytes.formatted_string(998_199_999), "998 MB");
assert_eq!(DataRepr::Bits.formatted_string(998_199_999), "998 Mb");
assert_eq!(DataRepr::Packets.formatted_string(999_999_999), "999999999");
assert_eq!(DataRepr::Bytes.formatted_string(999_999_999), "999 MB");
assert_eq!(DataRepr::Bits.formatted_string(999_999_999), "999 Mb");
assert_eq!(
DataRepr::Packets.formatted_string(1_000_000_000),
"1000000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(1_000_000_000), "1.0 GB");
assert_eq!(DataRepr::Bits.formatted_string(1_000_000_000), "1.0 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(7_770_000_000),
"7770000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(7_770_000_000), "7.8 GB");
assert_eq!(DataRepr::Bits.formatted_string(7_770_000_000), "7.8 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(9_950_000_000),
"9950000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(9_950_000_000), "9.9 GB");
assert_eq!(DataRepr::Bits.formatted_string(9_950_000_000), "9.9 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(9_951_000_000),
"9951000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(9_951_000_000), "10 GB");
assert_eq!(DataRepr::Bits.formatted_string(9_951_000_000), "10 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(19_951_000_000),
"19951000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(19_951_000_000), "20 GB");
assert_eq!(DataRepr::Bits.formatted_string(19_951_000_000), "20 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(399_951_000_000),
"399951000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(399_951_000_000), "400 GB");
assert_eq!(DataRepr::Bits.formatted_string(399_951_000_000), "400 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(999_999_999_999),
"999999999999"
);
assert_eq!(DataRepr::Bytes.formatted_string(999_999_999_999), "999 GB");
assert_eq!(DataRepr::Bits.formatted_string(999_999_999_999), "999 Gb");
assert_eq!(
DataRepr::Packets.formatted_string(1_000_000_000_000),
"1000000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(1_000_000_000_000),
"1.0 TB"
);
assert_eq!(DataRepr::Bits.formatted_string(1_000_000_000_000), "1.0 Tb");
assert_eq!(
DataRepr::Packets.formatted_string(9_950_000_000_000),
"9950000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(9_950_000_000_000),
"9.9 TB"
);
assert_eq!(DataRepr::Bits.formatted_string(9_950_000_000_000), "9.9 Tb");
assert_eq!(
DataRepr::Packets.formatted_string(9_951_000_000_000),
"9951000000000"
);
assert_eq!(DataRepr::Bytes.formatted_string(9_951_000_000_000), "10 TB");
assert_eq!(DataRepr::Bits.formatted_string(9_951_000_000_000), "10 Tb");
assert_eq!(
DataRepr::Packets.formatted_string(999_950_000_000_000),
"999950000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(999_950_000_000_000),
"999 TB"
);
assert_eq!(
DataRepr::Bits.formatted_string(999_950_000_000_000),
"999 Tb"
);
assert_eq!(
DataRepr::Packets.formatted_string(999_999_999_999_999),
"999999999999999"
);
assert_eq!(
DataRepr::Bytes.formatted_string(999_999_999_999_999),
"999 TB"
);
assert_eq!(
DataRepr::Bits.formatted_string(999_999_999_999_999),
"999 Tb"
);
assert_eq!(
DataRepr::Packets.formatted_string(1_000_000_000_000_000),
"1000000000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(1_000_000_000_000_000),
"1.0 PB"
);
assert_eq!(
DataRepr::Bits.formatted_string(1_000_000_000_000_000),
"1.0 Pb"
);
assert_eq!(
DataRepr::Packets.formatted_string(1_000_000_000_000_000_0),
"10000000000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(1_000_000_000_000_000_0),
"10 PB"
);
assert_eq!(
DataRepr::Bits.formatted_string(1_000_000_000_000_000_0),
"10 Pb"
);
assert_eq!(
DataRepr::Packets.formatted_string(999_999_999_000_000_000),
"999999999000000000"
);
assert_eq!(
DataRepr::Bytes.formatted_string(999_999_999_000_000_000),
"1000 PB"
);
assert_eq!(
DataRepr::Bits.formatted_string(999_999_999_000_000_000),
"1000 Pb"
);
assert_eq!(
DataRepr::Packets.formatted_string(u128::MAX / 2),
"170141183460469231731687303715884105727"
);
assert_eq!(
DataRepr::Bytes.formatted_string(u128::MAX / 2),
"170141184077655307190272 PB"
);
assert_eq!(
DataRepr::Bits.formatted_string(u128::MAX / 2),
"170141184077655307190272 Pb"
);
assert_eq!(
DataRepr::Packets.formatted_string(u128::MAX),
"340282366920938463463374607431768211455"
);
assert_eq!(DataRepr::Bytes.formatted_string(u128::MAX), "inf PB");
assert_eq!(DataRepr::Bits.formatted_string(u128::MAX), "inf Pb");
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/service_query.rs | src/networking/types/service_query.rs | // WARNING: this file is imported in build.rs
use std::hash::Hash;
/// Used to query the phf services map (key of the map).
#[derive(Hash, Eq, PartialEq)]
pub struct ServiceQuery(pub u16, pub crate::Protocol);
impl phf_shared::PhfHash for ServiceQuery {
fn phf_hash<H: core::hash::Hasher>(&self, state: &mut H) {
let ServiceQuery(port, protocol) = self;
port.hash(state);
protocol.hash(state);
}
}
impl phf_shared::PhfBorrow<ServiceQuery> for ServiceQuery {
fn borrow(&self) -> &ServiceQuery {
self
}
}
impl phf_shared::FmtConst for ServiceQuery {
fn fmt_const(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let ServiceQuery(port, protocol) = self;
write!(f, "ServiceQuery({port}, Protocol::{protocol})",)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/my_device.rs | src/networking/types/my_device.rs | use pcap::{Address, Device, DeviceFlags};
use crate::networking::types::my_link_type::MyLinkType;
/// Represents the current inspected device.
/// Used to keep in sync the device addresses in case of changes
/// (e.g., device not connected to the internet acquires new IP address)
#[derive(Clone, Debug)]
pub struct MyDevice {
name: String,
desc: Option<String>,
addresses: Vec<Address>,
link_type: MyLinkType,
}
impl MyDevice {
pub fn to_pcap_device(&self) -> Device {
for device in Device::list().unwrap_or_default() {
if device.name.eq(&self.name) {
return device;
}
}
Device {
name: String::new(),
desc: None,
addresses: vec![],
flags: DeviceFlags::empty(),
}
}
pub fn from_pcap_device(device: Device) -> Self {
MyDevice {
name: device.name,
desc: device.desc,
addresses: device.addresses,
link_type: MyLinkType::default(),
}
}
pub fn get_name(&self) -> &String {
&self.name
}
pub fn get_desc(&self) -> Option<&String> {
self.desc.as_ref()
}
pub fn get_addresses(&self) -> &Vec<Address> {
&self.addresses
}
pub fn set_addresses(&mut self, addresses: Vec<Address>) {
self.addresses = addresses;
}
pub fn get_link_type(&self) -> MyLinkType {
self.link_type
}
pub fn set_link_type(&mut self, link_type: MyLinkType) {
self.link_type = link_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/icmp_type.rs | src/networking/types/icmp_type.rs | use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use etherparse::{Icmpv4Type, Icmpv6Type};
use std::fmt::Write;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum IcmpType {
V4(IcmpTypeV4),
V6(IcmpTypeV6),
}
impl IcmpType {
pub fn pretty_print_types(map: &HashMap<IcmpType, usize>) -> String {
let mut ret_val = String::new();
let mut vec: Vec<(&IcmpType, &usize)> = map.iter().collect();
vec.sort_by(|(_, a), (_, b)| b.cmp(a));
for (icmp_type, n) in vec {
let _ = writeln!(ret_val, " {icmp_type} ({n})");
}
ret_val
}
}
impl Default for IcmpType {
fn default() -> Self {
Self::V4(IcmpTypeV4::default())
}
}
impl Display for IcmpType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
IcmpType::V4(icmpv4_type) => {
icmpv4_type.to_string()
}
IcmpType::V6(icmpv6_type) => {
icmpv6_type.to_string()
}
}
)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default, Debug)]
#[allow(clippy::module_name_repetitions)]
pub enum IcmpTypeV4 {
EchoReply,
DestinationUnreachable,
SourceQuench,
Redirect,
AlternateHostAddress,
Echo,
RouterAdvertisement,
RouterSolicitation,
TimeExceeded,
ParameterProblem,
Timestamp,
TimestampReply,
InformationRequest,
InformationReply,
AddressMaskRequest,
AddressMaskReply,
Traceroute,
DatagramConversionError,
MobileHostRedirect,
IPv6WhereAreYou,
IPv6IAmHere,
MobileRegistrationRequest,
MobileRegistrationReply,
DomainNameRequest,
DomainNameReply,
Skip,
Photuris,
ExtendedEchoRequest,
ExtendedEchoReply,
#[default]
Unknown,
}
impl IcmpTypeV4 {
pub fn from_etherparse(icmpv4type: &Icmpv4Type) -> IcmpType {
IcmpType::V4(match icmpv4type {
Icmpv4Type::EchoReply(_) => Self::EchoReply,
Icmpv4Type::DestinationUnreachable(_) => Self::DestinationUnreachable,
Icmpv4Type::Redirect(_) => Self::Redirect,
Icmpv4Type::EchoRequest(_) => Self::Echo,
Icmpv4Type::TimeExceeded(_) => Self::TimeExceeded,
Icmpv4Type::ParameterProblem(_) => Self::ParameterProblem,
Icmpv4Type::TimestampRequest(_) => Self::Timestamp,
Icmpv4Type::TimestampReply(_) => Self::TimestampReply,
Icmpv4Type::Unknown { type_u8: id, .. } => match id {
4 => Self::SourceQuench,
6 => Self::AlternateHostAddress,
9 => Self::RouterAdvertisement,
10 => Self::RouterSolicitation,
15 => Self::InformationRequest,
16 => Self::InformationReply,
17 => Self::AddressMaskRequest,
18 => Self::AddressMaskReply,
30 => Self::Traceroute,
31 => Self::DatagramConversionError,
32 => Self::MobileHostRedirect,
33 => Self::IPv6WhereAreYou,
34 => Self::IPv6IAmHere,
35 => Self::MobileRegistrationRequest,
36 => Self::MobileRegistrationReply,
37 => Self::DomainNameRequest,
38 => Self::DomainNameReply,
39 => Self::Skip,
40 => Self::Photuris,
42 => Self::ExtendedEchoRequest,
43 => Self::ExtendedEchoReply,
_ => Self::Unknown,
},
})
}
}
impl Display for IcmpTypeV4 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
IcmpTypeV4::EchoReply => "Echo Reply",
IcmpTypeV4::DestinationUnreachable => "Destination Unreachable",
IcmpTypeV4::SourceQuench => "Source Quench",
IcmpTypeV4::Redirect => "Redirect",
IcmpTypeV4::AlternateHostAddress => "Alternate Host Address",
IcmpTypeV4::Echo => "Echo",
IcmpTypeV4::RouterAdvertisement => "Router Advertisement",
IcmpTypeV4::RouterSolicitation => "Router Solicitation",
IcmpTypeV4::TimeExceeded => "Time Exceeded",
IcmpTypeV4::ParameterProblem => "Parameter Problem",
IcmpTypeV4::Timestamp => "Timestamp",
IcmpTypeV4::TimestampReply => "Timestamp Reply",
IcmpTypeV4::InformationRequest => "Information Request",
IcmpTypeV4::InformationReply => "Information Reply",
IcmpTypeV4::AddressMaskRequest => "Address Mask Request",
IcmpTypeV4::AddressMaskReply => "Address Mask Reply",
IcmpTypeV4::Traceroute => "Traceroute",
IcmpTypeV4::DatagramConversionError => "Datagram Conversion Error",
IcmpTypeV4::MobileHostRedirect => "Mobile Host Redirect",
IcmpTypeV4::IPv6WhereAreYou => "IPv6 Where-Are-You",
IcmpTypeV4::IPv6IAmHere => "IPv6 I-Am-Here",
IcmpTypeV4::MobileRegistrationRequest => "Mobile Registration Request",
IcmpTypeV4::MobileRegistrationReply => "Mobile Registration Reply",
IcmpTypeV4::DomainNameRequest => "Domain Name Request",
IcmpTypeV4::DomainNameReply => "Domain Name Reply",
IcmpTypeV4::Skip => "SKIP",
IcmpTypeV4::Photuris => "Photuris",
IcmpTypeV4::ExtendedEchoRequest => "Extended Echo Request",
IcmpTypeV4::ExtendedEchoReply => "Extended Echo Reply",
IcmpTypeV4::Unknown => "?",
}
)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default, Debug)]
#[allow(clippy::module_name_repetitions)]
pub enum IcmpTypeV6 {
DestinationUnreachable,
PacketTooBig,
TimeExceeded,
ParameterProblem,
EchoRequest,
EchoReply,
MulticastListenerQuery,
MulticastListenerReport,
MulticastListenerDone,
RouterSolicitation,
RouterAdvertisement,
NeighborSolicitation,
NeighborAdvertisement,
RedirectMessage,
RouterRenumbering,
ICMPNodeInformationQuery,
ICMPNodeInformationResponse,
InverseNeighborDiscoverySolicitationMessage,
InverseNeighborDiscoveryAdvertisementMessage,
Version2MulticastListenerReport,
HomeAgentAddressDiscoveryRequestMessage,
HomeAgentAddressDiscoveryReplyMessage,
MobilePrefixSolicitation,
MobilePrefixAdvertisement,
CertificationPathSolicitationMessage,
CertificationPathAdvertisementMessage,
MulticastRouterAdvertisement,
MulticastRouterSolicitation,
MulticastRouterTermination,
FMIPv6Messages,
RPLControlMessage,
ILNPv6LocatorUpdateMessage,
DuplicateAddressRequest,
DuplicateAddressConfirmation,
MPLControlMessage,
ExtendedEchoRequest,
ExtendedEchoReply,
#[default]
Unknown,
}
impl IcmpTypeV6 {
pub fn from_etherparse(icmpv6type: &Icmpv6Type) -> IcmpType {
IcmpType::V6(match icmpv6type {
Icmpv6Type::DestinationUnreachable(_) => Self::DestinationUnreachable,
Icmpv6Type::PacketTooBig { .. } => Self::PacketTooBig,
Icmpv6Type::TimeExceeded(_) => Self::TimeExceeded,
Icmpv6Type::ParameterProblem(_) => Self::ParameterProblem,
Icmpv6Type::EchoRequest(_) => Self::EchoRequest,
Icmpv6Type::EchoReply(_) => Self::EchoReply,
Icmpv6Type::RouterSolicitation => Self::RouterSolicitation,
Icmpv6Type::RouterAdvertisement(_) => Self::RouterAdvertisement,
Icmpv6Type::NeighborSolicitation => Self::NeighborSolicitation,
Icmpv6Type::NeighborAdvertisement(_) => Self::NeighborAdvertisement,
Icmpv6Type::Redirect => Self::RedirectMessage,
Icmpv6Type::Unknown { type_u8: id, .. } => match id {
130 => Self::MulticastListenerQuery,
131 => Self::MulticastListenerReport,
132 => Self::MulticastListenerDone,
138 => Self::RouterRenumbering,
139 => Self::ICMPNodeInformationQuery,
140 => Self::ICMPNodeInformationResponse,
141 => Self::InverseNeighborDiscoverySolicitationMessage,
142 => Self::InverseNeighborDiscoveryAdvertisementMessage,
143 => Self::Version2MulticastListenerReport,
144 => Self::HomeAgentAddressDiscoveryRequestMessage,
145 => Self::HomeAgentAddressDiscoveryReplyMessage,
146 => Self::MobilePrefixSolicitation,
147 => Self::MobilePrefixAdvertisement,
148 => Self::CertificationPathSolicitationMessage,
149 => Self::CertificationPathAdvertisementMessage,
151 => Self::MulticastRouterAdvertisement,
152 => Self::MulticastRouterSolicitation,
153 => Self::MulticastRouterTermination,
154 => Self::FMIPv6Messages,
155 => Self::RPLControlMessage,
156 => Self::ILNPv6LocatorUpdateMessage,
157 => Self::DuplicateAddressRequest,
158 => Self::DuplicateAddressConfirmation,
159 => Self::MPLControlMessage,
160 => Self::ExtendedEchoRequest,
161 => Self::ExtendedEchoReply,
_ => Self::Unknown,
},
})
}
}
impl Display for IcmpTypeV6 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
IcmpTypeV6::DestinationUnreachable => "Destination Unreachable",
IcmpTypeV6::PacketTooBig => "Packet Too Big",
IcmpTypeV6::TimeExceeded => "Time Exceeded",
IcmpTypeV6::ParameterProblem => "Parameter Problem",
IcmpTypeV6::EchoRequest => "Echo Request",
IcmpTypeV6::EchoReply => "Echo Reply",
IcmpTypeV6::MulticastListenerQuery => "Multicast Listener Query",
IcmpTypeV6::MulticastListenerReport => "Multicast Listener Report",
IcmpTypeV6::MulticastListenerDone => "Multicast Listener Done",
IcmpTypeV6::RouterSolicitation => "Router Solicitation",
IcmpTypeV6::RouterAdvertisement => "Router Advertisement",
IcmpTypeV6::NeighborSolicitation => "Neighbor Solicitation",
IcmpTypeV6::NeighborAdvertisement => "Neighbor Advertisement",
IcmpTypeV6::RedirectMessage => "Redirect Message",
IcmpTypeV6::RouterRenumbering => "Router Renumbering",
IcmpTypeV6::ICMPNodeInformationQuery => "ICMP Node Information Query",
IcmpTypeV6::ICMPNodeInformationResponse => "ICMP Node Information Response",
IcmpTypeV6::InverseNeighborDiscoverySolicitationMessage =>
"Inverse Neighbor Discovery Solicitation Message",
IcmpTypeV6::InverseNeighborDiscoveryAdvertisementMessage =>
"Inverse Neighbor Discovery Advertisement Message",
IcmpTypeV6::Version2MulticastListenerReport =>
"Version 2 Multicast Listener Report",
IcmpTypeV6::HomeAgentAddressDiscoveryRequestMessage =>
"Home Agent Address Discovery Request Message",
IcmpTypeV6::HomeAgentAddressDiscoveryReplyMessage =>
"Home Agent Address Discovery Reply Message",
IcmpTypeV6::MobilePrefixSolicitation => "Mobile Prefix Solicitation",
IcmpTypeV6::MobilePrefixAdvertisement => "Mobile Prefix Advertisement",
IcmpTypeV6::CertificationPathSolicitationMessage =>
"Certification Path Solicitation Message",
IcmpTypeV6::CertificationPathAdvertisementMessage =>
"Certification Path Advertisement Message",
IcmpTypeV6::MulticastRouterAdvertisement => "Multicast Router Advertisement",
IcmpTypeV6::MulticastRouterSolicitation => "Multicast Router Solicitation",
IcmpTypeV6::MulticastRouterTermination => "Multicast Router Termination",
IcmpTypeV6::FMIPv6Messages => "FMIPv6 Messages",
IcmpTypeV6::RPLControlMessage => "RPL Control Message",
IcmpTypeV6::ILNPv6LocatorUpdateMessage => "ILNPv6 Locator Update Message",
IcmpTypeV6::DuplicateAddressRequest => "Duplicate Address Request",
IcmpTypeV6::DuplicateAddressConfirmation => "Duplicate Address Confirmation",
IcmpTypeV6::MPLControlMessage => "MPL Control Message",
IcmpTypeV6::ExtendedEchoRequest => "Extended Echo Request",
IcmpTypeV6::ExtendedEchoReply => "Extended Echo Reply",
IcmpTypeV6::Unknown => "?",
}
)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/capture_context.rs | src/networking/types/capture_context.rs | use crate::gui::types::conf::Conf;
use crate::gui::types::filters::Filters;
use crate::location;
use crate::networking::types::my_device::MyDevice;
use crate::networking::types::my_link_type::MyLinkType;
use crate::translations::translations::network_adapter_translation;
use crate::translations::translations_4::capture_file_translation;
use crate::translations::types::language::Language;
use crate::utils::error_logger::{ErrorLogger, Location};
use pcap::{Active, Address, Capture, Device, Error, Packet, Savefile, Stat};
use serde::{Deserialize, Serialize};
pub enum CaptureContext {
Live(Live),
LiveWithSavefile(LiveWithSavefile),
Offline(Offline),
Error(String),
}
impl CaptureContext {
pub fn new(source: &CaptureSource, pcap_out_path: Option<&String>, filters: &Filters) -> Self {
let mut cap_type = match CaptureType::from_source(source, pcap_out_path) {
Ok(c) => c,
Err(e) => return Self::Error(e.to_string()),
};
// only apply BPF filter if it is active, and return an error if it fails to apply
if filters.is_some_filter_active()
&& let Err(e) = cap_type.set_bpf(filters.bpf())
{
return Self::Error(e.to_string());
}
let cap = match cap_type {
CaptureType::Live(cap) => cap,
CaptureType::Offline(cap) => return Self::new_offline(cap),
};
if let Some(out_path) = pcap_out_path {
let savefile_res = cap.savefile(out_path);
match savefile_res {
Ok(s) => Self::new_live_with_savefile(cap, s),
Err(e) => Self::Error(e.to_string()),
}
} else {
Self::new_live(cap)
}
}
fn new_live(cap: Capture<Active>) -> Self {
Self::Live(Live { cap })
}
fn new_live_with_savefile(cap: Capture<Active>, savefile: Savefile) -> Self {
Self::LiveWithSavefile(LiveWithSavefile {
live: Live { cap },
savefile,
})
}
fn new_offline(cap: Capture<pcap::Offline>) -> Self {
Self::Offline(Offline { cap })
}
pub fn error(&self) -> Option<&str> {
match self {
Self::Error(e) => Some(e),
_ => None,
}
}
pub fn consume(self) -> (Option<CaptureType>, Option<Savefile>) {
match self {
Self::Live(on) => (Some(CaptureType::Live(on.cap)), None),
Self::LiveWithSavefile(onws) => {
(Some(CaptureType::Live(onws.live.cap)), Some(onws.savefile))
}
Self::Offline(off) => (Some(CaptureType::Offline(off.cap)), None),
Self::Error(_) => (None, None),
}
}
pub fn my_link_type(&self) -> MyLinkType {
match self {
Self::Live(on) => MyLinkType::from_pcap_link_type(on.cap.get_datalink()),
Self::LiveWithSavefile(onws) => {
MyLinkType::from_pcap_link_type(onws.live.cap.get_datalink())
}
Self::Offline(off) => MyLinkType::from_pcap_link_type(off.cap.get_datalink()),
Self::Error(_) => MyLinkType::default(),
}
}
}
pub struct Live {
cap: Capture<Active>,
}
pub struct LiveWithSavefile {
live: Live,
savefile: Savefile,
}
pub struct Offline {
cap: Capture<pcap::Offline>,
}
pub enum CaptureType {
Live(Capture<Active>),
Offline(Capture<pcap::Offline>),
}
impl CaptureType {
pub fn next_packet(&mut self) -> Result<Packet<'_>, Error> {
match self {
Self::Live(on) => on.next_packet(),
Self::Offline(off) => off.next_packet(),
}
}
pub fn stats(&mut self) -> Result<Stat, Error> {
match self {
Self::Live(on) => on.stats(),
Self::Offline(off) => off.stats(),
}
}
fn from_source(source: &CaptureSource, pcap_out_path: Option<&String>) -> Result<Self, Error> {
match source {
CaptureSource::Device(device) => {
let inactive = Capture::from_device(device.to_pcap_device())?;
let cap = inactive
.promisc(false)
.buffer_size(2_000_000) // 2MB buffer -> 10k packets of 200 bytes
.snaplen(if pcap_out_path.is_some() {
i32::from(u16::MAX)
} else {
200 // limit stored packets slice dimension (to keep more in the buffer)
})
.immediate_mode(false)
.timeout(150) // ensure UI is updated even if no packets are captured
.open()?;
Ok(Self::Live(cap))
}
CaptureSource::File(file) => Ok(Self::Offline(Capture::from_file(&file.path)?)),
}
}
fn set_bpf(&mut self, bpf: &str) -> Result<(), Error> {
match self {
Self::Live(cap) => cap.filter(bpf, true),
Self::Offline(cap) => cap.filter(bpf, true),
}
}
pub fn pause(&mut self) {
if let Self::Live(cap) = self {
let _ = cap.filter("less 2", true).log_err(location!());
}
}
pub fn resume(&mut self, filters: &Filters) {
if let Self::Live(cap) = self {
if filters.is_some_filter_active() {
let _ = cap.filter(filters.bpf(), true).log_err(location!());
} else if cap.filter("", true).log_err(location!()).is_err() {
let _ = cap.filter("greater 0", true).log_err(location!());
}
}
}
}
#[derive(Clone)]
pub enum CaptureSource {
Device(MyDevice),
File(MyPcapImport),
}
impl CaptureSource {
pub fn from_conf(conf: &Conf) -> Self {
match conf.capture_source_picklist {
CaptureSourcePicklist::Device => {
let device = conf.device.to_my_device();
Self::Device(device)
}
CaptureSourcePicklist::File => {
let path = conf.import_pcap_path.clone();
Self::File(MyPcapImport::new(path))
}
}
}
pub fn title(&self, language: Language) -> &str {
match self {
Self::Device(_) => network_adapter_translation(language),
Self::File(_) => capture_file_translation(language),
}
}
pub fn get_addresses(&self) -> &Vec<Address> {
match self {
Self::Device(device) => device.get_addresses(),
Self::File(file) => &file.addresses,
}
}
pub fn set_addresses(&mut self) {
if let Self::Device(my_device) = self {
let mut addresses = Vec::new();
for dev in Device::list().log_err(location!()).unwrap_or_default() {
if matches!(
my_device.get_link_type(),
MyLinkType::LinuxSll(_) | MyLinkType::LinuxSll2(_)
) {
addresses.extend(dev.addresses);
} else if dev.name.eq(my_device.get_name()) {
addresses.extend(dev.addresses);
break;
}
}
my_device.set_addresses(addresses);
}
}
pub fn get_link_type(&self) -> MyLinkType {
match self {
Self::Device(device) => device.get_link_type(),
Self::File(file) => file.link_type,
}
}
pub fn set_link_type(&mut self, link_type: MyLinkType) {
match self {
Self::Device(device) => device.set_link_type(link_type),
Self::File(file) => file.link_type = link_type,
}
}
pub fn get_name(&self) -> String {
match self {
Self::Device(device) => device.get_name().clone(),
Self::File(file) => file.path.clone(),
}
}
#[cfg(target_os = "windows")]
pub fn get_desc(&self) -> Option<String> {
match self {
Self::Device(device) => device.get_desc().cloned(),
Self::File(_) => None,
}
}
}
#[derive(Clone)]
pub struct MyPcapImport {
path: String,
link_type: MyLinkType,
addresses: Vec<Address>, // this is always empty!
}
impl MyPcapImport {
pub fn new(path: String) -> Self {
Self {
path,
link_type: MyLinkType::default(),
addresses: vec![],
}
}
}
#[derive(Clone, Eq, PartialEq, Debug, Copy, Default, Serialize, Deserialize)]
pub enum CaptureSourcePicklist {
#[default]
Device,
File,
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/networking/types/arp_type.rs | src/networking/types/arp_type.rs | use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use etherparse::ArpOperation;
use std::fmt::Write;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default, Debug)]
pub enum ArpType {
Request,
Reply,
#[default]
Unknown,
}
impl ArpType {
pub fn from_etherparse(arp_operation: ArpOperation) -> ArpType {
match arp_operation {
ArpOperation(1) => Self::Request,
ArpOperation(2) => Self::Reply,
ArpOperation(_) => Self::Unknown,
}
}
pub fn pretty_print_types(map: &HashMap<ArpType, usize>) -> String {
let mut ret_val = String::new();
let mut vec: Vec<(&ArpType, &usize)> = map.iter().collect();
vec.sort_by(|(_, a), (_, b)| b.cmp(a));
for (arp_type, n) in vec {
let _ = writeln!(ret_val, " {arp_type} ({n})");
}
ret_val
}
}
impl Display for ArpType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
ArpType::Request => "Request",
ArpType::Reply => "Reply",
ArpType::Unknown => "?",
}
)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/countries/country_utils.rs | src/countries/country_utils.rs | use iced::widget::Tooltip;
use iced::widget::svg::Handle;
use iced::widget::tooltip::Position;
use iced::widget::{Svg, Text};
use crate::countries::flags_pictures::{
AD, AE, AF, AG, AI, AL, AM, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI,
BJ, BM, BN, BO, BOGON, BR, BROADCAST, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK,
CL, CM, CN, CO, COMPUTER, CR, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH,
ER, ES, ET, FI, FJ, FK, FLAGS_HEIGHT_BIG, FLAGS_WIDTH_BIG, FLAGS_WIDTH_SMALL, FM, FO, FR, GA,
GB, GD, GE, GG, GH, GI, GL, GM, GN, GQ, GR, GS, GT, GU, GW, GY, HK, HN, HOME, HR, HT, HU, ID,
IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ,
LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MG, MH, MK, ML, MM, MN, MO, MP, MR,
MS, MT, MU, MULTICAST, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM,
PA, PE, PF, PG, PH, PK, PL, PN, PR, PS, PT, PW, PY, QA, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG,
SH, SI, SK, SL, SM, SN, SO, SR, SS, ST, SV, SX, SY, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN,
TO, TR, TT, TV, TW, TZ, UA, UG, UNKNOWN, US, UY, UZ, VA, VC, VE, VG, VI, VN, VU, WS, YE, ZA,
ZM, ZW,
};
use crate::countries::types::country::Country;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::TOOLTIP_DELAY;
use crate::gui::styles::svg::SvgType;
use crate::gui::types::message::Message;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::traffic_type::TrafficType;
use crate::translations::translations_2::{
local_translation, unknown_translation, your_network_adapter_translation,
};
use crate::translations::translations_4::reserved_address_translation;
use crate::{Language, StyleType};
fn get_flag_from_country<'a>(
country: Country,
width: f32,
is_local: bool,
is_loopback: bool,
is_bogon: Option<&str>,
traffic_type: TrafficType,
language: Language,
) -> (Svg<'a, StyleType>, String) {
#![allow(clippy::too_many_lines)]
let mut tooltip = country.to_string();
let mut svg_style = SvgType::Standard;
let svg = Svg::new(Handle::from_memory(Vec::from(match country {
Country::AD => AD,
Country::AE => AE,
Country::AF => AF,
Country::AG => AG,
Country::AI => AI,
Country::AL => AL,
Country::AM => AM,
Country::AO => AO,
Country::AQ => AQ,
Country::AR => AR,
Country::AS => AS,
Country::AT => AT,
Country::AU | Country::HM => AU,
Country::AW => AW,
Country::AX => AX,
Country::AZ => AZ,
Country::BA => BA,
Country::BB => BB,
Country::BD => BD,
Country::BE => BE,
Country::BF => BF,
Country::BG => BG,
Country::BH => BH,
Country::BI => BI,
Country::BJ => BJ,
Country::BM => BM,
Country::BN => BN,
Country::BO => BO,
Country::BR => BR,
Country::BS => BS,
Country::BT => BT,
Country::BV => BV,
Country::BW => BW,
Country::BY => BY,
Country::BZ => BZ,
Country::CA => CA,
Country::CC => CC,
Country::CD => CD,
Country::CF => CF,
Country::CG => CG,
Country::CH => CH,
Country::CI => CI,
Country::CK => CK,
Country::CL => CL,
Country::CM => CM,
Country::CN => CN,
Country::CO => CO,
Country::CR => CR,
Country::CU => CU,
Country::CV => CV,
Country::CW => CW,
Country::CX => CX,
Country::CY => CY,
Country::CZ => CZ,
Country::DE => DE,
Country::DJ => DJ,
Country::DK => DK,
Country::DM => DM,
Country::DO => DO,
Country::DZ => DZ,
Country::EC => EC,
Country::EE => EE,
Country::EG => EG,
Country::EH => EH,
Country::ER => ER,
Country::ES => ES,
Country::ET => ET,
Country::FI => FI,
Country::FJ => FJ,
Country::FK => FK,
Country::FM => FM,
Country::FO => FO,
Country::FR
| Country::BL
| Country::GF
| Country::GP
| Country::MF
| Country::MQ
| Country::PM
| Country::RE
| Country::WF
| Country::YT => FR,
Country::GA => GA,
Country::GB => GB,
Country::GD => GD,
Country::GE => GE,
Country::GG => GG,
Country::GH => GH,
Country::GI => GI,
Country::GL => GL,
Country::GM => GM,
Country::GN => GN,
Country::GQ => GQ,
Country::GR => GR,
Country::GS => GS,
Country::GT => GT,
Country::GU => GU,
Country::GW => GW,
Country::GY => GY,
Country::HK => HK,
Country::HN => HN,
Country::HR => HR,
Country::HT => HT,
Country::HU => HU,
Country::ID => ID,
Country::IE => IE,
Country::IL => IL,
Country::IM => IM,
Country::IN => IN,
Country::IO => IO,
Country::IQ => IQ,
Country::IR => IR,
Country::IS => IS,
Country::IT => IT,
Country::JE => JE,
Country::JM => JM,
Country::JO => JO,
Country::JP => JP,
Country::KE => KE,
Country::KG => KG,
Country::KH => KH,
Country::KI => KI,
Country::KM => KM,
Country::KN => KN,
Country::KP => KP,
Country::KR => KR,
Country::KW => KW,
Country::KY => KY,
Country::KZ => KZ,
Country::LA => LA,
Country::LB => LB,
Country::LC => LC,
Country::LI => LI,
Country::LK => LK,
Country::LR => LR,
Country::LS => LS,
Country::LT => LT,
Country::LU => LU,
Country::LV => LV,
Country::LY => LY,
Country::MA => MA,
Country::MC => MC,
Country::MD => MD,
Country::ME => ME,
Country::MG => MG,
Country::MH => MH,
Country::MK => MK,
Country::ML => ML,
Country::MM => MM,
Country::MN => MN,
Country::MO => MO,
Country::MP => MP,
Country::MR => MR,
Country::MS => MS,
Country::MT => MT,
Country::MU => MU,
Country::MV => MV,
Country::MW => MW,
Country::MX => MX,
Country::MY => MY,
Country::MZ => MZ,
Country::NA => NA,
Country::NC => NC,
Country::NE => NE,
Country::NF => NF,
Country::NG => NG,
Country::NI => NI,
Country::NL | Country::BQ => NL,
Country::NO | Country::SJ => NO,
Country::NP => NP,
Country::NR => NR,
Country::NU => NU,
Country::NZ => NZ,
Country::OM => OM,
Country::PA => PA,
Country::PE => PE,
Country::PF => PF,
Country::PG => PG,
Country::PH => PH,
Country::PK => PK,
Country::PL => PL,
Country::PN => PN,
Country::PR => PR,
Country::PS => PS,
Country::PT => PT,
Country::PW => PW,
Country::PY => PY,
Country::QA => QA,
Country::RO => RO,
Country::RS => RS,
Country::RU => RU,
Country::RW => RW,
Country::SA => SA,
Country::SB => SB,
Country::SC => SC,
Country::SD => SD,
Country::SE => SE,
Country::SG => SG,
Country::SH => SH,
Country::SI => SI,
Country::SK => SK,
Country::SL => SL,
Country::SM => SM,
Country::SN => SN,
Country::SO => SO,
Country::SR => SR,
Country::SS => SS,
Country::ST => ST,
Country::SV => SV,
Country::SX => SX,
Country::SY => SY,
Country::SZ => SZ,
Country::TC => TC,
Country::TD => TD,
Country::TF => TF,
Country::TG => TG,
Country::TH => TH,
Country::TJ => TJ,
Country::TK => TK,
Country::TL => TL,
Country::TM => TM,
Country::TN => TN,
Country::TO => TO,
Country::TR => TR,
Country::TT => TT,
Country::TV => TV,
Country::TW => TW,
Country::TZ => TZ,
Country::UA => UA,
Country::UG => UG,
Country::US | Country::UM => US,
Country::UY => UY,
Country::UZ => UZ,
Country::VA => VA,
Country::VC => VC,
Country::VE => VE,
Country::VG => VG,
Country::VI => VI,
Country::VN => VN,
Country::VU => VU,
Country::WS => WS,
Country::YE => YE,
Country::ZA => ZA,
Country::ZM => ZM,
Country::ZW => ZW,
Country::ZZ => {
let (flag, new_tooltip) = if is_loopback {
(
COMPUTER,
your_network_adapter_translation(language).to_string(),
)
} else if traffic_type.eq(&TrafficType::Multicast) {
(MULTICAST, "Multicast".to_string())
} else if traffic_type.eq(&TrafficType::Broadcast) {
(BROADCAST, "Broadcast".to_string())
} else if is_local {
(HOME, local_translation(language).to_string())
} else if let Some(bogon) = is_bogon {
(BOGON, reserved_address_translation(language, bogon))
} else {
(UNKNOWN, unknown_translation(language).to_string())
};
svg_style = SvgType::AdaptColor;
tooltip = new_tooltip;
flag
}
})))
.class(svg_style)
.width(width)
.height(width * 0.75);
(svg, tooltip)
}
pub fn get_flag_tooltip<'a>(
country: Country,
host_info: &DataInfoHost,
language: Language,
thumbnail: bool,
) -> Tooltip<'a, Message, StyleType> {
let width = if thumbnail {
FLAGS_WIDTH_SMALL
} else {
FLAGS_WIDTH_BIG
};
let is_local = host_info.is_local;
let is_loopback = host_info.is_loopback;
let is_bogon = host_info.is_bogon;
let traffic_type = host_info.traffic_type;
let (content, tooltip) = get_flag_from_country(
country,
width,
is_local,
is_loopback,
is_bogon,
traffic_type,
language,
);
let actual_tooltip = if thumbnail { String::new() } else { tooltip };
let tooltip_style = if thumbnail {
ContainerType::Standard
} else {
ContainerType::Tooltip
};
let mut tooltip = Tooltip::new(content, Text::new(actual_tooltip), Position::FollowCursor)
.snap_within_viewport(true)
.class(tooltip_style)
.delay(TOOLTIP_DELAY);
if width == FLAGS_WIDTH_SMALL {
tooltip = tooltip.padding(3);
}
tooltip
}
pub fn get_computer_tooltip<'a>(
is_my_address: bool,
is_local: bool,
is_bogon: Option<&str>,
traffic_type: TrafficType,
language: Language,
) -> Tooltip<'a, Message, StyleType> {
let content = Svg::new(Handle::from_memory(Vec::from(
match (is_my_address, is_local, is_bogon, traffic_type) {
(true, _, _, _) => COMPUTER,
(false, _, _, TrafficType::Multicast) => MULTICAST,
(false, _, _, TrafficType::Broadcast) => BROADCAST,
(false, true, _, _) => HOME,
(false, false, Some(_), _) => BOGON,
(false, false, None, TrafficType::Unicast) => UNKNOWN,
},
)))
.class(SvgType::AdaptColor)
.width(FLAGS_WIDTH_BIG)
.height(FLAGS_HEIGHT_BIG);
let tooltip = match (is_my_address, is_local, is_bogon, traffic_type) {
(true, _, _, _) => your_network_adapter_translation(language).to_string(),
(false, _, _, TrafficType::Multicast) => "Multicast".to_string(),
(false, _, _, TrafficType::Broadcast) => "Broadcast".to_string(),
(false, true, _, _) => local_translation(language).to_string(),
(false, false, Some(t), _) => reserved_address_translation(language, t),
(false, false, None, TrafficType::Unicast) => unknown_translation(language).to_string(),
};
Tooltip::new(content, Text::new(tooltip), Position::FollowCursor)
.snap_within_viewport(true)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/countries/mod.rs | src/countries/mod.rs | pub mod country_utils;
pub mod flags_pictures;
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/countries/flags_pictures.rs | src/countries/flags_pictures.rs | pub const FLAGS_WIDTH_SMALL: f32 = 20.0;
pub const FLAGS_WIDTH_BIG: f32 = 37.5;
pub const FLAGS_HEIGHT_BIG: f32 = FLAGS_WIDTH_BIG * 3.0 / 4.0;
pub const AD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ad.svg");
pub const AE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ae.svg");
pub const AF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/af.svg");
pub const AG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ag.svg");
pub const AI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ai.svg");
pub const AL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/al.svg");
pub const AM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/am.svg");
pub const AO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ao.svg");
pub const AQ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/aq.svg");
pub const AR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ar.svg");
pub const AS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/as.svg");
pub const AT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/at.svg");
pub const AU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/au.svg");
pub const AW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/aw.svg");
pub const AX: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ax.svg");
pub const AZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/az.svg");
pub const BA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ba.svg");
pub const BB: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bb.svg");
pub const BD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bd.svg");
pub const BE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/be.svg");
pub const BF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bf.svg");
pub const BG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bg.svg");
pub const BH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bh.svg");
pub const BI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bi.svg");
pub const BJ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bj.svg");
// pub const BL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bl.svg");
pub const BM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bm.svg");
pub const BN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bn.svg");
pub const BO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bo.svg");
// pub const BQ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bq.svg");
pub const BR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/br.svg");
pub const BS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bs.svg");
pub const BT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bt.svg");
pub const BV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bv.svg");
pub const BW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bw.svg");
pub const BY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/by.svg");
pub const BZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/bz.svg");
pub const CA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ca.svg");
pub const CC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cc.svg");
pub const CD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cd.svg");
pub const CF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cf.svg");
pub const CG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cg.svg");
pub const CH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ch.svg");
pub const CI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ci.svg");
pub const CK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ck.svg");
pub const CL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cl.svg");
pub const CM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cm.svg");
pub const CN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cn.svg");
pub const CO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/co.svg");
pub const CR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cr.svg");
pub const CU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cu.svg");
pub const CV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cv.svg");
pub const CW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cw.svg");
pub const CX: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cx.svg");
pub const CY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cy.svg");
pub const CZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/cz.svg");
pub const DE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/de.svg");
pub const DJ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/dj.svg");
pub const DK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/dk.svg");
pub const DM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/dm.svg");
pub const DO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/do.svg");
pub const DZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/dz.svg");
pub const EC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ec.svg");
pub const EE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ee.svg");
pub const EG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/eg.svg");
pub const EH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/eh.svg");
pub const ER: &[u8] = include_bytes!("../../resources/countries_flags/4x3/er.svg");
pub const ES: &[u8] = include_bytes!("../../resources/countries_flags/4x3/es.svg");
pub const ET: &[u8] = include_bytes!("../../resources/countries_flags/4x3/et.svg");
pub const FI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fi.svg");
pub const FJ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fj.svg");
pub const FK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fk.svg");
pub const FM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fm.svg");
pub const FO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fo.svg");
pub const FR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/fr.svg");
pub const GA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ga.svg");
pub const GB: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gb.svg");
pub const GD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gd.svg");
pub const GE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ge.svg");
// pub const GF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gf.svg");
pub const GG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gg.svg");
pub const GH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gh.svg");
pub const GI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gi.svg");
pub const GL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gl.svg");
pub const GM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gm.svg");
pub const GN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gn.svg");
// pub const GP: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gp.svg");
pub const GQ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gq.svg");
pub const GR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gr.svg");
pub const GS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gs.svg");
pub const GT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gt.svg");
pub const GU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gu.svg");
pub const GW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gw.svg");
pub const GY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/gy.svg");
pub const HK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/hk.svg");
// pub const HM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/hm.svg");
pub const HN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/hn.svg");
pub const HR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/hr.svg");
pub const HT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ht.svg");
pub const HU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/hu.svg");
pub const ID: &[u8] = include_bytes!("../../resources/countries_flags/4x3/id.svg");
pub const IE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ie.svg");
pub const IL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/il.svg");
pub const IM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/im.svg");
pub const IN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/in.svg");
pub const IO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/io.svg");
pub const IQ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/iq.svg");
pub const IR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ir.svg");
pub const IS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/is.svg");
pub const IT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/it.svg");
pub const JE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/je.svg");
pub const JM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/jm.svg");
pub const JO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/jo.svg");
pub const JP: &[u8] = include_bytes!("../../resources/countries_flags/4x3/jp.svg");
pub const KE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ke.svg");
pub const KG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kg.svg");
pub const KH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kh.svg");
pub const KI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ki.svg");
pub const KM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/km.svg");
pub const KN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kn.svg");
pub const KP: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kp.svg");
pub const KR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kr.svg");
pub const KW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kw.svg");
pub const KY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ky.svg");
pub const KZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/kz.svg");
pub const LA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/la.svg");
pub const LB: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lb.svg");
pub const LC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lc.svg");
pub const LI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/li.svg");
pub const LK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lk.svg");
pub const LR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lr.svg");
pub const LS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ls.svg");
pub const LT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lt.svg");
pub const LU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lu.svg");
pub const LV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/lv.svg");
pub const LY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ly.svg");
pub const MA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ma.svg");
pub const MC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mc.svg");
pub const MD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/md.svg");
pub const ME: &[u8] = include_bytes!("../../resources/countries_flags/4x3/me.svg");
// pub const MF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mf.svg");
pub const MG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mg.svg");
pub const MH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mh.svg");
pub const MK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mk.svg");
pub const ML: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ml.svg");
pub const MM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mm.svg");
pub const MN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mn.svg");
pub const MO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mo.svg");
pub const MP: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mp.svg");
// pub const MQ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mq.svg");
pub const MR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mr.svg");
pub const MS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ms.svg");
pub const MT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mt.svg");
pub const MU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mu.svg");
pub const MV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mv.svg");
pub const MW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mw.svg");
pub const MX: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mx.svg");
pub const MY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/my.svg");
pub const MZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/mz.svg");
pub const NA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/na.svg");
pub const NC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nc.svg");
pub const NE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ne.svg");
pub const NF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nf.svg");
pub const NG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ng.svg");
pub const NI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ni.svg");
pub const NL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nl.svg");
pub const NO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/no.svg");
pub const NP: &[u8] = include_bytes!("../../resources/countries_flags/4x3/np.svg");
pub const NR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nr.svg");
pub const NU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nu.svg");
pub const NZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/nz.svg");
pub const OM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/om.svg");
pub const PA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pa.svg");
pub const PE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pe.svg");
pub const PF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pf.svg");
pub const PG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pg.svg");
pub const PH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ph.svg");
pub const PK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pk.svg");
pub const PL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pl.svg");
// pub const PM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pm.svg");
pub const PN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pn.svg");
pub const PR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pr.svg");
pub const PS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ps.svg");
pub const PT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pt.svg");
pub const PW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/pw.svg");
pub const PY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/py.svg");
pub const QA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/qa.svg");
// pub const RE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/re.svg");
pub const RO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ro.svg");
pub const RS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/rs.svg");
pub const RU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ru.svg");
pub const RW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/rw.svg");
pub const SA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sa.svg");
pub const SB: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sb.svg");
pub const SC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sc.svg");
pub const SD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sd.svg");
pub const SE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/se.svg");
pub const SG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sg.svg");
pub const SH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sh.svg");
pub const SI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/si.svg");
// pub const SJ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sj.svg");
pub const SK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sk.svg");
pub const SL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sl.svg");
pub const SM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sm.svg");
pub const SN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sn.svg");
pub const SO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/so.svg");
pub const SR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sr.svg");
pub const SS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ss.svg");
pub const ST: &[u8] = include_bytes!("../../resources/countries_flags/4x3/st.svg");
pub const SV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sv.svg");
pub const SX: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sx.svg");
pub const SY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sy.svg");
pub const SZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/sz.svg");
pub const TC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tc.svg");
pub const TD: &[u8] = include_bytes!("../../resources/countries_flags/4x3/td.svg");
pub const TF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tf.svg");
pub const TG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tg.svg");
pub const TH: &[u8] = include_bytes!("../../resources/countries_flags/4x3/th.svg");
pub const TJ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tj.svg");
pub const TK: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tk.svg");
pub const TL: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tl.svg");
pub const TM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tm.svg");
pub const TN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tn.svg");
pub const TO: &[u8] = include_bytes!("../../resources/countries_flags/4x3/to.svg");
pub const TR: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tr.svg");
pub const TT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tt.svg");
pub const TV: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tv.svg");
pub const TW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tw.svg");
pub const TZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/tz.svg");
pub const UA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ua.svg");
pub const UG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ug.svg");
// pub const UM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/um.svg");
pub const US: &[u8] = include_bytes!("../../resources/countries_flags/4x3/usa.svg");
pub const UY: &[u8] = include_bytes!("../../resources/countries_flags/4x3/uy.svg");
pub const UZ: &[u8] = include_bytes!("../../resources/countries_flags/4x3/uz.svg");
pub const VA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/va.svg");
pub const VC: &[u8] = include_bytes!("../../resources/countries_flags/4x3/vc.svg");
pub const VE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ve.svg");
pub const VG: &[u8] = include_bytes!("../../resources/countries_flags/4x3/vg.svg");
pub const VI: &[u8] = include_bytes!("../../resources/countries_flags/4x3/vi.svg");
pub const VN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/vn.svg");
pub const VU: &[u8] = include_bytes!("../../resources/countries_flags/4x3/vu.svg");
// pub const WF: &[u8] = include_bytes!("../../resources/countries_flags/4x3/wf.svg");
pub const WS: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ws.svg");
pub const YE: &[u8] = include_bytes!("../../resources/countries_flags/4x3/ye.svg");
// pub const YT: &[u8] = include_bytes!("../../resources/countries_flags/4x3/yt.svg");
pub const ZA: &[u8] = include_bytes!("../../resources/countries_flags/4x3/za.svg");
pub const ZM: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zm.svg");
pub const ZW: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zw.svg");
pub const HOME: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-home.svg");
pub const MULTICAST: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-multicast.svg");
pub const BROADCAST: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-broadcast.svg");
pub const UNKNOWN: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-unknown.svg");
pub const COMPUTER: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-computer.svg");
pub const BOGON: &[u8] = include_bytes!("../../resources/countries_flags/4x3/zz-bogon.svg");
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/countries/types/country.rs | src/countries/types/country.rs | use std::fmt;
use std::fmt::Formatter;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
pub enum Country {
AD,
AE,
AF,
AG,
AI,
AL,
AM,
AO,
AQ,
AR,
AS,
AT,
AU,
AW,
AX,
AZ,
BA,
BB,
BD,
BE,
BF,
BG,
BH,
BI,
BJ,
BL,
BM,
BN,
BO,
BQ,
BR,
BS,
BT,
BV,
BW,
BY,
BZ,
CA,
CC,
CD,
CF,
CG,
CH,
CI,
CK,
CL,
CM,
CN,
CO,
CR,
CU,
CV,
CW,
CX,
CY,
CZ,
DE,
DJ,
DK,
DM,
DO,
DZ,
EC,
EE,
EG,
EH,
ER,
ES,
ET,
FI,
FJ,
FK,
FM,
FO,
FR,
GA,
GB,
GD,
GE,
GF,
GG,
GH,
GI,
GL,
GM,
GN,
GP,
GQ,
GR,
GS,
GT,
GU,
GW,
GY,
HK,
HM,
HN,
HR,
HT,
HU,
ID,
IE,
IL,
IM,
IN,
IO,
IQ,
IR,
IS,
IT,
JE,
JM,
JO,
JP,
KE,
KG,
KH,
KI,
KM,
KN,
KP,
KR,
KW,
KY,
KZ,
LA,
LB,
LC,
LI,
LK,
LR,
LS,
LT,
LU,
LV,
LY,
MA,
MC,
MD,
ME,
MF,
MG,
MH,
MK,
ML,
MM,
MN,
MO,
MP,
MQ,
MR,
MS,
MT,
MU,
MV,
MW,
MX,
MY,
MZ,
NA,
NC,
NE,
NF,
NG,
NI,
NL,
NO,
NP,
NR,
NU,
NZ,
OM,
PA,
PE,
PF,
PG,
PH,
PK,
PL,
PM,
PN,
PR,
PS,
PT,
PW,
PY,
QA,
RE,
RO,
RS,
RU,
RW,
SA,
SB,
SC,
SD,
SE,
SG,
SH,
SI,
SJ,
SK,
SL,
SM,
SN,
SO,
SR,
SS,
ST,
SV,
SX,
SY,
SZ,
TC,
TD,
TF,
TG,
TH,
TJ,
TK,
TL,
TM,
TN,
TO,
TR,
TT,
TV,
TW,
TZ,
UA,
UG,
UM,
US,
UY,
UZ,
VA,
VC,
VE,
VG,
VI,
VN,
VU,
WF,
WS,
YE,
YT,
ZA,
ZM,
ZW,
#[default]
ZZ,
}
impl fmt::Display for Country {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if self.eq(&Country::ZZ) {
write!(f, "?")
} else {
write!(f, "{self:?}")
}
}
}
impl Country {
pub fn from_str(code: &str) -> Self {
#![allow(clippy::too_many_lines)]
match code {
"AD" => Country::AD,
"AE" => Country::AE,
"AF" => Country::AF,
"AG" => Country::AG,
"AI" => Country::AI,
"AL" => Country::AL,
"AM" => Country::AM,
"AO" => Country::AO,
"AQ" => Country::AQ,
"AR" => Country::AR,
"AS" => Country::AS,
"AT" => Country::AT,
"AU" => Country::AU,
"AW" => Country::AW,
"AX" => Country::AX,
"AZ" => Country::AZ,
"BA" => Country::BA,
"BB" => Country::BB,
"BD" => Country::BD,
"BE" => Country::BE,
"BF" => Country::BF,
"BG" => Country::BG,
"BH" => Country::BH,
"BI" => Country::BI,
"BJ" => Country::BJ,
"BL" => Country::BL,
"BM" => Country::BM,
"BN" => Country::BN,
"BO" => Country::BO,
"BQ" => Country::BQ,
"BR" => Country::BR,
"BS" => Country::BS,
"BT" => Country::BT,
"BV" => Country::BV,
"BW" => Country::BW,
"BY" => Country::BY,
"BZ" => Country::BZ,
"CA" => Country::CA,
"CC" => Country::CC,
"CD" => Country::CD,
"CF" => Country::CF,
"CG" => Country::CG,
"CH" => Country::CH,
"CI" => Country::CI,
"CK" => Country::CK,
"CL" => Country::CL,
"CM" => Country::CM,
"CN" => Country::CN,
"CO" => Country::CO,
"CR" => Country::CR,
"CU" => Country::CU,
"CV" => Country::CV,
"CW" => Country::CW,
"CX" => Country::CX,
"CY" => Country::CY,
"CZ" => Country::CZ,
"DE" => Country::DE,
"DJ" => Country::DJ,
"DK" => Country::DK,
"DM" => Country::DM,
"DO" => Country::DO,
"DZ" => Country::DZ,
"EC" => Country::EC,
"EE" => Country::EE,
"EG" => Country::EG,
"EH" => Country::EH,
"ER" => Country::ER,
"ES" => Country::ES,
"ET" => Country::ET,
"FI" => Country::FI,
"FJ" => Country::FJ,
"FK" => Country::FK,
"FM" => Country::FM,
"FO" => Country::FO,
"FR" => Country::FR,
"GA" => Country::GA,
"GB" => Country::GB,
"GD" => Country::GD,
"GE" => Country::GE,
"GF" => Country::GF,
"GG" => Country::GG,
"GH" => Country::GH,
"GI" => Country::GI,
"GL" => Country::GL,
"GM" => Country::GM,
"GN" => Country::GN,
"GP" => Country::GP,
"GQ" => Country::GQ,
"GR" => Country::GR,
"GS" => Country::GS,
"GT" => Country::GT,
"GU" => Country::GU,
"GW" => Country::GW,
"GY" => Country::GY,
"HK" => Country::HK,
"HM" => Country::HM,
"HN" => Country::HN,
"HR" => Country::HR,
"HT" => Country::HT,
"HU" => Country::HU,
"ID" => Country::ID,
"IE" => Country::IE,
"IL" => Country::IL,
"IM" => Country::IM,
"IN" => Country::IN,
"IO" => Country::IO,
"IQ" => Country::IQ,
"IR" => Country::IR,
"IS" => Country::IS,
"IT" => Country::IT,
"JE" => Country::JE,
"JM" => Country::JM,
"JO" => Country::JO,
"JP" => Country::JP,
"KE" => Country::KE,
"KG" => Country::KG,
"KH" => Country::KH,
"KI" => Country::KI,
"KM" => Country::KM,
"KN" => Country::KN,
"KP" => Country::KP,
"KR" => Country::KR,
"KW" => Country::KW,
"KY" => Country::KY,
"KZ" => Country::KZ,
"LA" => Country::LA,
"LB" => Country::LB,
"LC" => Country::LC,
"LI" => Country::LI,
"LK" => Country::LK,
"LR" => Country::LR,
"LS" => Country::LS,
"LT" => Country::LT,
"LU" => Country::LU,
"LV" => Country::LV,
"LY" => Country::LY,
"MA" => Country::MA,
"MC" => Country::MC,
"MD" => Country::MD,
"ME" => Country::ME,
"MF" => Country::MF,
"MG" => Country::MG,
"MH" => Country::MH,
"MK" => Country::MK,
"ML" => Country::ML,
"MM" => Country::MM,
"MN" => Country::MN,
"MO" => Country::MO,
"MP" => Country::MP,
"MQ" => Country::MQ,
"MR" => Country::MR,
"MS" => Country::MS,
"MT" => Country::MT,
"MU" => Country::MU,
"MV" => Country::MV,
"MW" => Country::MW,
"MX" => Country::MX,
"MY" => Country::MY,
"MZ" => Country::MZ,
"NA" => Country::NA,
"NC" => Country::NC,
"NE" => Country::NE,
"NF" => Country::NF,
"NG" => Country::NG,
"NI" => Country::NI,
"NL" => Country::NL,
"NO" => Country::NO,
"NP" => Country::NP,
"NR" => Country::NR,
"NU" => Country::NU,
"NZ" => Country::NZ,
"OM" => Country::OM,
"PA" => Country::PA,
"PE" => Country::PE,
"PF" => Country::PF,
"PG" => Country::PG,
"PH" => Country::PH,
"PK" => Country::PK,
"PL" => Country::PL,
"PM" => Country::PM,
"PN" => Country::PN,
"PR" => Country::PR,
"PS" => Country::PS,
"PT" => Country::PT,
"PW" => Country::PW,
"PY" => Country::PY,
"QA" => Country::QA,
"RE" => Country::RE,
"RO" => Country::RO,
"RS" => Country::RS,
"RU" => Country::RU,
"RW" => Country::RW,
"SA" => Country::SA,
"SB" => Country::SB,
"SC" => Country::SC,
"SD" => Country::SD,
"SE" => Country::SE,
"SG" => Country::SG,
"SH" => Country::SH,
"SI" => Country::SI,
"SJ" => Country::SJ,
"SK" => Country::SK,
"SL" => Country::SL,
"SM" => Country::SM,
"SN" => Country::SN,
"SO" => Country::SO,
"SR" => Country::SR,
"SS" => Country::SS,
"ST" => Country::ST,
"SV" => Country::SV,
"SX" => Country::SX,
"SY" => Country::SY,
"SZ" => Country::SZ,
"TC" => Country::TC,
"TD" => Country::TD,
"TF" => Country::TF,
"TG" => Country::TG,
"TH" => Country::TH,
"TJ" => Country::TJ,
"TK" => Country::TK,
"TL" => Country::TL,
"TM" => Country::TM,
"TN" => Country::TN,
"TO" => Country::TO,
"TR" => Country::TR,
"TT" => Country::TT,
"TV" => Country::TV,
"TW" => Country::TW,
"TZ" => Country::TZ,
"UA" => Country::UA,
"UG" => Country::UG,
"UM" => Country::UM,
"US" => Country::US,
"UY" => Country::UY,
"UZ" => Country::UZ,
"VA" => Country::VA,
"VC" => Country::VC,
"VE" => Country::VE,
"VG" => Country::VG,
"VI" => Country::VI,
"VN" => Country::VN,
"VU" => Country::VU,
"WF" => Country::WF,
"WS" => Country::WS,
"YE" => Country::YE,
"YT" => Country::YT,
"ZA" => Country::ZA,
"ZM" => Country::ZM,
"ZW" => Country::ZW,
_ => Country::ZZ,
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/countries/types/mod.rs | src/countries/types/mod.rs | pub mod country;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/report/get_report_entries.rs | src/report/get_report_entries.rs | use std::cmp::min;
use crate::networking::manage_packets::get_address_to_lookup;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::report::types::sort_type::SortType;
use crate::{InfoTraffic, Service, Sniffer};
/// Return the elements that satisfy the search constraints and belong to the given page,
/// and the total number of elements which satisfy the search constraints,
/// with their packets, in-bytes, and out-bytes count
pub fn get_searched_entries(
sniffer: &Sniffer,
) -> (Vec<(AddressPortPair, InfoAddressPortPair)>, usize, DataInfo) {
let mut agglomerate = DataInfo::default();
let info_traffic = &sniffer.info_traffic;
let mut all_results: Vec<(&AddressPortPair, &InfoAddressPortPair)> = info_traffic
.map
.iter()
.filter(|(key, value)| {
let address_to_lookup = &get_address_to_lookup(key, value.traffic_direction);
let r_dns_host = sniffer.addresses_resolved.get(address_to_lookup);
let is_favorite = if let Some(e) = r_dns_host {
info_traffic
.hosts
.get(&e.1)
.unwrap_or(&DataInfoHost::default())
.is_favorite
} else {
false
};
sniffer
.search
.match_entry(key, value, r_dns_host, is_favorite)
})
.map(|(key, val)| {
agglomerate.add_packets(
val.transmitted_packets,
val.transmitted_bytes,
val.traffic_direction,
);
(key, val)
})
.collect();
all_results.sort_by(|&(_, a), &(_, b)| {
a.compare(b, sniffer.conf.report_sort_type, sniffer.conf.data_repr)
});
let upper_bound = min(sniffer.page_number * 20, all_results.len());
(
all_results
.get((sniffer.page_number.saturating_sub(1)) * 20..upper_bound)
.unwrap_or_default()
.iter()
.map(|&(key, val)| (key.to_owned(), val.to_owned()))
.collect(),
all_results.len(),
agglomerate,
)
}
pub fn get_host_entries(
info_traffic: &InfoTraffic,
data_repr: DataRepr,
sort_type: SortType,
) -> Vec<(Host, DataInfoHost)> {
let mut sorted_vec: Vec<(&Host, &DataInfoHost)> = info_traffic.hosts.iter().collect();
sorted_vec.sort_by(|&(_, a), &(_, b)| a.data_info.compare(&b.data_info, sort_type, data_repr));
let n_entry = min(sorted_vec.len(), 30);
sorted_vec[0..n_entry]
.iter()
.map(|&(host, data_info_host)| (host.to_owned(), data_info_host.to_owned()))
.collect()
}
pub fn get_service_entries(
info_traffic: &InfoTraffic,
data_repr: DataRepr,
sort_type: SortType,
) -> Vec<(Service, DataInfo)> {
let mut sorted_vec: Vec<(&Service, &DataInfo)> = info_traffic
.services
.iter()
.filter(|(service, _)| service != &&Service::NotApplicable)
.collect();
sorted_vec.sort_by(|&(_, a), &(_, b)| a.compare(b, sort_type, data_repr));
let n_entry = min(sorted_vec.len(), 30);
sorted_vec[0..n_entry]
.iter()
.map(|&(service, data_info)| (*service, *data_info))
.collect()
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/report/mod.rs | src/report/mod.rs | pub mod get_report_entries;
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/report/types/sort_type.rs | src/report/types/sort_type.rs | use crate::gui::styles::button::ButtonType;
use crate::gui::styles::types::style_type::StyleType;
use crate::utils::types::icon::Icon;
use iced::widget::Text;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum SortType {
Ascending,
Descending,
#[default]
Neutral,
}
impl SortType {
pub fn next_sort(self) -> Self {
match self {
SortType::Ascending => SortType::Neutral,
SortType::Descending => SortType::Ascending,
SortType::Neutral => SortType::Descending,
}
}
pub fn icon<'a>(self) -> Text<'a, StyleType> {
let mut size = 14;
match self {
SortType::Ascending => Icon::SortAscending,
SortType::Descending => Icon::SortDescending,
SortType::Neutral => {
size = 18;
Icon::SortNeutral
}
}
.to_text()
.size(size)
}
pub fn button_type(self) -> ButtonType {
match self {
SortType::Ascending | SortType::Descending => ButtonType::SortArrowActive,
SortType::Neutral => ButtonType::SortArrows,
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/report/types/search_parameters.rs | src/report/types/search_parameters.rs | use crate::countries::types::country::Country;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::host::Host;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::networking::types::service::Service;
/// Used to express the search filters applied to GUI inspect page
#[derive(Clone, Debug, Default, Hash)]
pub struct SearchParameters {
/// IP address (source)
pub address_src: String,
/// Transport port (source)
pub port_src: String,
/// IP address (destination)
pub address_dst: String,
/// Transport port (destination)
pub port_dst: String,
/// Protocol
pub proto: String,
/// Service
pub service: String,
/// Country
pub country: String,
/// Domain
pub domain: String,
/// Autonomous System name
pub as_name: String,
/// Whether to display only favorites
pub only_favorites: bool,
}
impl SearchParameters {
pub fn match_entry(
&self,
key: &AddressPortPair,
value: &InfoAddressPortPair,
r_dns_host: Option<&(String, Host)>,
is_favorite: bool,
) -> bool {
// if a host-related filter is active and this address has not been resolved yet => false
if r_dns_host.is_none() && self.is_some_host_filter_active() {
return false;
}
for filter_input_type in FilterInputType::ALL {
if !filter_input_type.matches_entry(self, key, value, r_dns_host) {
return false;
}
}
// check favorites filter
if self.only_favorites && !is_favorite {
return false;
}
// if arrived at this point all filters are satisfied
true
}
pub fn is_some_host_filter_active(&self) -> bool {
self.only_favorites
|| !self.country.is_empty()
|| !self.as_name.is_empty()
|| !self.domain.is_empty()
}
pub fn reset_host_filters(&self) -> Self {
Self {
country: String::new(),
domain: String::new(),
as_name: String::new(),
only_favorites: false,
..self.clone()
}
}
pub fn new_host_search(host: &Host) -> Self {
Self {
domain: host.domain.clone(),
as_name: host.asn.name.clone(),
country: if host.country == Country::ZZ {
String::new()
} else {
host.country.to_string()
},
..SearchParameters::default()
}
}
pub fn new_service_search(service: &Service) -> Self {
Self {
service: service.to_string_with_equal_prefix(),
..SearchParameters::default()
}
}
}
#[derive(Copy, Clone)]
pub enum FilterInputType {
AddressSrc,
PortSrc,
AddressDst,
PortDst,
Proto,
Service,
Country,
Domain,
AsName,
}
impl FilterInputType {
pub const ALL: [FilterInputType; 9] = [
Self::AddressSrc,
Self::PortSrc,
Self::AddressDst,
Self::PortDst,
Self::Proto,
Self::Service,
Self::Country,
Self::Domain,
Self::AsName,
];
pub fn matches_entry(
self,
search_params: &SearchParameters,
key: &AddressPortPair,
value: &InfoAddressPortPair,
r_dns_host: Option<&(String, Host)>,
) -> bool {
let filter_value = self.current_value(search_params).to_lowercase();
if filter_value.is_empty() {
return true;
}
let entry_value = self.entry_value(key, value, r_dns_host).to_lowercase();
if let Some(stripped_filter) = filter_value.strip_prefix('=') {
return entry_value.eq(stripped_filter);
}
entry_value.contains(&filter_value)
}
pub fn current_value(self, search_params: &SearchParameters) -> &str {
match self {
FilterInputType::AddressSrc => &search_params.address_src,
FilterInputType::PortSrc => &search_params.port_src,
FilterInputType::AddressDst => &search_params.address_dst,
FilterInputType::PortDst => &search_params.port_dst,
FilterInputType::Proto => &search_params.proto,
FilterInputType::Service => &search_params.service,
FilterInputType::Country => &search_params.country,
FilterInputType::Domain => &search_params.domain,
FilterInputType::AsName => &search_params.as_name,
}
}
pub fn entry_value(
self,
key: &AddressPortPair,
value: &InfoAddressPortPair,
r_dns_host: Option<&(String, Host)>,
) -> String {
match self {
FilterInputType::AddressSrc => key.source.to_string(),
FilterInputType::PortSrc => {
if let Some(port) = key.sport {
port.to_string()
} else {
"-".to_string()
}
}
FilterInputType::AddressDst => key.dest.to_string(),
FilterInputType::PortDst => {
if let Some(port) = key.dport {
port.to_string()
} else {
"-".to_string()
}
}
FilterInputType::Proto => key.protocol.to_string(),
FilterInputType::Service => value.service.to_string(),
FilterInputType::Country => r_dns_host
.unwrap_or(&(String::new(), Host::default()))
.1
.country
.to_string(),
FilterInputType::Domain => r_dns_host
.unwrap_or(&(String::new(), Host::default()))
.0
.clone(),
FilterInputType::AsName => r_dns_host
.unwrap_or(&(String::new(), Host::default()))
.1
.asn
.name
.clone(),
}
}
pub fn clear_search(self, search_params: &SearchParameters) -> SearchParameters {
match self {
FilterInputType::AddressSrc => SearchParameters {
address_src: String::new(),
..search_params.clone()
},
FilterInputType::PortSrc => SearchParameters {
port_src: String::new(),
..search_params.clone()
},
FilterInputType::AddressDst => SearchParameters {
address_dst: String::new(),
..search_params.clone()
},
FilterInputType::PortDst => SearchParameters {
port_dst: String::new(),
..search_params.clone()
},
FilterInputType::Proto => SearchParameters {
proto: String::new(),
..search_params.clone()
},
FilterInputType::Service => SearchParameters {
service: String::new(),
..search_params.clone()
},
FilterInputType::Domain => SearchParameters {
domain: String::new(),
..search_params.clone()
},
FilterInputType::Country => SearchParameters {
country: String::new(),
..search_params.clone()
},
FilterInputType::AsName => SearchParameters {
as_name: String::new(),
..search_params.clone()
},
}
}
pub fn new_search(
self,
search_params: &SearchParameters,
new_value: String,
) -> SearchParameters {
match self {
FilterInputType::AddressSrc => SearchParameters {
address_src: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::PortSrc => SearchParameters {
port_src: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::AddressDst => SearchParameters {
address_dst: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::PortDst => SearchParameters {
port_dst: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::Proto => SearchParameters {
proto: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::Service => SearchParameters {
service: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::Domain => SearchParameters {
domain: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::Country => SearchParameters {
country: new_value.trim().to_string(),
..search_params.clone()
},
FilterInputType::AsName => SearchParameters {
as_name: new_value,
..search_params.clone()
},
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/report/types/report_col.rs | src/report/types/report_col.rs | use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::report::types::search_parameters::FilterInputType;
use crate::translations::translations::{address_translation, protocol_translation};
use crate::translations::translations_2::{destination_translation, source_translation};
use crate::translations::translations_3::{port_translation, service_translation};
use crate::translations::types::language::Language;
// total width: 1012.0
const LARGE_COL_WIDTH: f32 = 221.0;
const SMALL_COL_WIDTH: f32 = 95.0;
const LARGE_COL_MAX_CHARS: usize = 25;
const SMALL_COL_MAX_CHARS: usize = 10;
#[derive(Eq, PartialEq)]
pub enum ReportCol {
SrcIp,
SrcPort,
DstIp,
DstPort,
Proto,
Service,
Data,
}
impl ReportCol {
pub(crate) const ALL: [ReportCol; 7] = [
ReportCol::SrcIp,
ReportCol::SrcPort,
ReportCol::DstIp,
ReportCol::DstPort,
ReportCol::Proto,
ReportCol::Service,
ReportCol::Data,
];
pub(crate) const FILTER_COLUMNS_WIDTH: f32 = 4.0 * SMALL_COL_WIDTH + 2.0 * LARGE_COL_WIDTH;
pub(crate) fn get_title(&self, language: Language, data_repr: DataRepr) -> String {
match self {
ReportCol::SrcIp | ReportCol::DstIp => address_translation(language).to_string(),
ReportCol::SrcPort | ReportCol::DstPort => port_translation(language).to_string(),
ReportCol::Proto => protocol_translation(language).to_string(),
ReportCol::Service => service_translation(language).to_string(),
ReportCol::Data => {
let mut str = data_repr.get_label(language).to_string();
str.remove(0).to_uppercase().to_string() + &str
}
}
}
pub(crate) fn get_title_direction_info(&self, language: Language) -> String {
match self {
ReportCol::SrcIp | ReportCol::SrcPort => {
format!(" ({})", source_translation(language).to_lowercase())
}
ReportCol::DstIp | ReportCol::DstPort => {
format!(" ({})", destination_translation(language).to_lowercase())
}
_ => String::new(),
}
}
pub(crate) fn get_value(
&self,
key: &AddressPortPair,
val: &InfoAddressPortPair,
data_repr: DataRepr,
) -> String {
match self {
ReportCol::SrcIp => key.source.to_string(),
ReportCol::SrcPort => {
if let Some(port) = key.sport {
port.to_string()
} else {
"-".to_string()
}
}
ReportCol::DstIp => key.dest.to_string(),
ReportCol::DstPort => {
if let Some(port) = key.dport {
port.to_string()
} else {
"-".to_string()
}
}
ReportCol::Proto => key.protocol.to_string(),
ReportCol::Service => val.service.to_string(),
ReportCol::Data => data_repr.formatted_string(val.transmitted_data(data_repr)),
}
}
pub(crate) fn get_width(&self) -> f32 {
match self {
ReportCol::SrcIp | ReportCol::DstIp => LARGE_COL_WIDTH,
_ => SMALL_COL_WIDTH,
}
}
pub(crate) fn get_max_chars(&self, language_opt: Option<Language>) -> usize {
let reduction_factor = if [Language::JA, Language::KO, Language::ZH, Language::ZH_TW]
.contains(&language_opt.unwrap_or(Language::EN))
{
2
} else {
1
};
match self {
ReportCol::SrcIp | ReportCol::DstIp => LARGE_COL_MAX_CHARS / reduction_factor,
_ => SMALL_COL_MAX_CHARS / reduction_factor,
}
}
pub(crate) fn get_filter_input_type(&self) -> FilterInputType {
match self {
ReportCol::SrcIp => FilterInputType::AddressSrc,
ReportCol::DstIp => FilterInputType::AddressDst,
ReportCol::SrcPort => FilterInputType::PortSrc,
ReportCol::DstPort => FilterInputType::PortDst,
ReportCol::Proto => FilterInputType::Proto,
ReportCol::Service => FilterInputType::Service,
ReportCol::Data => FilterInputType::Country, // just to not panic...
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/report/types/mod.rs | src/report/types/mod.rs | pub mod report_col;
pub mod search_parameters;
pub mod sort_type;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/notifications/notify_and_log.rs | src/notifications/notify_and_log.rs | use crate::networking::types::capture_context::CaptureSource;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::service::Service;
use crate::notifications::types::logged_notification::{
DataThresholdExceeded, FavoriteTransmitted, LoggedNotification,
};
use crate::notifications::types::notifications::{Notifications, RemoteNotifications};
use crate::notifications::types::sound::{Sound, play};
use crate::report::types::sort_type::SortType;
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::formatted_strings::APP_VERSION;
use crate::utils::formatted_strings::get_formatted_timestamp;
use crate::{InfoTraffic, SNIFFNET_LOWERCASE, location};
use std::cmp::min;
use std::collections::{HashSet, VecDeque};
/// Checks if one or more notifications have to be emitted and logs them.
///
/// It returns the number of new notifications emitted
pub fn notify_and_log(
logged_notifications: &mut (VecDeque<LoggedNotification>, usize),
notifications: &Notifications,
info_traffic_msg: &InfoTraffic,
favorites: &HashSet<Host>,
cs: &CaptureSource,
) -> usize {
let mut sound_to_play = Sound::None;
let emitted_notifications_prev = logged_notifications.1;
let timestamp = info_traffic_msg.last_packet_timestamp;
let data_info = info_traffic_msg.tot_data_info;
// data threshold
if let Some(threshold) = notifications.data_notification.threshold {
let data_repr = notifications.data_notification.data_repr;
if data_info.tot_data(data_repr) > u128::from(threshold) {
let notification = LoggedNotification::DataThresholdExceeded(DataThresholdExceeded {
id: logged_notifications.1,
data_repr,
threshold: notifications.data_notification.previous_threshold,
data_info,
timestamp: get_formatted_timestamp(timestamp),
is_expanded: false,
hosts: hosts_list(info_traffic_msg, data_repr),
services: services_list(info_traffic_msg, data_repr),
});
//log this notification
logged_notifications.1 += 1;
if logged_notifications.0.len() >= 30 {
logged_notifications.0.pop_back();
}
logged_notifications.0.push_front(notification.clone());
// send remote notification
send_remote_notification(notification, notifications.remote_notifications.clone());
// register sound to play
if sound_to_play.eq(&Sound::None) {
sound_to_play = notifications.data_notification.sound;
}
}
}
// from favorites
if notifications.favorite_notification.notify_on_favorite {
let favorites_last_interval: HashSet<(Host, DataInfoHost)> = info_traffic_msg
.hosts
.iter()
.filter(|(h, _)| favorites.contains(h))
.map(|(h, data)| (h.clone(), *data))
.collect();
if !favorites_last_interval.is_empty() {
for (host, data_info_host) in favorites_last_interval {
let notification = LoggedNotification::FavoriteTransmitted(FavoriteTransmitted {
id: logged_notifications.1,
host,
data_info_host,
timestamp: get_formatted_timestamp(timestamp),
});
//log this notification
logged_notifications.1 += 1;
if logged_notifications.0.len() >= 30 {
logged_notifications.0.pop_back();
}
logged_notifications.0.push_front(notification.clone());
// send remote notification
send_remote_notification(notification, notifications.remote_notifications.clone());
}
// register sound to play
if sound_to_play.eq(&Sound::None) {
sound_to_play = notifications.favorite_notification.sound;
}
}
}
// don't play sound when importing data from pcap file
if matches!(cs, CaptureSource::Device(_)) {
play(sound_to_play, notifications.volume);
}
logged_notifications.1 - emitted_notifications_prev
}
fn hosts_list(info_traffic_msg: &InfoTraffic, data_repr: DataRepr) -> Vec<(Host, DataInfoHost)> {
let mut hosts: Vec<(Host, DataInfoHost)> = info_traffic_msg
.hosts
.iter()
.map(|(h, data)| (h.clone(), *data))
.collect();
hosts.sort_by(|(_, a), (_, b)| {
a.data_info
.compare(&b.data_info, SortType::Descending, data_repr)
});
let n_entry = min(hosts.len(), 4);
hosts
.get(..n_entry)
.unwrap_or_default()
.to_owned()
.into_iter()
.collect()
}
fn services_list(info_traffic_msg: &InfoTraffic, data_repr: DataRepr) -> Vec<(Service, DataInfo)> {
let mut services: Vec<(Service, DataInfo)> = info_traffic_msg
.services
.iter()
.filter(|(service, _)| service != &&Service::NotApplicable)
.map(|(s, data)| (*s, *data))
.collect();
services.sort_by(|(_, a), (_, b)| a.compare(b, SortType::Descending, data_repr));
let n_entry = min(services.len(), 4);
services
.get(..n_entry)
.unwrap_or_default()
.to_owned()
.into_iter()
.collect()
}
fn send_remote_notification(
notification: LoggedNotification,
remote_notifications: RemoteNotifications,
) {
if remote_notifications.is_active_and_set() {
tokio::task::spawn(async move {
let Ok(client) = reqwest::Client::builder()
.user_agent(format!("{SNIFFNET_LOWERCASE}-{APP_VERSION}"))
.build()
.log_err(location!())
else {
return;
};
let Ok(response) = client
.post(remote_notifications.url())
.header("User-agent", format!("{SNIFFNET_LOWERCASE}-{APP_VERSION}"))
.body(notification.to_json())
.send()
.await
.log_err(location!())
else {
return;
};
let _ = response.error_for_status().log_err(location!());
});
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/notifications/mod.rs | src/notifications/mod.rs | pub mod notify_and_log;
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/notifications/types/sound.rs | src/notifications/types/sound.rs | use std::fmt;
use std::thread;
use iced::widget::Text;
use rodio::{Decoder, OutputStreamBuilder, Sink};
use serde::{Deserialize, Serialize};
use crate::gui::styles::style_constants::FONT_SIZE_FOOTER;
use crate::notifications::types::sound::Sound::{Gulp, Pop, Swhoosh};
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::types::icon::Icon;
use crate::{StyleType, location};
/// Enum representing the possible notification sounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Sound {
Gulp,
#[default]
Pop,
Swhoosh,
None,
}
pub const GULP: &[u8] = include_bytes!("../../../resources/sounds/gulp.mp3");
pub const POP: &[u8] = include_bytes!("../../../resources/sounds/pop.mp3");
pub const SWHOOSH: &[u8] = include_bytes!("../../../resources/sounds/swhoosh.mp3");
impl fmt::Display for Sound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl Sound {
pub(crate) const ALL: [Sound; 4] = [Gulp, Pop, Swhoosh, Sound::None];
fn mp3_sound(self) -> &'static [u8] {
match self {
Gulp => GULP,
Pop => POP,
Swhoosh => SWHOOSH,
Sound::None => &[],
}
}
pub fn get_text<'a>(self) -> iced::widget::Text<'a, StyleType> {
match self {
Sound::Gulp => Text::new("Gulp"),
Sound::Pop => Text::new("Pop"),
Sound::Swhoosh => Text::new("Swhoosh"),
Sound::None => Icon::Forbidden.to_text(),
}
.size(FONT_SIZE_FOOTER)
}
}
pub fn play(sound: Sound, volume: u8) {
if sound.eq(&Sound::None) || volume == 0 || cfg!(test) {
return;
}
let mp3_sound = sound.mp3_sound();
let _ = thread::Builder::new()
.name("thread_play_sound".to_string())
.spawn(move || {
// Get an output stream handle to the default physical sound device
let Ok(mut stream_handle) =
OutputStreamBuilder::open_default_stream().log_err(location!())
else {
return;
};
stream_handle.log_on_drop(false);
let sink = Sink::connect_new(stream_handle.mixer());
//load data
let data = std::io::Cursor::new(mp3_sound);
// Decode that sound file into a source
let Ok(source) = Decoder::new(data).log_err(location!()) else {
return;
};
// Play the sound directly on the device
sink.set_volume(f32::from(volume) / 200.0); // set the desired volume
sink.append(source);
// The sound plays in a separate thread. This call will block the current thread until the sink
// has finished playing all its queued sounds.
sink.sleep_until_end();
})
.log_err(location!());
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/notifications/types/mod.rs | src/notifications/types/mod.rs | pub mod logged_notification;
pub mod notifications;
pub mod sound;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/notifications/types/logged_notification.rs | src/notifications/types/logged_notification.rs | use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::service::Service;
use crate::translations::translations::favorite_transmitted_translation;
use crate::translations::types::language::Language;
use serde_json::json;
/// Enum representing the possible notification events.
#[derive(Clone)]
pub enum LoggedNotification {
/// Data threshold exceeded
DataThresholdExceeded(DataThresholdExceeded),
/// Favorite connection exchanged data
FavoriteTransmitted(FavoriteTransmitted),
}
impl LoggedNotification {
pub fn id(&self) -> usize {
match self {
LoggedNotification::DataThresholdExceeded(d) => d.id,
LoggedNotification::FavoriteTransmitted(f) => f.id,
}
}
pub fn data_info(&self) -> DataInfo {
match self {
LoggedNotification::DataThresholdExceeded(d) => d.data_info,
LoggedNotification::FavoriteTransmitted(f) => f.data_info_host.data_info,
}
}
pub fn expand(&mut self, expand: bool) {
match self {
LoggedNotification::DataThresholdExceeded(d) => d.is_expanded = expand,
LoggedNotification::FavoriteTransmitted(_) => {}
}
}
pub fn to_json(&self) -> String {
match self {
LoggedNotification::DataThresholdExceeded(d) => d.to_json(),
LoggedNotification::FavoriteTransmitted(f) => f.to_json(),
}
}
}
#[derive(Clone)]
pub struct DataThresholdExceeded {
pub(crate) id: usize,
pub(crate) data_repr: DataRepr,
pub(crate) threshold: u64,
pub(crate) data_info: DataInfo,
pub(crate) timestamp: String,
pub(crate) is_expanded: bool,
pub(crate) hosts: Vec<(Host, DataInfoHost)>,
pub(crate) services: Vec<(Service, DataInfo)>,
}
impl DataThresholdExceeded {
pub fn to_json(&self) -> String {
json!({
"info": self.data_repr.data_exceeded_translation(Language::EN),
"timestamp": self.timestamp,
"threshold": self.data_repr.formatted_string(self.threshold.into()),
"data": self.data_repr.formatted_string(self.data_info.tot_data(self.data_repr)),
})
.to_string()
}
}
#[derive(Clone)]
pub struct FavoriteTransmitted {
pub(crate) id: usize,
pub(crate) host: Host,
pub(crate) data_info_host: DataInfoHost,
pub(crate) timestamp: String,
}
impl FavoriteTransmitted {
pub fn to_json(&self) -> String {
json!({
"info": favorite_transmitted_translation(Language::EN),
"timestamp": self.timestamp,
"favorite": {
"country": self.host.country.to_string(),
"domain": self.host.domain,
"asn": self.host.asn.name,
},
"data": DataRepr::Bytes.formatted_string(self.data_info_host.data_info.tot_data(DataRepr::Bytes)),
})
.to_string()
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/notifications/types/notifications.rs | src/notifications/types/notifications.rs | use serde::{Deserialize, Serialize};
use crate::ByteMultiple;
use crate::gui::types::conf::deserialize_or_default;
use crate::networking::types::data_representation::DataRepr;
use crate::notifications::types::sound::Sound;
/// Used to contain the notifications configuration set by the user
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(default)]
pub struct Notifications {
#[serde(deserialize_with = "deserialize_or_default")]
pub volume: u8,
// ---------------------------------------------------------------------------------------------
#[serde(deserialize_with = "deserialize_or_default")]
pub data_notification: DataNotification,
#[serde(deserialize_with = "deserialize_or_default")]
pub favorite_notification: FavoriteNotification,
#[allow(clippy::struct_field_names)]
#[serde(deserialize_with = "deserialize_or_default")]
pub remote_notifications: RemoteNotifications,
}
impl Default for Notifications {
fn default() -> Self {
Notifications {
volume: 50,
data_notification: DataNotification::default(),
favorite_notification: FavoriteNotification::default(),
remote_notifications: RemoteNotifications::default(),
}
}
}
/// Enum representing the possible notifications.
#[derive(Debug, Clone, Copy)]
pub enum Notification {
/// Data notification
Data(DataNotification),
/// Favorites notification
Favorite(FavoriteNotification),
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug, Copy)]
#[serde(default)]
pub struct DataNotification {
/// The sound to emit
#[serde(deserialize_with = "deserialize_or_default")]
pub sound: Sound,
/// Data representation
#[serde(deserialize_with = "deserialize_or_default")]
pub data_repr: DataRepr,
/// Threshold of received + sent bytes; if exceeded a notification is emitted
#[serde(deserialize_with = "deserialize_or_default")]
pub threshold: Option<u64>,
/// B, KB, MB or GB
#[serde(deserialize_with = "deserialize_or_default")]
pub byte_multiple: ByteMultiple,
/// The last used Some value for the threshold field
#[serde(deserialize_with = "deserialize_or_default")]
pub previous_threshold: u64,
}
impl Default for DataNotification {
fn default() -> Self {
DataNotification {
data_repr: DataRepr::default(),
threshold: None,
byte_multiple: ByteMultiple::KB,
sound: Sound::Gulp,
previous_threshold: 800_000,
}
}
}
impl DataNotification {
/// Arbitrary string constructor. Will fallback values to existing notification if set, or default otherwise
pub fn from(value: &str, existing: Option<Self>) -> Self {
let default = existing.unwrap_or_default();
let mut byte_multiple_inserted = ByteMultiple::B;
let chars: Vec<char> = value.trim().chars().collect();
let new_threshold = if chars.is_empty() {
0
} else if !chars.iter().map(|c| char::is_numeric(*c)).any(|x| !x) {
// no multiple
value.parse::<u64>().unwrap_or(default.previous_threshold)
} else {
// multiple
let last_char = chars.last().unwrap_or(&' ');
byte_multiple_inserted = ByteMultiple::from_char(*last_char);
let without_multiple: String = chars[0..chars.len() - 1].iter().collect();
if without_multiple.parse::<u64>().is_ok()
&& TryInto::<u64>::try_into(
without_multiple.parse::<u128>().unwrap_or_default()
* u128::from(byte_multiple_inserted.multiplier()),
)
.is_ok()
{
without_multiple.parse::<u64>().unwrap_or_default()
* byte_multiple_inserted.multiplier()
} else if without_multiple.is_empty() {
byte_multiple_inserted = ByteMultiple::B;
0
} else {
byte_multiple_inserted = default.byte_multiple;
default.previous_threshold
}
};
Self {
threshold: Some(new_threshold),
previous_threshold: new_threshold,
byte_multiple: byte_multiple_inserted,
..default
}
}
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug, Copy)]
#[serde(default)]
pub struct FavoriteNotification {
/// Flag to determine if this notification is enabled
#[serde(deserialize_with = "deserialize_or_default")]
pub notify_on_favorite: bool,
/// The sound to emit
#[serde(deserialize_with = "deserialize_or_default")]
pub sound: Sound,
}
impl Default for FavoriteNotification {
fn default() -> Self {
FavoriteNotification {
notify_on_favorite: false,
sound: Sound::Swhoosh,
}
}
}
impl FavoriteNotification {
/// Constructor when the notification is in use
pub fn on(sound: Sound) -> Self {
FavoriteNotification {
notify_on_favorite: true,
sound,
}
}
/// Constructor when the notification is not in use. Note that sound is used here for caching, although it won't actively be used.
pub fn off(sound: Sound) -> Self {
FavoriteNotification {
notify_on_favorite: false,
sound,
}
}
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug, Default)]
#[serde(default)]
pub struct RemoteNotifications {
/// Flag to determine if remote notifications are enabled
#[serde(deserialize_with = "deserialize_or_default")]
is_active: bool,
/// The URL to send notifications to
#[serde(deserialize_with = "deserialize_or_default")]
url: String,
}
impl RemoteNotifications {
pub fn is_active(&self) -> bool {
self.is_active
}
pub fn url(&self) -> &str {
&self.url
}
pub fn toggle(&mut self) {
self.is_active = !self.is_active;
}
pub fn set_url(&mut self, url: &str) {
self.url = url.trim().to_string();
}
pub fn is_active_and_set(&self) -> bool {
self.is_active && !self.url.is_empty()
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[rstest]
#[case("123",
DataNotification{
previous_threshold: 123, threshold: Some(123), byte_multiple: ByteMultiple::B, ..DataNotification::default() }
)]
#[case("500k",
DataNotification{
previous_threshold: 500_000, threshold: Some(500_000),byte_multiple: ByteMultiple::KB, ..DataNotification::default() }
)]
#[case("420m",
DataNotification{
previous_threshold: 420_000_000, threshold: Some(420_000_000),byte_multiple: ByteMultiple::MB, ..DataNotification::default() }
)]
#[case("744ь",
DataNotification{
previous_threshold: 744, threshold: Some(744),byte_multiple: ByteMultiple::B, ..DataNotification::default() }
)]
#[case("888g",
DataNotification{
previous_threshold: 888_000_000_000, threshold: Some(888_000_000_000),byte_multiple: ByteMultiple::GB, ..DataNotification::default() }
)]
fn test_can_instantiate_bytes_notification_from_string(
#[case] input: &str,
#[case] expected: DataNotification,
) {
assert_eq!(expected, DataNotification::from(input, None));
}
#[rstest]
#[case("foob@r")]
#[case("2O6")]
fn test_will_reuse_previous_value_if_cannot_parse(#[case] input: &str) {
let existing_notification = DataNotification {
previous_threshold: 420_000_000_000,
byte_multiple: ByteMultiple::GB,
..Default::default()
};
let expected = DataNotification {
previous_threshold: 420_000_000_000,
threshold: Some(420_000_000_000),
byte_multiple: ByteMultiple::GB,
..Default::default()
};
assert_eq!(
expected,
DataNotification::from(input, Some(existing_notification))
);
}
#[test]
fn test_can_instantiate_favourite_notification() {
assert_eq!(
FavoriteNotification::on(Sound::Gulp),
FavoriteNotification {
notify_on_favorite: true,
sound: Sound::Gulp
}
);
assert_eq!(
FavoriteNotification::on(Sound::Swhoosh),
FavoriteNotification {
notify_on_favorite: true,
sound: Sound::Swhoosh
}
);
assert_eq!(
FavoriteNotification::off(Sound::Pop),
FavoriteNotification {
notify_on_favorite: false,
sound: Sound::Pop
}
);
assert_eq!(
FavoriteNotification::off(Sound::None),
FavoriteNotification {
notify_on_favorite: false,
sound: Sound::None
}
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/chart/mod.rs | src/chart/mod.rs | 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/chart/types/chart_series.rs | src/chart/types/chart_series.rs | use splines::{Interpolation, Key, Spline};
#[derive(Default, Clone)]
pub struct ChartSeries {
/// Series to be displayed DURING live/offline capture
pub spline: Spline<f32, f32>,
/// Used to draw overall data, after the offline capture is over (not used in live captures)
pub all_time: Vec<(f32, f32)>,
}
impl ChartSeries {
pub(super) fn update_series(
&mut self,
point: (f32, f32),
is_live_capture: bool,
no_more_packets: bool,
) {
// update spline
let spline = &mut self.spline;
let key = Key::new(point.0, point.1, Interpolation::Cosine);
if spline.len() >= 30 {
spline.remove(0);
}
spline.add(key);
// if offline capture, update all time data
if !is_live_capture {
let all_time = &mut self.all_time;
all_time.push(point);
// if we reached the end of the PCAP, reduce all time data into spline
if no_more_packets {
reduce_all_time_data(all_time);
let keys = all_time
.iter()
.map(|p| Key::new(p.0, p.1, Interpolation::Cosine))
.collect();
*spline = Spline::from_vec(keys);
}
}
}
/// Finds the minimum y value to be displayed in chart.
pub(super) fn get_min(&self) -> f32 {
let mut min = 0.0;
for key in &self.spline {
if key.value < min {
min = key.value;
}
}
min
}
/// Finds the maximum y value to be displayed in chart.
pub(super) fn get_max(&self) -> f32 {
let mut max = 0.0;
for key in &self.spline {
if key.value > max {
max = key.value;
}
}
max
}
/// Finds the total y values displayed in chart.
pub(super) fn get_tot(&self) -> f32 {
let mut tot = 0.0;
for key in &self.spline {
tot += key.value;
}
tot
}
}
pub(super) fn sample_spline(spline: &Spline<f32, f32>, multiplier: f32) -> Vec<(f32, f32)> {
let len = spline.len();
let pts = len * 10; // 10 samples per key
let mut ret_val = Vec::new();
let first_x = spline
.get(0)
.unwrap_or(&Key::new(0.0, 0.0, Interpolation::Cosine))
.t;
let last_x = spline
.get(len.saturating_sub(1))
.unwrap_or(&Key::new(0.0, 0.0, Interpolation::Cosine))
.t;
#[allow(clippy::cast_precision_loss)]
let delta = (last_x - first_x) / (pts as f32 - 1.0);
for i in 0..pts {
#[allow(clippy::cast_precision_loss)]
let x = first_x + delta * i as f32;
let p = spline.clamped_sample(x).unwrap_or_default() * multiplier;
ret_val.push((x, p));
}
ret_val
}
fn reduce_all_time_data(all_time: &mut Vec<(f32, f32)>) {
// bisect data until we have less than 150 points
while all_time.len() > 150 {
let mut new_vec = Vec::new();
all_time.iter().enumerate().for_each(|(i, (x, y))| {
if i % 2 == 0
&& let Some(next) = all_time.get(i + 1)
{
new_vec.push((*x, (y + next.1) / 2.0));
}
});
*all_time = new_vec;
}
}
// impl TrafficChart {
// use crate::gui::styles::types::style_type::StyleType;
// use crate::translations::types::language::Language;
// use std::io::Read;
// pub fn sample_for_screenshot() -> Self {
// let get_rand = |delta: f32| {
// let mut f = std::fs::File::open("/dev/urandom").unwrap();
// let mut buf = [0u8; 1];
// f.read_exact(&mut buf).unwrap();
// let x = buf[0];
// x as f32 / 255.0 * 2.0 * delta - delta
// };
//
// let mut chart = TrafficChart::new(StyleType::default(), Language::default());
//
// chart.ticks = 5 * 60 - 2;
// let x_range = chart.ticks - 30..chart.ticks;
//
// let in_base = 35_000.0;
// let in_delta = 7_000.0;
// let out_base = -15_000.0;
// let out_delta = 3_000.0;
//
// chart.in_bytes.spline = Spline::from_vec(
// x_range
// .clone()
// .map(|x| {
// Key::new(
// x as f32,
// in_base + get_rand(in_delta),
// Interpolation::Cosine,
// )
// })
// .collect(),
// );
// chart.out_bytes.spline = Spline::from_vec(
// x_range
// .map(|x| {
// Key::new(
// x as f32,
// out_base + get_rand(out_delta),
// Interpolation::Cosine,
// )
// })
// .collect(),
// );
// chart.min_bytes = get_min(&chart.out_bytes);
// chart.max_bytes = get_max(&chart.in_bytes);
// chart
// }
// }
#[cfg(test)]
mod tests {
use splines::{Interpolation, Key, Spline};
use crate::chart::types::chart_series::ChartSeries;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_representation::DataRepr;
use crate::utils::types::timestamp::Timestamp;
use crate::{InfoTraffic, Language, StyleType, TrafficChart};
fn spline_from_vec(vec: Vec<(i32, i32)>) -> Spline<f32, f32> {
Spline::from_vec(
vec.iter()
.map(|&(x, y)| Key::new(x as f32, y as f32, Interpolation::Cosine))
.collect::<Vec<Key<f32, f32>>>(),
)
}
#[test]
fn test_chart_data_updates() {
let sent_vec = vec![
(0, -500),
(1, -1000),
(2, -1000),
(3, -1000),
(4, -1000),
(5, -1000),
(6, -1000),
(7, -1000),
(8, -1000),
(9, -1000),
(10, -1000),
(11, -1000),
(12, -1000),
(13, -1000),
(14, -1000),
(15, -1000),
(16, -1000),
(17, -1000),
(18, -1000),
(19, -1000),
(20, -1000),
(21, -1000),
(22, -1000),
(23, -1000),
(24, -1000),
(25, -1000),
(26, -1000),
(27, -1000),
(28, -1000),
];
let sent_spl = spline_from_vec(sent_vec);
let sent = ChartSeries {
spline: sent_spl,
all_time: vec![],
};
let received_vec = vec![
(0, 1000),
(1, 21000),
(2, 21000),
(3, 21000),
(4, 21000),
(5, 21000),
(6, 21000),
(7, 21000),
(8, 21000),
(9, 21000),
(10, 21000),
(11, 21000),
(12, 21000),
(13, 21000),
(14, 21000),
(15, 21000),
(16, 21000),
(17, 21000),
(18, 21000),
(19, 21000),
(20, 21000),
(21, 21000),
(22, 21000),
(23, 21000),
(24, 21000),
(25, 21000),
(26, 21000),
(27, 21000),
(28, 21000),
];
let received_spl = spline_from_vec(received_vec);
let received = ChartSeries {
spline: received_spl,
all_time: vec![],
};
let tot_data_info = DataInfo::new_for_tests(4444, 3333, 2222, 1111);
let mut traffic_chart = TrafficChart {
ticks: 29,
out_bytes: sent.clone(),
in_bytes: received.clone(),
out_packets: sent.clone(),
in_packets: received.clone(),
min_bytes: -1000.0,
max_bytes: 21000.0,
min_packets: -1000.0,
max_packets: 21000.0,
language: Language::default(),
data_repr: DataRepr::Packets,
style: StyleType::default(),
thumbnail: false,
is_live_capture: true,
first_packet_timestamp: Timestamp::default(),
no_more_packets: false,
};
let mut info_traffic = InfoTraffic {
tot_data_info,
dropped_packets: 0,
..Default::default()
};
assert_eq!(sent.get_min(), -1000.0);
assert_eq!(received.get_max(), 21000.0);
traffic_chart.update_charts_data(&info_traffic, false);
assert_eq!(traffic_chart.out_packets.get_min(), -3333.0);
assert_eq!(traffic_chart.in_bytes.get_max(), 21000.0);
let mut sent_bytes = sent.clone();
sent_bytes
.spline
.add(Key::new(29.0, -1111.0, Interpolation::Cosine));
let mut received_packets = received.clone();
received_packets
.spline
.add(Key::new(29.0, 4444.0, Interpolation::Cosine));
let mut sent_packets = sent;
sent_packets
.spline
.add(Key::new(29.0, -3333.0, Interpolation::Cosine));
let mut received_bytes = received;
received_bytes
.spline
.add(Key::new(29.0, 2222.0, Interpolation::Cosine));
// traffic_chart correctly updated?
assert_eq!(traffic_chart.ticks, 30);
assert_eq!(traffic_chart.min_bytes, -1111.0);
assert_eq!(traffic_chart.min_packets, -3333.0);
assert_eq!(traffic_chart.max_bytes, 21000.0);
assert_eq!(traffic_chart.max_packets, 21000.0);
assert_eq!(
traffic_chart.out_bytes.spline.keys(),
sent_bytes.spline.keys()
);
assert_eq!(
traffic_chart.in_packets.spline.keys(),
received_packets.spline.keys()
);
assert_eq!(
traffic_chart.out_packets.spline.keys(),
sent_packets.spline.keys()
);
assert_eq!(
traffic_chart.in_bytes.spline.keys(),
received_bytes.spline.keys()
);
info_traffic.tot_data_info = DataInfo::new_for_tests(990, 1, 2, 99);
traffic_chart.update_charts_data(&info_traffic, false);
info_traffic.tot_data_info = DataInfo::new_for_tests(1, 220, 0, 77);
traffic_chart.update_charts_data(&info_traffic, false);
sent_bytes.spline.remove(0);
sent_bytes.spline.remove(0);
sent_bytes
.spline
.add(Key::new(30.0, -99.0, Interpolation::Cosine));
sent_bytes
.spline
.add(Key::new(31.0, -77.0, Interpolation::Cosine));
received_packets.spline.remove(0);
received_packets.spline.remove(0);
received_packets
.spline
.add(Key::new(30.0, 990.0, Interpolation::Cosine));
received_packets
.spline
.add(Key::new(31.0, 1.0, Interpolation::Cosine));
sent_packets.spline.remove(0);
sent_packets.spline.remove(0);
sent_packets
.spline
.add(Key::new(30.0, -1.0, Interpolation::Cosine));
sent_packets
.spline
.add(Key::new(31.0, -220.0, Interpolation::Cosine));
received_bytes.spline.remove(0);
received_bytes.spline.remove(0);
received_bytes
.spline
.add(Key::new(30.0, 2.0, Interpolation::Cosine));
received_bytes
.spline
.add(Key::new(31.0, 0.0, Interpolation::Cosine));
// traffic_chart correctly updated?
assert_eq!(traffic_chart.ticks, 32);
assert_eq!(traffic_chart.min_bytes, -1111.0);
assert_eq!(traffic_chart.min_packets, -3333.0);
assert_eq!(traffic_chart.max_bytes, 21000.0);
assert_eq!(traffic_chart.max_packets, 21000.0);
assert_eq!(
traffic_chart.out_bytes.spline.keys(),
sent_bytes.spline.keys()
);
assert_eq!(
traffic_chart.in_packets.spline.keys(),
received_packets.spline.keys()
);
assert_eq!(
traffic_chart.out_packets.spline.keys(),
sent_packets.spline.keys()
);
assert_eq!(
traffic_chart.in_bytes.spline.keys(),
received_bytes.spline.keys()
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/chart/types/preview_chart.rs | src/chart/types/preview_chart.rs | use std::ops::Range;
use iced::Element;
use iced::widget::Column;
use plotters::prelude::*;
use plotters_iced2::{Chart, ChartBuilder, ChartWidget, DrawingBackend};
use crate::chart::types::chart_series::{ChartSeries, sample_spline};
use crate::gui::styles::style_constants::CHARTS_LINE_BORDER;
use crate::gui::styles::types::palette::to_rgb_color;
use crate::gui::types::message::Message;
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::{StyleType, location};
/// Struct defining the traffic preview charts to be displayed in GUI initial page
pub struct PreviewChart {
/// Current time interval number
pub ticks: u32,
/// Packets (sent & received)
pub packets: ChartSeries,
/// Maximum number of packets per time interval (computed on last 30 intervals)
pub max_packets: f32,
/// Total number of packets (last 30 seconds)
pub tot_packets: f32,
/// Style of the chart
pub style: StyleType,
}
impl PreviewChart {
pub fn new(style: StyleType) -> Self {
Self {
ticks: 0,
packets: ChartSeries::default(),
max_packets: 0.0,
tot_packets: 0.0,
style,
}
}
pub fn update_charts_data(&mut self, packets: u128) {
#[allow(clippy::cast_precision_loss)]
let tot_seconds = self.ticks as f32;
self.ticks += 1;
#[allow(clippy::cast_precision_loss)]
let packets_entry = packets as f32;
let packets_point = (tot_seconds, packets_entry);
// update traffic data
self.packets.update_series(packets_point, true, false);
self.max_packets = self.packets.get_max();
self.tot_packets = self.packets.get_tot();
}
pub fn view(&self) -> Element<'_, Message, StyleType> {
Column::new().height(45).push(ChartWidget::new(self)).into()
}
pub fn change_style(&mut self, style: StyleType) {
self.style = style;
}
fn x_axis_range(&self) -> Range<f32> {
// if we have only one tick, we need to add a second point to draw the area
if self.ticks == 1 {
return 0.0..0.1;
}
let first_time_displayed = self.ticks.saturating_sub(30);
let last_time_displayed = self.ticks - 1;
#[allow(clippy::cast_precision_loss)]
let range = first_time_displayed as f32..last_time_displayed as f32;
range
}
fn y_axis_range(&self) -> Range<f32> {
let max = self.max_packets;
let gap = max * 0.1;
0.0..max + gap
}
fn area_series<DB: DrawingBackend>(&self) -> AreaSeries<DB, f32, f32> {
let color = to_rgb_color(self.style.get_palette().secondary);
let alpha = self.style.get_extension().alpha_chart_badge;
let spline = &self.packets.spline;
let data = match spline.keys() {
// if we have only one tick, we need to add a second point to draw the area
[k] => vec![(0.0, k.value), (0.1, k.value)],
_ => sample_spline(spline, 1.0),
};
AreaSeries::new(data, 0.0, color.mix(alpha.into()))
.border_style(ShapeStyle::from(&color).stroke_width(CHARTS_LINE_BORDER))
}
}
impl Chart<Message> for PreviewChart {
type State = ();
fn build_chart<DB: DrawingBackend>(
&self,
_state: &Self::State,
mut chart_builder: ChartBuilder<DB>,
) {
if self.ticks < 1 {
return;
}
let x_axis_range = self.x_axis_range();
let y_axis_range = self.y_axis_range();
let Ok(mut chart) = chart_builder
.build_cartesian_2d(x_axis_range, y_axis_range)
.log_err(location!())
else {
return;
};
let buttons_color = to_rgb_color(self.style.get_extension().buttons_color);
// chart mesh
let _ = chart
.configure_mesh()
.axis_style(buttons_color)
.max_light_lines(0)
.y_labels(0)
.x_labels(0)
.draw()
.log_err(location!());
// draw packets series
let area_series = self.area_series();
let _ = chart.draw_series(area_series).log_err(location!());
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/chart/types/mod.rs | src/chart/types/mod.rs | pub mod chart_series;
pub mod donut_chart;
pub mod preview_chart;
pub mod traffic_chart;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/chart/types/donut_chart.rs | src/chart/types/donut_chart.rs | use crate::gui::styles::donut::Catalog;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE, SARASA_MONO};
use crate::networking::types::data_representation::DataRepr;
use iced::alignment::Vertical;
use iced::widget::canvas::path::Arc;
use iced::widget::canvas::{Frame, Text};
use iced::widget::text::Alignment;
use iced::widget::{Canvas, canvas};
use iced::{Length, Radians, Renderer, mouse};
use std::f32::consts;
pub struct DonutChart {
data_repr: DataRepr,
incoming: u128,
outgoing: u128,
dropped: u128,
thumbnail: bool,
}
impl DonutChart {
fn new(
data_repr: DataRepr,
incoming: u128,
outgoing: u128,
dropped: u128,
thumbnail: bool,
) -> Self {
Self {
data_repr,
incoming,
outgoing,
dropped,
thumbnail,
}
}
fn total(&self) -> u128 {
self.incoming + self.outgoing + self.dropped
}
fn title(&self) -> String {
let total = self.total();
self.data_repr.formatted_string(total)
}
fn angles(&self) -> [(Radians, Radians); 3] {
#[allow(clippy::cast_precision_loss)]
let mut values = [
self.incoming as f32,
self.outgoing as f32,
self.dropped as f32,
];
let total: f32 = values.iter().sum();
let min_val = 2.0 * total / 100.0;
let mut diff = 0.0;
for value in &mut values {
if *value > 0.0 && *value < min_val {
diff += min_val - *value;
*value = min_val;
}
}
// remove the diff from the max value
if diff > 0.0 {
let _ = values
.iter_mut()
.max_by(|a, b| a.total_cmp(b))
.map(|max| *max -= diff);
}
let mut start_angle = Radians(-consts::FRAC_PI_2);
values.map(|value| {
let start = start_angle;
let end = start + Radians(consts::TAU) * value / total;
start_angle = end;
(start, end)
})
}
}
impl<Message, Theme: Catalog> canvas::Program<Message, Theme> for DonutChart {
type State = ();
fn draw(
&self,
(): &Self::State,
renderer: &Renderer,
theme: &Theme,
bounds: iced::Rectangle,
_: mouse::Cursor,
) -> Vec<canvas::Geometry> {
let mut frame = Frame::new(renderer, bounds.size());
let center = frame.center();
let radius = (frame.width().min(frame.height()) / 2.0) * 0.9;
let style = <Theme as Catalog>::style(theme, &<Theme as Catalog>::default());
let colors = [style.incoming, style.outgoing, style.dropped];
for ((start_angle, end_angle), color) in self.angles().into_iter().zip(colors) {
let path = canvas::Path::new(|builder| {
builder.arc(Arc {
center,
radius,
start_angle,
end_angle,
});
builder.line_to(center);
builder.close();
});
frame.fill(&path, color);
}
let inner_circle = canvas::Path::circle(center, radius - 6.0);
frame.fill(&inner_circle, style.background);
frame.fill_text(Text {
content: self.title().clone(),
position: center,
color: style.text_color,
size: if self.thumbnail {
FONT_SIZE_FOOTER
} else {
FONT_SIZE_SUBTITLE
}
.into(),
font: SARASA_MONO,
align_x: Alignment::Center,
align_y: Vertical::Center,
..Default::default()
});
vec![frame.into_geometry()]
}
}
pub fn donut_chart<Message, Theme: Catalog>(
data_repr: DataRepr,
incoming: u128,
outgoing: u128,
dropped: u128,
thumbnail: bool,
) -> Canvas<DonutChart, Message, Theme, Renderer> {
let size = if thumbnail {
Length::Fill
} else {
Length::Fixed(110.0)
};
iced::widget::canvas(DonutChart::new(
data_repr, incoming, outgoing, dropped, thumbnail,
))
.width(size)
.height(size)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/chart/types/traffic_chart.rs | src/chart/types/traffic_chart.rs | //! This module defines the behavior of the `TrafficChart` struct, used to display chart in GUI run page
use std::cmp::min;
use std::ops::Range;
use iced::widget::{Column, Row, Space};
use iced::{Element, Length, Padding};
use plotters::prelude::*;
use plotters::series::LineSeries;
use plotters_iced2::{Chart, ChartBuilder, ChartWidget, DrawingBackend};
use splines::Spline;
use crate::chart::types::chart_series::{ChartSeries, sample_spline};
use crate::gui::sniffer::FONT_FAMILY_NAME;
use crate::gui::styles::style_constants::CHARTS_LINE_BORDER;
use crate::gui::styles::types::palette::to_rgb_color;
use crate::gui::types::message::Message;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::info_traffic::InfoTraffic;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::translations::translations::{incoming_translation, outgoing_translation};
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::formatted_strings::{get_formatted_num_seconds, get_formatted_timestamp};
use crate::utils::types::timestamp::Timestamp;
use crate::{Language, StyleType, location};
/// Struct defining the chart to be displayed in gui run page
pub struct TrafficChart {
/// Current time interval number
pub ticks: u32,
/// Sent bytes and their time occurrence
pub out_bytes: ChartSeries,
/// Received bytes and their time occurrence
pub in_bytes: ChartSeries,
/// Sent packets and their time occurrence
pub out_packets: ChartSeries,
/// Received packets and their time occurrence
pub in_packets: ChartSeries,
/// Minimum number of bytes per time interval (computed on last 30 intervals)
pub min_bytes: f32,
/// Maximum number of bytes per time interval (computed on last 30 intervals)
pub max_bytes: f32,
/// Minimum number of packets per time interval (computed on last 30 intervals)
pub min_packets: f32,
/// Maximum number of packets per time interval (computed on last 30 intervals)
pub max_packets: f32,
/// Language used for the chart legend
pub language: Language,
/// Packets or bytes
pub data_repr: DataRepr,
/// Style of the chart
pub style: StyleType,
/// Whether the chart is for the thumbnail page
pub thumbnail: bool,
/// Whether this is a live capture
pub is_live_capture: bool,
/// Whether this is a terminated offline capture
pub no_more_packets: bool,
/// Timestamp of the first packet displayed in the chart
pub first_packet_timestamp: Timestamp,
}
impl TrafficChart {
pub fn new(style: StyleType, language: Language, data_repr: DataRepr) -> Self {
Self {
ticks: 0,
out_bytes: ChartSeries::default(),
in_bytes: ChartSeries::default(),
out_packets: ChartSeries::default(),
in_packets: ChartSeries::default(),
min_bytes: 0.0,
max_bytes: 0.0,
min_packets: 0.0,
max_packets: 0.0,
language,
data_repr,
style,
thumbnail: false,
is_live_capture: true,
no_more_packets: false,
first_packet_timestamp: Timestamp::default(),
}
}
pub fn update_charts_data(&mut self, info_traffic_msg: &InfoTraffic, no_more_packets: bool) {
self.no_more_packets = no_more_packets;
if self.ticks == 0 {
self.first_packet_timestamp = info_traffic_msg.last_packet_timestamp;
}
#[allow(clippy::cast_precision_loss)]
let tot_seconds = self.ticks as f32;
self.ticks += 1;
#[allow(clippy::cast_precision_loss)]
let out_bytes_entry = -(info_traffic_msg
.tot_data_info
.outgoing_data(DataRepr::Bytes) as f32);
#[allow(clippy::cast_precision_loss)]
let in_bytes_entry = info_traffic_msg
.tot_data_info
.incoming_data(DataRepr::Bytes) as f32;
#[allow(clippy::cast_precision_loss)]
let out_packets_entry = -(info_traffic_msg
.tot_data_info
.outgoing_data(DataRepr::Packets) as f32);
#[allow(clippy::cast_precision_loss)]
let in_packets_entry = info_traffic_msg
.tot_data_info
.incoming_data(DataRepr::Packets) as f32;
let out_bytes_point = (tot_seconds, out_bytes_entry);
let in_bytes_point = (tot_seconds, in_bytes_entry);
let out_packets_point = (tot_seconds, out_packets_entry);
let in_packets_point = (tot_seconds, in_packets_entry);
// update sent bytes traffic data
self.out_bytes
.update_series(out_bytes_point, self.is_live_capture, no_more_packets);
self.min_bytes = self.out_bytes.get_min();
// update received bytes traffic data
self.in_bytes
.update_series(in_bytes_point, self.is_live_capture, no_more_packets);
self.max_bytes = self.in_bytes.get_max();
// update sent packets traffic data
self.out_packets
.update_series(out_packets_point, self.is_live_capture, no_more_packets);
self.min_packets = self.out_packets.get_min();
// update received packets traffic data
self.in_packets
.update_series(in_packets_point, self.is_live_capture, no_more_packets);
self.max_packets = self.in_packets.get_max();
}
pub fn push_offline_gap_to_splines(&mut self, gap: u32) {
for i in 0..gap {
#[allow(clippy::cast_precision_loss)]
let point = ((self.ticks + i) as f32, 0.0);
self.in_bytes.update_series(point, false, false);
self.out_bytes.update_series(point, false, false);
self.in_packets.update_series(point, false, false);
self.out_packets.update_series(point, false, false);
}
self.ticks += gap;
}
pub fn view(&self) -> Element<'_, Message, StyleType> {
let x_labels = if self.is_live_capture || self.thumbnail {
None
} else {
let ts_1 = self.first_packet_timestamp;
let mut ts_2 = ts_1;
ts_2.add_secs(i64::from(self.ticks) - 1);
Some(
Row::new()
.padding(Padding::new(8.0).bottom(15).left(55).right(25))
.width(Length::Fill)
.push(if self.no_more_packets {
Some(iced::widget::Text::new(get_formatted_timestamp(ts_1)).size(12.5))
} else {
None
})
.push(Space::new().width(Length::Fill))
.push(iced::widget::Text::new(get_formatted_timestamp(ts_2)).size(12.5)),
)
};
Column::new()
.push(ChartWidget::new(self))
.push(x_labels)
.into()
}
pub fn change_kind(&mut self, kind: DataRepr) {
self.data_repr = kind;
}
pub fn change_language(&mut self, language: Language) {
self.language = language;
}
pub fn change_style(&mut self, style: StyleType) {
self.style = style;
}
pub fn change_capture_source(&mut self, is_live_capture: bool) {
self.is_live_capture = is_live_capture;
}
fn set_margins_and_label_areas<DB: DrawingBackend>(
&self,
chart_builder: &mut ChartBuilder<DB>,
) {
if self.thumbnail {
chart_builder.margin_right(0);
chart_builder.margin_left(0);
chart_builder.margin_bottom(0);
chart_builder.margin_top(5);
} else {
chart_builder
.margin_right(25)
.margin_top(6)
.set_label_area_size(LabelAreaPosition::Left, 55);
if self.is_live_capture {
chart_builder.set_label_area_size(LabelAreaPosition::Bottom, 40);
}
}
}
fn x_axis_range(&self) -> Range<f32> {
// if we have only one tick, we need to add a second point to draw the area
if self.ticks == 1 {
return 0.0..0.1;
}
let first_time_displayed = if self.no_more_packets {
0
} else {
self.ticks.saturating_sub(30)
};
let last_time_displayed = self.ticks - 1;
#[allow(clippy::cast_precision_loss)]
let range = first_time_displayed as f32..last_time_displayed as f32;
range
}
fn y_axis_range(&self) -> Range<f32> {
let (min, max) = match self.data_repr {
DataRepr::Packets => (self.min_packets, self.max_packets),
DataRepr::Bytes => (self.min_bytes, self.max_bytes),
DataRepr::Bits => (self.min_bytes * 8.0, self.max_bytes * 8.0),
};
let fs = max - min;
let gap = fs * 0.05;
min - gap..max + gap
}
fn font<'a>(&self, size: f64) -> TextStyle<'a> {
(FONT_FAMILY_NAME, size)
.into_font()
.style(FontStyle::Normal)
.color(&to_rgb_color(self.style.get_palette().text_body))
}
fn spline_to_plot(&self, direction: TrafficDirection) -> &Spline<f32, f32> {
match self.data_repr {
DataRepr::Packets => match direction {
TrafficDirection::Incoming => &self.in_packets.spline,
TrafficDirection::Outgoing => &self.out_packets.spline,
},
DataRepr::Bytes | DataRepr::Bits => match direction {
TrafficDirection::Incoming => &self.in_bytes.spline,
TrafficDirection::Outgoing => &self.out_bytes.spline,
},
}
}
fn series_label(&self, direction: TrafficDirection) -> &str {
match direction {
TrafficDirection::Incoming => incoming_translation(self.language),
TrafficDirection::Outgoing => outgoing_translation(self.language),
}
}
fn series_color(&self, direction: TrafficDirection) -> RGBColor {
match direction {
TrafficDirection::Incoming => to_rgb_color(self.style.get_palette().secondary),
TrafficDirection::Outgoing => to_rgb_color(self.style.get_palette().outgoing),
}
}
fn area_series<DB: DrawingBackend>(
&self,
direction: TrafficDirection,
) -> AreaSeries<DB, f32, f32> {
let color = self.series_color(direction);
let alpha = self.style.get_extension().alpha_chart_badge;
let spline = self.spline_to_plot(direction);
let multiplier = if self.data_repr == DataRepr::Bits {
8.0
} else {
1.0
};
let data = match spline.keys() {
// if we have only one tick, we need to add a second point to draw the area
[k] => vec![(0.0, k.value * multiplier), (0.1, k.value * multiplier)],
_ => sample_spline(spline, multiplier),
};
AreaSeries::new(data, 0.0, color.mix(alpha.into()))
.border_style(ShapeStyle::from(&color).stroke_width(CHARTS_LINE_BORDER))
}
}
impl Chart<Message> for TrafficChart {
type State = ();
fn build_chart<DB: DrawingBackend>(
&self,
_state: &Self::State,
mut chart_builder: ChartBuilder<DB>,
) {
if self.ticks < 1 {
return;
}
self.set_margins_and_label_areas(&mut chart_builder);
let x_axis_range = self.x_axis_range();
let x_axis_start = x_axis_range.start;
let x_axis_end = x_axis_range.end;
let y_axis_range = self.y_axis_range();
let x_labels = if self.thumbnail || !self.is_live_capture {
0
} else if self.ticks == 1 {
// if we have only one tick, we need to add a second point to draw the area
2
} else {
self.ticks as usize
};
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let y_labels = if self.thumbnail {
0
} else {
1 + (y_axis_range.end - y_axis_range.start) as usize
};
let Ok(mut chart) = chart_builder
.build_cartesian_2d(x_axis_range, y_axis_range)
.log_err(location!())
else {
return;
};
let ext = self.style.get_extension();
let alpha = ext.alpha_chart_badge;
let buttons_color = to_rgb_color(ext.buttons_color);
// chart mesh
let _ = chart
.configure_mesh()
.axis_style(buttons_color)
.bold_line_style(buttons_color.mix(alpha.into()))
.light_line_style(buttons_color.mix(0.0))
.max_light_lines(0)
.label_style(self.font(12.5))
.y_labels(min(5, y_labels))
.y_label_formatter(
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
&|amount| self.data_repr.formatted_string(amount.abs() as u128),
)
.x_labels(min(6, x_labels))
.x_label_formatter(
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
&|seconds| get_formatted_num_seconds(seconds.abs() as u128),
)
.draw()
.log_err(location!());
// draw incoming and outgoing series
for direction in [TrafficDirection::Incoming, TrafficDirection::Outgoing] {
let area_series = self.area_series(direction);
let label = self.series_label(direction);
let legend_style = self.series_color(direction).filled();
let Ok(data_series) = chart.draw_series(area_series).log_err(location!()) else {
return;
};
data_series
.label(label)
.legend(move |(x, y)| Rectangle::new([(x, y - 5), (x + 25, y + 5)], legend_style));
}
// draw x axis to hide zeroed values
let _ = chart
.draw_series(LineSeries::new(
[(x_axis_start, 0.0), (x_axis_end, 0.0)],
ShapeStyle::from(&buttons_color).stroke_width(CHARTS_LINE_BORDER),
))
.log_err(location!());
// chart legend
if !self.thumbnail {
let _ = chart
.configure_series_labels()
.position(SeriesLabelPosition::UpperRight)
.background_style(buttons_color.mix(alpha.into()))
.border_style(buttons_color.stroke_width(CHARTS_LINE_BORDER * 2))
.label_font(self.font(13.5))
.draw()
.log_err(location!());
}
}
}
#[cfg(test)]
mod tests {
use splines::{Interpolation, Key, Spline};
use crate::chart::types::traffic_chart::sample_spline;
#[test]
fn test_spline_samples() {
let vec = vec![
(0, -500),
(1, -1000),
(2, -1000),
(3, -1000),
(4, -1000),
(5, -1000),
(6, -1000),
(7, -1000),
(8, -1000),
(9, -1000),
(10, -1000),
(11, -1000),
(12, -1000),
(13, -1000),
(14, -1000),
(15, -1000),
(16, -1000),
(17, -1000),
(18, -1000),
(19, -1000),
(20, -1000),
(21, -1000),
(22, -1000),
(23, -1000),
(24, -1000),
(25, -1000),
(26, -1000),
(27, -1000),
(28, -1000),
];
let spline = Spline::from_vec(
vec.iter()
.map(|&(x, y)| Key::new(x as f32, y as f32, Interpolation::Cosine))
.collect::<Vec<Key<f32, f32>>>(),
);
let eps = 0.001;
let pts = spline.len() * 10;
let samples = sample_spline(&spline, 1.0);
assert_eq!(samples.len(), pts);
let delta = samples[1].0 - samples[0].0;
assert_eq!(samples[0].0, 0.0);
assert_eq!(samples[0].1, -500.0);
for i in 0..pts - 1 {
assert_eq!(
(samples[i + 1].0 * 10_000.0 - samples[i].0 * 10_000.0).round() / 10_000.0,
(delta * 10_000.0).round() / 10_000.0
);
assert!(samples[i].1 <= -500.0);
assert!(samples[i].1 >= -1000.0 - eps);
assert!(samples[i + 1].1 < samples[i].1 + eps);
}
assert_eq!(samples[pts - 1].0, 28.0);
assert_eq!(samples[pts - 1].1, -1000.0);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/cli/mod.rs | src/cli/mod.rs | use crate::SNIFFNET_LOWERCASE;
use crate::gui::types::conf::{CONF, Conf};
use crate::gui::types::message::Message;
use crate::networking::types::capture_context::CaptureSourcePicklist;
use crate::utils::formatted_strings::APP_VERSION;
use clap::Parser;
use iced::{Task, window};
#[derive(Parser, Debug)]
#[command(
name = SNIFFNET_LOWERCASE,
bin_name = SNIFFNET_LOWERCASE,
version = APP_VERSION,
about = "Application to comfortably monitor your network traffic"
)]
struct Args {
/// Start sniffing packets from the supplied network adapter
#[arg(short, long, value_name = "NAME", default_missing_value = CONF.device.device_name.as_str(), num_args = 0..=1)]
adapter: Option<String>,
#[cfg(all(windows, not(debug_assertions)))]
/// Show the logs (stdout and stderr) of the most recent application run
#[arg(short, long, exclusive = true)]
logs: bool,
/// Restore default settings
#[arg(short, long, exclusive = true)]
restore_default: bool,
}
pub fn handle_cli_args() -> Task<Message> {
let args = Args::parse();
#[cfg(all(windows, not(debug_assertions)))]
if let Some(logs_file) = crate::utils::formatted_strings::get_logs_file_path() {
if args.logs {
std::process::Command::new("explorer")
.arg(logs_file)
.spawn()
.unwrap()
.wait()
.unwrap_or_default();
std::process::exit(0);
} else {
// truncate logs file
let _ = std::fs::OpenOptions::new()
.write(true)
.truncate(true)
.open(logs_file);
}
}
if args.restore_default {
if Conf::default().store().is_ok() {
println!("Restored default settings");
}
std::process::exit(0);
}
let mut boot_task_chain = window::latest().map(Message::StartApp);
if let Some(adapter) = args.adapter {
boot_task_chain = boot_task_chain
.chain(Task::done(Message::SetCaptureSource(
CaptureSourcePicklist::Device,
)))
.chain(Task::done(Message::DeviceSelection(adapter)))
.chain(Task::done(Message::Start));
}
boot_task_chain
}
#[cfg(test)]
mod tests {
use serial_test::serial;
use crate::gui::pages::types::running_page::RunningPage;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::conf::Conf;
use crate::gui::types::config_window::ConfigWindow;
use crate::gui::types::export_pcap::ExportPcap;
use crate::gui::types::filters::Filters;
use crate::gui::types::settings::Settings;
use crate::networking::types::capture_context::CaptureSourcePicklist;
use crate::networking::types::config_device::ConfigDevice;
use crate::networking::types::data_representation::DataRepr;
use crate::notifications::types::notifications::Notifications;
use crate::report::types::sort_type::SortType;
use crate::{Language, Sniffer, StyleType};
#[test]
#[serial]
fn test_restore_default_configs() {
// initial configs stored are the default ones
assert_eq!(Conf::load(), Conf::default());
let modified_conf = Conf {
settings: Settings {
color_gradient: GradientType::Wild,
language: Language::ZH,
scale_factor: 0.65,
mmdb_country: "countrymmdb".to_string(),
mmdb_asn: "asnmmdb".to_string(),
style_path: format!(
"{}/resources/themes/catppuccin.toml",
env!("CARGO_MANIFEST_DIR")
),
notifications: Notifications {
volume: 100,
data_notification: Default::default(),
favorite_notification: Default::default(),
remote_notifications: Default::default(),
},
style: StyleType::DraculaDark,
},
device: ConfigDevice {
device_name: "hey-hey".to_string(),
},
window: ConfigWindow::new((452.0, 870.0), (440.0, 99.0), (20.0, 20.0)),
capture_source_picklist: CaptureSourcePicklist::File,
report_sort_type: SortType::Ascending,
host_sort_type: SortType::Descending,
service_sort_type: SortType::Neutral,
filters: Filters {
bpf: "tcp".to_string(),
expanded: true,
},
import_pcap_path: "whole_day.pcapng".to_string(),
export_pcap: ExportPcap {
enabled: true,
file_name: "sniffnet.pcap".to_string(),
directory: "home".to_string(),
},
last_opened_setting: SettingsPage::General,
last_opened_page: RunningPage::Inspect,
data_repr: DataRepr::Packets,
};
// we want to be sure that modified config is different from defaults
assert_ne!(Conf::default(), modified_conf);
//store modified configs
modified_conf.clone().store().unwrap();
// assert they've been stored
assert_eq!(Conf::load(), modified_conf);
// restore defaults
Conf::default().store().unwrap();
// assert that defaults are stored
assert_eq!(Conf::load(), Conf::default());
// only needed because it will delete config files via its Drop implementation
Sniffer::new(Conf::default());
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/mod.rs | src/gui/mod.rs | pub mod components;
pub mod pages;
pub mod sniffer;
pub mod styles;
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/gui/sniffer.rs | src/gui/sniffer.rs | //! Module defining the application structure: messages, updates, subscriptions.
use crate::gui::pages::waiting_page::waiting_page;
use async_channel::Receiver;
use iced::Event::{Keyboard, Window};
use iced::keyboard::key::Named;
use iced::keyboard::{Event, Key, Modifiers};
use iced::mouse::Event::ButtonPressed;
use iced::widget::Column;
use iced::window::{Id, Level};
use iced::{Element, Point, Size, Subscription, Task, window};
use rfd::FileHandle;
use std::collections::{HashMap, HashSet, VecDeque};
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::chart::types::preview_chart::PreviewChart;
use crate::gui::components::footer::footer;
use crate::gui::components::header::header;
use crate::gui::components::modal::{get_clear_all_overlay, get_exit_overlay, modal};
use crate::gui::components::types::my_modal::MyModal;
use crate::gui::pages::connection_details_page::connection_details_page;
use crate::gui::pages::initial_page::initial_page;
use crate::gui::pages::inspect_page::inspect_page;
use crate::gui::pages::notifications_page::notifications_page;
use crate::gui::pages::overview_page::overview_page;
use crate::gui::pages::settings_general_page::settings_general_page;
use crate::gui::pages::settings_notifications_page::settings_notifications_page;
use crate::gui::pages::settings_style_page::settings_style_page;
use crate::gui::pages::thumbnail_page::thumbnail_page;
use crate::gui::pages::types::running_page::RunningPage;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::pages::welcome_page::welcome_page;
use crate::gui::styles::types::custom_palette::CustomPalette;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::styles::types::palette::Palette;
use crate::gui::types::conf::Conf;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::gui::types::timing_events::TimingEvents;
use crate::mmdb::asn::ASN_MMDB;
use crate::mmdb::country::COUNTRY_MMDB;
use crate::mmdb::types::mmdb_reader::{MmdbReader, MmdbReaders};
use crate::networking::parse_packets::BackendTrafficMessage;
use crate::networking::parse_packets::parse_packets;
use crate::networking::traffic_preview::{TrafficPreview, traffic_preview};
use crate::networking::types::capture_context::{
CaptureContext, CaptureSource, CaptureSourcePicklist, MyPcapImport,
};
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::{Host, HostMessage};
use crate::networking::types::host_data_states::HostDataStates;
use crate::networking::types::info_traffic::InfoTraffic;
use crate::networking::types::my_device::MyDevice;
use crate::notifications::notify_and_log::notify_and_log;
use crate::notifications::types::logged_notification::LoggedNotification;
use crate::notifications::types::notifications::{DataNotification, Notification};
use crate::notifications::types::sound::{Sound, play};
use crate::report::get_report_entries::get_searched_entries;
use crate::report::types::search_parameters::SearchParameters;
use crate::report::types::sort_type::SortType;
use crate::translations::types::language::Language;
use crate::utils::check_updates::set_newer_release_status;
use crate::utils::error_logger::{ErrorLogger, Location};
use crate::utils::types::file_info::FileInfo;
use crate::utils::types::web_page::WebPage;
use crate::{StyleType, TrafficChart, location};
pub const FONT_FAMILY_NAME: &str = "Sarasa Mono SC for Sniffnet";
pub const ICON_FONT_FAMILY_NAME: &str = "Icons for Sniffnet";
const THUMBNAIL_SIZE: Size = Size {
width: 360.0,
height: 222.0,
};
/// Struct on which the GUI is based
///
/// It carries statuses, network traffic statistics, and more
pub struct Sniffer {
/// Parameters that are persistent across runs
pub conf: Conf,
/// Are we during welcome / quit animation? None if not, true if welcome, false if quit
pub welcome: Option<(bool, u8)>,
/// Capture receiver clone (to close the channel after every run), with the current capture id (to ignore pending messages from previous captures)
pub current_capture_rx: (usize, Option<Receiver<BackendTrafficMessage>>),
/// Preview captures receiver clone (to close the channel when starting the analysis)
pub preview_captures_rx: Option<Receiver<TrafficPreview>>,
/// Capture data
pub info_traffic: InfoTraffic,
/// Map of the resolved addresses with their full rDNS value and the corresponding host
pub addresses_resolved: HashMap<IpAddr, (String, Host)>,
/// Collection of the favorite hosts
pub favorite_hosts: HashSet<Host>,
/// Log of the displayed notifications, with the total number of notifications for this capture
pub logged_notifications: (VecDeque<LoggedNotification>, usize),
/// Reports if a newer release of the software is available on GitHub
pub newer_release_available: Option<bool>,
/// Network device to be analyzed, or PCAP file to be imported
pub capture_source: CaptureSource,
/// Signals if a pcap error occurred
pub pcap_error: Option<String>,
/// Messages status
pub dots_pulse: (String, u8),
/// Traffic chart displayed in the Overview page
pub traffic_chart: TrafficChart,
/// Traffic preview charts displayed in the initial page
pub preview_charts: Vec<(MyDevice, PreviewChart)>,
/// Currently displayed modal; None if no modal is displayed
pub modal: Option<MyModal>,
/// Currently displayed settings page; None if settings is closed
pub settings_page: Option<SettingsPage>,
/// Defines the current running page; None if initial page
pub running_page: Option<RunningPage>,
/// Number of unread notifications
pub unread_notifications: usize,
/// Search parameters of inspect page
pub search: SearchParameters,
/// Current page number of inspect search results
pub page_number: usize,
/// MMDB readers for country and ASN
pub mmdb_readers: MmdbReaders,
/// Time-related events
pub timing_events: TimingEvents,
/// Whether thumbnail mode is currently active
pub thumbnail: bool,
/// Window id
pub id: Option<Id>,
/// Host data for filter dropdowns (comboboxes)
pub host_data_states: HostDataStates,
/// Flag reporting whether the packet capture is frozen
pub frozen: bool,
/// Sender to freeze the packet capture
pub freeze_tx: Option<tokio::sync::broadcast::Sender<()>>,
}
impl Sniffer {
pub fn new(conf: Conf) -> Self {
let Settings {
style,
language,
mmdb_country,
mmdb_asn,
..
} = conf.settings.clone();
let data_repr = conf.data_repr;
let capture_source = CaptureSource::from_conf(&conf);
let preview_charts = pcap::Device::list()
.unwrap_or_default()
.into_iter()
.map(|dev| (MyDevice::from_pcap_device(dev), PreviewChart::new(style)))
.collect();
Self {
conf,
welcome: Some((true, 0)),
current_capture_rx: (0, None),
preview_captures_rx: None,
info_traffic: InfoTraffic::default(),
addresses_resolved: HashMap::new(),
favorite_hosts: HashSet::new(),
logged_notifications: (VecDeque::new(), 0),
newer_release_available: None,
capture_source,
pcap_error: None,
dots_pulse: (".".to_string(), 0),
traffic_chart: TrafficChart::new(style, language, data_repr),
preview_charts,
modal: None,
settings_page: None,
running_page: None,
unread_notifications: 0,
search: SearchParameters::default(),
page_number: 1,
mmdb_readers: MmdbReaders {
country: Arc::new(MmdbReader::from(&mmdb_country, COUNTRY_MMDB)),
asn: Arc::new(MmdbReader::from(&mmdb_asn, ASN_MMDB)),
},
timing_events: TimingEvents::default(),
thumbnail: false,
id: None,
host_data_states: HostDataStates::default(),
frozen: false,
freeze_tx: None,
}
}
fn keyboard_subscription(&self) -> Subscription<Message> {
if self.welcome.is_some() {
return Subscription::none();
}
if self.thumbnail {
iced::event::listen_with(|event, _, _| match event {
Keyboard(Event::KeyPressed {
key,
modifiers: Modifiers::COMMAND,
..
}) => match key.as_ref() {
Key::Character("q") => Some(Message::QuitWrapper),
Key::Character("t") => Some(Message::CtrlTPressed),
Key::Named(Named::Space) => Some(Message::CtrlSpacePressed),
_ => None,
},
_ => None,
})
} else {
iced::event::listen_with(|event, _, _| match event {
Keyboard(Event::KeyPressed { key, modifiers, .. }) => match modifiers {
Modifiers::COMMAND => match key.as_ref() {
Key::Character("q") => Some(Message::QuitWrapper),
Key::Character("t") => Some(Message::CtrlTPressed),
Key::Named(Named::Space) => Some(Message::CtrlSpacePressed),
Key::Character(",") => Some(Message::OpenLastSettings),
Key::Named(Named::Backspace) => Some(Message::ResetButtonPressed),
Key::Character("d") => Some(Message::CtrlDPressed),
Key::Named(Named::ArrowLeft) => Some(Message::ArrowPressed(false)),
Key::Named(Named::ArrowRight) => Some(Message::ArrowPressed(true)),
Key::Character("-") => Some(Message::ScaleFactorShortcut(false)),
Key::Character("+") => Some(Message::ScaleFactorShortcut(true)),
_ => None,
},
Modifiers::SHIFT => match key {
Key::Named(Named::Tab) => Some(Message::SwitchPage(false)),
_ => None,
},
Modifiers::NONE => match key {
Key::Named(Named::Enter) => Some(Message::ReturnKeyPressed),
Key::Named(Named::Escape) => Some(Message::EscKeyPressed),
Key::Named(Named::Tab) => Some(Message::SwitchPage(true)),
_ => None,
},
_ => None,
},
_ => None,
})
}
}
fn mouse_subscription(&self) -> Subscription<Message> {
if self.thumbnail {
iced::event::listen_with(|event, _, _| match event {
iced::event::Event::Mouse(ButtonPressed(_)) => Some(Message::Drag),
_ => None,
})
} else {
Subscription::none()
}
}
fn time_subscription(&self) -> Subscription<Message> {
if let Some((w, _)) = self.welcome {
let sub = iced::time::every(Duration::from_millis(100));
if w {
sub.map(|_| Message::Welcome)
} else {
sub.map(|_| Message::Quit)
}
} else {
iced::time::every(Duration::from_millis(1000)).map(|_| Message::Periodic)
}
}
fn window_subscription() -> Subscription<Message> {
iced::event::listen_with(|event, _, _| match event {
Window(window::Event::Focused) => Some(Message::WindowFocused),
Window(window::Event::Moved(Point { x, y })) => Some(Message::WindowMoved(x, y)),
Window(window::Event::Resized(Size { width, height })) => {
Some(Message::WindowResized(width, height))
}
Window(window::Event::CloseRequested) => Some(Message::QuitWrapper),
_ => None,
})
}
pub fn update(&mut self, message: Message) -> Task<Message> {
self.dots_pulse.1 = (self.dots_pulse.1 + 1) % 3;
match message {
Message::StartApp(id) => return self.start_app(id),
Message::TickRun(cap_id, msg, host_msgs, no_more_packets) => {
self.tick_run(cap_id, msg, host_msgs, no_more_packets);
}
Message::DeviceSelection(name) => self.device_selection(&name),
Message::SetCaptureSource(cs_pick) => self.set_capture_source(cs_pick),
Message::ToggleFilters => self.toggle_filters(),
Message::BpfFilter(value) => self.bpf_filter(value),
Message::DataReprSelection(unit) => self.data_repr_selection(unit),
Message::ReportSortSelection(sort) => self.report_sort_selection(sort),
Message::OpenWebPage(web_page) => Self::open_web_page(&web_page),
Message::Start => return self.start(),
Message::Reset => return self.reset(),
Message::Style(style) => self.style(style),
Message::LoadStyle(path) => self.load_style(path),
Message::AddOrRemoveFavorite(host, add) => self.add_or_remove_favorite(&host, add),
Message::ShowModal(modal) => self.show_modal(modal),
Message::HideModal => self.hide_modal(),
Message::OpenSettings(settings_page) => self.open_settings(settings_page),
Message::OpenLastSettings => self.open_last_settings(),
Message::CloseSettings => self.close_settings(),
Message::ChangeRunningPage(running_page) => self.change_running_page(running_page),
Message::LanguageSelection(language) => self.language_selection(language),
Message::UpdateNotificationSettings(notification, emit_sound) => {
self.update_notifications_settings(notification, emit_sound);
}
Message::ChangeVolume(volume) => self.change_volume(volume),
Message::ClearAllNotifications => self.clear_all_notifications(),
Message::SwitchPage(next) => self.switch_page(next),
Message::ReturnKeyPressed => return self.return_key_pressed(),
Message::EscKeyPressed => self.esc_key_pressed(),
Message::ResetButtonPressed => return self.reset_button_pressed(),
Message::CtrlDPressed => self.ctrl_d_pressed(),
Message::Search(parameters) => self.search(parameters),
Message::UpdatePageNumber(increment) => self.update_page_number(increment),
Message::ArrowPressed(increment) => self.arrow_pressed(increment),
Message::WindowFocused => self.window_focused(),
Message::GradientsSelection(gradient_type) => self.gradients_selection(gradient_type),
Message::ChangeScaleFactor(slider_val) => self.change_scale_factor(slider_val),
Message::WindowMoved(x, y) => self.window_moved(x, y),
Message::WindowResized(width, height) => return self.window_resized(width, height),
Message::CustomCountryDb(db) => self.custom_country_db(&db),
Message::CustomAsnDb(db) => self.custom_asn_db(&db),
Message::QuitWrapper => return self.quit_wrapper(),
Message::Quit => return self.quit(),
Message::Welcome => self.welcome(),
Message::CopyIp(ip) => return self.copy_ip(ip),
Message::OpenFile(old_file, file_info, consumer_message) => {
return self.open_file(old_file, file_info, consumer_message);
}
Message::HostSortSelection(sort_type) => self.host_sort_selection(sort_type),
Message::ServiceSortSelection(sort_type) => self.service_sort_selection(sort_type),
Message::ToggleExportPcap => self.toggle_export_pcap(),
Message::OutputPcapDir(path) => self.output_pcap_dir(path),
Message::OutputPcapFile(name) => self.output_pcap_file(&name),
Message::ToggleThumbnail(triggered_by_resize) => {
return self.toggle_thumbnail(triggered_by_resize);
}
Message::Drag => return self.drag(),
Message::CtrlTPressed => return self.ctrl_t_pressed(),
Message::CtrlSpacePressed => self.ctrl_space_pressed(),
Message::ScaleFactorShortcut(increase) => self.scale_factor_shortcut(increase),
Message::SetNewerReleaseStatus(status) => self.set_newer_release_status(status),
Message::SetPcapImport(path) => self.set_pcap_import(path),
Message::PendingHosts(cap_id, host_msgs) => self.pending_hosts(cap_id, host_msgs),
Message::OfflineGap(cap_id, gap) => self.offline_gap(cap_id, gap),
Message::Periodic => self.periodic(),
Message::ExpandNotification(id, expand) => self.expand_notification(id, expand),
Message::ToggleRemoteNotifications => self.toggle_remote_notifications(),
Message::RemoteNotificationsUrl(url) => self.remote_notifications_url(&url),
Message::Freeze => self.freeze(),
Message::TrafficPreview(msg) => self.traffic_preview(msg),
}
Task::none()
}
pub fn view(&self) -> Element<'_, Message, StyleType> {
let Settings {
language,
color_gradient,
..
} = self.conf.settings;
if let Some((_, x)) = self.welcome {
return welcome_page(x, self.thumbnail).into();
}
let header = header(self);
let body = if self.thumbnail {
thumbnail_page(self)
} else {
match self.running_page {
None => initial_page(self),
Some(running_page) => {
if let Some(waiting_page) = waiting_page(self) {
waiting_page
} else {
match running_page {
RunningPage::Overview => overview_page(self),
RunningPage::Inspect => inspect_page(self),
RunningPage::Notifications => notifications_page(self),
}
}
}
}
};
let footer = footer(
self.thumbnail,
language,
color_gradient,
self.newer_release_available,
&self.dots_pulse,
);
let content: Element<Message, StyleType> =
Column::new().push(header).push(body).push(footer).into();
match self.modal.clone() {
None => {
if let Some(settings_page) = self.settings_page {
let overlay: Element<Message, StyleType> = match settings_page {
SettingsPage::Notifications => settings_notifications_page(self),
SettingsPage::Appearance => settings_style_page(self),
SettingsPage::General => settings_general_page(self),
}
.into();
modal(content, overlay, Message::CloseSettings)
} else {
content
}
}
Some(m) => {
let overlay: Element<Message, StyleType> = match m {
MyModal::Reset => get_exit_overlay(Message::Reset, color_gradient, language),
MyModal::Quit => get_exit_overlay(Message::Quit, color_gradient, language),
MyModal::ClearAll => get_clear_all_overlay(color_gradient, language),
MyModal::ConnectionDetails(key) => connection_details_page(self, key),
}
.into();
modal(content, overlay, Message::HideModal)
}
}
}
pub fn subscription(&self) -> Subscription<Message> {
Subscription::batch([
self.keyboard_subscription(),
self.mouse_subscription(),
self.time_subscription(),
Sniffer::window_subscription(),
])
}
pub fn theme(&self) -> StyleType {
self.conf.settings.style
}
pub fn scale_factor(&self) -> f32 {
self.conf.settings.scale_factor
}
fn start_app(&mut self, id: Option<Id>) -> Task<Message> {
self.id = id;
let previews_task = self.start_traffic_previews();
Task::batch([
Sniffer::register_sigint_handler(),
Task::perform(set_newer_release_status(), Message::SetNewerReleaseStatus),
previews_task,
])
}
fn tick_run(
&mut self,
cap_id: usize,
msg: InfoTraffic,
host_msgs: Vec<HostMessage>,
no_more_packets: bool,
) {
if cap_id == self.current_capture_rx.0 {
for host_msg in host_msgs {
self.handle_new_host(host_msg);
}
self.refresh_data(msg, no_more_packets);
}
}
fn set_capture_source(&mut self, cs_pick: CaptureSourcePicklist) {
self.conf.capture_source_picklist = cs_pick;
if cs_pick == CaptureSourcePicklist::File {
self.set_pcap_import(self.conf.import_pcap_path.clone());
} else {
self.device_selection(&self.conf.device.device_name.clone());
}
}
fn toggle_filters(&mut self) {
self.conf.filters.toggle();
}
fn bpf_filter(&mut self, value: String) {
self.conf.filters.set_bpf(value);
}
fn data_repr_selection(&mut self, unit: DataRepr) {
self.conf.data_repr = unit;
self.traffic_chart.change_kind(unit);
}
fn report_sort_selection(&mut self, sort: SortType) {
self.page_number = 1;
self.conf.report_sort_type = sort;
}
fn style(&mut self, style: StyleType) {
self.conf.settings.style = style;
self.change_charts_style();
}
fn load_style(&mut self, path: String) {
self.conf.settings.style_path.clone_from(&path);
if let Ok(palette) = Palette::from_file(path) {
let style = StyleType::Custom(CustomPalette::from_palette(palette));
self.conf.settings.style = style;
self.change_charts_style();
}
}
fn show_modal(&mut self, modal: MyModal) {
if self.settings_page.is_none() && self.modal.is_none() {
self.modal = Some(modal);
}
}
fn hide_modal(&mut self) {
self.modal = None;
}
fn open_settings(&mut self, settings_page: SettingsPage) {
if self.modal.is_none() {
self.settings_page = Some(settings_page);
self.conf.last_opened_setting = settings_page;
}
}
fn open_last_settings(&mut self) {
if self.modal.is_none() && self.settings_page.is_none() {
self.settings_page = Some(self.conf.last_opened_setting);
}
}
fn change_running_page(&mut self, running_page: RunningPage) {
self.running_page = Some(running_page);
self.conf.last_opened_page = running_page;
if running_page.eq(&RunningPage::Notifications) {
self.unread_notifications = 0;
}
}
fn language_selection(&mut self, language: Language) {
self.conf.settings.language = language;
self.traffic_chart.change_language(language);
}
fn change_volume(&mut self, volume: u8) {
play(Sound::Pop, volume);
self.conf.settings.notifications.volume = volume;
}
fn clear_all_notifications(&mut self) {
self.logged_notifications.0 = VecDeque::new();
self.modal = None;
}
fn search(&mut self, parameters: SearchParameters) {
// update comboboxes
let host_data = &mut self.host_data_states.data;
host_data.countries.1 = self.search.country != parameters.country;
host_data.asns.1 = self.search.as_name != parameters.as_name;
host_data.domains.1 = self.search.domain != parameters.domain;
self.host_data_states.update_states(¶meters);
self.page_number = 1;
self.running_page = Some(RunningPage::Inspect);
self.conf.last_opened_page = RunningPage::Inspect;
self.search = parameters;
}
fn update_page_number(&mut self, increment: bool) {
if increment {
if self.page_number < get_searched_entries(self).1.div_ceil(20) {
self.page_number = self.page_number.checked_add(1).unwrap_or(1);
}
} else if self.page_number > 1 {
self.page_number = self.page_number.checked_sub(1).unwrap_or(1);
}
}
fn arrow_pressed(&mut self, increment: bool) {
if self
.running_page
.is_some_and(|p| p.eq(&RunningPage::Inspect))
&& self.settings_page.is_none()
&& self.modal.is_none()
{
self.update_page_number(increment);
}
}
fn window_focused(&mut self) {
self.timing_events.focus_now();
}
fn gradients_selection(&mut self, gradient_type: GradientType) {
self.conf.settings.color_gradient = gradient_type;
}
fn change_scale_factor(&mut self, scale_factor: f32) {
let old = self.conf.settings.scale_factor;
self.conf.settings.scale_factor = scale_factor;
self.conf.window.scale_size(old, scale_factor);
}
fn window_moved(&mut self, x: f32, y: f32) {
let scale_factor = self.conf.settings.scale_factor;
if self.thumbnail {
self.conf.window.set_thumbnail_position(x, y, scale_factor);
} else {
self.conf.window.set_position(x, y, scale_factor);
}
}
fn window_resized(&mut self, width: f32, height: f32) -> Task<Message> {
if !self.thumbnail {
let scale_factor = self.conf.settings.scale_factor;
self.conf.window.set_size(width, height, scale_factor);
} else if !self.timing_events.was_just_thumbnail_enter() {
return self.toggle_thumbnail(true);
}
Task::none()
}
fn custom_country_db(&mut self, db: &String) {
self.conf.settings.mmdb_country.clone_from(db);
self.mmdb_readers.country = Arc::new(MmdbReader::from(db, COUNTRY_MMDB));
}
fn custom_asn_db(&mut self, db: &String) {
self.conf.settings.mmdb_asn.clone_from(db);
self.mmdb_readers.asn = Arc::new(MmdbReader::from(db, ASN_MMDB));
}
fn open_file(
&mut self,
old_file: String,
file_info: FileInfo,
consumer_message: fn(String) -> Message,
) -> Task<Message> {
Task::perform(
Self::open_file_inner(old_file, file_info, self.conf.settings.language),
consumer_message,
)
}
fn host_sort_selection(&mut self, sort_type: SortType) {
self.conf.host_sort_type = sort_type;
}
fn service_sort_selection(&mut self, sort_type: SortType) {
self.conf.service_sort_type = sort_type;
}
fn toggle_export_pcap(&mut self) {
self.conf.export_pcap.toggle();
}
fn output_pcap_dir(&mut self, path: String) {
self.conf.export_pcap.set_directory(path);
}
fn output_pcap_file(&mut self, name: &str) {
self.conf.export_pcap.set_file_name(name);
}
fn toggle_thumbnail(&mut self, triggered_by_resize: bool) -> Task<Message> {
let window_id = self.id.unwrap_or_else(Id::unique);
self.thumbnail = !self.thumbnail;
self.traffic_chart.thumbnail = self.thumbnail;
if self.thumbnail {
let size = THUMBNAIL_SIZE;
let position = self.conf.window.thumbnail_position();
self.timing_events.thumbnail_enter_now();
Task::batch([
window::maximize(window_id, false),
window::toggle_decorations(window_id),
window::resize(window_id, size),
window::move_to(window_id, position),
window::set_level(window_id, Level::AlwaysOnTop),
])
} else {
if self
.running_page
.is_some_and(|p| p.eq(&RunningPage::Notifications))
{
self.unread_notifications = 0;
}
let mut commands = vec![
window::toggle_decorations(window_id),
window::set_level(window_id, Level::Normal),
];
if !triggered_by_resize {
let size = self.conf.window.size();
let position = self.conf.window.position();
commands.push(window::move_to(window_id, position));
commands.push(window::resize(window_id, size));
}
Task::batch(commands)
}
}
fn drag(&mut self) -> Task<Message> {
let was_just_thumbnail_click = self.timing_events.was_just_thumbnail_click();
self.timing_events.thumbnail_click_now();
if was_just_thumbnail_click {
return window::drag(self.id.unwrap_or_else(Id::unique));
}
Task::none()
}
fn ctrl_t_pressed(&mut self) -> Task<Message> {
if self.running_page.is_some()
&& self.settings_page.is_none()
&& self.modal.is_none()
&& !self.timing_events.was_just_thumbnail_enter()
{
return self.toggle_thumbnail(false);
}
Task::none()
}
fn ctrl_space_pressed(&mut self) {
if self.running_page.is_some() && self.settings_page.is_none() && self.modal.is_none() {
self.freeze();
}
}
fn scale_factor_shortcut(&mut self, increase: bool) {
let scale_factor = self.conf.settings.scale_factor;
if !(scale_factor > 2.99 && increase || scale_factor < 0.31 && !increase) {
let delta = if increase { 0.1 } else { -0.1 };
let new = scale_factor + delta;
self.change_scale_factor(new);
}
}
fn set_newer_release_status(&mut self, status: Option<bool>) {
self.newer_release_available = status;
}
fn set_pcap_import(&mut self, path: String) {
if !path.is_empty() {
self.conf.import_pcap_path.clone_from(&path);
self.capture_source = CaptureSource::File(MyPcapImport::new(path));
}
}
fn pending_hosts(&mut self, cap_id: usize, host_msgs: Vec<HostMessage>) {
if cap_id == self.current_capture_rx.0 {
for host_msg in host_msgs {
self.handle_new_host(host_msg);
}
}
}
fn offline_gap(&mut self, cap_id: usize, gap: u32) {
if cap_id == self.current_capture_rx.0 {
self.traffic_chart.push_offline_gap_to_splines(gap);
}
}
fn periodic(&mut self) {
self.update_waiting_dots();
self.capture_source.set_addresses();
self.update_threshold();
}
fn expand_notification(&mut self, id: usize, expand: bool) {
if let Some(n) = self
.logged_notifications
.0
.iter_mut()
.find(|n| n.id() == id)
{
n.expand(expand);
}
}
fn toggle_remote_notifications(&mut self) {
self.conf
.settings
.notifications
.remote_notifications
.toggle();
}
fn remote_notifications_url(&mut self, url: &str) {
self.conf
.settings
.notifications
.remote_notifications
.set_url(url);
}
fn freeze(&mut self) {
self.frozen = !self.frozen;
if let Some(tx) = &self.freeze_tx {
let _ = tx.send(());
}
}
fn traffic_preview(&mut self, msg: TrafficPreview) {
self.preview_charts.retain(|(my_dev, _)| {
msg.data
.iter()
.any(|(d, _)| d.get_name().eq(my_dev.get_name()))
});
for (dev, packets) in msg.data {
let Some((my_dev, chart)) = self
.preview_charts
.iter_mut()
.find(|(my_dev, _)| my_dev.get_name().eq(dev.get_name()))
else {
let mut chart = PreviewChart::new(self.conf.settings.style);
chart.update_charts_data(packets);
self.preview_charts.push((dev, chart));
continue;
};
*my_dev = dev;
chart.update_charts_data(packets);
}
self.preview_charts
.sort_by(|(_, c1), (_, c2)| c2.tot_packets.total_cmp(&c1.tot_packets));
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | true |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/button.rs | src/gui/styles/button.rs | //! Buttons style
#![allow(clippy::module_name_repetitions)]
use iced::border::Radius;
use iced::widget::button;
use iced::widget::button::{Catalog, Status, Style};
use iced::{Background, Border, Color, Shadow, Vector};
use crate::StyleType;
use crate::gui::styles::style_constants::{BORDER_BUTTON_RADIUS, BORDER_WIDTH};
use crate::gui::styles::types::gradient_type::{
GradientType, get_gradient_buttons, get_gradient_hovered_buttons,
};
use crate::gui::styles::types::palette::mix_colors;
#[derive(Default)]
pub enum ButtonType {
#[default]
Standard,
BorderedRound,
BorderedRoundSelected,
TabActive,
TabInactive,
Starred,
NotStarred,
Neutral,
Alert,
Gradient(GradientType),
SortArrows,
SortArrowActive,
Thumbnail,
}
impl ButtonType {
fn active(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
button::Style {
background: Some(match self {
ButtonType::TabActive | ButtonType::BorderedRoundSelected => {
Background::Color(mix_colors(colors.primary, ext.buttons_color))
}
ButtonType::Starred => Background::Color(colors.starred),
ButtonType::BorderedRound => Background::Color(Color {
a: ext.alpha_round_containers,
..ext.buttons_color
}),
ButtonType::Neutral
| ButtonType::Thumbnail
| ButtonType::NotStarred
| ButtonType::SortArrows
| ButtonType::SortArrowActive => Background::Color(Color::TRANSPARENT),
ButtonType::Gradient(GradientType::None) => Background::Color(colors.secondary),
ButtonType::Gradient(gradient_type) => Background::Gradient(get_gradient_buttons(
&colors,
*gradient_type,
ext.is_nightly,
1.0,
)),
_ => Background::Color(ext.buttons_color),
}),
border: Border {
radius: match self {
ButtonType::Neutral => 0.0.into(),
ButtonType::TabActive | ButtonType::TabInactive => Radius::new(0).bottom(30),
ButtonType::BorderedRound
| ButtonType::BorderedRoundSelected
| ButtonType::Gradient(_) => 12.0.into(),
ButtonType::Starred | ButtonType::NotStarred => 100.0.into(),
_ => BORDER_BUTTON_RADIUS.into(),
},
width: match self {
ButtonType::TabActive
| ButtonType::TabInactive
| ButtonType::SortArrows
| ButtonType::SortArrowActive
| ButtonType::Starred
| ButtonType::NotStarred
| ButtonType::Neutral
| ButtonType::Thumbnail => 0.0,
ButtonType::BorderedRound => BORDER_WIDTH * 2.0,
_ => BORDER_WIDTH,
},
color: match self {
ButtonType::Alert => ext.red_alert_color,
ButtonType::BorderedRound => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
_ => colors.secondary,
},
},
text_color: match self {
ButtonType::Starred => Color::BLACK,
ButtonType::SortArrows => Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
ButtonType::SortArrowActive => colors.secondary,
ButtonType::Gradient(_) => colors.text_headers,
ButtonType::Thumbnail => mix_colors(colors.text_headers, colors.secondary),
_ => colors.text_body,
},
shadow: match self {
ButtonType::TabActive | ButtonType::TabInactive => Shadow {
color: Color::BLACK,
offset: Vector::new(3.0, 2.0),
blur_radius: 4.0,
},
_ => Shadow::default(),
},
snap: true,
}
}
fn hovered(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
button::Style {
shadow: match self {
ButtonType::Neutral
| ButtonType::SortArrows
| ButtonType::SortArrowActive
| ButtonType::Thumbnail => Shadow::default(),
_ => Shadow {
color: Color::BLACK,
offset: match self {
ButtonType::TabActive | ButtonType::TabInactive => Vector::new(3.0, 3.0),
_ => Vector::new(0.0, 2.0),
},
blur_radius: match self {
ButtonType::TabActive | ButtonType::TabInactive => 4.0,
_ => 2.0,
},
},
},
background: Some(match self {
ButtonType::Starred => Background::Color(colors.starred),
ButtonType::SortArrows | ButtonType::SortArrowActive | ButtonType::Thumbnail => {
Background::Color(Color::TRANSPARENT)
}
ButtonType::Neutral => Background::Color(Color {
a: ext.alpha_round_borders,
..ext.buttons_color
}),
ButtonType::Gradient(GradientType::None) => {
Background::Color(mix_colors(colors.primary, colors.secondary))
}
ButtonType::Gradient(gradient_type) => Background::Gradient(
get_gradient_hovered_buttons(&colors, *gradient_type, ext.is_nightly),
),
ButtonType::BorderedRoundSelected => Background::Color(ext.buttons_color),
_ => Background::Color(mix_colors(colors.primary, ext.buttons_color)),
}),
border: Border {
radius: match self {
ButtonType::Neutral => 0.0.into(),
ButtonType::TabActive | ButtonType::TabInactive => Radius::new(0).bottom(30),
ButtonType::BorderedRound
| ButtonType::BorderedRoundSelected
| ButtonType::Gradient(_) => 12.0.into(),
ButtonType::Starred | ButtonType::NotStarred => 100.0.into(),
_ => BORDER_BUTTON_RADIUS.into(),
},
width: match self {
ButtonType::Starred
| ButtonType::TabActive
| ButtonType::SortArrows
| ButtonType::SortArrowActive
| ButtonType::TabInactive
| ButtonType::Thumbnail
| ButtonType::BorderedRound => 0.0,
_ => BORDER_WIDTH,
},
color: match self {
ButtonType::Alert => ext.red_alert_color,
ButtonType::BorderedRound | ButtonType::NotStarred => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
ButtonType::Neutral => ext.buttons_color,
_ => colors.secondary,
},
},
text_color: match self {
ButtonType::Starred => Color::BLACK,
ButtonType::Gradient(_) | ButtonType::Thumbnail => colors.text_headers,
ButtonType::SortArrowActive | ButtonType::SortArrows => colors.secondary,
_ => colors.text_body,
},
snap: true,
}
}
fn disabled(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
match self {
ButtonType::Gradient(_) => Style {
background: Some(match self {
ButtonType::Gradient(GradientType::None) => Background::Color(Color {
a: ext.alpha_chart_badge,
..colors.secondary
}),
ButtonType::Gradient(gradient_type) => {
Background::Gradient(get_gradient_buttons(
&colors,
*gradient_type,
ext.is_nightly,
ext.alpha_chart_badge,
))
}
_ => Background::Color(ext.buttons_color),
}),
border: Border {
radius: 12.0.into(),
width: BORDER_WIDTH,
color: Color {
a: ext.alpha_chart_badge,
..colors.secondary
},
},
text_color: Color {
a: 0.5,
..colors.text_headers
},
shadow: Shadow::default(),
snap: true,
},
ButtonType::Standard => Style {
background: Some(Background::Color(Color {
a: ext.alpha_chart_badge,
..ext.buttons_color
})),
border: Border {
radius: BORDER_BUTTON_RADIUS.into(),
width: BORDER_WIDTH,
color: Color {
a: ext.alpha_chart_badge,
..colors.secondary
},
},
text_color: Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
shadow: Shadow::default(),
snap: true,
},
_ => self.active(style),
}
}
}
impl Catalog for StyleType {
type Class<'a> = ButtonType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active | Status::Pressed => class.active(self),
Status::Hovered => class.hovered(self),
Status::Disabled => class.disabled(self),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/donut.rs | src/gui/styles/donut.rs | use crate::gui::styles::types::style_type::StyleType;
use iced::Color;
#[derive(Default)]
pub enum DonutType {
#[default]
Standard,
}
impl DonutType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
let primary = colors.primary;
let buttons = ext.buttons_color;
let background = Color {
r: primary.r + (buttons.r - primary.r) * ext.alpha_round_containers,
g: primary.g + (buttons.g - primary.g) * ext.alpha_round_containers,
b: primary.b + (buttons.b - primary.b) * ext.alpha_round_containers,
a: 1.0,
};
Style {
background,
incoming: colors.secondary,
outgoing: colors.outgoing,
text_color: colors.text_body,
dropped: ext.buttons_color,
}
}
}
impl Catalog for StyleType {
type Class<'a> = DonutType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>) -> Style {
class.active(self)
}
}
pub struct Style {
pub(crate) background: Color,
pub(crate) text_color: Color,
pub(crate) incoming: Color,
pub(crate) outgoing: Color,
pub(crate) dropped: Color,
}
pub trait Catalog: Sized {
type Class<'a>;
fn default<'a>() -> Self::Class<'a>;
fn style(&self, class: &Self::Class<'_>) -> Style;
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/svg.rs | src/gui/styles/svg.rs | //! SVG style
#![allow(clippy::module_name_repetitions)]
use iced::widget::svg::{Catalog, Status, Style};
use crate::StyleType;
#[derive(Default)]
pub enum SvgType {
AdaptColor,
#[default]
Standard,
}
impl SvgType {
fn appearance(&self, style: &StyleType) -> Style {
Style {
color: match self {
SvgType::AdaptColor => Some(style.get_palette().text_body),
SvgType::Standard => None,
},
}
}
}
impl Catalog for StyleType {
type Class<'a> = SvgType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Idle | Status::Hovered => class.appearance(self),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/style_constants.rs | src/gui/styles/style_constants.rs | //! Module defining the constants used for aesthetic purposes (colors, borders...)
use iced::font::{Family, Stretch, Style, Weight};
use iced::{Color, Font};
use std::time::Duration;
use crate::gui::sniffer::{FONT_FAMILY_NAME, ICON_FONT_FAMILY_NAME};
// main font
pub const SARASA_MONO_BYTES: &[u8] =
include_bytes!("../../../resources/fonts/subset/sarasa-mono-sc-regular.subset.ttf");
pub const SARASA_MONO: Font = Font {
family: Family::Name(FONT_FAMILY_NAME),
weight: Weight::Normal,
stretch: Stretch::Normal,
style: Style::Normal,
};
//font to display icons
pub const ICONS_BYTES: &[u8] = include_bytes!("../../../resources/fonts/subset/icons.ttf");
pub const ICONS: Font = Font::with_name(ICON_FONT_FAMILY_NAME);
// font sizes
pub const FONT_SIZE_FOOTER: f32 = 14.3;
pub const FONT_SIZE_BODY: f32 = 16.8;
pub const FONT_SIZE_SUBTITLE: f32 = 18.3;
pub const FONT_SIZE_TITLE: f32 = 19.9;
// border styles
pub const BORDER_WIDTH: f32 = 2.0;
pub const CHARTS_LINE_BORDER: u32 = 1;
pub const BORDER_ROUNDED_RADIUS: f32 = 15.0;
pub const BORDER_BUTTON_RADIUS: f32 = 180.0;
// red colors for alerts
pub const RED_ALERT_COLOR_NIGHTLY: Color = Color {
r: 1.0,
g: 0.4,
b: 0.4,
a: 1.0,
};
pub const RED_ALERT_COLOR_DAILY: Color = Color {
r: 0.701_960_8,
g: 0.0,
b: 0.0,
a: 1.0,
};
// delays
pub const TOOLTIP_DELAY: Duration = Duration::from_millis(300);
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/container.rs | src/gui/styles/container.rs | //! Containers style
#![allow(clippy::module_name_repetitions)]
use iced::border::Radius;
use iced::widget::container::{Catalog, Style};
use iced::{Background, Border, Color, Shadow};
use crate::StyleType;
use crate::gui::styles::style_constants::{BORDER_ROUNDED_RADIUS, BORDER_WIDTH};
use crate::gui::styles::types::gradient_type::{GradientType, get_gradient_headers};
#[derive(Default)]
pub enum ContainerType {
#[default]
Standard,
BorderedRound,
Tooltip,
Badge,
BadgeInfo,
Palette,
Gradient(GradientType),
Modal,
Highlighted,
HighlightedOnHeader,
ModalBackground,
AdapterAddress,
}
impl ContainerType {
fn appearance(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
text_color: Some(match self {
ContainerType::Gradient(_) | ContainerType::Highlighted => colors.text_headers,
_ => colors.text_body,
}),
background: Some(match self {
ContainerType::Gradient(GradientType::None) | ContainerType::Highlighted => {
Background::Color(colors.secondary)
}
ContainerType::Tooltip => Background::Color(ext.buttons_color),
ContainerType::BorderedRound => Background::Color(Color {
a: ext.alpha_round_containers,
..ext.buttons_color
}),
ContainerType::Badge | ContainerType::BadgeInfo => Background::Color(Color {
a: ext.alpha_chart_badge,
..colors.secondary
}),
ContainerType::Gradient(gradient_type) => Background::Gradient(
get_gradient_headers(&colors, *gradient_type, ext.is_nightly),
),
ContainerType::Modal | ContainerType::HighlightedOnHeader => {
Background::Color(colors.primary)
}
ContainerType::Standard | ContainerType::Palette => {
Background::Color(Color::TRANSPARENT)
}
ContainerType::ModalBackground => Background::Color(Color {
a: 0.75,
..Color::BLACK
}),
ContainerType::AdapterAddress => Background::Color(Color {
a: if ext.is_nightly { 0.4 } else { 0.7 },
..ext.buttons_color
}),
}),
border: Border {
radius: match self {
ContainerType::BorderedRound => BORDER_ROUNDED_RADIUS.into(),
ContainerType::Modal => Radius::new(0).bottom(BORDER_ROUNDED_RADIUS),
ContainerType::Tooltip => 7.0.into(),
ContainerType::Badge
| ContainerType::AdapterAddress
| ContainerType::BadgeInfo
| ContainerType::Highlighted
| ContainerType::HighlightedOnHeader => 100.0.into(),
_ => 0.0.into(),
},
width: match self {
ContainerType::Standard
| ContainerType::ModalBackground
| ContainerType::Gradient(_)
| ContainerType::HighlightedOnHeader
| ContainerType::Highlighted => 0.0,
ContainerType::Tooltip => BORDER_WIDTH / 2.0,
ContainerType::BorderedRound => BORDER_WIDTH * 2.0,
_ => BORDER_WIDTH,
},
color: match self {
ContainerType::AdapterAddress => colors.primary,
ContainerType::Palette => Color::BLACK,
ContainerType::BadgeInfo => colors.secondary,
ContainerType::Modal => ext.buttons_color,
_ => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
},
},
shadow: Shadow::default(),
snap: true,
}
}
}
impl Catalog for StyleType {
type Class<'a> = ContainerType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>) -> Style {
class.appearance(self)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/text_input.rs | src/gui/styles/text_input.rs | //! Text Input style
#![allow(clippy::module_name_repetitions)]
use iced::widget::text_input::{Catalog, Status, Style};
use iced::{Background, Border, Color};
use crate::StyleType;
use crate::gui::styles::style_constants::BORDER_WIDTH;
#[derive(Default)]
pub enum TextInputType {
#[default]
Standard,
Badge,
// Error,
}
const TEXT_INPUT_BORDER_RADIUS: f32 = 5.0;
impl TextInputType {
fn active(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(match self {
TextInputType::Badge => Color::TRANSPARENT,
// TextInputType::Error |
TextInputType::Standard => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
}),
border: Border {
radius: TEXT_INPUT_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: match self {
TextInputType::Badge => Color::TRANSPARENT,
TextInputType::Standard => ext.buttons_color,
// TextInputType::Error => ext.red_alert_color,
},
},
icon: Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
placeholder: self.placeholder_color(style),
value: self.value_color(style),
selection: self.selection_color(style),
}
}
fn focused(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(colors.primary),
border: Border {
radius: TEXT_INPUT_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: colors.secondary, // match self {
// TextInputType::Error => ext.red_alert_color,
// _ => colors.secondary,
// },
},
icon: Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
placeholder: self.placeholder_color(style),
value: self.value_color(style),
selection: self.selection_color(style),
}
}
#[allow(clippy::unused_self)]
fn placeholder_color(&self, style: &StyleType) -> Color {
let color = style.get_palette().text_body;
let ext = style.get_extension();
Color {
a: ext.alpha_chart_badge,
..color
}
}
#[allow(clippy::unused_self)]
fn value_color(&self, style: &StyleType) -> Color {
style.get_palette().text_body
}
#[allow(clippy::unused_self)]
fn disabled_color(&self, style: &StyleType) -> Color {
let color = style.get_palette().text_body;
let ext = style.get_extension();
Color {
a: ext.alpha_chart_badge,
..color
}
}
#[allow(clippy::unused_self)]
fn selection_color(&self, style: &StyleType) -> Color {
let color = style.get_palette().text_body;
Color { a: 0.2, ..color }
}
fn hovered(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(match self {
TextInputType::Badge => Color::TRANSPARENT,
// TextInputType::Error |
TextInputType::Standard => ext.buttons_color,
}),
border: Border {
radius: TEXT_INPUT_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: colors.secondary, // match self {
// TextInputType::Error => ext.red_alert_color,
// _ => colors.secondary,
// },
},
icon: Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
placeholder: self.placeholder_color(style),
value: self.value_color(style),
selection: self.selection_color(style),
}
}
fn disabled(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(match self {
TextInputType::Badge => Color::TRANSPARENT,
// TextInputType::Error |
TextInputType::Standard => Color {
a: ext.alpha_round_containers,
..ext.buttons_color
},
}),
border: Border {
radius: TEXT_INPUT_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: match self {
TextInputType::Badge => Color::TRANSPARENT,
TextInputType::Standard => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
// TextInputType::Error => Color {
// a: ext.alpha_round_borders,
// ..ext.red_alert_color
// },
},
},
icon: Color {
a: ext.alpha_chart_badge,
..colors.text_body
},
placeholder: self.disabled_color(style),
value: self.disabled_color(style),
selection: self.disabled_color(style),
}
}
}
impl Catalog for StyleType {
type Class<'a> = TextInputType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active => class.active(self),
Status::Hovered => class.hovered(self),
Status::Disabled => class.disabled(self),
Status::Focused { .. } => class.focused(self),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/slider.rs | src/gui/styles/slider.rs | //! Slider style
#![allow(clippy::module_name_repetitions)]
use iced::widget::slider::Style;
use iced::widget::slider::{Catalog, Handle, HandleShape, Rail, Status};
use iced::{Background, Border};
use crate::StyleType;
use crate::gui::styles::style_constants::{BORDER_ROUNDED_RADIUS, BORDER_WIDTH};
use crate::gui::styles::types::palette::mix_colors;
#[derive(Default)]
pub enum SliderType {
#[default]
Standard,
}
impl SliderType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
rail: Rail {
backgrounds: (
Background::Color(mix_colors(colors.secondary, ext.buttons_color)),
Background::Color(ext.buttons_color),
),
width: 3.0,
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
..Default::default()
},
},
handle: Handle {
shape: HandleShape::Circle { radius: 5.5 },
background: Background::Color(mix_colors(colors.secondary, ext.buttons_color)),
border_width: 0.0,
border_color: colors.secondary,
},
}
}
#[allow(clippy::unused_self)]
fn hovered(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
rail: Rail {
backgrounds: (
Background::Color(colors.secondary),
Background::Color(ext.buttons_color),
),
width: 3.0,
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
..Default::default()
},
},
handle: Handle {
shape: HandleShape::Circle { radius: 8.0 },
background: Background::Color(colors.secondary),
border_width: 0.0,
border_color: colors.secondary,
},
}
}
#[allow(clippy::unused_self)]
fn dragging(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
rail: Rail {
backgrounds: (
Background::Color(colors.secondary),
Background::Color(ext.buttons_color),
),
width: 3.0,
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
..Default::default()
},
},
handle: Handle {
shape: HandleShape::Circle { radius: 8.0 },
background: Background::Color(colors.secondary),
border_width: BORDER_WIDTH,
border_color: mix_colors(colors.secondary, ext.buttons_color),
},
}
}
}
impl Catalog for StyleType {
type Class<'a> = SliderType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active => class.active(self),
Status::Hovered => class.hovered(self),
Status::Dragged => class.dragging(self),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/toggler.rs | src/gui/styles/toggler.rs | //! Toggler style
#![allow(clippy::module_name_repetitions)]
use iced::widget::toggler::{Catalog, Status, Style};
use iced::{Background, Color};
use crate::StyleType;
use crate::gui::styles::style_constants::BORDER_WIDTH;
#[derive(Default)]
pub enum TogglerType {
#[default]
Standard,
}
impl TogglerType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType, is_active: bool) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
let bg_color = if is_active {
Color {
a: ext.alpha_chart_badge,
..colors.secondary
}
} else {
ext.buttons_color
};
Style {
background: Background::Color(bg_color),
background_border_width: BORDER_WIDTH,
background_border_color: bg_color,
foreground: Background::Color(colors.primary),
foreground_border_width: BORDER_WIDTH,
foreground_border_color: if is_active {
colors.secondary
} else {
Color::TRANSPARENT
},
text_color: None,
border_radius: None,
padding_ratio: 0.1,
}
}
#[allow(clippy::unused_self)]
fn hovered(&self, style: &StyleType, is_active: bool) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
let bg_color = if is_active {
Color {
a: ext.alpha_chart_badge,
..colors.secondary
}
} else {
ext.buttons_color
};
Style {
background: Background::Color(bg_color),
background_border_width: BORDER_WIDTH,
background_border_color: colors.secondary,
foreground: Background::Color(colors.primary),
foreground_border_width: BORDER_WIDTH,
foreground_border_color: if is_active {
colors.secondary
} else {
Color::TRANSPARENT
},
text_color: None,
border_radius: None,
padding_ratio: 0.1,
}
}
}
impl Catalog for StyleType {
type Class<'a> = TogglerType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active { is_toggled } | Status::Disabled { is_toggled } => {
class.active(self, is_toggled)
}
Status::Hovered { is_toggled } => class.hovered(self, is_toggled),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/picklist.rs | src/gui/styles/picklist.rs | //! Picklists style
#![allow(clippy::module_name_repetitions)]
use iced::widget::pick_list::{Catalog, Status, Style};
use iced::{Background, Border, Color, Shadow};
use crate::StyleType;
use crate::gui::styles::style_constants::BORDER_WIDTH;
use crate::gui::styles::types::palette::mix_colors;
#[derive(Default)]
pub enum PicklistType {
#[default]
Standard,
}
const PICKLIST_BORDER_RADIUS: f32 = 8.0;
impl PicklistType {
#[allow(clippy::unused_self)]
fn appearance(&self, style: &StyleType) -> iced::overlay::menu::Style {
let colors = style.get_palette();
let ext = style.get_extension();
iced::overlay::menu::Style {
text_color: colors.text_body,
background: Background::Color(mix_colors(ext.buttons_color, colors.primary)),
border: Border {
width: BORDER_WIDTH,
radius: PICKLIST_BORDER_RADIUS.into(),
color: colors.secondary,
},
selected_text_color: colors.text_body,
selected_background: Background::Color(ext.buttons_color),
shadow: Shadow::default(),
}
}
}
impl PicklistType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
text_color: colors.text_body,
placeholder_color: colors.text_body,
handle_color: colors.text_body,
background: Background::Color(mix_colors(ext.buttons_color, colors.primary)),
border: Border {
radius: PICKLIST_BORDER_RADIUS.into(),
width: 0.0,
color: Color::TRANSPARENT,
},
}
}
#[allow(clippy::unused_self)]
fn hovered(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
text_color: colors.text_body,
placeholder_color: colors.text_body,
handle_color: colors.text_body,
background: Background::Color(ext.buttons_color),
border: Border {
radius: PICKLIST_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: colors.secondary,
},
}
}
}
impl iced::overlay::menu::Catalog for StyleType {
type Class<'a> = PicklistType;
fn default<'a>() -> <Self as iced::overlay::menu::Catalog>::Class<'a> {
<Self as iced::overlay::menu::Catalog>::Class::default()
}
fn style(
&self,
class: &<Self as iced::overlay::menu::Catalog>::Class<'_>,
) -> iced::overlay::menu::Style {
class.appearance(self)
}
}
impl Catalog for StyleType {
type Class<'a> = PicklistType;
fn default<'a>() -> <Self as Catalog>::Class<'a> {
<Self as Catalog>::Class::default()
}
fn style(&self, class: &<Self as Catalog>::Class<'_>, status: Status) -> Style {
match status {
Status::Active => class.active(self),
Status::Hovered | Status::Opened { .. } => class.hovered(self),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/text.rs | src/gui/styles/text.rs | //! Text style
#![allow(clippy::module_name_repetitions)]
use crate::StyleType;
use crate::gui::types::message::Message;
use iced::Color;
use iced::widget::text::{Catalog, Style};
use iced::widget::{Column, Text};
#[derive(Copy, Clone, Default, PartialEq)]
pub enum TextType {
#[default]
Standard,
Incoming,
Outgoing,
Title,
Subtitle,
Danger,
Sponsor,
Welcome(f32),
}
/// Returns a formatted caption followed by subtitle, new line, tab, and desc
impl TextType {
pub fn highlighted_subtitle_with_desc<'a>(
subtitle: &str,
desc: &str,
) -> Column<'a, Message, StyleType> {
Column::new()
.push(Text::new(format!("{subtitle}:")).class(TextType::Subtitle))
.push(Text::new(format!(" {desc}")))
}
fn appearance(self, style: &StyleType) -> Style {
Style {
color: if self == TextType::Standard {
None
} else {
Some(highlight(style, self))
},
}
}
}
pub fn highlight(style: &StyleType, element: TextType) -> Color {
let colors = style.get_palette();
let ext = style.get_extension();
let secondary = colors.secondary;
let is_nightly = style.get_extension().is_nightly;
match element {
TextType::Title => {
let (p1, c) = if is_nightly { (0.6, 1.0) } else { (0.9, 0.7) };
Color {
r: c * (1.0 - p1) + secondary.r * p1,
g: c * (1.0 - p1) + secondary.g * p1,
b: c * (1.0 - p1) + secondary.b * p1,
a: 1.0,
}
}
TextType::Subtitle => {
let (p1, c) = if is_nightly { (0.4, 1.0) } else { (0.6, 0.7) };
Color {
r: c * (1.0 - p1) + secondary.r * p1,
g: c * (1.0 - p1) + secondary.g * p1,
b: c * (1.0 - p1) + secondary.b * p1,
a: 1.0,
}
}
TextType::Welcome(mut n) => {
if !(0.0..=1.0).contains(&n) {
n = 1.0;
}
Color { a: n, ..secondary }
}
TextType::Incoming => colors.secondary,
TextType::Outgoing => colors.outgoing,
TextType::Danger | TextType::Sponsor => ext.red_alert_color,
TextType::Standard => colors.text_body,
}
}
impl Catalog for StyleType {
type Class<'a> = TextType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>) -> Style {
class.appearance(self)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/mod.rs | src/gui/styles/mod.rs | pub mod button;
pub mod checkbox;
pub mod combobox;
pub mod container;
pub mod custom_themes;
pub mod donut;
pub mod picklist;
pub mod radio;
pub mod rule;
pub mod scrollbar;
pub mod slider;
pub mod style_constants;
pub mod svg;
pub mod text;
pub mod text_input;
mod toggler;
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/gui/styles/radio.rs | src/gui/styles/radio.rs | // //! Radios style
//
// #![allow(clippy::module_name_repetitions)]
//
// use iced::Background;
//
// use crate::gui::styles::style_constants::BORDER_WIDTH;
// use crate::StyleType;
//
// #[derive(Default)]
// pub enum RadioType {
// #[default]
// Standard,
// }
//
// impl iced::widget::radio::StyleSheet for StyleType {
// type Style = RadioType;
//
// fn active(&self, _: &Self::Style, is_selected: bool) -> iced::widget::radio::Appearance {
// let colors = self.get_palette();
// let ext = self.get_extension();
// iced::widget::radio::Appearance {
// background: Background::Color(ext.buttons_color),
// dot_color: colors.secondary,
// border_width: if is_selected { BORDER_WIDTH } else { 0.0 },
// border_color: colors.secondary,
// text_color: None,
// }
// }
//
// fn hovered(&self, _: &Self::Style, _is_selected: bool) -> iced::widget::radio::Appearance {
// let colors = self.get_palette();
// let ext = self.get_extension();
// iced::widget::radio::Appearance {
// background: Background::Color(ext.buttons_color),
// dot_color: colors.secondary,
// border_width: BORDER_WIDTH,
// border_color: colors.secondary,
// text_color: None,
// }
// }
// }
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/checkbox.rs | src/gui/styles/checkbox.rs | //! Checkbox style
#![allow(clippy::module_name_repetitions)]
use iced::widget::checkbox::{Catalog, Status, Style};
use iced::{Background, Border};
use crate::StyleType;
use crate::gui::styles::style_constants::BORDER_WIDTH;
#[derive(Default)]
pub enum CheckboxType {
#[default]
Standard,
}
const CHECKBOX_BORDER_RADIUS: f32 = 5.0;
impl CheckboxType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType, is_checked: bool) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(ext.buttons_color),
icon_color: colors.text_body,
border: Border {
radius: CHECKBOX_BORDER_RADIUS.into(),
width: if is_checked { BORDER_WIDTH } else { 0.0 },
color: colors.secondary,
},
text_color: None,
}
}
#[allow(clippy::unused_self)]
fn hovered(&self, style: &StyleType, _is_checked: bool) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
background: Background::Color(ext.buttons_color),
icon_color: colors.text_body,
border: Border {
radius: CHECKBOX_BORDER_RADIUS.into(),
width: BORDER_WIDTH,
color: colors.secondary,
},
text_color: None,
}
}
}
impl Catalog for StyleType {
type Class<'a> = CheckboxType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active { is_checked } | Status::Disabled { is_checked } => {
class.active(self, is_checked)
}
Status::Hovered { is_checked } => class.hovered(self, is_checked),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/rule.rs | src/gui/styles/rule.rs | //! Rule style
#![allow(clippy::module_name_repetitions)]
use crate::StyleType;
use crate::gui::types::message::Message;
use iced::widget::rule::{Catalog, FillMode, Style};
use iced::widget::{Container, rule};
use iced::{Alignment, Color, Length};
#[derive(Default)]
pub enum RuleType {
#[default]
Standard,
PaletteColor(Color),
Incoming,
Outgoing,
Dropped,
}
impl RuleType {
fn appearance(&self, style: &StyleType) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
Style {
color: match self {
RuleType::Incoming => colors.secondary,
RuleType::Outgoing => colors.outgoing,
RuleType::PaletteColor(color) => *color,
RuleType::Dropped => ext.buttons_color,
RuleType::Standard => Color {
a: ext.alpha_round_borders,
..ext.buttons_color
},
},
radius: 0.0.into(),
fill_mode: FillMode::Full,
snap: true,
}
}
fn thickness(&self) -> u32 {
match self {
RuleType::Standard => 3,
RuleType::PaletteColor(_) => 25,
RuleType::Dropped | RuleType::Incoming | RuleType::Outgoing => 5,
}
}
pub fn horizontal<'a>(self, height: impl Into<Length>) -> Container<'a, Message, StyleType> {
let rule = rule::horizontal(self.thickness()).class(self);
Container::new(rule)
.height(height)
.align_y(Alignment::Center)
}
pub fn vertical<'a>(self, width: impl Into<Length>) -> Container<'a, Message, StyleType> {
let rule = rule::vertical(self.thickness()).class(self);
Container::new(rule).width(width).align_x(Alignment::Center)
}
}
impl Catalog for StyleType {
type Class<'a> = RuleType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>) -> Style {
class.appearance(self)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/scrollbar.rs | src/gui/styles/scrollbar.rs | //! Scrollbars style
#![allow(clippy::module_name_repetitions)]
use iced::widget::container;
use iced::widget::scrollable::{AutoScroll, Catalog, Rail, Status, Style};
use iced::widget::scrollable::{Scrollbar, Scroller};
use iced::{Background, Border, Color, Shadow};
use crate::StyleType;
use crate::gui::styles::style_constants::BORDER_ROUNDED_RADIUS;
use crate::gui::styles::types::palette::mix_colors;
#[derive(Default)]
pub enum ScrollbarType {
#[default]
Standard,
}
impl ScrollbarType {
#[allow(clippy::unused_self)]
fn active(&self, style: &StyleType) -> Style {
let ext = style.get_extension();
let rail = Rail {
background: Some(Background::Color(Color::TRANSPARENT)),
scroller: Scroller {
background: Background::Color(Color {
a: ext.alpha_round_borders,
..ext.buttons_color
}),
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
width: 0.0,
color: Color::TRANSPARENT,
},
},
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
width: 0.0,
color: Color::TRANSPARENT,
},
};
Style {
container: container::Style::default(),
vertical_rail: rail,
horizontal_rail: rail,
gap: None,
auto_scroll: AutoScroll {
background: Background::Color(Color::TRANSPARENT),
border: Border::default(),
shadow: Shadow::default(),
icon: Color::default(),
},
}
}
#[allow(clippy::unused_self)]
fn hovered(&self, style: &StyleType, is_mouse_over_x: bool, is_mouse_over_y: bool) -> Style {
let colors = style.get_palette();
let ext = style.get_extension();
let [horizontal_rail, vertical_rail] =
[is_mouse_over_x, is_mouse_over_y].map(|is_over| Rail {
background: Some(Background::Color(Color {
a: ext.alpha_round_borders,
..ext.buttons_color
})),
scroller: Scroller {
background: Background::Color(if is_over {
colors.secondary
} else {
mix_colors(colors.secondary, ext.buttons_color)
}),
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
width: 0.0,
color: Color::TRANSPARENT,
},
},
border: Border {
radius: BORDER_ROUNDED_RADIUS.into(),
width: 0.0,
color: Color::TRANSPARENT,
},
});
Style {
container: container::Style::default(),
vertical_rail,
horizontal_rail,
gap: None,
auto_scroll: AutoScroll {
background: Background::Color(Color::TRANSPARENT),
border: Border::default(),
shadow: Shadow::default(),
icon: Color::default(),
},
}
}
pub fn properties() -> Scrollbar {
Scrollbar::new().width(5).scroller_width(5).margin(3)
}
}
impl Catalog for StyleType {
type Class<'a> = ScrollbarType;
fn default<'a>() -> Self::Class<'a> {
Self::Class::default()
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
match status {
Status::Active { .. } => class.active(self),
Status::Hovered {
is_horizontal_scrollbar_hovered,
is_vertical_scrollbar_hovered,
..
} => class.hovered(
self,
is_horizontal_scrollbar_hovered,
is_vertical_scrollbar_hovered,
),
Status::Dragged {
is_horizontal_scrollbar_dragged,
is_vertical_scrollbar_dragged,
..
} => class.hovered(
self,
is_horizontal_scrollbar_dragged,
is_vertical_scrollbar_dragged,
),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/combobox.rs | src/gui/styles/combobox.rs | //! Combobox style
#![allow(clippy::module_name_repetitions)]
use iced::widget::combo_box::Catalog;
use crate::StyleType;
impl Catalog for StyleType {}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/dracula.rs | src/gui/styles/custom_themes/dracula.rs | #![allow(clippy::unreadable_literal)]
//! Dracula theme
//! <https://draculatheme.com/>
//! Light style from: <https://github.com/AshGrowem/Dracula.min/>
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
pub static DRACULA_DARK_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0x282a36), // Background
secondary: color!(0xff79c6), // Pink
outgoing: color!(0x8be9fd), // Cyan
starred: color!(0xf1fa8c, 0.7),
text_headers: color!(0x282a36), // Background
text_body: color!(0xf8f8f2), // Foreground
});
pub static DRACULA_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| DRACULA_DARK_PALETTE.generate_palette_extension());
// Light Darker variant
pub static DRACULA_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xf8f8f2),
secondary: color!(0x9f1670),
outgoing: color!(0x005d6f),
starred: color!(0xffb86c),
text_headers: color!(0xf8f8f2),
text_body: color!(0x282a36),
});
pub static DRACULA_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| DRACULA_LIGHT_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/nord.rs | src/gui/styles/custom_themes/nord.rs | #![allow(clippy::unreadable_literal)]
//! Nord theme
//! <https://www.nordtheme.com/docs/colors-and-palettes>
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
pub static NORD_DARK_PALETTE: std::sync::LazyLock<Palette> = std::sync::LazyLock::new(|| Palette {
primary: color!(0x2e3440), // nord0
secondary: color!(0x88c0d0), // nord8
outgoing: color!(0xB48EAD), // nord15
starred: color!(0xebcb8b), // nord13
text_headers: color!(0x2e3440), // nord0
text_body: color!(0xd8dee9), // nord4
});
pub static NORD_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| NORD_DARK_PALETTE.generate_palette_extension());
pub static NORD_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xeceff4), // nord6
secondary: color!(0x05e81ac), // nord10
outgoing: color!(0xb48ead), // nord15
starred: color!(0xD08770, 0.8), // nord12
text_headers: color!(0xeceff4), // nord6
text_body: color!(0x2e3440), // nord0
});
pub static NORD_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| NORD_LIGHT_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/yeti.rs | src/gui/styles/custom_themes/yeti.rs | #![allow(clippy::unreadable_literal)]
//! Original light and dark themes for Sniffnet
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
pub static YETI_DARK_PALETTE: std::sync::LazyLock<Palette> = std::sync::LazyLock::new(|| Palette {
primary: color!(0x282828),
secondary: color!(0xb35900),
outgoing: color!(0x0059b3),
starred: color!(0xf5c127, 0.5),
text_headers: color!(0x000000),
text_body: color!(0xffffff),
});
pub static YETI_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| YETI_DARK_PALETTE.generate_palette_extension());
pub static YETI_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xffffff),
secondary: color!(0x0059b3),
outgoing: color!(0xb35900),
starred: color!(0xd7a313, 0.9),
text_headers: color!(0xffffff),
text_body: color!(0x000000),
});
pub static YETI_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| YETI_LIGHT_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/a11y.rs | src/gui/styles/custom_themes/a11y.rs | #![allow(clippy::unreadable_literal)]
//! Themes optimized for Accessibility
//! <https://github.com/GyulyVGC/sniffnet/pull/785>
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
pub static A11Y_DARK_PALETTE: std::sync::LazyLock<Palette> = std::sync::LazyLock::new(|| Palette {
primary: color!(0x0f1e3c),
secondary: color!(0xFCB608),
outgoing: color!(0x0BB1FC),
starred: color!(0xFBFF0F),
text_headers: color!(0x081020),
text_body: color!(0xdddddd),
});
pub static A11Y_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| A11Y_DARK_PALETTE.generate_palette_extension());
pub static A11Y_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xFFFFFF),
secondary: color!(0xB30000),
outgoing: color!(0x004ECC),
starred: color!(0xC25E00),
text_headers: color!(0xFFFFFF),
text_body: color!(0x081020),
});
pub static A11Y_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| A11Y_LIGHT_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/gruvbox.rs | src/gui/styles/custom_themes/gruvbox.rs | #![allow(clippy::unreadable_literal)]
//! Gruvbox
//! <https://github.com/morhetz/gruvbox>
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
/// Gruvbox (night style)
pub static GRUVBOX_DARK_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0x282828), // bg
secondary: color!(0xfe8019), // orange
outgoing: color!(0x8ec07c), // aqua
starred: color!(0xd79921, 0.8),
text_headers: color!(0x1d2021), // bg0_h
text_body: color!(0xebdbb2), // fg
});
pub static GRUVBOX_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| GRUVBOX_DARK_PALETTE.generate_palette_extension());
/// Gruvbox (day style)
pub static GRUVBOX_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xfbf1c7), // bg
secondary: color!(0xd65d0e), // orange
outgoing: color!(0x689d6a), // aqua
starred: color!(0xd79921, 0.9), // yellow
text_headers: color!(0xf9f5d7), // bg0_h
text_body: color!(0x282828), // fg
});
pub static GRUVBOX_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| GRUVBOX_LIGHT_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/mod.rs | src/gui/styles/custom_themes/mod.rs | pub mod a11y;
pub mod dracula;
pub mod gruvbox;
pub mod nord;
pub mod solarized;
pub mod yeti;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/custom_themes/solarized.rs | src/gui/styles/custom_themes/solarized.rs | #![allow(clippy::unreadable_literal)]
//! Solarized
//! <https://ethanschoonover.com/solarized/>
use iced::color;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
/// Solarized light (Day style)
pub static SOLARIZED_LIGHT_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0xfdf6e3), // base3
secondary: color!(0x859900), // green
outgoing: color!(0x268bd2), // blue
starred: color!(0xb58900, 0.9), // yellow
text_headers: color!(0xfdf6e3), // base3
text_body: color!(0x002b36), // base03
});
pub static SOLARIZED_LIGHT_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| SOLARIZED_LIGHT_PALETTE.generate_palette_extension());
/// Solarized dark (Night style)
pub static SOLARIZED_DARK_PALETTE: std::sync::LazyLock<Palette> =
std::sync::LazyLock::new(|| Palette {
primary: color!(0x002b36), // base03
secondary: color!(0x859900), // green
outgoing: color!(0x268bd2), // blue
starred: color!(0xb58900), // yellow
text_headers: color!(0x002b36), // base03
text_body: color!(0xeee8d5), // base2
});
pub static SOLARIZED_DARK_PALETTE_EXTENSION: std::sync::LazyLock<PaletteExtension> =
std::sync::LazyLock::new(|| SOLARIZED_DARK_PALETTE.generate_palette_extension());
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/color_remote.rs | src/gui/styles/types/color_remote.rs | //! Remote implementation of [`serde::Deserialize`] and [`serde::Serialize`] for [`iced::Color`].
//!
//! This implementation deserializes hexadecimal RGB(A) as string to float RGB(A) and back.
//! NOTE: The alpha channel is optional and defaults to #ff or 1.0.
//! `#ffffffff` deserializes to `1.0`, `1.0`, `1.0`, `1.0`.
//! `1.0`, `1.0`, `1.0`, `1.0` serializes to #ffffffff
use std::hash::{Hash, Hasher};
use iced::Color;
use serde::{
Deserialize, Deserializer, Serializer,
de::{Error as DeErrorTrait, Unexpected},
};
// #aabbcc is seven bytes long
const HEX_STR_BASE_LEN: usize = 7;
// #aabbccdd is nine bytes long
const HEX_STR_ALPHA_LEN: usize = 9;
#[allow(clippy::unnecessary_wraps)]
pub(super) fn deserialize_color<'de, D>(deserializer: D) -> Result<Color, D::Error>
where
D: Deserializer<'de>,
{
Ok(deserialize_color_inner(deserializer).unwrap_or(Color::BLACK))
}
fn deserialize_color_inner<'de, D>(deserializer: D) -> Result<Color, D::Error>
where
D: Deserializer<'de>,
{
// Field should be a hex string i.e. #aabbcc
let hex = String::deserialize(deserializer)?;
// The string should be seven bytes long (octothorpe + six hex chars).
// Safety: Hexadecimal is ASCII so bytes are okay here.
let hex_len = hex.len();
if hex_len == HEX_STR_BASE_LEN || hex_len == HEX_STR_ALPHA_LEN {
let color = hex
.strip_prefix('#') // Remove the octothorpe or fail
.ok_or_else(|| {
DeErrorTrait::invalid_value(
Unexpected::Char(hex.chars().next().unwrap_or_default()),
&"#",
)
})?
// Iterating over bytes is safe because hex is ASCII.
// If the hex is not ASCII or invalid hex, then the iterator will short circuit and fail on `from_str_radix`
// TODO: This can be cleaned up when `iter_array_chunks` is stabilized (https://github.com/rust-lang/rust/issues/100450)
.bytes()
.step_by(2) // Step by every first hex char of the two char sequence
.zip(hex.bytes().skip(2).step_by(2)) // Step by every second hex char
.map(|(first, second)| {
// Parse hex strings
let maybe_hex = [first, second];
std::str::from_utf8(&maybe_hex)
.map_err(|_| {
DeErrorTrait::invalid_value(Unexpected::Str(&hex), &"valid hexadecimal")
})
.and_then(|s| {
u8::from_str_radix(s, 16)
.map_err(DeErrorTrait::custom)
.map(|rgb| f32::from(rgb) / 255.0)
})
})
.collect::<Result<Vec<f32>, _>>()?;
// Alpha isn't always part of the color scheme. The resulting Vec should always have at least three elements.
// Accessing the first three elements without [slice::get] is okay because I checked the length of the hex string earlier.
Ok(Color {
r: color[0],
g: color[1],
b: color[2],
a: *color.get(3).unwrap_or(&1.0),
})
} else {
Err(DeErrorTrait::invalid_length(
hex_len,
&&*format!("{HEX_STR_BASE_LEN} or {HEX_STR_ALPHA_LEN}"),
))
}
}
/// Hash delegate for [`iced::Color`] that hashes RGBA in lieu of floats.
#[inline]
pub(super) fn color_hash<H: Hasher>(color: Color, state: &mut H) {
// Hash isn't implemented for floats, so I hash the color as RGBA instead.
let color = color.into_rgba8();
color.hash(state);
}
/// Serialize [`iced::Color`] as a hex string.
#[inline]
pub(super) fn serialize_color<S>(color: &Color, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// iced::Color to [u8; 4]
let color = color.into_rgba8();
// [u8; 4] to hex string, precluding the alpha if it's 0xff.
let hex_color = if color[3] == 255 {
format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])
} else {
format!(
"#{:02x}{:02x}{:02x}{:02x}",
color[0], color[1], color[2], color[3]
)
};
// Serialize the hex string
serializer.serialize_str(&hex_color)
}
#[cfg(test)]
mod tests {
use iced::Color;
use serde::{Deserialize, Serialize};
use serde_test::{Token, assert_de_tokens, assert_tokens};
use super::{deserialize_color, serialize_color};
// https://github.com/catppuccin/catppuccin
const CATPPUCCIN_PINK_HEX: &str = "#f5c2e7";
const CATPPUCCIN_PINK: Color = Color {
r: 245.0 / 255.0,
g: 194.0 / 255.0,
b: 231.0 / 255.0,
a: 1.0,
};
const CATPPUCCIN_PINK_HEX_ALPHA: &str = "#f5c2e780";
const CATPPUCCIN_PINK_ALPHA: Color = Color {
r: 245.0 / 255.0,
g: 194.0 / 255.0,
b: 231.0 / 255.0,
a: 128.0 / 255.0,
};
#[derive(Debug, PartialEq, Deserialize, Serialize)]
#[serde(transparent)]
struct DelegateTest {
#[serde(
flatten,
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
color: Color,
}
const CATPPUCCIN_PINK_DELEGATE: DelegateTest = DelegateTest {
color: CATPPUCCIN_PINK,
};
const CATPPUCCIN_PINK_ALPHA_DELEGATE: DelegateTest = DelegateTest {
color: CATPPUCCIN_PINK_ALPHA,
};
// Invalid hex colors
const CATPPUCCIN_PINK_NO_OCTO: &str = "%f5c2e7";
const CATPPUCCIN_PINK_TRUNCATED: &str = "#c2e7";
const CATPPUCCIN_PINK_TOO_LONG: &str = "#f5c2e7f5c2e7f5";
const INVALID_COLOR: &str = "#cal✘";
// test if deserializing and serializing a color works.
#[test]
fn test_working_color_round_trip() {
assert_tokens(
&CATPPUCCIN_PINK_DELEGATE,
&[Token::Str(CATPPUCCIN_PINK_HEX)],
);
}
// test if deserializing and serializing a color with an alpha channel works.
#[test]
fn test_working_color_with_alpha_round_trip() {
assert_tokens(
&CATPPUCCIN_PINK_ALPHA_DELEGATE,
&[Token::Str(CATPPUCCIN_PINK_HEX_ALPHA)],
);
}
// missing octothorpe should fail -> use Color::BLACK
#[test]
fn test_no_octothrope_color_rt() {
assert_de_tokens(
&DelegateTest {
color: Color::BLACK,
},
&[Token::Str(CATPPUCCIN_PINK_NO_OCTO)],
);
}
// a hex color that is missing components should fail -> use Color::BLACK
#[test]
fn test_len_too_small_color_de() {
assert_de_tokens(
&DelegateTest {
color: Color::BLACK,
},
&[Token::Str(CATPPUCCIN_PINK_TRUNCATED)],
);
}
// a hex string that is too long should fail -> use Color::BLACK
#[test]
fn test_len_too_large_color_de() {
assert_de_tokens(
&DelegateTest {
color: Color::BLACK,
},
&[Token::Str(CATPPUCCIN_PINK_TOO_LONG)],
);
}
// invalid hexadecimal should fail -> use Color::BLACK
#[test]
fn test_invalid_hex_color_de() {
assert_de_tokens(
&DelegateTest {
color: Color::BLACK,
},
&[Token::Str(INVALID_COLOR)],
);
}
// not string should fail -> use Color::BLACK
#[test]
fn test_no_string_color_de() {
assert_de_tokens(
&DelegateTest {
color: Color::BLACK,
},
&[Token::I8(12)],
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/palette_extension.rs | src/gui/styles/types/palette_extension.rs | use std::hash::{Hash, Hasher};
use iced::Color;
use serde::{Deserialize, Serialize};
use super::color_remote::{deserialize_color, serialize_color};
use crate::gui::styles::types::color_remote::color_hash;
use crate::gui::styles::types::style_type::StyleType;
use crate::gui::types::conf::deserialize_or_default;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PaletteExtension {
#[serde(deserialize_with = "deserialize_or_default")]
pub is_nightly: bool,
#[serde(deserialize_with = "deserialize_or_default")]
pub alpha_chart_badge: f32,
#[serde(deserialize_with = "deserialize_or_default")]
pub alpha_round_borders: f32,
#[serde(deserialize_with = "deserialize_or_default")]
pub alpha_round_containers: f32,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub buttons_color: Color,
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub red_alert_color: Color,
}
impl Default for PaletteExtension {
fn default() -> Self {
<StyleType as std::default::Default>::default().get_extension()
}
}
impl Hash for PaletteExtension {
fn hash<H: Hasher>(&self, state: &mut H) {
let PaletteExtension {
is_nightly,
alpha_chart_badge,
alpha_round_borders,
alpha_round_containers,
buttons_color,
red_alert_color,
} = self;
is_nightly.hash(state);
#[allow(clippy::cast_possible_truncation)]
(997 * (alpha_chart_badge + alpha_round_borders + alpha_round_containers) as i32)
.hash(state);
color_hash(*buttons_color, state);
color_hash(*red_alert_color, state);
}
}
#[cfg(test)]
mod tests {
use iced::Color;
use serde_test::{Token, assert_tokens};
use crate::gui::styles::style_constants::RED_ALERT_COLOR_DAILY;
use crate::gui::styles::types::palette_extension::PaletteExtension;
// Test if deserializing and serializing a PaletteExtension works.
#[test]
fn test_working_palette_extension_round_trip() {
let ext = PaletteExtension {
is_nightly: false,
alpha_chart_badge: 0.5,
alpha_round_borders: 0.25,
alpha_round_containers: 0.1778,
buttons_color: Color {
r: 0.6,
g: 0.4,
b: 0.2,
a: 1.0,
},
red_alert_color: RED_ALERT_COLOR_DAILY,
};
assert_tokens(
&ext,
&[
Token::Struct {
name: "PaletteExtension",
len: 6,
},
Token::Str("is_nightly"),
Token::Bool(false),
Token::Str("alpha_chart_badge"),
Token::F32(0.5),
Token::Str("alpha_round_borders"),
Token::F32(0.25),
Token::Str("alpha_round_containers"),
Token::F32(0.1778),
Token::Str("buttons_color"),
Token::Str("#996633"),
Token::Str("red_alert_color"),
Token::Str("#b30000"),
Token::StructEnd,
],
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/palette.rs | src/gui/styles/types/palette.rs | //! Module defining the `Colors` struct, which defines the colors in use in the GUI.
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{BufReader, Read};
use std::path::Path;
use iced::Color;
use plotters::style::RGBColor;
use serde::{Deserialize, Serialize};
use super::color_remote::{deserialize_color, serialize_color};
use crate::gui::styles::style_constants::{RED_ALERT_COLOR_DAILY, RED_ALERT_COLOR_NIGHTLY};
use crate::gui::styles::types::color_remote::color_hash;
use crate::gui::styles::types::palette_extension::PaletteExtension;
use crate::gui::styles::types::style_type::StyleType;
/// Set of colors to apply to GUI
///
/// Best practices:
/// - `primary` should be a kind of neutral color
/// - `secondary` and `outgoing` should be complementary colors if possible
/// - `text_headers` should be black or white and must have a strong contrast with `secondary`
/// - `text_body` should be black or white and must have a strong contrast with `primary`
#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct Palette {
/// Main color of the GUI (background, hovered buttons, active tab)
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub primary: Color,
/// Secondary color of the GUI (incoming connections, header, footer, buttons' borders, radio selection)
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub secondary: Color,
/// Color of outgoing connections
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub outgoing: Color,
/// Color of favorites' star symbol
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub starred: Color,
/// Color of header and footer text
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub text_headers: Color,
/// Color of body and buttons text
#[serde(
deserialize_with = "deserialize_color",
serialize_with = "serialize_color"
)]
pub text_body: Color,
}
impl Palette {
pub fn generate_buttons_color(self) -> Color {
let primary = self.primary;
let is_nightly = primary.r + primary.g + primary.b <= 1.5;
if is_nightly {
Color {
r: f32::min(primary.r + 0.15, 1.0),
g: f32::min(primary.g + 0.15, 1.0),
b: f32::min(primary.b + 0.15, 1.0),
a: 1.0,
}
} else {
Color {
r: f32::max(primary.r - 0.15, 0.0),
g: f32::max(primary.g - 0.15, 0.0),
b: f32::max(primary.b - 0.15, 0.0),
a: 1.0,
}
}
}
pub fn generate_palette_extension(self) -> PaletteExtension {
let primary = self.primary;
let is_nightly = primary.r + primary.g + primary.b <= 1.5;
let alpha_chart_badge = if is_nightly { 0.3 } else { 0.5 };
let alpha_round_borders = if is_nightly { 0.3 } else { 0.6 };
let alpha_round_containers = if is_nightly { 0.12 } else { 0.24 };
let buttons_color = self.generate_buttons_color();
let red_alert_color = if is_nightly {
RED_ALERT_COLOR_NIGHTLY
} else {
RED_ALERT_COLOR_DAILY
};
PaletteExtension {
is_nightly,
alpha_chart_badge,
alpha_round_borders,
alpha_round_containers,
buttons_color,
red_alert_color,
}
}
/// Deserialize [`Palette`] from `path`.
///
/// # Arguments
/// * `path` - Path to a UTF-8 encoded file containing a custom style as TOML.
pub fn from_file<P>(path: P) -> Result<Self, toml::de::Error>
where
P: AsRef<Path>,
{
// Try to open the file at `path`
let mut toml_reader = File::open(path)
.map_err(serde::de::Error::custom)
.map(BufReader::new)?;
// Read the ostensible TOML
let mut style_toml = String::new();
toml_reader
.read_to_string(&mut style_toml)
.map_err(serde::de::Error::custom)?;
toml::de::from_str(&style_toml)
}
}
impl Default for Palette {
fn default() -> Self {
<StyleType as std::default::Default>::default().get_palette()
}
}
impl Hash for Palette {
fn hash<H: Hasher>(&self, state: &mut H) {
let Palette {
primary,
secondary,
outgoing,
starred,
text_headers,
text_body,
} = self;
color_hash(*primary, state);
color_hash(*secondary, state);
color_hash(*outgoing, state);
color_hash(*starred, state);
color_hash(*text_headers, state);
color_hash(*text_body, state);
}
}
pub fn to_rgb_color(color: Color) -> RGBColor {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
if color.r <= 1.0
&& color.r >= 0.0
&& color.g <= 1.0
&& color.g >= 0.0
&& color.b <= 1.0
&& color.b >= 0.0
{
RGBColor(
(color.r * 255.0) as u8,
(color.g * 255.0) as u8,
(color.b * 255.0) as u8,
)
} else {
RGBColor(0, 0, 0) // Black
}
}
/// Returns the average of two colors; color intensity is fixed to 100%
pub fn mix_colors(color_1: Color, color_2: Color) -> Color {
Color {
r: f32::midpoint(color_1.r, color_2.r),
g: f32::midpoint(color_1.g, color_2.g),
b: f32::midpoint(color_1.b, color_2.b),
a: 1.0,
}
}
#[cfg(test)]
mod tests {
use iced::Color;
use iced::color;
use crate::gui::styles::style_constants::{RED_ALERT_COLOR_DAILY, RED_ALERT_COLOR_NIGHTLY};
use crate::gui::styles::types::palette_extension::PaletteExtension;
use super::Palette;
fn style_path(name: &str) -> String {
format!(
"{}/resources/themes/{}.toml",
env!("CARGO_MANIFEST_DIR"),
name
)
}
// NOTE: This has to be updated if `resources/themes/catppuccin.toml` changes
fn catppuccin_style() -> Palette {
Palette {
primary: color!(0x30, 0x34, 0x46),
secondary: color!(0xa6, 0xd1, 0x89),
outgoing: color!(0xf4, 0xb8, 0xe4),
starred: color!(0xe5, 0xc8, 0x90, 0.6666667),
text_headers: color!(0x23, 0x26, 0x34),
text_body: color!(0xc6, 0xd0, 0xf5),
}
}
#[test]
fn custompalette_from_file_de() -> Result<(), toml::de::Error> {
let style = catppuccin_style();
let style_de = Palette::from_file(style_path("catppuccin"))?;
assert_eq!(style, style_de);
Ok(())
}
#[test]
fn test_generate_palette_extension_dark() {
let palette = Palette {
primary: Color {
r: 1.0,
g: 0.4,
b: 0.05,
a: 1.0,
},
secondary: Color {
r: 0.7,
g: 0.9,
b: 0.5,
a: 1.0,
},
outgoing: Color {
r: 0.9,
g: 0.5,
b: 0.7,
a: 1.0,
},
starred: Color {
r: 0.5,
g: 0.5,
b: 0.5,
a: 0.5,
},
text_headers: Color {
r: 0.0,
g: 0.2,
b: 0.2,
a: 1.0,
},
text_body: Color {
r: 0.5,
g: 0.5,
b: 0.51,
a: 1.0,
},
};
assert_eq!(
palette.generate_palette_extension(),
PaletteExtension {
is_nightly: true,
alpha_chart_badge: 0.3,
alpha_round_borders: 0.3,
alpha_round_containers: 0.12,
buttons_color: Color {
r: 1.0,
g: 0.55,
b: 0.2,
a: 1.0
},
red_alert_color: RED_ALERT_COLOR_NIGHTLY,
}
)
}
#[test]
fn test_generate_palette_extension_light() {
let palette = Palette {
primary: Color {
r: 1.0,
g: 0.9,
b: 0.05,
a: 1.0,
},
secondary: Color {
r: 0.7,
g: 0.9,
b: 0.5,
a: 1.0,
},
outgoing: Color {
r: 0.9,
g: 0.5,
b: 0.7,
a: 1.0,
},
starred: Color {
r: 0.5,
g: 0.5,
b: 0.5,
a: 0.5,
},
text_headers: Color {
r: 0.7,
g: 0.2,
b: 0.2,
a: 1.0,
},
text_body: Color {
r: 1.0,
g: 0.9,
b: 0.4,
a: 1.0,
},
};
assert_eq!(
palette.generate_palette_extension(),
PaletteExtension {
is_nightly: false,
alpha_chart_badge: 0.5,
alpha_round_borders: 0.6,
alpha_round_containers: 0.24,
buttons_color: Color {
r: 0.85,
g: 0.75,
b: 0.0,
a: 1.0
},
red_alert_color: RED_ALERT_COLOR_DAILY,
}
)
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/gradient_type.rs | src/gui/styles/types/gradient_type.rs | use iced::{Color, Degrees, Gradient};
use serde::{Deserialize, Serialize};
use crate::gui::styles::types::palette::{Palette, mix_colors};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default, Serialize, Deserialize)]
pub enum GradientType {
/// A harmonious color gradient
Mild,
/// A crazy yet good-looking color gradient
Wild,
/// No gradient applied
#[default]
None,
}
pub fn get_gradient_headers(
colors: &Palette,
gradient_type: GradientType,
is_nightly: bool,
) -> Gradient {
let mix = if is_nightly {
Color::BLACK
} else {
Color::WHITE
};
Gradient::Linear(
iced::gradient::Linear::new(Degrees(90.0))
.add_stop(
0.0,
match gradient_type {
GradientType::Mild => mix_colors(mix, colors.secondary),
GradientType::Wild => colors.outgoing,
GradientType::None => colors.secondary,
},
)
.add_stop(0.3, colors.secondary)
.add_stop(0.7, colors.secondary)
.add_stop(
1.0,
match gradient_type {
GradientType::Mild => mix_colors(mix, colors.secondary),
GradientType::Wild => colors.outgoing,
GradientType::None => colors.secondary,
},
),
)
}
pub fn get_gradient_buttons(
colors: &Palette,
gradient_type: GradientType,
is_nightly: bool,
alpha: f32,
) -> Gradient {
let mix = if is_nightly {
Color::BLACK
} else {
Color::WHITE
};
Gradient::Linear(
iced::gradient::Linear::new(Degrees(135.0))
.add_stop(
0.0,
Color {
a: alpha,
..match gradient_type {
GradientType::Mild => mix_colors(mix, colors.secondary),
GradientType::Wild => colors.outgoing,
GradientType::None => colors.secondary,
}
},
)
.add_stop(
1.0,
Color {
a: alpha,
..colors.secondary
},
),
)
}
pub fn get_gradient_hovered_buttons(
colors: &Palette,
gradient_type: GradientType,
is_nightly: bool,
) -> Gradient {
let mix = if is_nightly {
Color::BLACK
} else {
Color::WHITE
};
Gradient::Linear(
iced::gradient::Linear::new(Degrees(135.0))
.add_stop(0.0, colors.secondary)
.add_stop(
1.0,
match gradient_type {
GradientType::Mild => mix_colors(mix, colors.secondary),
GradientType::Wild => colors.outgoing,
GradientType::None => colors.secondary,
},
),
)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/style_type.rs | src/gui/styles/types/style_type.rs | use crate::gui::styles::custom_themes::a11y::{
A11Y_DARK_PALETTE, A11Y_DARK_PALETTE_EXTENSION, A11Y_LIGHT_PALETTE,
A11Y_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::custom_themes::dracula::{
DRACULA_DARK_PALETTE, DRACULA_DARK_PALETTE_EXTENSION, DRACULA_LIGHT_PALETTE,
DRACULA_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::custom_themes::gruvbox::{
GRUVBOX_DARK_PALETTE, GRUVBOX_DARK_PALETTE_EXTENSION, GRUVBOX_LIGHT_PALETTE,
GRUVBOX_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::custom_themes::nord::{
NORD_DARK_PALETTE, NORD_DARK_PALETTE_EXTENSION, NORD_LIGHT_PALETTE,
NORD_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::custom_themes::solarized::{
SOLARIZED_DARK_PALETTE, SOLARIZED_DARK_PALETTE_EXTENSION, SOLARIZED_LIGHT_PALETTE,
SOLARIZED_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::custom_themes::yeti::{
YETI_DARK_PALETTE, YETI_DARK_PALETTE_EXTENSION, YETI_LIGHT_PALETTE,
YETI_LIGHT_PALETTE_EXTENSION,
};
use crate::gui::styles::types::custom_palette::CustomPalette;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
use iced::theme::{Base, Mode, Style};
use serde::{Deserialize, Serialize};
use std::fmt;
/// Used to specify the kind of style of the application
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Hash, PartialEq, Default)]
#[serde(tag = "style", content = "attributes")]
#[allow(clippy::large_enum_variant)]
pub enum StyleType {
#[default]
A11yDark,
A11yLight,
DraculaDark,
DraculaLight,
GruvboxDark,
GruvboxLight,
NordDark,
NordLight,
SolarizedDark,
SolarizedLight,
YetiDark,
YetiLight,
Custom(CustomPalette),
}
impl Base for StyleType {
fn default(preference: Mode) -> Self {
match preference {
Mode::Light => Self::A11yLight,
_ => Self::A11yDark,
}
}
fn mode(&self) -> Mode {
if self.get_extension().is_nightly {
Mode::Dark
} else {
Mode::Light
}
}
fn base(&self) -> Style {
let colors = self.get_palette();
Style {
background_color: colors.primary,
text_color: colors.text_body,
}
}
fn palette(&self) -> Option<iced::theme::Palette> {
None
}
fn name(&self) -> &str {
match self {
Self::A11yDark => "A11y Dark",
Self::A11yLight => "A11y Light",
Self::DraculaDark => "Dracula Dark",
Self::DraculaLight => "Dracula Light",
Self::GruvboxDark => "Gruvbox Dark",
Self::GruvboxLight => "Gruvbox Light",
Self::NordDark => "Nord Dark",
Self::NordLight => "Nord Light",
Self::SolarizedDark => "Solarized Dark",
Self::SolarizedLight => "Solarized Light",
Self::YetiDark => "Yeti Dark",
Self::YetiLight => "Yeti Light",
Self::Custom(_) => "Custom",
}
}
}
impl StyleType {
/// [`Palette`] of the [`StyleType`] variant
pub fn get_palette(self) -> Palette {
match self {
Self::A11yDark => *A11Y_DARK_PALETTE,
Self::A11yLight => *A11Y_LIGHT_PALETTE,
Self::DraculaDark => *DRACULA_DARK_PALETTE,
Self::DraculaLight => *DRACULA_LIGHT_PALETTE,
Self::GruvboxDark => *GRUVBOX_DARK_PALETTE,
Self::GruvboxLight => *GRUVBOX_LIGHT_PALETTE,
Self::NordDark => *NORD_DARK_PALETTE,
Self::NordLight => *NORD_LIGHT_PALETTE,
Self::SolarizedDark => *SOLARIZED_DARK_PALETTE,
Self::SolarizedLight => *SOLARIZED_LIGHT_PALETTE,
Self::YetiDark => *YETI_DARK_PALETTE,
Self::YetiLight => *YETI_LIGHT_PALETTE,
Self::Custom(custom_palette) => custom_palette.palette,
}
}
/// [`PaletteExtension`] of the [`StyleType`] variant
pub fn get_extension(self) -> PaletteExtension {
match self {
Self::A11yDark => *A11Y_DARK_PALETTE_EXTENSION,
Self::A11yLight => *A11Y_LIGHT_PALETTE_EXTENSION,
Self::DraculaDark => *DRACULA_DARK_PALETTE_EXTENSION,
Self::DraculaLight => *DRACULA_LIGHT_PALETTE_EXTENSION,
Self::GruvboxDark => *GRUVBOX_DARK_PALETTE_EXTENSION,
Self::GruvboxLight => *GRUVBOX_LIGHT_PALETTE_EXTENSION,
Self::NordDark => *NORD_DARK_PALETTE_EXTENSION,
Self::NordLight => *NORD_LIGHT_PALETTE_EXTENSION,
Self::SolarizedDark => *SOLARIZED_DARK_PALETTE_EXTENSION,
Self::SolarizedLight => *SOLARIZED_LIGHT_PALETTE_EXTENSION,
Self::YetiDark => *YETI_DARK_PALETTE_EXTENSION,
Self::YetiLight => *YETI_LIGHT_PALETTE_EXTENSION,
Self::Custom(custom_palette) => custom_palette.extension,
}
}
/// Slice of all implemented custom styles
pub const fn all_styles() -> &'static [Self] {
&[
Self::A11yDark,
Self::A11yLight,
Self::DraculaDark,
Self::DraculaLight,
Self::GruvboxDark,
Self::GruvboxLight,
Self::NordDark,
Self::NordLight,
Self::SolarizedDark,
Self::SolarizedLight,
Self::YetiDark,
Self::YetiLight,
]
}
}
impl fmt::Display for StyleType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::A11yLight | Self::A11yDark => write!(f, "A11y"),
Self::DraculaLight | Self::DraculaDark => write!(f, "Dracula"),
Self::GruvboxDark | Self::GruvboxLight => write!(f, "Gruvbox"),
Self::NordLight | Self::NordDark => write!(f, "Nord"),
Self::SolarizedLight | Self::SolarizedDark => write!(f, "Solarized"),
Self::YetiLight | Self::YetiDark => write!(f, "Yeti"),
Self::Custom(_) => write!(f, "Custom"),
}
}
}
#[cfg(test)]
mod tests {
use iced::{Color, color};
use serde_test::{Token, assert_tokens};
use crate::StyleType;
use crate::gui::styles::types::custom_palette::CustomPalette;
use crate::gui::styles::types::palette::Palette;
// test if deserializing and serializing a StyleType works n.1
// simple case: one of the default themes
#[test]
fn test_working_style_type_round_trip_1() {
let style = StyleType::A11yDark;
assert_tokens(
&style,
&[
Token::Struct {
name: "StyleType",
len: 1,
},
Token::Str("style"),
Token::UnitVariant {
name: "StyleType",
variant: "A11yDark",
},
Token::StructEnd,
],
);
}
// test if deserializing and serializing a StyleType works n.2
// complex case: a custom theme from a TOML file
#[test]
fn test_working_style_type_round_trip_2() {
let palette = Palette {
primary: color!(0x22, 0x22, 0x22),
secondary: color!(0xa6, 0xd1, 0x89),
outgoing: color!(0xf4, 0xb8, 0xe4),
starred: color!(0xe5, 0xc8, 0x90, 0.6666667),
text_headers: color!(0x23, 0x26, 0x34),
text_body: color!(0xc6, 0xd0, 0xf5),
};
let mut extension = palette.generate_palette_extension();
// reassigned only because of floating precision errors otherwise
extension.buttons_color = Color {
r: 0.28235295,
g: 0.28235295,
b: 0.28235295,
a: 1.0,
};
let custom_palette = CustomPalette { palette, extension };
let style = StyleType::Custom(custom_palette);
assert_tokens(
&style,
&[
Token::Struct {
name: "StyleType",
len: 2,
},
Token::Str("style"),
Token::UnitVariant {
name: "StyleType",
variant: "Custom",
},
Token::Str("attributes"),
Token::Map { len: None },
Token::Str("primary"),
Token::Str("#222222"),
Token::Str("secondary"),
Token::Str("#a6d189"),
Token::Str("outgoing"),
Token::Str("#f4b8e4"),
Token::Str("starred"),
Token::Str("#e5c890aa"),
Token::Str("text_headers"),
Token::Str("#232634"),
Token::Str("text_body"),
Token::Str("#c6d0f5"),
Token::Str("is_nightly"),
Token::Bool(true),
Token::Str("alpha_chart_badge"),
Token::F32(0.3),
Token::Str("alpha_round_borders"),
Token::F32(0.3),
Token::Str("alpha_round_containers"),
Token::F32(0.12),
Token::Str("buttons_color"),
Token::Str("#484848"),
Token::Str("red_alert_color"),
Token::Str("#ff6666"),
Token::MapEnd,
Token::StructEnd,
],
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/custom_palette.rs | src/gui/styles/types/custom_palette.rs | use std::hash::Hash;
use serde::{Deserialize, Serialize};
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
use crate::gui::types::conf::deserialize_or_default;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CustomPalette {
#[serde(flatten)]
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) palette: Palette,
#[serde(flatten)]
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) extension: PaletteExtension,
}
impl CustomPalette {
pub fn from_palette(palette: Palette) -> Self {
Self {
palette,
extension: palette.generate_palette_extension(),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/styles/types/mod.rs | src/gui/styles/types/mod.rs | pub(super) mod color_remote;
pub mod custom_palette;
pub mod gradient_type;
pub mod palette;
pub mod palette_extension;
pub mod style_type;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/settings_style_page.rs | src/gui/pages/settings_style_page.rs | use iced::widget::scrollable::Direction;
use iced::widget::{Button, Column, Container, Row, Scrollable, Text, row};
use iced::widget::{Space, button, lazy};
use iced::{Alignment, Color, Element, Length, Padding};
use crate::gui::components::button::button_open_file;
use crate::gui::components::tab::get_settings_tabs;
use crate::gui::pages::settings_notifications_page::settings_header;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{BORDER_WIDTH, FONT_SIZE_SUBTITLE};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::styles::types::palette::Palette;
use crate::gui::styles::types::palette_extension::PaletteExtension;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::translations::translations::appearance_title_translation;
use crate::translations::translations_2::color_gradients_translation;
use crate::translations::translations_3::custom_style_translation;
use crate::utils::formatted_strings::get_path_termination_string;
use crate::utils::types::file_info::FileInfo;
use crate::utils::types::icon::Icon;
use crate::{Language, Sniffer, StyleType};
pub fn settings_style_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings {
style,
language,
color_gradient,
style_path,
..
} = sniffer.conf.settings.clone();
let mut content = Column::new()
.align_x(Alignment::Center)
.width(Length::Fill)
.push(settings_header(color_gradient, language))
.push(get_settings_tabs(SettingsPage::Appearance, language))
.push(Space::new().height(15))
.push(
appearance_title_translation(language)
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(Space::new().height(15))
.push(gradients_row(color_gradient, language))
.push(Space::new().height(15));
let mut styles_col = Column::new().align_x(Alignment::Center).width(Length::Fill);
for children in get_extra_palettes(StyleType::all_styles(), style) {
styles_col = styles_col.push(children);
}
styles_col = styles_col
.push(lazy((language, style_path.clone(), style), move |_| {
lazy_custom_style_input(language, &style_path, style)
}))
.push(Space::new().height(10));
let styles_scroll = Scrollable::with_direction(
styles_col,
Direction::Vertical(ScrollbarType::properties().margin(15)),
);
content = content.push(styles_scroll);
Container::new(content)
.height(400)
.width(800)
.class(ContainerType::Modal)
}
fn gradients_row<'a>(
color_gradient: GradientType,
language: Language,
) -> row::Wrapping<'a, Message, StyleType> {
Row::new()
.align_y(Alignment::Center)
.spacing(10)
.push(Text::new(format!(
"{}:",
color_gradients_translation(language)
)))
.push(
button(
Icon::Forbidden
.to_text()
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(12),
)
.padding(0)
.height(20.0)
.width(if color_gradient.eq(&GradientType::None) {
60
} else {
20
})
.on_press(Message::GradientsSelection(GradientType::None)),
)
.push(
button(
Icon::Waves
.to_text()
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(13),
)
.padding(0)
.height(20.0)
.width(if color_gradient.eq(&GradientType::Mild) {
60
} else {
20
})
.on_press(Message::GradientsSelection(GradientType::Mild)),
)
.push(
button(
Icon::Lightning
.to_text()
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(13),
)
.padding(0)
.height(20.0)
.width(if color_gradient.eq(&GradientType::Wild) {
60
} else {
20
})
.on_press(Message::GradientsSelection(GradientType::Wild)),
)
.wrap()
}
fn get_palette_container<'a>(
style: StyleType,
name: String,
on_press: StyleType,
) -> Button<'a, Message, StyleType> {
let PaletteExtension {
buttons_color,
is_nightly,
..
} = on_press.get_extension();
let caption = Row::new()
.spacing(7)
.push(Text::new(name))
.push(if is_nightly {
Icon::Moon.to_text().size(15)
} else {
Icon::Sun.to_text()
});
let content = Column::new()
.width(Length::Fill)
.align_x(Alignment::Center)
.spacing(5)
.push(caption)
.push(get_palette_rule(on_press.get_palette(), buttons_color));
Button::new(content)
.height(80)
.width(350)
.padding(Padding::ZERO.top(10))
.class(if on_press.eq(&style) {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::Style(on_press))
}
fn get_palette_rule<'a>(
palette: Palette,
buttons_color: Color,
) -> Container<'a, Message, StyleType> {
let height = 25.0;
Container::new(
Row::new()
.push(
Row::new()
.width(120)
.push(RuleType::PaletteColor(palette.primary).horizontal(height)),
)
.push(
Row::new()
.width(80)
.push(RuleType::PaletteColor(palette.secondary).horizontal(height)),
)
.push(
Row::new()
.width(60)
.push(RuleType::PaletteColor(palette.outgoing).horizontal(height)),
)
.push(
Row::new()
.width(40)
.push(RuleType::PaletteColor(buttons_color).horizontal(height)),
),
)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.width(300.0 + 2.0 * BORDER_WIDTH)
.height(height + 1.7 * BORDER_WIDTH)
.class(ContainerType::Palette)
}
// Buttons for each extra style arranged in rows of two
fn get_extra_palettes<'a>(
styles: &[StyleType],
current_style: StyleType,
) -> Vec<Element<'a, Message, StyleType>> {
// Map each extra style into a palette container
let mut styles = styles.iter().map(|&style| {
let name = style.to_string();
get_palette_container(current_style, name, style)
});
// The best way to do this would be with itertools, but that would introduce another dependency.
let mut children = Vec::with_capacity(styles.len());
// This handles the case where there aren't an even number of styles.
// [Iterator::zip] drops remainders. Itertools' `zip_longest` and the unstable array chunks API
// are both better solutions.
while let (Some(first), second) = (styles.next(), styles.next()) {
// Add both styles and the vertical space if there are two styles.
if let Some(second) = second {
children.extend([
Row::new()
.spacing(15)
.push(first)
.push(second)
.wrap()
.into(),
<Space as Into<Element<Message, StyleType>>>::into(Space::new().height(15)),
]);
} else {
children.extend([
Row::new().push(first).into(),
<Space as Into<Element<Message, StyleType>>>::into(Space::new().height(15)),
]);
}
}
children
}
fn lazy_custom_style_input<'a>(
language: Language,
custom_path: &str,
style: StyleType,
) -> Button<'a, Message, StyleType> {
let is_custom_toml_style_set = matches!(style, StyleType::Custom(_));
let custom_palette = Palette::from_file(custom_path);
let is_error = if custom_path.is_empty() {
false
} else {
custom_palette.is_err()
};
let button_row = Row::new()
.align_y(Alignment::Center)
.push(
Text::new(get_path_termination_string(custom_path, 17)).class(if is_error {
TextType::Danger
} else {
TextType::Standard
}),
)
.push(button_open_file(
custom_path.to_owned(),
FileInfo::Style,
language,
true,
Message::LoadStyle,
));
let mut content = Column::new()
.width(Length::Fill)
.align_x(Alignment::Center)
.spacing(5)
.push(Text::new(custom_style_translation(language)))
.push(button_row);
if is_custom_toml_style_set {
content = content.push(get_palette_rule(
style.get_palette(),
style.get_extension().buttons_color,
));
} else if let Ok(palette) = custom_palette {
content = content.push(get_palette_rule(palette, palette.generate_buttons_color()));
}
Button::new(content)
.height(if custom_palette.is_ok() || is_custom_toml_style_set {
110
} else {
75
})
.width(350)
.padding(Padding::ZERO.top(10).bottom(5))
.class(if is_custom_toml_style_set {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::LoadStyle(custom_path.to_string()))
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/initial_page.rs | src/gui/pages/initial_page.rs | //! Module defining the initial page of the application.
//!
//! It contains elements to select network adapter and traffic filters.
use crate::gui::components::button::button_open_file;
use crate::gui::sniffer::Sniffer;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE, FONT_SIZE_TITLE};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::export_pcap::ExportPcap;
use crate::gui::types::filters::Filters;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::capture_context::{CaptureSource, CaptureSourcePicklist};
use crate::networking::types::my_device::MyDevice;
use crate::networking::types::my_link_type::MyLinkType;
use crate::translations::translations::{network_adapter_translation, start_translation};
use crate::translations::translations_3::{
directory_translation, export_capture_translation, file_name_translation,
};
use crate::translations::translations_4::capture_file_translation;
use crate::translations::translations_5::{filter_traffic_translation, traffic_source_translation};
use crate::utils::formatted_strings::get_path_termination_string;
use crate::utils::types::file_info::FileInfo;
use crate::utils::types::icon::Icon;
use crate::{Language, StyleType};
use iced::Length::FillPortion;
use iced::widget::scrollable::Direction;
use iced::widget::{
Button, Checkbox, Column, Container, PickList, Row, Scrollable, Space, Text, TextInput, button,
center, row,
};
use iced::{Alignment, Length, Padding, alignment};
use pcap::Address;
/// Computes the body of gui initial page
pub fn initial_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings {
language,
color_gradient,
..
} = sniffer.conf.settings;
let col_data_source = get_col_data_source(sniffer, language);
let col_checkboxes = Column::new()
.spacing(10)
.push(get_filters_group(&sniffer.conf.filters, language))
.push(get_export_pcap_group_maybe(
sniffer.conf.capture_source_picklist,
&sniffer.conf.export_pcap,
language,
));
let is_capture_source_consistent = sniffer.is_capture_source_consistent();
let right_col = Column::new()
.width(FillPortion(1))
.padding(10)
.push(Space::new().height(76))
.push(col_checkboxes)
.push(Space::new().height(Length::Fill))
.push(button_start(
language,
color_gradient,
is_capture_source_consistent,
))
.push(Space::new().height(Length::Fill));
let body = Column::new().push(Space::new().height(5)).push(
Row::new()
.push(col_data_source)
.push(Space::new().width(15))
.push(right_col),
);
Container::new(body).height(Length::Fill)
}
fn button_start<'a>(
language: Language,
color_gradient: GradientType,
is_capture_source_consistent: bool,
) -> Button<'a, Message, StyleType> {
button(
Text::new(start_translation(language))
.size(FONT_SIZE_TITLE)
.width(Length::Fill)
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
)
.padding(20)
.width(Length::Fill)
.class(ButtonType::Gradient(color_gradient))
.on_press_maybe(if is_capture_source_consistent {
Some(Message::Start)
} else {
None
})
}
fn get_col_data_source(sniffer: &Sniffer, language: Language) -> Column<'_, Message, StyleType> {
let current_option = if sniffer.conf.capture_source_picklist == CaptureSourcePicklist::Device {
network_adapter_translation(language)
} else {
capture_file_translation(language)
};
let picklist = PickList::new(
[
network_adapter_translation(language),
capture_file_translation(language),
],
Some(current_option),
move |option| {
if option == network_adapter_translation(language) {
Message::SetCaptureSource(CaptureSourcePicklist::Device)
} else {
Message::SetCaptureSource(CaptureSourcePicklist::File)
}
},
)
.padding([2, 7]);
let mut col = Column::new()
.align_x(Alignment::Center)
.padding(Padding::new(10.0).top(30).bottom(0))
.spacing(30)
.height(Length::Fill)
.width(FillPortion(1))
.push(
Row::new()
.spacing(10)
.push(
Text::new(traffic_source_translation(language))
.class(TextType::Title)
.size(FONT_SIZE_TITLE),
)
.push(picklist),
);
match &sniffer.conf.capture_source_picklist {
CaptureSourcePicklist::Device => {
col = col.push(get_col_adapter(sniffer));
}
CaptureSourcePicklist::File => {
col = col.push(get_col_import_pcap(
language,
&sniffer.capture_source,
&sniffer.conf.import_pcap_path,
));
}
}
col
}
fn get_col_adapter(sniffer: &Sniffer) -> Column<'_, Message, StyleType> {
Column::new()
.spacing(5)
.height(Length::Fill)
.push(if sniffer.preview_charts.is_empty() {
Into::<iced::Element<Message, StyleType>>::into(center(
Icon::get_hourglass(sniffer.dots_pulse.0.len()).size(60),
))
} else {
Scrollable::with_direction(
sniffer.preview_charts.iter().fold(
Column::new()
.padding(Padding::ZERO.right(13).bottom(10))
.spacing(5),
|scroll_adapters, (my_dev, chart)| {
let name = my_dev.get_name();
let addresses_row =
get_addresses_row(my_dev.get_link_type(), my_dev.get_addresses());
let (title, subtitle) = get_adapter_title_subtitle(my_dev);
scroll_adapters.push(
Button::new(
Column::new()
.spacing(5)
.push(
Text::new(title)
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(subtitle.map(Text::new))
.push(addresses_row)
.push(if chart.max_packets > 0.0 {
Some(chart.view())
} else {
None
}),
)
.padding(15)
.width(Length::Fill)
.class(
if let CaptureSource::Device(device) = &sniffer.capture_source {
if name == device.get_name() {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
}
} else {
ButtonType::BorderedRound
},
)
.on_press(Message::DeviceSelection(name.clone())),
)
},
),
Direction::Vertical(ScrollbarType::properties()),
)
.into()
})
}
pub(crate) fn get_addresses_row(
link_type: MyLinkType,
addresses: &Vec<Address>,
) -> Option<row::Wrapping<'_, Message, StyleType>> {
if addresses.is_empty()
|| matches!(
link_type,
MyLinkType::LinuxSll(_) | MyLinkType::LinuxSll2(_)
)
{
return None;
}
let mut row = Row::new().spacing(5);
for addr in addresses {
let address_string = addr.addr.to_string();
row = row.push(
Container::new(Text::new(address_string).size(FONT_SIZE_FOOTER))
.padding(Padding::new(5.0).left(10).right(10))
.class(ContainerType::AdapterAddress),
);
}
Some(row.wrap())
}
fn get_adapter_title_subtitle(my_dev: &MyDevice) -> (String, Option<String>) {
let mut title = String::new();
#[allow(unused_mut)]
let mut subtitle: Option<String> = None;
let name = my_dev.get_name();
match my_dev.get_desc() {
None => {
title.push_str(name);
}
Some(description) => {
#[cfg(not(target_os = "windows"))]
{
title.push_str(name);
subtitle = Some(description.to_owned());
}
#[cfg(target_os = "windows")]
title.push_str(description);
}
}
(title, subtitle)
}
fn get_col_import_pcap<'a>(
language: Language,
cs: &CaptureSource,
path: &str,
) -> Column<'a, Message, StyleType> {
let is_import_pcap_set = matches!(cs, CaptureSource::File(_));
let button_row = Row::new()
.align_y(Alignment::Center)
.push(Text::new(get_path_termination_string(path, 25)))
.push(button_open_file(
path.to_string(),
FileInfo::PcapImport,
language,
true,
Message::SetPcapImport,
));
let content = Column::new()
.width(Length::Fill)
.align_x(alignment::Alignment::Center)
.spacing(5)
.push(button_row);
let button = Container::new(
Button::new(content)
.width(Length::Fill)
.padding([20, 30])
.class(if is_import_pcap_set {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::SetPcapImport(path.to_string())),
)
.padding(Padding::ZERO.right(13));
Column::new().spacing(5).push(button)
}
fn get_filters_group<'a>(
filters: &Filters,
language: Language,
) -> Container<'a, Message, StyleType> {
let expanded = filters.expanded();
let bpf = filters.bpf();
let caption = filter_traffic_translation(language);
let checkbox = Checkbox::new(expanded)
.label(caption)
.on_toggle(move |_| Message::ToggleFilters)
.size(18);
let mut ret_val = Column::new().spacing(10).push(checkbox);
if expanded {
let input = TextInput::new("", bpf)
.on_input(Message::BpfFilter)
.padding([2, 5]);
let inner_col = Column::new()
.spacing(10)
.padding(Padding::ZERO.left(26))
.push(
Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(Text::new("BPF:"))
.push(input),
);
ret_val = ret_val.push(inner_col);
}
Container::new(ret_val)
.padding(15)
.width(Length::Fill)
.class(ContainerType::BorderedRound)
}
fn get_export_pcap_group_maybe<'a>(
cs_pick: CaptureSourcePicklist,
export_pcap: &ExportPcap,
language: Language,
) -> Option<Container<'a, Message, StyleType>> {
if cs_pick == CaptureSourcePicklist::File {
return None;
}
let enabled = export_pcap.enabled();
let file_name = export_pcap.file_name();
let directory = export_pcap.directory();
let caption = export_capture_translation(language);
let checkbox = Checkbox::new(enabled)
.label(caption)
.on_toggle(move |_| Message::ToggleExportPcap)
.size(18);
let mut ret_val = Column::new().spacing(10).push(checkbox);
if enabled {
let inner_col = Column::new()
.spacing(10)
.padding(Padding::ZERO.left(26))
.push(
Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(Text::new(format!("{}:", file_name_translation(language))))
.push(
TextInput::new(ExportPcap::DEFAULT_FILE_NAME, file_name)
.on_input(Message::OutputPcapFile)
.padding([2, 5]),
),
)
.push(
Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(Text::new(format!("{}:", directory_translation(language))))
.push(Text::new(get_path_termination_string(directory, 25)))
.push(button_open_file(
directory.to_owned(),
FileInfo::Directory,
language,
true,
Message::OutputPcapDir,
)),
);
ret_val = ret_val.push(inner_col);
}
Some(
Container::new(ret_val)
.padding(15)
.width(Length::Fill)
.class(ContainerType::BorderedRound),
)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/connection_details_page.rs | src/gui/pages/connection_details_page.rs | use std::net::IpAddr;
use crate::countries::country_utils::{get_computer_tooltip, get_flag_tooltip};
use crate::gui::components::button::button_hide;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{FONT_SIZE_TITLE, TOOLTIP_DELAY};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::gui::types::timing_events::TimingEvents;
use crate::networking::manage_packets::{
get_address_to_lookup, get_traffic_type, is_local_connection, is_my_address,
};
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::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::icmp_type::IcmpType;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::translations::translations::{
address_translation, incoming_translation, outgoing_translation, packets_translation,
protocol_translation,
};
use crate::translations::translations_2::{
administrative_entity_translation, connection_details_translation, destination_translation,
fqdn_translation, mac_address_translation, socket_address_translation, source_translation,
transmitted_data_translation,
};
use crate::translations::translations_3::{
copy_translation, messages_translation, service_translation,
};
use crate::utils::formatted_strings::{get_formatted_timestamp, get_socket_address};
use crate::utils::types::icon::Icon;
use crate::{Language, Protocol, Sniffer, StyleType};
use iced::alignment::Vertical;
use iced::widget::scrollable::Direction;
use iced::widget::tooltip::Position;
use iced::widget::{Column, Container, Row, Space, Text, Tooltip};
use iced::widget::{Scrollable, button};
use iced::{Alignment, Length, Padding};
pub fn connection_details_page(
sniffer: &Sniffer,
key: AddressPortPair,
) -> Container<'_, Message, StyleType> {
Container::new(page_content(sniffer, &key))
}
fn page_content<'a>(sniffer: &Sniffer, key: &AddressPortPair) -> Container<'a, Message, StyleType> {
let Settings {
language,
color_gradient,
..
} = sniffer.conf.settings;
let data_repr = sniffer.conf.data_repr;
let info_traffic = &sniffer.info_traffic;
let val = info_traffic
.map
.get(key)
.unwrap_or(&InfoAddressPortPair::default())
.clone();
let address_to_lookup = get_address_to_lookup(key, val.traffic_direction);
let host_option = sniffer.addresses_resolved.get(&address_to_lookup).cloned();
let host_info_option = info_traffic
.hosts
.get(&host_option.clone().unwrap_or_default().1)
.copied();
let header_and_content = Column::new()
.width(Length::Fill)
.push(page_header(color_gradient, language));
let mut source_caption = Row::new().align_y(Alignment::Center).spacing(10).push(
Text::new(source_translation(language))
.size(FONT_SIZE_TITLE)
.class(TextType::Title),
);
let mut dest_caption = Row::new().align_y(Alignment::Center).spacing(10).push(
Text::new(destination_translation(language))
.size(FONT_SIZE_TITLE)
.class(TextType::Title),
);
let mut host_info_col = Column::new();
if let Some((r_dns, host)) = host_option {
host_info_col = get_host_info_col(&r_dns, &host, language);
let host_info = host_info_option.unwrap_or_default();
let flag = get_flag_tooltip(host.country, &host_info, language, false);
let computer = get_local_tooltip(sniffer, &address_to_lookup, key);
if address_to_lookup.eq(&key.source) {
source_caption = source_caption.push(flag);
dest_caption = dest_caption.push(computer);
} else {
dest_caption = dest_caption.push(flag);
source_caption = source_caption.push(computer);
}
}
let mut source_col = get_src_or_dest_col(
source_caption,
&key.source,
key.sport,
val.mac_address1.as_ref(),
language,
&sniffer.timing_events,
);
let mut dest_col = get_src_or_dest_col(
dest_caption,
&key.dest,
key.dport,
val.mac_address2.as_ref(),
language,
&sniffer.timing_events,
);
if address_to_lookup.eq(&key.source) {
source_col = source_col.push(host_info_col);
} else {
dest_col = dest_col.push(host_info_col);
}
let col_info = col_info(key, &val, data_repr, language);
let content = assemble_widgets(col_info, source_col, dest_col);
Container::new(header_and_content.push(content))
.width(1000)
.height(500)
.class(ContainerType::Modal)
}
fn page_header<'a>(
color_gradient: GradientType,
language: Language,
) -> Container<'a, Message, StyleType> {
Container::new(
Row::new()
.push(Space::new().width(Length::Fill))
.push(
Text::new(connection_details_translation(language))
.size(FONT_SIZE_TITLE)
.width(Length::FillPortion(6))
.align_x(Alignment::Center),
)
.push(
Container::new(button_hide(Message::HideModal, language))
.width(Length::Fill)
.align_x(Alignment::Center),
),
)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.height(40.0)
.width(Length::Fill)
.class(ContainerType::Gradient(color_gradient))
}
fn col_info<'a>(
key: &AddressPortPair,
val: &InfoAddressPortPair,
data_repr: DataRepr,
language: Language,
) -> Column<'a, Message, StyleType> {
let is_icmp = key.protocol.eq(&Protocol::ICMP);
let is_arp = key.protocol.eq(&Protocol::ARP);
let mut ret_val = Column::new()
.spacing(10)
.padding(Padding::new(20.0).right(10).left(40))
.width(Length::FillPortion(2))
.push(Space::new().height(Length::Fill))
.push(
Row::new()
.spacing(8)
.align_y(Vertical::Center)
.push(Icon::Clock.to_text())
.push(Text::new(format!(
"{}\n{}",
get_formatted_timestamp(val.initial_timestamp),
get_formatted_timestamp(val.final_timestamp)
))),
)
.push(TextType::highlighted_subtitle_with_desc(
protocol_translation(language),
&key.protocol.to_string(),
));
if !is_icmp && !is_arp {
ret_val = ret_val.push(TextType::highlighted_subtitle_with_desc(
service_translation(language),
&val.service.to_string(),
));
}
ret_val = ret_val.push(TextType::highlighted_subtitle_with_desc(
&format!(
"{} ({})",
transmitted_data_translation(language),
if val.traffic_direction.eq(&TrafficDirection::Outgoing) {
outgoing_translation(language).to_lowercase()
} else {
incoming_translation(language).to_lowercase()
}
),
&(data_repr.formatted_string(val.transmitted_data(data_repr))
+ if data_repr == DataRepr::Packets {
format!(" {}", packets_translation(language))
} else {
String::new()
}
.as_ref()),
));
if is_icmp || is_arp {
ret_val = ret_val.push(
Column::new()
.push(
Text::new(format!("{}:", messages_translation(language)))
.class(TextType::Subtitle),
)
.push(Scrollable::with_direction(
Column::new()
.padding(Padding::ZERO.right(10).bottom(10))
.push(Text::new(if is_icmp {
IcmpType::pretty_print_types(&val.icmp_types)
} else {
ArpType::pretty_print_types(&val.arp_types)
})),
Direction::Both {
vertical: ScrollbarType::properties(),
horizontal: ScrollbarType::properties(),
},
)),
);
}
ret_val = ret_val.push(Space::new().height(Length::Fill));
ret_val
}
fn get_host_info_col<'a>(
r_dns: &str,
host: &Host,
language: Language,
) -> Column<'a, Message, StyleType> {
let mut host_info_col = Column::new().spacing(4);
if r_dns.parse::<IpAddr>().is_err() || (!host.asn.name.is_empty() && !host.asn.code.is_empty())
{
host_info_col = host_info_col.push(RuleType::Standard.horizontal(10));
}
if r_dns.parse::<IpAddr>().is_err() {
host_info_col = host_info_col.push(TextType::highlighted_subtitle_with_desc(
fqdn_translation(language),
r_dns,
));
}
if !host.asn.name.is_empty() && !host.asn.code.is_empty() {
host_info_col = host_info_col.push(TextType::highlighted_subtitle_with_desc(
administrative_entity_translation(language),
&format!("{} (ASN {})", host.asn.name, host.asn.code),
));
}
host_info_col
}
fn get_local_tooltip<'a>(
sniffer: &Sniffer,
address_to_lookup: &IpAddr,
key: &AddressPortPair,
) -> Tooltip<'a, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let local_address = if address_to_lookup.eq(&key.source) {
&key.dest
} else {
&key.source
};
let my_interface_addresses = sniffer.capture_source.get_addresses();
get_computer_tooltip(
is_my_address(local_address, my_interface_addresses),
is_local_connection(local_address, my_interface_addresses),
is_bogon(local_address),
get_traffic_type(
if address_to_lookup.eq(&key.source) {
&key.dest
} else {
&key.source
},
my_interface_addresses,
TrafficDirection::Outgoing,
),
language,
)
}
fn get_src_or_dest_col<'a>(
caption: Row<'a, Message, StyleType>,
ip: &IpAddr,
port: Option<u16>,
mac: Option<&String>,
language: Language,
timing_events: &TimingEvents,
) -> Column<'a, Message, StyleType> {
let address_caption = if port.is_some() {
socket_address_translation(language)
} else {
address_translation(language)
};
let mac_str = if let Some(val) = mac { val } else { "-" };
Column::new()
.spacing(4)
.push(
Container::new(caption)
.width(Length::Fill)
.align_x(Alignment::Center),
)
.push(RuleType::Standard.horizontal(10))
.push(
Row::new()
.spacing(10)
.align_y(Alignment::End)
.push(TextType::highlighted_subtitle_with_desc(
address_caption,
&get_socket_address(ip, port),
))
.push(get_button_copy(language, ip, timing_events)),
)
.push(TextType::highlighted_subtitle_with_desc(
mac_address_translation(language),
mac_str,
))
}
fn assemble_widgets<'a>(
col_info: Column<'a, Message, StyleType>,
source_col: Column<'a, Message, StyleType>,
dest_col: Column<'a, Message, StyleType>,
) -> Row<'a, Message, StyleType> {
let [source_container, dest_container] = [source_col, dest_col].map(|col| {
Container::new(col)
.padding(7)
.width(Length::Fill)
.class(ContainerType::BorderedRound)
});
Row::new()
.padding([0, 10])
.spacing(10)
.align_y(Alignment::Center)
.width(Length::Fill)
.height(Length::Fill)
.push(col_info)
.push(
Column::new()
.width(Length::FillPortion(3))
.align_x(Alignment::Center)
.spacing(5)
.push(Space::new().height(Length::Fill))
.push(source_container)
.push(Icon::ArrowsDown.to_text())
.push(dest_container)
.push(Space::new().height(Length::Fill)),
)
}
fn get_button_copy<'a>(
language: Language,
ip: &IpAddr,
timing_events: &TimingEvents,
) -> Tooltip<'a, Message, StyleType> {
let icon = if timing_events.was_just_copy_ip(ip) {
Text::new("✔").size(14)
} else {
Icon::Copy.to_text().size(12)
};
let content = button(icon.align_x(Alignment::Center).align_y(Alignment::Center))
.padding(0)
.height(25)
.width(25)
.on_press(Message::CopyIp(*ip));
Tooltip::new(
content,
Text::new(format!("{} (IP)", copy_translation(language))),
Position::Right,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/settings_general_page.rs | src/gui/pages/settings_general_page.rs | use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Column, Container, PickList, Row, Slider, Space, Text, Tooltip, button};
use iced::{Alignment, Length, Padding};
use crate::gui::components::button::{button_open_file, row_open_link_tooltip};
use crate::gui::components::tab::get_settings_tabs;
use crate::gui::pages::settings_notifications_page::settings_header;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::style_constants::{FONT_SIZE_SUBTITLE, TOOLTIP_DELAY};
use crate::gui::styles::text::TextType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::mmdb::types::mmdb_reader::{MmdbReader, MmdbReaders};
use crate::translations::translations::language_translation;
use crate::translations::translations_2::country_translation;
use crate::translations::translations_3::{
mmdb_files_translation, params_not_editable_translation, zoom_translation,
};
use crate::translations::translations_4::share_feedback_translation;
use crate::utils::formatted_strings::get_path_termination_string;
use crate::utils::types::file_info::FileInfo;
use crate::utils::types::icon::Icon;
use crate::utils::types::web_page::WebPage;
use crate::{Language, Sniffer, StyleType};
pub fn settings_general_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings {
language,
color_gradient,
..
} = sniffer.conf.settings;
let content = Column::new()
.align_x(Alignment::Center)
.width(Length::Fill)
.push(settings_header(color_gradient, language))
.push(get_settings_tabs(SettingsPage::General, language))
.push(Space::new().height(10))
.push(column_all_general_setting(sniffer));
Container::new(content)
.height(400)
.width(800)
.class(ContainerType::Modal)
}
fn column_all_general_setting(sniffer: &Sniffer) -> Column<'_, Message, StyleType> {
let Settings {
language,
scale_factor,
mmdb_country,
mmdb_asn,
..
} = sniffer.conf.settings.clone();
let is_editable = sniffer.running_page.is_none();
let mut column = Column::new()
.align_x(Alignment::Center)
.padding([5, 10])
.push(row_language_scale_factor(language, scale_factor))
.push(RuleType::Standard.horizontal(25));
if !is_editable {
column = column
.push(
Container::new(Text::new(params_not_editable_translation(language)))
.padding(10.0)
.class(ContainerType::Badge),
)
.push(Space::new().height(10));
}
column = column.push(mmdb_settings(
is_editable,
language,
&mmdb_country,
&mmdb_asn,
&sniffer.mmdb_readers,
));
column
}
fn row_language_scale_factor<'a>(
language: Language,
scale_factor: f32,
) -> Row<'a, Message, StyleType> {
Row::new()
.align_y(Alignment::Start)
.height(100)
.push(language_picklist(language))
.push(RuleType::Standard.vertical(25))
.push(scale_factor_slider(language, scale_factor))
.push(RuleType::Standard.vertical(25))
.push(need_help(language))
}
fn language_picklist<'a>(language: Language) -> Container<'a, Message, StyleType> {
let mut flag_row = Row::new()
.align_y(Alignment::Center)
.spacing(10)
.push(language.get_flag());
if !language.is_up_to_date() {
flag_row = flag_row.push(
Tooltip::new(
button(
Text::new("!")
.class(TextType::Danger)
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(15)
.line_height(LineHeight::Relative(1.0)),
)
.on_press(Message::OpenWebPage(WebPage::IssueLanguages))
.padding(2)
.height(20)
.width(20)
.class(ButtonType::Alert),
row_open_link_tooltip("The selected language is not\nfully updated to version 1.4"),
Position::FollowCursor,
)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY),
);
}
let content = Column::new()
.align_x(Alignment::Center)
.push(
Text::new(language_translation(language))
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(Space::new().height(Length::Fill))
.push(flag_row)
.push(Space::new().height(10))
.push(
PickList::new(
&Language::ALL[..],
Some(language),
Message::LanguageSelection,
)
.menu_height(200)
.padding([2, 7]),
)
.push(Space::new().height(Length::Fill));
Container::new(content)
.width(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
}
fn scale_factor_slider<'a>(
language: Language,
scale_factor: f32,
) -> Container<'a, Message, StyleType> {
let slider_width = 130.0 / scale_factor;
let slider_val = scale_factor.log(3.0);
Container::new(
Column::new()
.align_x(Alignment::Center)
.push(
Text::new(zoom_translation(language))
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(Space::new().height(Length::Fill))
.push(Text::new(format!("{:.0}%", scale_factor * 100.0)))
.push(Space::new().height(5))
.push(
Slider::new(-1.0..=1.0, slider_val, |slider_val| {
let scale_factor_str = format!("{:.1}", 3.0_f32.powf(slider_val));
let scale_factor = scale_factor_str.parse().unwrap_or(1.0);
Message::ChangeScaleFactor(scale_factor)
})
.step(0.01)
.width(slider_width),
)
.push(Space::new().height(Length::Fill)),
)
.width(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
}
fn need_help<'a>(language: Language) -> Container<'a, Message, StyleType> {
let content = Column::new()
.align_x(Alignment::Center)
.push(
Text::new(share_feedback_translation(language))
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(Space::new().height(Length::Fill))
.push(
Tooltip::new(
button(
Icon::Feedback
.to_text()
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(20)
.line_height(LineHeight::Relative(1.0)),
)
.on_press(Message::OpenWebPage(WebPage::Issues))
.padding(Padding::new(2.0).top(5))
.height(40)
.width(60),
row_open_link_tooltip("GitHub Issues"),
Position::Right,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY),
)
.push(Space::new().height(Length::Fill));
Container::new(content)
.width(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
}
fn mmdb_settings<'a>(
is_editable: bool,
language: Language,
country_path: &str,
asn_path: &str,
mmdb_readers: &MmdbReaders,
) -> Column<'a, Message, StyleType> {
Column::new()
.spacing(5)
.align_x(Alignment::Center)
.push(
Text::new(mmdb_files_translation(language))
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
)
.push(mmdb_selection_row(
is_editable,
Message::CustomCountryDb,
country_path,
&mmdb_readers.country,
country_translation(language),
language,
))
.push(mmdb_selection_row(
is_editable,
Message::CustomAsnDb,
asn_path,
&mmdb_readers.asn,
"ASN",
language,
))
}
fn mmdb_selection_row<'a>(
is_editable: bool,
message: fn(String) -> Message,
custom_path: &str,
mmdb_reader: &MmdbReader,
caption: &str,
language: Language,
) -> Row<'a, Message, StyleType> {
let is_error = if custom_path.is_empty() {
false
} else {
match *mmdb_reader {
MmdbReader::Default(_) | MmdbReader::Empty => true,
MmdbReader::Custom(_) => false,
}
};
Row::new()
.align_y(Alignment::Center)
.push(Text::new(format!("{caption}: ")))
.push(
Text::new(get_path_termination_string(custom_path, 25)).class(if is_error {
TextType::Danger
} else {
TextType::Standard
}),
)
.push(if custom_path.is_empty() {
button_open_file(
custom_path.to_owned(),
FileInfo::Database,
language,
is_editable,
message,
)
} else {
button_clear_mmdb(message, is_editable)
})
}
fn button_clear_mmdb<'a>(
message: fn(String) -> Message,
is_editable: bool,
) -> Tooltip<'a, Message, StyleType> {
let mut button = button(
Text::new("×")
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(15)
.line_height(LineHeight::Relative(1.0)),
)
.padding(2)
.height(20)
.width(20);
if is_editable {
button = button.on_press(message(String::new()));
}
Tooltip::new(button, "", Position::Right).delay(TOOLTIP_DELAY)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/thumbnail_page.rs | src/gui/pages/thumbnail_page.rs | use std::cmp::min;
use std::net::IpAddr;
use iced::widget::{Column, Container, Row, Space, Text};
use iced::{Alignment, Length};
use crate::chart::types::donut_chart::donut_chart;
use crate::countries::country_utils::get_flag_tooltip;
use crate::gui::sniffer::Sniffer;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::style_constants::FONT_SIZE_FOOTER;
use crate::gui::styles::types::style_type::StyleType;
use crate::gui::types::message::Message;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::{Host, ThumbnailHost};
use crate::networking::types::info_traffic::InfoTraffic;
use crate::report::get_report_entries::{get_host_entries, get_service_entries};
use crate::report::types::sort_type::SortType;
use crate::translations::types::language::Language;
const MAX_ENTRIES: usize = 4;
const MAX_CHARS_HOST: usize = 26;
const MAX_CHARS_SERVICE: usize = 13;
/// Computes the body of the thumbnail view
pub fn thumbnail_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let tot_packets = sniffer
.info_traffic
.tot_data_info
.tot_data(DataRepr::Packets);
if tot_packets == 0 {
return Container::new(
Column::new()
.push(Space::new().height(Length::Fill))
.push(Text::new(&sniffer.dots_pulse.0).size(50))
.push(Space::new().height(Length::FillPortion(2))),
)
.width(Length::Fill)
.align_x(Alignment::Center);
}
let info_traffic = &sniffer.info_traffic;
let data_repr = sniffer.conf.data_repr;
let (in_data, out_data, dropped) = info_traffic.get_thumbnail_data(data_repr);
let charts = Row::new()
.padding(5)
.height(Length::Fill)
.align_y(Alignment::Center)
.push(donut_chart(
data_repr,
in_data,
out_data,
dropped,
sniffer.thumbnail,
))
.push(
Container::new(sniffer.traffic_chart.view())
.height(Length::Fill)
.width(Length::FillPortion(2)),
);
let report = Row::new()
.padding([5, 0])
.height(Length::Fill)
.align_y(Alignment::Start)
.push(host_col(
info_traffic,
data_repr,
sniffer.conf.host_sort_type,
))
.push(RuleType::Standard.vertical(10))
.push(service_col(
info_traffic,
data_repr,
sniffer.conf.service_sort_type,
));
let content = Column::new().push(charts).push(report);
Container::new(content)
}
fn host_col<'a>(
info_traffic: &InfoTraffic,
data_repr: DataRepr,
sort_type: SortType,
) -> Column<'a, Message, StyleType> {
let mut host_col = Column::new()
.padding([0, 5])
.spacing(3)
.width(Length::FillPortion(2));
let hosts = get_host_entries(info_traffic, data_repr, sort_type);
let mut thumbnail_hosts = Vec::new();
for (host, data_info_host) in &hosts {
let text = host_text(host);
let country = host.country;
let thumbnail_host = ThumbnailHost {
country,
text: text.clone(),
};
if thumbnail_hosts.contains(&thumbnail_host) {
continue;
}
thumbnail_hosts.push(thumbnail_host);
let flag = get_flag_tooltip(country, data_info_host, Language::default(), true);
let host_row = Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(flag)
.push(Text::new(text).size(FONT_SIZE_FOOTER));
host_col = host_col.push(host_row);
if thumbnail_hosts.len() >= MAX_ENTRIES {
break;
}
}
host_col
}
fn service_col<'a>(
info_traffic: &InfoTraffic,
data_repr: DataRepr,
sort_type: SortType,
) -> Column<'a, Message, StyleType> {
let mut service_col = Column::new().padding([0, 5]).spacing(3).width(Length::Fill);
let services = get_service_entries(info_traffic, data_repr, sort_type);
let n_entry = min(services.len(), MAX_ENTRIES);
for (service, _) in services.get(..n_entry).unwrap_or_default() {
service_col = service_col.push(
Text::new(clip_text(&service.to_string(), MAX_CHARS_SERVICE)).size(FONT_SIZE_FOOTER),
);
}
service_col
}
fn host_text(host: &Host) -> String {
let domain = &host.domain;
let asn = &host.asn.name;
let text = if asn.is_empty() || (!domain.trim().is_empty() && domain.parse::<IpAddr>().is_err())
{
domain
} else {
asn
};
clip_text(text, MAX_CHARS_HOST)
}
fn clip_text(text: &str, max_chars: usize) -> String {
let text = text.trim();
let chars = text.chars().collect::<Vec<char>>();
let tot_len = chars.len();
let slice_len = min(max_chars, tot_len);
let suspensions = if tot_len > max_chars { "…" } else { "" };
let slice = if tot_len > max_chars {
&chars[..slice_len - 2]
} else {
&chars[..slice_len]
}
.iter()
.collect::<String>();
[slice.trim(), suspensions].concat()
}
#[cfg(test)]
mod tests {
use crate::gui::pages::thumbnail_page::{
MAX_CHARS_HOST, MAX_CHARS_SERVICE, clip_text, host_text,
};
use crate::networking::types::asn::Asn;
use crate::networking::types::host::Host;
fn host_for_tests(domain: &str, asn: &str) -> Host {
Host {
domain: domain.to_string(),
asn: Asn {
name: asn.to_string(),
code: "512".to_string(),
},
country: Default::default(),
}
}
#[test]
fn test_clip_text() {
assert_eq!(
clip_text("iphone-di-doofenshmirtz.local", MAX_CHARS_HOST),
"iphone-di-doofenshmirtz.…"
);
assert_eq!(clip_text("github.com", MAX_CHARS_HOST), "github.com");
assert_eq!(clip_text("https6789012", MAX_CHARS_SERVICE), "https6789012");
assert_eq!(
clip_text("https67890123", MAX_CHARS_SERVICE),
"https67890123"
);
assert_eq!(
clip_text("https678901234", MAX_CHARS_SERVICE),
"https678901…"
);
assert_eq!(
clip_text("https6789012345", MAX_CHARS_SERVICE),
"https678901…"
);
assert_eq!(
clip_text("protocol with space", MAX_CHARS_SERVICE),
"protocol wi…"
);
assert_eq!(
clip_text("protocol90 23456", MAX_CHARS_SERVICE),
"protocol90…"
);
assert_eq!(
clip_text(" \n\t sniffnet.net ", MAX_CHARS_HOST),
"sniffnet.net"
);
assert_eq!(
clip_text(" protocol90 23456 \n ", MAX_CHARS_SERVICE),
"protocol90…"
);
assert_eq!(
clip_text(" protocol90 23456 ", MAX_CHARS_HOST),
"protocol90 23456"
);
}
#[test]
fn test_host_text() {
let host = host_for_tests("iphone-di-doofenshmirtz.local", "AS1234");
assert_eq!(host_text(&host), "iphone-di-doofenshmirtz.…");
let host = host_for_tests("", "");
assert_eq!(host_text(&host), "");
let host = host_for_tests("192.168.1.113", "AS1234");
assert_eq!(host_text(&host), "AS1234");
let host = host_for_tests("192.168.1.113", "");
assert_eq!(host_text(&host), "192.168.1.113");
let host = host_for_tests("", "FASTLY");
assert_eq!(host_text(&host), "FASTLY");
let host = host_for_tests("::", "GOOGLE");
assert_eq!(host_text(&host), "GOOGLE");
let host = host_for_tests("::f", "AKAMAI-TECHNOLOGIES-INCORPORATED");
assert_eq!(host_text(&host), "AKAMAI-TECHNOLOGIES-INCO…");
let host = host_for_tests("::g", "GOOGLE");
assert_eq!(host_text(&host), "::g");
let host = host_for_tests(" ", "GOOGLE");
assert_eq!(host_text(&host), "GOOGLE");
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/notifications_page.rs | src/gui/pages/notifications_page.rs | use crate::countries::country_utils::get_computer_tooltip;
use crate::countries::flags_pictures::FLAGS_HEIGHT_BIG;
use crate::gui::components::header::get_button_settings;
use crate::gui::components::tab::get_pages_tabs;
use crate::gui::components::types::my_modal::MyModal;
use crate::gui::pages::overview_page::{get_bars, get_bars_length, host_bar, service_bar};
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, TOOLTIP_DELAY};
use crate::gui::styles::text::TextType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::service::Service;
use crate::networking::types::traffic_type::TrafficType;
use crate::notifications::types::logged_notification::{
DataThresholdExceeded, FavoriteTransmitted, LoggedNotification,
};
use crate::report::types::sort_type::SortType;
use crate::translations::translations::{
clear_all_translation, favorite_transmitted_translation, no_notifications_received_translation,
no_notifications_set_translation, only_last_30_translation, per_second_translation,
threshold_translation,
};
use crate::utils::types::icon::Icon;
use crate::{Language, RunningPage, Sniffer, StyleType};
use iced::Length::FillPortion;
use iced::widget::scrollable::Direction;
use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Column, Container, Row, Scrollable, Text, Tooltip};
use iced::widget::{Space, button};
use iced::{Alignment, Length, Padding};
use std::cmp::max;
/// Computes the body of gui notifications page
pub fn notifications_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings {
language,
notifications,
..
} = sniffer.conf.settings.clone();
let mut tab_and_body = Column::new()
.align_x(Alignment::Center)
.height(Length::Fill);
let tabs = get_pages_tabs(
RunningPage::Notifications,
language,
sniffer.unread_notifications,
);
tab_and_body = tab_and_body.push(tabs);
if notifications.data_notification.threshold.is_none()
&& !notifications.favorite_notification.notify_on_favorite
&& sniffer.logged_notifications.0.is_empty()
{
let body = body_no_notifications_set(language);
tab_and_body = tab_and_body.push(body);
} else if sniffer.logged_notifications.0.is_empty() {
let body = body_no_notifications_received(language, &sniffer.dots_pulse.0);
tab_and_body = tab_and_body.push(body);
} else {
let logged_notifications = logged_notifications(sniffer);
let body_row = Row::new()
.spacing(10)
.padding(Padding::new(10.0).bottom(0))
.push(
Container::new(if sniffer.logged_notifications.0.len() < 30 {
Text::new("")
} else {
Text::new(only_last_30_translation(language))
})
.width(150)
.height(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.push(Scrollable::with_direction(
logged_notifications,
Direction::Vertical(ScrollbarType::properties()),
))
.push(
Container::new(get_button_clear_all(language))
.width(150)
.height(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
);
tab_and_body = tab_and_body.push(body_row);
}
Container::new(Column::new().push(tab_and_body)).height(Length::Fill)
}
fn body_no_notifications_set<'a>(language: Language) -> Column<'a, Message, StyleType> {
Column::new()
.padding(5)
.spacing(5)
.align_x(Alignment::Center)
.width(Length::Fill)
.push(Space::new().height(Length::Fill))
.push(no_notifications_set_translation(language).align_x(Alignment::Center))
.push(get_button_settings(language, SettingsPage::Notifications))
.push(Space::new().height(FillPortion(2)))
}
fn body_no_notifications_received(
language: Language,
dots: &str,
) -> Column<'_, Message, StyleType> {
Column::new()
.padding(5)
.spacing(5)
.align_x(Alignment::Center)
.width(Length::Fill)
.push(Space::new().height(Length::Fill))
.push(no_notifications_received_translation(language).align_x(Alignment::Center))
.push(Text::new(dots.to_owned()).size(50))
.push(Space::new().height(FillPortion(2)))
}
fn data_notification_log<'a>(
logged_notification: &DataThresholdExceeded,
first_entry_data_info: DataInfo,
language: Language,
) -> Container<'a, Message, StyleType> {
let data_repr = logged_notification.data_repr;
let data_string = data_repr.formatted_string(logged_notification.threshold.into());
let icon = if data_repr == DataRepr::Packets {
Icon::PacketsThreshold
} else {
Icon::BytesThreshold
}
.to_text()
.size(80)
.line_height(LineHeight::Relative(1.0));
let threshold_str = format!(
"{}: {data_string} {}",
threshold_translation(language),
per_second_translation(language)
);
let content = Row::new()
.align_y(Alignment::Center)
.spacing(30)
.push(icon)
.push(
Column::new()
.spacing(7)
.width(250)
.push(
Row::new()
.spacing(8)
.push(Icon::Clock.to_text())
.push(Text::new(logged_notification.timestamp.clone())),
)
.push(
Text::new(data_repr.data_exceeded_translation(language).to_string())
.class(TextType::Title),
)
.push(
Text::new(threshold_str)
.class(TextType::Subtitle)
.size(FONT_SIZE_FOOTER),
),
)
.push(threshold_bar(
logged_notification,
first_entry_data_info,
language,
));
let content_and_extra = Column::new()
.spacing(10)
.push(content)
.push(button_expand(
logged_notification.id,
logged_notification.is_expanded,
))
.push(data_notification_extra(logged_notification, language));
Container::new(content_and_extra)
.width(Length::Fill)
.padding(15)
.class(ContainerType::BorderedRound)
}
fn favorite_notification_log<'a>(
logged_notification: &FavoriteTransmitted,
first_entry_data_info: DataInfo,
data_repr: DataRepr,
language: Language,
) -> Container<'a, Message, StyleType> {
let host_bar = host_bar(
&logged_notification.host,
&logged_notification.data_info_host,
data_repr,
first_entry_data_info,
language,
);
let content = Row::new()
.spacing(30)
.align_y(Alignment::Center)
.push(
Icon::Star
.to_text()
.size(80)
.line_height(LineHeight::Relative(1.0)),
)
.push(
Column::new()
.width(250)
.spacing(7)
.push(
Row::new()
.spacing(8)
.push(Icon::Clock.to_text())
.push(Text::new(logged_notification.timestamp.clone())),
)
.push(Text::new(favorite_transmitted_translation(language)).class(TextType::Title)),
)
.push(host_bar);
Container::new(content)
.width(Length::Fill)
.padding(15)
.class(ContainerType::BorderedRound)
}
fn get_button_clear_all<'a>(language: Language) -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::Bin
.to_text()
.size(20)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(10)
.height(50)
.width(75)
.on_press(Message::ShowModal(MyModal::ClearAll));
Tooltip::new(
content,
Text::new(clear_all_translation(language)),
Position::Top,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn logged_notifications<'a>(sniffer: &Sniffer) -> Column<'a, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let data_repr = sniffer.conf.data_repr;
let mut ret_val = Column::new()
.padding(Padding::ZERO.right(15).bottom(10))
.spacing(10)
.align_x(Alignment::Center);
let first_entry_data_info = sniffer
.logged_notifications
.0
.iter()
.map(LoggedNotification::data_info)
.max_by(|d1, d2| d1.compare(d2, SortType::Ascending, data_repr))
.unwrap_or_default();
for logged_notification in &sniffer.logged_notifications.0 {
ret_val = ret_val.push(match logged_notification {
LoggedNotification::DataThresholdExceeded(data_threshold_exceeded) => {
data_notification_log(data_threshold_exceeded, first_entry_data_info, language)
}
LoggedNotification::FavoriteTransmitted(favorite_transmitted) => {
favorite_notification_log(
favorite_transmitted,
first_entry_data_info,
data_repr,
language,
)
}
});
}
ret_val
}
fn threshold_bar<'a>(
logged_notification: &DataThresholdExceeded,
first_entry_data_info: DataInfo,
language: Language,
) -> Row<'a, Message, StyleType> {
let data_repr = logged_notification.data_repr;
let data_info = logged_notification.data_info;
let (incoming_bar_len, outgoing_bar_len) =
get_bars_length(data_repr, &first_entry_data_info, &data_info);
Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(get_computer_tooltip(
true,
true,
None,
TrafficType::Unicast,
language,
))
.push(
Column::new()
.spacing(1)
.push(
Row::new()
.push(Space::new().width(Length::Fill))
.push(Text::new(
data_repr.formatted_string(data_info.tot_data(data_repr)),
)),
)
.push(get_bars(incoming_bar_len, outgoing_bar_len)),
)
}
fn button_expand<'a>(
notification_id: usize,
is_expanded: bool,
) -> Container<'a, Message, StyleType> {
let button = button(
if is_expanded {
Icon::SortAscending
} else {
Icon::SortDescending
}
.to_text()
.size(11)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(Padding::ZERO.top(if is_expanded { 0 } else { 2 }))
.width(25)
.height(25)
.on_press(Message::ExpandNotification(notification_id, !is_expanded));
Container::new(button)
.padding(Padding::ZERO.left(395))
.align_y(Alignment::Center)
}
fn data_notification_extra<'a>(
logged_notification: &DataThresholdExceeded,
language: Language,
) -> Option<Row<'a, Message, StyleType>> {
let max_entries = max(
logged_notification.hosts.len(),
logged_notification.services.len(),
);
if !logged_notification.is_expanded || max_entries == 0 {
return None;
}
let spacing = 10.0;
#[allow(clippy::cast_precision_loss)]
let height = (FLAGS_HEIGHT_BIG + spacing) * max_entries as f32;
let mut hosts_col = Column::new().spacing(spacing).width(Length::FillPortion(5));
let first_data_info_host = logged_notification
.hosts
.first()
.unwrap_or(&(Host::default(), DataInfoHost::default()))
.1
.data_info;
for (host, data_info_host) in &logged_notification.hosts {
let host_bar = host_bar(
host,
data_info_host,
logged_notification.data_repr,
first_data_info_host,
language,
);
hosts_col = hosts_col.push(host_bar);
}
let mut services_col = Column::new().spacing(spacing).width(Length::FillPortion(2));
let first_data_info_service = logged_notification
.services
.first()
.unwrap_or(&(Service::default(), DataInfo::default()))
.1;
for (service, data_info) in &logged_notification.services {
let service_bar = service_bar(
service,
data_info,
logged_notification.data_repr,
first_data_info_service,
);
services_col = services_col.push(service_bar);
}
Some(
Row::new()
.push(hosts_col)
.push(Container::new(RuleType::Standard.vertical(30)).height(height))
.push(services_col),
)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/settings_notifications_page.rs | src/gui/pages/settings_notifications_page.rs | use iced::widget::scrollable::Direction;
use iced::widget::{Button, Slider, row};
use iced::widget::{Checkbox, Column, Container, Row, Scrollable, Space, Text, TextInput};
use iced::{Alignment, Length, Padding};
use crate::gui::components::button::button_hide;
use crate::gui::components::tab::get_settings_tabs;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE, FONT_SIZE_TITLE};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::data_representation::DataRepr;
use crate::notifications::types::notifications::{
DataNotification, FavoriteNotification, Notification, RemoteNotifications,
};
use crate::notifications::types::sound::Sound;
use crate::translations::translations::{
favorite_transmitted_translation, notifications_title_translation, per_second_translation,
settings_translation, sound_translation, threshold_translation, volume_translation,
};
use crate::translations::translations_2::data_representation_translation;
use crate::translations::translations_4::data_exceeded_translation;
use crate::translations::translations_5::remote_notifications_translation;
use crate::utils::types::icon::Icon;
use crate::{Language, Sniffer, StyleType};
const CONTAINERS_WIDTH: f32 = 715.0;
pub fn settings_notifications_page<'a>(sniffer: &Sniffer) -> Container<'a, Message, StyleType> {
let Settings {
language,
color_gradient,
mut notifications,
..
} = sniffer.conf.settings.clone();
// Use threshold that has not yet been applied, if available
if let Some(temp_data_notification) = sniffer.timing_events.temp_threshold() {
notifications.data_notification.threshold = temp_data_notification.threshold;
notifications.data_notification.byte_multiple = temp_data_notification.byte_multiple;
notifications.data_notification.previous_threshold =
temp_data_notification.previous_threshold;
}
let mut content = Column::new()
.align_x(Alignment::Center)
.width(Length::Fill)
.push(settings_header(color_gradient, language))
.push(get_settings_tabs(SettingsPage::Notifications, language))
.push(Space::new().height(15))
.push(
notifications_title_translation(language)
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE)
.width(Length::Fill)
.align_x(Alignment::Center),
)
.push(Space::new().height(5));
let volume_notification_col = Column::new()
.spacing(10)
.align_x(Alignment::Center)
.width(Length::Fill)
.push(volume_slider(language, notifications.volume))
.push(Scrollable::with_direction(
Column::new()
.padding(Padding::ZERO.bottom(10))
.spacing(10)
.align_x(Alignment::Center)
.width(Length::Fill)
.push(get_data_notify(notifications.data_notification, language))
.push(get_favorite_notify(
notifications.favorite_notification,
language,
))
.push(
Container::new(RuleType::Standard.horizontal(10))
.padding(Padding::ZERO.left(40).right(40)),
)
.push(get_remote_notifications(
¬ifications.remote_notifications,
language,
)),
Direction::Vertical(ScrollbarType::properties().margin(15)),
));
content = content.push(volume_notification_col);
Container::new(content)
.height(400)
.width(800)
.class(ContainerType::Modal)
}
fn get_data_notify<'a>(
data_notification: DataNotification,
language: Language,
) -> Container<'a, Message, StyleType> {
let checkbox = Checkbox::new(data_notification.threshold.is_some())
.label(data_exceeded_translation(language))
.on_toggle(move |toggled| {
if toggled {
Message::UpdateNotificationSettings(
Notification::Data(DataNotification {
threshold: Some(data_notification.previous_threshold),
..data_notification
}),
false,
)
} else {
Message::UpdateNotificationSettings(
Notification::Data(DataNotification {
threshold: None,
..data_notification
}),
false,
)
}
})
.size(18);
let mut ret_val = Column::new().spacing(15).push(checkbox);
if data_notification.threshold.is_none() {
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
} else {
let data_representation_row =
row_data_representation(data_notification, language, data_notification.data_repr);
let input_row = input_group_bytes(data_notification, language);
let sound_row = sound_buttons(Notification::Data(data_notification), language);
ret_val = ret_val
.push(sound_row)
.push(data_representation_row)
.push(input_row);
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
}
}
fn get_favorite_notify<'a>(
favorite_notification: FavoriteNotification,
language: Language,
) -> Container<'a, Message, StyleType> {
let checkbox = Checkbox::new(favorite_notification.notify_on_favorite)
.label(favorite_transmitted_translation(language))
.on_toggle(move |toggled| {
Message::UpdateNotificationSettings(
if toggled {
Notification::Favorite(FavoriteNotification::on(favorite_notification.sound))
} else {
Notification::Favorite(FavoriteNotification::off(favorite_notification.sound))
},
false,
)
})
.size(18);
let mut ret_val = Column::new().spacing(15).push(checkbox);
if favorite_notification.notify_on_favorite {
let sound_row = sound_buttons(Notification::Favorite(favorite_notification), language);
ret_val = ret_val.push(sound_row);
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
} else {
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
}
}
fn get_remote_notifications<'a>(
remote_notifications: &RemoteNotifications,
language: Language,
) -> Container<'a, Message, StyleType> {
let checkbox = Checkbox::new(remote_notifications.is_active())
.label(remote_notifications_translation(language))
.on_toggle(move |_| Message::ToggleRemoteNotifications)
.size(18);
let mut ret_val = Column::new().spacing(15).push(checkbox);
if remote_notifications.is_active() {
let input_row = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.padding(Padding::ZERO.left(26))
.push(Text::new("URL:".to_string()))
.push(
TextInput::new("https://example.com/notify", remote_notifications.url())
.on_input(Message::RemoteNotificationsUrl)
.padding([2, 5]),
);
ret_val = ret_val.push(input_row);
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
} else {
Container::new(ret_val)
.padding(15)
.width(CONTAINERS_WIDTH)
.class(ContainerType::BorderedRound)
}
}
fn input_group_bytes<'a>(
bytes_notification: DataNotification,
language: Language,
) -> Container<'a, Message, StyleType> {
let mut curr_threshold_str = (bytes_notification.threshold.unwrap_or_default()
/ bytes_notification.byte_multiple.multiplier())
.to_string();
curr_threshold_str.push_str(&bytes_notification.byte_multiple.get_char());
let input_row = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.padding(Padding::ZERO.left(26))
.push(Text::new(format!("{}:", threshold_translation(language))))
.push(
TextInput::new(
"0",
if curr_threshold_str.starts_with('0') {
""
} else {
&curr_threshold_str
},
)
.on_input(move |value| {
let bytes_notification = DataNotification::from(&value, Some(bytes_notification));
Message::UpdateNotificationSettings(Notification::Data(bytes_notification), false)
})
.padding([2, 5])
.width(100),
)
.push(
Text::new(per_second_translation(language))
.align_y(Alignment::Center)
.size(FONT_SIZE_FOOTER),
);
Container::new(input_row)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
}
fn volume_slider<'a>(language: Language, volume: u8) -> Container<'a, Message, StyleType> {
Container::new(
Column::new()
.spacing(5)
.align_x(Alignment::Center)
.push(Text::new(format!(
"{}: {volume:^3}%",
volume_translation(language)
)))
.push(
Row::new()
.align_y(Alignment::Center)
.push(
Icon::AudioMute
.to_text()
.width(30)
.align_y(Alignment::Center)
.size(20),
)
.push(
Slider::new(0..=100, volume, Message::ChangeVolume)
.step(5)
.width(200),
)
.push(Space::new().width(15))
.push(
Icon::AudioHigh
.to_text()
.align_y(Alignment::Center)
.size(20),
),
),
)
.padding(5)
.width(Length::Fill)
.height(60)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
}
fn sound_buttons<'a>(
notification: Notification,
language: Language,
) -> row::Wrapping<'a, Message, StyleType> {
let current_sound = match notification {
Notification::Data(n) => n.sound,
Notification::Favorite(n) => n.sound,
};
let mut ret_val = Row::new()
.width(Length::Shrink)
.align_y(Alignment::Center)
.spacing(5)
.padding(Padding::ZERO.left(26))
.push(Text::new(format!("{}:", sound_translation(language))));
for option in Sound::ALL {
let is_active = current_sound.eq(&option);
let message_value = match notification {
Notification::Data(n) => Notification::Data(DataNotification { sound: option, ..n }),
Notification::Favorite(n) => {
Notification::Favorite(FavoriteNotification { sound: option, ..n })
}
};
ret_val = ret_val.push(
Button::new(
option
.get_text()
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(Padding::ZERO.left(15).right(15))
.height(25)
.class(if is_active {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::UpdateNotificationSettings(
message_value,
option.ne(&Sound::None),
)),
);
}
ret_val.wrap()
}
pub fn settings_header<'a>(
color_gradient: GradientType,
language: Language,
) -> Container<'a, Message, StyleType> {
Container::new(
Row::new()
.push(Space::new().width(Length::Fill))
.push(
Text::new(settings_translation(language))
.size(FONT_SIZE_TITLE)
.width(Length::FillPortion(6))
.align_x(Alignment::Center),
)
.push(
Container::new(button_hide(Message::CloseSettings, language))
.width(Length::Fill)
.align_x(Alignment::Center),
),
)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.height(40)
.width(Length::Fill)
.class(ContainerType::Gradient(color_gradient))
}
fn row_data_representation<'a>(
data_notification: DataNotification,
language: Language,
data_repr: DataRepr,
) -> row::Wrapping<'a, Message, StyleType> {
let mut ret_val = Row::new()
.width(Length::Shrink)
.align_y(Alignment::Center)
.spacing(5)
.padding(Padding::ZERO.left(26))
.push(Text::new(format!(
"{}:",
data_representation_translation(language)
)));
for option in DataRepr::ALL {
let is_active = data_repr.eq(&option);
ret_val = ret_val.push(
Button::new(
Text::new(option.get_label(language).to_owned())
.size(FONT_SIZE_FOOTER)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(Padding::ZERO.left(15).right(15))
.height(25)
.class(if is_active {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::UpdateNotificationSettings(
Notification::Data(DataNotification {
data_repr: option,
..data_notification
}),
false,
)),
);
}
ret_val.wrap()
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/inspect_page.rs | src/gui/pages/inspect_page.rs | use std::cmp::min;
use iced::widget::scrollable::Direction;
use iced::widget::text::LineHeight;
use iced::widget::text_input::Side;
use iced::widget::tooltip::Position;
use iced::widget::{Button, Column, Container, Row, Scrollable, Text, TextInput};
use iced::widget::{ComboBox, Space, Toggler, Tooltip, button, combo_box, text_input};
use iced::{Alignment, Length, Padding, Pixels, alignment};
use crate::gui::components::tab::get_pages_tabs;
use crate::gui::components::types::my_modal::MyModal;
use crate::gui::pages::overview_page::{get_bars, get_bars_length};
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{
FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE, ICONS, TOOLTIP_DELAY,
};
use crate::gui::styles::text::TextType;
use crate::gui::styles::text_input::TextInputType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::address_port_pair::AddressPortPair;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host_data_states::HostStates;
use crate::networking::types::info_address_port_pair::InfoAddressPortPair;
use crate::networking::types::traffic_direction::TrafficDirection;
use crate::report::get_report_entries::get_searched_entries;
use crate::report::types::report_col::ReportCol;
use crate::report::types::search_parameters::{FilterInputType, SearchParameters};
use crate::report::types::sort_type::SortType;
use crate::translations::translations_2::{
administrative_entity_translation, country_translation, domain_name_translation,
no_search_results_translation, only_show_favorites_translation, showing_results_translation,
};
use crate::translations::translations_3::filter_by_host_translation;
use crate::utils::types::icon::Icon;
use crate::{Language, RunningPage, Sniffer, StyleType};
/// Computes the body of gui inspect page
pub fn inspect_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let mut body = Column::new()
.width(Length::Fill)
.padding(10)
.spacing(10)
.align_x(Alignment::Center);
let mut tab_and_body = Column::new().height(Length::Fill);
let tabs = get_pages_tabs(RunningPage::Inspect, language, sniffer.unread_notifications);
tab_and_body = tab_and_body.push(tabs);
let report = report(sniffer);
let col_report = Column::new()
.height(Length::Fill)
.width(Length::Fill)
.align_x(Alignment::Start)
.push(report_header_row(
language,
&sniffer.search,
sniffer.conf.report_sort_type,
sniffer.conf.data_repr,
))
.push(Space::new().height(4))
.push(RuleType::Standard.horizontal(5))
.push(report);
body = body
.push(
Container::new(host_filters_col(
&sniffer.search,
&sniffer.host_data_states.states,
language,
))
.padding(10)
.class(ContainerType::BorderedRound),
)
.push(
Container::new(col_report)
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.padding(Padding::new(7.0).top(10).bottom(3))
.width(947)
.class(ContainerType::BorderedRound),
);
Container::new(Column::new().push(tab_and_body.push(body))).height(Length::Fill)
}
fn report<'a>(sniffer: &Sniffer) -> Column<'a, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let data_repr = sniffer.conf.data_repr;
let (search_results, results_number, agglomerate) = get_searched_entries(sniffer);
let mut ret_val = Column::new()
.height(Length::Fill)
.width(Length::Fill)
.align_x(Alignment::Start);
let mut scroll_report = Column::new().align_x(Alignment::Start);
let start_entry_num = (sniffer.page_number.saturating_sub(1)) * 20 + 1;
let end_entry_num = start_entry_num + search_results.len() - 1;
for report_entry in search_results {
scroll_report = scroll_report.push(
button(row_report_entry(
&report_entry.0,
&report_entry.1,
data_repr,
))
.padding(2)
.on_press(Message::ShowModal(MyModal::ConnectionDetails(
report_entry.0,
)))
.class(ButtonType::Neutral),
);
}
if results_number > 0 {
ret_val = ret_val
.push(
Scrollable::with_direction(
scroll_report,
Direction::Vertical(ScrollbarType::properties()),
)
.height(Length::Fill)
.width(Length::Fill),
)
.push(RuleType::Standard.horizontal(5))
.push(get_agglomerates_row(agglomerate, sniffer.conf.data_repr))
.push(RuleType::Standard.horizontal(5))
.push(get_change_page_row(
language,
sniffer.page_number,
start_entry_num,
end_entry_num,
results_number,
));
} else {
ret_val = ret_val.push(
Column::new()
.width(Length::Fill)
.height(Length::Fill)
.padding(20)
.align_x(Alignment::Center)
.push(Space::new().height(Length::Fill))
.push(Icon::Funnel.to_text().size(60))
.push(Space::new().height(15))
.push(Text::new(no_search_results_translation(language)))
.push(Space::new().height(Length::FillPortion(2))),
);
}
ret_val
}
fn report_header_row(
language: Language,
search_params: &SearchParameters,
sort_type: SortType,
data_repr: DataRepr,
) -> Row<'_, Message, StyleType> {
let mut ret_val = Row::new().padding([0, 2]).align_y(Alignment::Center);
for report_col in ReportCol::ALL {
let (title_display, title_small_display, tooltip_val) =
title_report_col_display(&report_col, data_repr, language);
let title_row = Row::new()
.align_y(Alignment::End)
.push(Text::new(title_display))
.push(Text::new(title_small_display).size(FONT_SIZE_FOOTER));
let tooltip_style = if tooltip_val.is_empty() {
ContainerType::Standard
} else {
ContainerType::Tooltip
};
let title_tooltip = Tooltip::new(title_row, Text::new(tooltip_val), Position::FollowCursor)
.class(tooltip_style)
.delay(TOOLTIP_DELAY);
let mut col_header = Column::new()
.align_x(Alignment::Center)
.width(report_col.get_width())
.height(56)
.push(title_tooltip);
if report_col == ReportCol::Data {
col_header = col_header.push(sort_arrows(sort_type));
} else {
col_header = col_header.push(
Container::new(filter_input(
report_col.get_filter_input_type(),
search_params.clone(),
))
.height(Length::Fill)
.align_y(Alignment::Center),
);
}
ret_val = ret_val.push(col_header);
}
ret_val
}
fn title_report_col_display(
report_col: &ReportCol,
data_repr: DataRepr,
language: Language,
) -> (String, String, String) {
let max_chars = report_col.get_max_chars(Some(language));
let title = report_col.get_title(language, data_repr);
let title_direction_info = report_col.get_title_direction_info(language);
let chars_title = title.chars().collect::<Vec<char>>();
let chars_title_direction_info = title_direction_info.chars().collect::<Vec<char>>();
if chars_title.len() + chars_title_direction_info.len() <= max_chars {
(title, title_direction_info, String::new())
} else if chars_title.len() >= max_chars - 4 {
(
chars_title[..min(max_chars - 2, chars_title.len())]
.iter()
.collect::<String>(),
String::from("…"),
[title, title_direction_info].concat(),
)
} else {
// title length is < max_chars - 4, but with direction info the whole thing is too long
(
title.clone(),
[
&chars_title_direction_info[..max_chars - chars_title.len() - 2]
.iter()
.collect::<String>(),
"…",
]
.concat(),
[title, title_direction_info].concat(),
)
}
}
fn sort_arrows<'a>(active_sort_type: SortType) -> Container<'a, Message, StyleType> {
Container::new(
button(
active_sort_type
.icon()
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.class(active_sort_type.button_type())
.on_press(Message::ReportSortSelection(active_sort_type.next_sort())),
)
.align_y(Alignment::Center)
.height(Length::Fill)
}
fn row_report_entry<'a>(
key: &AddressPortPair,
val: &InfoAddressPortPair,
data_repr: DataRepr,
) -> Row<'a, Message, StyleType> {
let text_type = if val.traffic_direction == TrafficDirection::Outgoing {
TextType::Outgoing
} else {
TextType::Incoming
};
let mut ret_val = Row::new().align_y(Alignment::Center);
for report_col in ReportCol::ALL {
let max_chars = report_col.get_max_chars(None);
let col_value = report_col.get_value(key, val, data_repr);
ret_val = ret_val.push(
Container::new(
Text::new(if col_value.len() <= max_chars {
col_value
} else {
[&col_value[..max_chars - 2], "…"].concat()
})
.class(text_type),
)
.align_x(Alignment::Center)
.width(report_col.get_width()),
);
}
ret_val
}
fn host_filters_col<'a>(
search_params: &'a SearchParameters,
host_states: &'a HostStates,
language: Language,
) -> Column<'a, Message, StyleType> {
let search_params2 = search_params.clone();
let mut title_row = Row::new().spacing(10).align_y(Alignment::Center).push(
Text::new(filter_by_host_translation(language))
.class(TextType::Subtitle)
.size(FONT_SIZE_SUBTITLE),
);
if search_params.is_some_host_filter_active() {
title_row = title_row.push(button_clear_filter(search_params.reset_host_filters()));
}
let combobox_country = filter_combobox(
FilterInputType::Country,
&host_states.countries,
search_params.clone(),
)
.width(95);
let combobox_domain = filter_combobox(
FilterInputType::Domain,
&host_states.domains,
search_params.clone(),
)
.width(190);
let combobox_as_name = filter_combobox(
FilterInputType::AsName,
&host_states.asns,
search_params.clone(),
)
.width(190);
let container_country = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.push(Text::new(format!("{}:", country_translation(language))))
.push(combobox_country);
let container_domain = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.push(Text::new(format!("{}:", domain_name_translation(language))))
.push(combobox_domain);
let container_as_name = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.push(Text::new(format!(
"{}:",
administrative_entity_translation(language)
)))
.push(combobox_as_name);
let col1 = Column::new()
.align_x(Alignment::Start)
.spacing(5)
.push(
Container::new(
Toggler::new(search_params.only_favorites)
.label(only_show_favorites_translation(language).to_owned())
.on_toggle(move |toggled| {
Message::Search(SearchParameters {
only_favorites: toggled,
..search_params2.clone()
})
})
.width(Length::Shrink)
.spacing(5)
.size(23),
)
.padding([5, 0]),
)
.push(container_domain);
let col2 = Column::new()
.align_x(Alignment::Start)
.spacing(5)
.push(container_country)
.push(container_as_name);
Column::new()
.align_x(Alignment::Start)
.push(title_row)
.push(Space::new().height(10))
.push(
Row::new()
.align_y(Alignment::Center)
.spacing(30)
.push(col1)
.push(col2),
)
}
fn filter_input<'a>(
filter_input_type: FilterInputType,
search_params: SearchParameters,
) -> Container<'a, Message, StyleType> {
let filter_value = filter_input_type.current_value(&search_params);
let is_filter_active = !filter_value.is_empty();
let button_clear = button_clear_filter(filter_input_type.clear_search(&search_params));
let mut input = TextInput::new("", filter_value)
.on_input(move |new_value| {
Message::Search(filter_input_type.new_search(&search_params, new_value))
})
.padding([2, 5])
.size(FONT_SIZE_FOOTER)
.width(Length::Fill)
.class(if is_filter_active {
TextInputType::Badge
} else {
TextInputType::Standard
});
if !is_filter_active {
input = input.icon(text_input::Icon {
font: ICONS,
code_point: Icon::Funnel.codepoint(),
size: Some(Pixels(12.0)),
spacing: 2.0,
side: Side::Left,
});
}
let mut content = Row::new().spacing(5).align_y(Alignment::Center).push(input);
if is_filter_active {
content = content.push(button_clear);
}
Container::new(content)
.padding(if is_filter_active {
Padding::new(5.0).left(10)
} else {
Padding::new(5.0).right(3).left(3)
})
.class(if is_filter_active {
ContainerType::Badge
} else {
ContainerType::Standard
})
}
fn filter_combobox(
filter_input_type: FilterInputType,
combo_box_state: &combo_box::State<String>,
search_params: SearchParameters,
) -> Container<'_, Message, StyleType> {
let filter_value = filter_input_type.current_value(&search_params).to_string();
let is_filter_active = !filter_value.is_empty();
let button_clear = button_clear_filter(filter_input_type.clear_search(&search_params));
let update_fn =
move |new_value| Message::Search(filter_input_type.new_search(&search_params, new_value));
let mut combobox = ComboBox::new(combo_box_state, "", Some(&filter_value), update_fn.clone())
.on_input(update_fn)
.padding([2, 5])
.size(FONT_SIZE_FOOTER)
.width(Length::Fill)
.input_class(if is_filter_active {
TextInputType::Badge
} else {
TextInputType::Standard
});
if combo_box_state.options().len() >= 9 {
combobox = combobox.menu_height(200);
}
if !is_filter_active {
combobox = combobox.icon(text_input::Icon {
font: ICONS,
code_point: Icon::Funnel.codepoint(),
size: Some(Pixels(12.0)),
spacing: 2.0,
side: Side::Left,
});
}
let mut content = Row::new()
.spacing(5)
.align_y(Alignment::Center)
.push(combobox);
if is_filter_active {
content = content.push(button_clear);
}
Container::new(content)
.padding(if is_filter_active {
Padding::new(5.0).left(10)
} else {
Padding::new(5.0).right(3).left(3)
})
.class(if is_filter_active {
ContainerType::Badge
} else {
ContainerType::Standard
})
}
fn get_button_change_page<'a>(increment: bool) -> Button<'a, Message, StyleType> {
button(
if increment {
Icon::ArrowRight
} else {
Icon::ArrowLeft
}
.to_text()
.size(8.0)
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
)
.padding(2)
.height(20)
.width(25)
.on_press(Message::UpdatePageNumber(increment))
}
fn get_agglomerates_row<'a>(tot: DataInfo, data_repr: DataRepr) -> Row<'a, Message, StyleType> {
let (in_length, out_length) = get_bars_length(data_repr, &tot, &tot);
let bars = get_bars(in_length, out_length).width(ReportCol::FILTER_COLUMNS_WIDTH);
let data_col = Column::new()
.align_x(Alignment::Center)
.width(ReportCol::Data.get_width())
.push(Text::new(
data_repr.formatted_string(tot.tot_data(data_repr)),
));
Row::new()
.padding([0, 2])
.height(40)
.align_y(Alignment::Center)
.push(bars)
.push(data_col)
}
fn get_change_page_row<'a>(
language: Language,
page_number: usize,
start_entry_num: usize,
end_entry_num: usize,
results_number: usize,
) -> Row<'a, Message, StyleType> {
Row::new()
.height(40)
.align_y(Alignment::Center)
.spacing(10)
.push(Space::new().width(Length::Fill))
.push(if page_number > 1 {
Container::new(get_button_change_page(false).width(25))
} else {
Container::new(Space::new().width(25))
})
.push(Text::new(showing_results_translation(
language,
start_entry_num,
end_entry_num,
results_number,
)))
.push(if page_number < results_number.div_ceil(20) {
Container::new(get_button_change_page(true).width(25))
} else {
Container::new(Space::new().width(25))
})
.push(Space::new().width(Length::Fill))
}
fn button_clear_filter<'a>(
new_search_parameters: SearchParameters,
) -> Button<'a, Message, StyleType> {
button(
Text::new("×")
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(15)
.line_height(LineHeight::Relative(1.0)),
)
.padding(2)
.height(20)
.width(20)
.on_press(Message::Search(new_search_parameters))
}
#[cfg(test)]
mod tests {
use crate::gui::pages::inspect_page::title_report_col_display;
use crate::networking::types::data_representation::DataRepr;
use crate::report::types::report_col::ReportCol;
use crate::translations::types::language::Language;
#[test]
fn test_table_titles_display_and_tooltip_values_for_each_language() {
// check glyph len when adding new language...
assert_eq!(Language::ALL.len(), 23);
for report_col in ReportCol::ALL {
for data_repr in DataRepr::ALL {
for language in Language::ALL {
let (title, title_small, tooltip_val) =
title_report_col_display(&report_col, data_repr, language);
let title_chars = title.chars().collect::<Vec<char>>();
let title_small_chars = title_small.chars().collect::<Vec<char>>();
let max_chars = report_col.get_max_chars(Some(language));
if tooltip_val.is_empty() {
// all is entirely displayed
assert!(title_chars.len() + title_small_chars.len() <= max_chars);
assert_eq!(title, report_col.get_title(language, data_repr));
assert_eq!(title_small, report_col.get_title_direction_info(language));
} else {
// tooltip is the full concatenation
assert_eq!(
tooltip_val,
[
report_col.get_title(language, data_repr),
report_col.get_title_direction_info(language)
]
.concat()
);
if report_col.get_title_direction_info(language).len() == 0 {
// displayed values have max len -1 (they include "…" that counts for 2 units)
assert_eq!(title_chars.len() + title_small_chars.len(), max_chars - 1);
} else {
match title_chars.len() {
x if x == max_chars - 4 || x == max_chars - 3 => {
assert_eq!(title_small_chars.len(), 1)
}
_ => assert_eq!(
title_chars.len() + title_small_chars.len(),
max_chars - 1
),
}
}
if title != report_col.get_title(language, data_repr) {
// first title part is not full, so second one is suspensions
assert_eq!(title_small, "…");
// check len wrt max
assert!(title_chars.len() >= max_chars - 4);
// first title part is max - 2 chars of full self
assert_eq!(
title,
report_col
.get_title(language, data_repr)
.chars()
.collect::<Vec<char>>()[..max_chars - 2]
.iter()
.collect::<String>()
);
} else {
// first part is untouched
// second title part is max - title.len - 2 chars of full self, plus suspensions
let mut second_part = [
&report_col
.get_title_direction_info(language)
.chars()
.collect::<Vec<char>>()[..max_chars - 2 - title_chars.len()]
.iter()
.collect::<String>(),
"…",
]
.concat();
if second_part == String::from(" (…")
|| second_part == String::from(" …")
{
second_part = String::from("…");
}
assert_eq!(title_small, second_part);
// second part never terminates with "(…"
assert!(!title_small.ends_with("(…"));
// second part never terminates with " …"
assert!(!title_small.ends_with(" …"));
}
}
}
}
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/welcome_page.rs | src/gui/pages/welcome_page.rs | use crate::StyleType;
use crate::gui::styles::text::TextType;
use crate::gui::types::message::Message;
use crate::utils::types::icon::Icon;
use iced::alignment::{Horizontal, Vertical};
use iced::widget::{Column, Container, Space, Text};
use iced::{Alignment, Length};
pub fn welcome_page<'a>(x: u8, thumbnail: bool) -> Container<'a, Message, StyleType> {
let icon = match x {
0..=3 | 20.. => Text::new(""),
4 => Icon::Sniffnet1.to_text(),
5 => Icon::Sniffnet2.to_text(),
6 => Icon::Sniffnet3.to_text(),
7 => Icon::Sniffnet4.to_text(),
8..=19 => Icon::Sniffnet.to_text(),
};
let text = Text::new(match x {
0..=3 | 20.. => "",
4 => "S",
5 => "Sn",
6 => "Sni",
7 => "Snif",
8 => "Sniff",
9 => "Sniffn",
10 => "Sniffne",
11..=19 => "Sniffnet",
});
let text_type = match x {
0..=3 | 20.. => TextType::Welcome(0.0),
4 => TextType::Welcome(0.125),
5 => TextType::Welcome(0.25),
6 => TextType::Welcome(0.375),
7 => TextType::Welcome(0.5),
8 => TextType::Welcome(0.625),
9 => TextType::Welcome(0.750),
10 => TextType::Welcome(0.875),
11..=19 => TextType::Welcome(1.0),
};
let icon_size = if thumbnail { 100 } else { 200 };
let text_size = if thumbnail { 40 } else { 75 };
let body = Column::new()
.align_x(Alignment::Center)
.push(Space::new().height(Length::Fill))
.push(icon.size(icon_size).line_height(0.9).class(text_type))
.push(text.size(text_size).class(text_type))
.push(Space::new().height(Length::FillPortion(2)));
Container::new(body)
.height(Length::Fill)
.width(Length::Fill)
.align_x(Horizontal::Center)
.align_y(Vertical::Center)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/mod.rs | src/gui/pages/mod.rs | pub mod connection_details_page;
pub mod initial_page;
pub mod inspect_page;
pub mod notifications_page;
pub mod overview_page;
pub mod settings_general_page;
pub mod settings_notifications_page;
pub mod settings_style_page;
pub mod thumbnail_page;
pub mod types;
pub mod waiting_page;
pub mod welcome_page;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/waiting_page.rs | src/gui/pages/waiting_page.rs | use crate::gui::pages::overview_page::col_device;
use crate::gui::sniffer::Sniffer;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::types::style_type::StyleType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::capture_context::CaptureSource;
use crate::networking::types::data_representation::DataRepr;
use crate::translations::translations::{
error_translation, no_addresses_translation, waiting_translation,
};
use crate::translations::translations_3::unsupported_link_type_translation;
use crate::translations::translations_4::reading_from_pcap_translation;
use crate::utils::types::icon::Icon;
use iced::widget::{Column, Container, Space, Text};
use iced::{Alignment, Length};
pub fn waiting_page(sniffer: &Sniffer) -> Option<Container<'_, Message, StyleType>> {
let Settings { language, .. } = sniffer.conf.settings;
let dots = &sniffer.dots_pulse.0;
let cs = &sniffer.capture_source;
let pcap_error = sniffer.pcap_error.as_ref();
let tot_packets = sniffer
.info_traffic
.tot_data_info
.tot_data(DataRepr::Packets);
if pcap_error.is_none() && tot_packets > 0 {
return None;
}
let link_type = cs.get_link_type();
let (icon_text, nothing_to_see_text) = if let Some(error) = pcap_error {
(
Icon::Error.to_text().size(60),
format!("{}\n\n{error}", error_translation(language)),
)
} else if !link_type.is_supported() {
(
Icon::Forbidden.to_text().size(60),
unsupported_link_type_translation(language).to_string(),
)
} else if matches!(cs, CaptureSource::File(_)) {
(
Icon::File.to_text().size(60),
reading_from_pcap_translation(language).to_string(),
)
} else if cs.get_addresses().is_empty() {
(
Icon::Warning.to_text().size(60),
no_addresses_translation(language).to_string(),
)
} else {
(
Icon::get_hourglass(dots.len()).size(60),
waiting_translation(language).to_string(),
)
};
let nothing_to_see_col = Column::new()
.align_x(Alignment::Center)
.push(icon_text)
.push(Space::new().height(25))
.push(Text::new(nothing_to_see_text).align_x(Alignment::Center))
.push(Text::new(dots.to_owned()).size(50));
Some(Container::new(
Column::new()
.width(Length::Fill)
.padding(10)
.align_x(Alignment::Center)
.push(Space::new().height(Length::Fill))
.push(
Container::new(
col_device(language, cs, &sniffer.conf.filters).height(Length::Shrink),
)
.padding([15, 30])
.class(ContainerType::BorderedRound),
)
.push(Space::new().height(20))
.push(
Container::new(nothing_to_see_col)
.align_x(Alignment::Center)
.width(Length::Fill)
.padding(15)
.class(ContainerType::BorderedRound),
)
.push(Space::new().height(Length::FillPortion(2))),
))
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/overview_page.rs | src/gui/pages/overview_page.rs | //! Module defining the run page of the application.
//!
//! It contains elements to display traffic statistics: chart, detailed connections data
//! and overall statistics about the traffic.
use crate::chart::types::donut_chart::donut_chart;
use crate::countries::country_utils::get_flag_tooltip;
use crate::countries::flags_pictures::{FLAGS_HEIGHT_BIG, FLAGS_WIDTH_BIG};
use crate::gui::components::tab::get_pages_tabs;
use crate::gui::pages::initial_page::get_addresses_row;
use crate::gui::sniffer::Sniffer;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_TITLE, TOOLTIP_DELAY};
use crate::gui::styles::text::TextType;
use crate::gui::types::filters::Filters;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::networking::types::capture_context::CaptureSource;
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_info_host::DataInfoHost;
use crate::networking::types::data_representation::DataRepr;
use crate::networking::types::host::Host;
use crate::networking::types::service::Service;
use crate::report::get_report_entries::{get_host_entries, get_service_entries};
use crate::report::types::search_parameters::SearchParameters;
use crate::report::types::sort_type::SortType;
use crate::translations::translations::{
active_filters_translation, incoming_translation, none_translation, outgoing_translation,
traffic_rate_translation,
};
use crate::translations::translations_2::{
data_representation_translation, dropped_translation, host_translation,
only_top_30_items_translation,
};
use crate::translations::translations_3::service_translation;
use crate::utils::types::icon::Icon;
use crate::{Language, RunningPage, StyleType};
use iced::Length::Fill;
use iced::alignment::{Horizontal, Vertical};
use iced::widget::scrollable::Direction;
use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Button, Column, Container, Row, Scrollable, Space, Text, Tooltip, button};
use iced::{Alignment, Element, Length, Padding};
/// Computes the body of gui overview page
pub fn overview_page(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let mut body = Column::new();
let mut tab_and_body = Column::new().height(Length::Fill);
// some packets are there!
let tabs = get_pages_tabs(
RunningPage::Overview,
language,
sniffer.unread_notifications,
);
tab_and_body = tab_and_body.push(tabs);
let container_chart = container_chart(sniffer);
let container_info = col_info(sniffer);
let container_report = row_report(sniffer);
body = body
.width(Length::Fill)
.padding(10)
.spacing(10)
.align_x(Alignment::Center)
.push(
Row::new()
.height(280)
.spacing(10)
.push(container_info)
.push(container_chart),
)
.push(container_report);
Container::new(Column::new().push(tab_and_body.push(body))).height(Length::Fill)
}
fn row_report<'a>(sniffer: &Sniffer) -> Row<'a, Message, StyleType> {
let col_host = col_host(sniffer);
let col_service = col_service(sniffer);
Row::new()
.spacing(10)
.push(
Container::new(col_host)
.width(Length::FillPortion(5))
.height(Length::Fill)
.padding(Padding::new(10.0).top(0).bottom(5))
.class(ContainerType::BorderedRound),
)
.push(
Container::new(col_service)
.width(Length::FillPortion(2))
.height(Length::Fill)
.padding(Padding::new(10.0).top(0).bottom(5))
.class(ContainerType::BorderedRound),
)
}
fn col_host<'a>(sniffer: &Sniffer) -> Column<'a, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let data_repr = sniffer.conf.data_repr;
let mut scroll_host = Column::new()
.padding(Padding::ZERO.right(11.0))
.align_x(Alignment::Center);
let entries = get_host_entries(
&sniffer.info_traffic,
data_repr,
sniffer.conf.host_sort_type,
);
let first_entry_data_info = entries
.iter()
.map(|(_, d)| d.data_info)
.max_by(|d1, d2| d1.compare(d2, SortType::Ascending, data_repr))
.unwrap_or_default();
for (host, data_info_host) in &entries {
let star_button = get_star_button(data_info_host.is_favorite, host.clone());
let host_bar = host_bar(
host,
data_info_host,
data_repr,
first_entry_data_info,
language,
);
let content = Row::new()
.align_y(Alignment::Center)
.spacing(5)
.push(star_button)
.push(host_bar);
scroll_host = scroll_host.push(
button(content)
.padding(Padding::new(5.0).right(15).left(10))
.on_press(Message::Search(SearchParameters::new_host_search(host)))
.class(ButtonType::Neutral),
);
}
if entries.len() >= 30 {
scroll_host = scroll_host
.push(Space::new().height(25))
.push(Text::new(only_top_30_items_translation(language)).align_x(Alignment::Center));
}
Column::new()
.push(
Row::new()
.height(45)
.align_y(Alignment::Center)
.push(
Text::new(host_translation(language))
.class(TextType::Title)
.size(FONT_SIZE_TITLE),
)
.push(Space::new().width(Length::Fill))
.push(sort_arrows(
sniffer.conf.host_sort_type,
Message::HostSortSelection,
)),
)
.push(
Scrollable::with_direction(
scroll_host,
Direction::Vertical(ScrollbarType::properties()),
)
.width(Length::Fill),
)
}
fn col_service<'a>(sniffer: &Sniffer) -> Column<'a, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let data_repr = sniffer.conf.data_repr;
let mut scroll_service = Column::new()
.padding(Padding::ZERO.right(11.0))
.align_x(Alignment::Center);
let entries = get_service_entries(
&sniffer.info_traffic,
data_repr,
sniffer.conf.service_sort_type,
);
let first_entry_data_info = entries
.iter()
.map(|&(_, d)| d)
.max_by(|d1, d2| d1.compare(d2, SortType::Ascending, data_repr))
.unwrap_or_default();
for (service, data_info) in &entries {
let content = service_bar(service, data_info, data_repr, first_entry_data_info);
scroll_service = scroll_service.push(
button(content)
.padding(Padding::new(5.0).right(15).left(10))
.on_press(Message::Search(SearchParameters::new_service_search(
service,
)))
.class(ButtonType::Neutral),
);
}
if entries.len() >= 30 {
scroll_service = scroll_service
.push(Space::new().height(25))
.push(Text::new(only_top_30_items_translation(language)).align_x(Alignment::Center));
}
Column::new()
.push(
Row::new()
.height(45)
.align_y(Alignment::Center)
.push(
Text::new(service_translation(language))
.class(TextType::Title)
.size(FONT_SIZE_TITLE),
)
.push(Space::new().width(Length::Fill))
.push(sort_arrows(
sniffer.conf.service_sort_type,
Message::ServiceSortSelection,
)),
)
.push(
Scrollable::with_direction(
scroll_service,
Direction::Vertical(ScrollbarType::properties()),
)
.width(Length::Fill),
)
}
pub fn host_bar<'a>(
host: &Host,
data_info_host: &DataInfoHost,
data_repr: DataRepr,
first_entry_data_info: DataInfo,
language: Language,
) -> Row<'a, Message, StyleType> {
let (incoming_bar_len, outgoing_bar_len) =
get_bars_length(data_repr, &first_entry_data_info, &data_info_host.data_info);
Row::new()
.height(FLAGS_HEIGHT_BIG)
.align_y(Alignment::Center)
.spacing(5)
.push(get_flag_tooltip(
host.country,
data_info_host,
language,
false,
))
.push(
Column::new()
.spacing(1)
.push(
Row::new()
.push(Text::new(host.domain.clone()))
.push(Text::new(if host.asn.name.is_empty() {
String::new()
} else {
format!(" - {}", host.asn.name)
}))
.push(Space::new().width(Length::Fill))
.push(Text::new(data_repr.formatted_string(
data_info_host.data_info.tot_data(data_repr),
))),
)
.push(get_bars(incoming_bar_len, outgoing_bar_len)),
)
}
pub fn service_bar<'a>(
service: &Service,
data_info: &DataInfo,
data_repr: DataRepr,
first_entry_data_info: DataInfo,
) -> Row<'a, Message, StyleType> {
let (incoming_bar_len, outgoing_bar_len) =
get_bars_length(data_repr, &first_entry_data_info, data_info);
Row::new()
.height(FLAGS_HEIGHT_BIG)
.align_y(Alignment::Center)
.spacing(5)
.push(
Column::new()
.spacing(1)
.push(
Row::new()
.push(Text::new(service.to_string()))
.push(Space::new().width(Length::Fill))
.push(Text::new(
data_repr.formatted_string(data_info.tot_data(data_repr)),
)),
)
.push(get_bars(incoming_bar_len, outgoing_bar_len)),
)
}
fn col_info(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let col_device = col_device(language, &sniffer.capture_source, &sniffer.conf.filters);
let col_data_representation = col_data_representation(language, sniffer.conf.data_repr);
let donut_row = donut_row(language, sniffer);
let content = Column::new()
.align_x(Alignment::Center)
.padding([5, 10])
.push(
Row::new()
.height(Length::Fill)
.push(
Scrollable::with_direction(
col_device,
Direction::Horizontal(ScrollbarType::properties()),
)
.width(Length::Fill),
)
.push(RuleType::Standard.vertical(25))
.push(col_data_representation.width(Length::Fill)),
)
.push(RuleType::Standard.horizontal(15))
.push(donut_row.height(Length::Fill));
Container::new(content)
.width(400)
.padding(Padding::new(5.0).top(10))
.align_x(Alignment::Center)
.class(ContainerType::BorderedRound)
}
fn container_chart(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let Settings { language, .. } = sniffer.conf.settings;
let traffic_chart = &sniffer.traffic_chart;
Container::new(
Column::new()
.align_x(Alignment::Center)
.push(
Row::new().padding([10, 0]).align_y(Alignment::Center).push(
traffic_rate_translation(language)
.class(TextType::Title)
.size(FONT_SIZE_TITLE),
),
)
.push(traffic_chart.view()),
)
.width(Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.class(ContainerType::BorderedRound)
}
pub(crate) fn col_device<'a>(
language: Language,
cs: &'a CaptureSource,
filters: &'a Filters,
) -> Column<'a, Message, StyleType> {
let link_type = cs.get_link_type();
#[cfg(not(target_os = "windows"))]
let cs_info = cs.get_name();
#[cfg(target_os = "windows")]
let cs_info = cs.get_desc().unwrap_or(cs.get_name());
let filters_desc: Element<Message, StyleType> = if filters.is_some_filter_active() {
Row::new()
.spacing(10)
.push(Text::new("BPF"))
.push(get_info_tooltip(Text::new(filters.bpf()).into()))
.into()
} else {
Text::new(none_translation(language)).into()
};
Column::new()
.height(Length::Fill)
.spacing(10)
.push(
Column::new()
.push(Text::new(format!("{}:", cs.title(language))).class(TextType::Subtitle))
.push(
Row::new()
.spacing(10)
.push(Text::new(format!(" {}", &cs_info)))
.push(get_info_tooltip(
Column::new()
.spacing(10)
.push(Text::new(link_type.full_print_on_one_line(language)))
.push(get_addresses_row(link_type, cs.get_addresses()))
.into(),
)),
),
)
.push(
Column::new()
.push(
Text::new(format!("{}:", active_filters_translation(language)))
.class(TextType::Subtitle),
)
.push(
Row::new()
.push(Text::new(" ".to_string()))
.push(filters_desc),
),
)
}
fn col_data_representation<'a>(
language: Language,
data_repr: DataRepr,
) -> Column<'a, Message, StyleType> {
let mut ret_val = Column::new().spacing(5).push(
Text::new(format!("{}:", data_representation_translation(language)))
.class(TextType::Subtitle),
);
let [bits, bytes, packets] = DataRepr::ALL.map(|option| {
let is_active = data_repr.eq(&option);
Button::new(
Text::new(option.get_label(language).to_owned())
.width(Length::Fill)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.width(Length::Fill)
.height(33)
.class(if is_active {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::DataReprSelection(option))
});
ret_val = ret_val
.push(Row::new().spacing(5).push(bits).push(bytes))
.push(packets);
ret_val
}
fn donut_row(language: Language, sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let data_repr = sniffer.conf.data_repr;
let (in_data, out_data, dropped) = sniffer.info_traffic.get_thumbnail_data(data_repr);
let legend_col = Column::new()
.spacing(5)
.push(donut_legend_entry(
in_data,
data_repr,
RuleType::Incoming,
language,
))
.push(donut_legend_entry(
out_data,
data_repr,
RuleType::Outgoing,
language,
))
.push(donut_legend_entry(
dropped,
data_repr,
RuleType::Dropped,
language,
));
let donut_row = Row::new()
.align_y(Vertical::Center)
.spacing(20)
.push(donut_chart(
data_repr,
in_data,
out_data,
dropped,
sniffer.thumbnail,
))
.push(legend_col);
Container::new(donut_row)
.height(Length::Fill)
.width(Length::Fill)
.align_x(Horizontal::Center)
.align_y(Vertical::Center)
}
fn donut_legend_entry<'a>(
value: u128,
data_repr: DataRepr,
rule_type: RuleType,
language: Language,
) -> Row<'a, Message, StyleType> {
let value_text = data_repr.formatted_string(value);
let label = match rule_type {
RuleType::Incoming => incoming_translation(language),
RuleType::Outgoing => outgoing_translation(language),
RuleType::Dropped => dropped_translation(language),
_ => "",
};
Row::new()
.spacing(10)
.align_y(Alignment::Center)
.push(Row::new().width(10).push(rule_type.horizontal(5)))
.push(Text::new(format!("{label}: {value_text}")))
}
const MIN_BARS_LENGTH: f32 = 4.0;
pub fn get_bars_length(
data_repr: DataRepr,
first_entry: &DataInfo,
data_info: &DataInfo,
) -> (u16, u16) {
let in_val = data_info.incoming_data(data_repr);
let out_val = data_info.outgoing_data(data_repr);
let first_entry_tot_val = first_entry.tot_data(data_repr);
let tot_val = in_val + out_val;
if tot_val == 0 {
return (0, 0);
}
#[allow(clippy::cast_precision_loss)]
let tot_len = 100.0 * tot_val as f32 / first_entry_tot_val as f32;
#[allow(clippy::cast_precision_loss)]
let (mut in_len, mut out_len) = (
tot_len * in_val as f32 / tot_val as f32,
tot_len * out_val as f32 / tot_val as f32,
);
if tot_len <= MIN_BARS_LENGTH {
// normalize small values
if in_val > 0 {
if out_val == 0 {
in_len = MIN_BARS_LENGTH;
} else {
in_len = MIN_BARS_LENGTH / 2.0;
}
}
if out_val > 0 {
if in_val == 0 {
out_len = MIN_BARS_LENGTH;
} else {
out_len = MIN_BARS_LENGTH / 2.0;
}
}
} else {
// tot_len is longer than minimum
if in_val > 0 && in_len < MIN_BARS_LENGTH / 2.0 {
let diff = MIN_BARS_LENGTH / 2.0 - in_len;
in_len += diff;
out_len -= diff;
}
if out_val > 0 && out_len < MIN_BARS_LENGTH / 2.0 {
let diff = MIN_BARS_LENGTH / 2.0 - out_len;
out_len += diff;
in_len -= diff;
}
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
(in_len.round() as u16, out_len.round() as u16)
}
pub fn get_bars<'a>(in_len: u16, out_len: u16) -> Row<'a, Message, StyleType> {
Row::new()
.push(if in_len > 0 {
Row::new()
.width(Length::FillPortion(in_len))
.push(RuleType::Incoming.horizontal(5))
} else {
Row::new()
})
.push(if out_len > 0 {
Row::new()
.width(Length::FillPortion(out_len))
.push(RuleType::Outgoing.horizontal(5))
} else {
Row::new()
})
.push(if in_len + out_len < 100 {
Row::new().width(Length::FillPortion(100 - in_len - out_len))
} else {
Row::new()
})
}
fn get_star_button<'a>(is_favorite: bool, host: Host) -> Button<'a, Message, StyleType> {
button(
Icon::Star
.to_text()
.size(20)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(0)
.height(FLAGS_HEIGHT_BIG)
.width(FLAGS_WIDTH_BIG)
.class(if is_favorite {
ButtonType::Starred
} else {
ButtonType::NotStarred
})
.on_press(Message::AddOrRemoveFavorite(host, !is_favorite))
}
fn get_info_tooltip(tooltip_content: Element<Message, StyleType>) -> Tooltip<Message, StyleType> {
Tooltip::new(
Container::new(
Text::new("i")
.size(FONT_SIZE_FOOTER)
.line_height(LineHeight::Relative(1.0)),
)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.height(20)
.width(20)
.class(ContainerType::BadgeInfo),
tooltip_content,
Position::FollowCursor,
)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn sort_arrows<'a>(
active_sort_type: SortType,
message: fn(SortType) -> Message,
) -> Container<'a, Message, StyleType> {
Container::new(
button(
active_sort_type
.icon()
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.class(active_sort_type.button_type())
.on_press(message(active_sort_type.next_sort())),
)
.width(60.0)
.align_x(Alignment::Center)
}
#[cfg(test)]
mod tests {
use crate::gui::pages::overview_page::{MIN_BARS_LENGTH, get_bars_length};
use crate::networking::types::data_info::DataInfo;
use crate::networking::types::data_representation::DataRepr;
#[test]
fn test_get_bars_length_simple() {
let first_entry = DataInfo::new_for_tests(50, 50, 150, 50);
let data_info = DataInfo::new_for_tests(25, 55, 165, 30);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(25, 55)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(83, 15)
);
assert_eq!(
get_bars_length(DataRepr::Bits, &first_entry, &data_info),
(83, 15)
);
}
#[test]
fn test_get_bars_length_normalize_small_values() {
let first_entry = DataInfo::new_for_tests(50, 50, 150, 50);
let mut data_info = DataInfo::new_for_tests(2, 1, 1, 0);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16 / 2, MIN_BARS_LENGTH as u16 / 2)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16, 0)
);
data_info = DataInfo::new_for_tests(0, 3, 0, 2);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(0, MIN_BARS_LENGTH as u16)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(0, MIN_BARS_LENGTH as u16)
);
}
#[test]
fn test_get_bars_length_normalize_very_small_values() {
let first_entry =
DataInfo::new_for_tests(u128::MAX / 2, u128::MAX / 2, u128::MAX / 2, u128::MAX / 2);
let mut data_info = DataInfo::new_for_tests(1, 1, 1, 1);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16 / 2, MIN_BARS_LENGTH as u16 / 2)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16 / 2, MIN_BARS_LENGTH as u16 / 2)
);
data_info = DataInfo::new_for_tests(0, 1, 0, 1);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(0, MIN_BARS_LENGTH as u16)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(0, MIN_BARS_LENGTH as u16)
);
data_info = DataInfo::new_for_tests(1, 0, 1, 0);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16, 0)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16, 0)
);
}
#[test]
fn test_get_bars_length_complex() {
let first_entry = DataInfo::new_for_tests(48, 7, 2, 12);
let mut data_info = DataInfo::new_for_tests(0, 9, 0, 10);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(0, 16)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(0, 71)
);
data_info = DataInfo::new_for_tests(9, 0, 13, 0);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(16, 0)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(93, 0)
);
data_info = DataInfo::new_for_tests(4, 5, 6, 7);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(7, 9)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(43, 50)
);
data_info = DataInfo::new_for_tests(5, 4, 7, 6);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(9, 7)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(50, 43)
);
data_info = DataInfo::new_for_tests(1, 8, 1, 12);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16 / 2, 14)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(7, 86)
);
data_info = DataInfo::new_for_tests(8, 1, 12, 1);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(14, MIN_BARS_LENGTH as u16 / 2)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(86, 7)
);
data_info = DataInfo::new_for_tests(6, 1, 10, 1);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(11, MIN_BARS_LENGTH as u16 / 2)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(71, 7)
);
data_info = DataInfo::new_for_tests(1, 6, 1, 9);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(MIN_BARS_LENGTH as u16 / 2, 11,)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(7, 64)
);
data_info = DataInfo::new_for_tests(1, 6, 5, 5);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(36, 36)
);
data_info = DataInfo::new_for_tests(0, 0, 0, 0);
assert_eq!(
get_bars_length(DataRepr::Packets, &first_entry, &data_info),
(0, 0)
);
assert_eq!(
get_bars_length(DataRepr::Bytes, &first_entry, &data_info),
(0, 0)
);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/types/settings_page.rs | src/gui/pages/types/settings_page.rs | use crate::gui::types::message::Message;
use crate::translations::translations::{notifications_translation, style_translation};
use crate::translations::translations_3::general_translation;
use crate::utils::types::icon::Icon;
use crate::{Language, StyleType};
use serde::{Deserialize, Serialize};
/// This enum defines the current settings page.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize, Default)]
pub enum SettingsPage {
/// Settings Notifications page.
#[default]
Notifications,
/// Settings Appearance page.
Appearance,
/// General settings.
General,
}
impl SettingsPage {
pub const ALL: [SettingsPage; 3] = [
SettingsPage::Notifications,
SettingsPage::Appearance,
SettingsPage::General,
];
pub fn get_tab_label(&self, language: Language) -> &str {
match self {
SettingsPage::Notifications => notifications_translation(language),
SettingsPage::Appearance => style_translation(language),
SettingsPage::General => general_translation(language),
}
}
pub fn next(self) -> Self {
match self {
SettingsPage::Notifications => SettingsPage::Appearance,
SettingsPage::Appearance => SettingsPage::General,
SettingsPage::General => SettingsPage::Notifications,
}
}
pub fn previous(self) -> Self {
match self {
SettingsPage::Notifications => SettingsPage::General,
SettingsPage::Appearance => SettingsPage::Notifications,
SettingsPage::General => SettingsPage::Appearance,
}
}
pub fn icon<'a>(self) -> iced::widget::Text<'a, StyleType> {
match self {
SettingsPage::Notifications => Icon::Notification,
SettingsPage::Appearance => Icon::HalfSun,
SettingsPage::General => Icon::Generals,
}
.to_text()
}
pub fn action(self) -> Message {
Message::OpenSettings(self)
}
}
#[cfg(test)]
mod tests {
use crate::gui::pages::types::settings_page::SettingsPage;
#[test]
fn test_previous_settings_page() {
assert_eq!(
SettingsPage::Notifications.previous(),
SettingsPage::General
);
assert_eq!(
SettingsPage::Appearance.previous(),
SettingsPage::Notifications
);
assert_eq!(SettingsPage::General.previous(), SettingsPage::Appearance);
}
#[test]
fn test_next_settings_page() {
assert_eq!(SettingsPage::Notifications.next(), SettingsPage::Appearance);
assert_eq!(SettingsPage::Appearance.next(), SettingsPage::General);
assert_eq!(SettingsPage::General.next(), SettingsPage::Notifications);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/types/mod.rs | src/gui/pages/types/mod.rs | pub mod running_page;
pub mod settings_page;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/pages/types/running_page.rs | src/gui/pages/types/running_page.rs | use crate::gui::types::message::Message;
use crate::translations::translations::{notifications_translation, overview_translation};
use crate::translations::translations_2::inspect_translation;
use crate::utils::types::icon::Icon;
use crate::{Language, StyleType};
use serde::{Deserialize, Serialize};
/// This enum defines the current running page.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize, Default)]
pub enum RunningPage {
/// Overview page.
#[default]
Overview,
/// Inspect page.
Inspect,
/// Notifications page.
Notifications,
}
impl RunningPage {
pub const ALL: [RunningPage; 3] = [
RunningPage::Overview,
RunningPage::Inspect,
RunningPage::Notifications,
];
pub fn get_tab_label(&self, language: Language) -> &str {
match self {
RunningPage::Overview => overview_translation(language),
RunningPage::Inspect => inspect_translation(language),
RunningPage::Notifications => notifications_translation(language),
}
}
pub fn next(self) -> Self {
match self {
RunningPage::Overview => RunningPage::Inspect,
RunningPage::Inspect => RunningPage::Notifications,
RunningPage::Notifications => RunningPage::Overview,
}
}
pub fn previous(self) -> Self {
match self {
RunningPage::Overview => RunningPage::Notifications,
RunningPage::Inspect => RunningPage::Overview,
RunningPage::Notifications => RunningPage::Inspect,
}
}
pub fn icon<'a>(self) -> iced::widget::Text<'a, StyleType> {
match self {
RunningPage::Overview => Icon::Overview,
RunningPage::Inspect => Icon::Inspect,
RunningPage::Notifications => Icon::Notification,
}
.to_text()
}
pub fn action(self) -> Message {
Message::ChangeRunningPage(self)
}
}
#[cfg(test)]
mod tests {
use crate::RunningPage;
#[test]
fn test_previous_running_page() {
assert_eq!(RunningPage::Overview.previous(), RunningPage::Notifications);
assert_eq!(RunningPage::Notifications.previous(), RunningPage::Inspect);
assert_eq!(RunningPage::Inspect.previous(), RunningPage::Overview);
}
#[test]
fn test_next_running_page() {
assert_eq!(RunningPage::Overview.next(), RunningPage::Inspect);
assert_eq!(RunningPage::Inspect.next(), RunningPage::Notifications);
assert_eq!(RunningPage::Notifications.next(), RunningPage::Overview);
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/button.rs | src/gui/components/button.rs | #![allow(clippy::module_name_repetitions)]
use iced::Alignment;
use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Row, Text, Tooltip, button};
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::TOOLTIP_DELAY;
use crate::gui::styles::text::TextType;
use crate::gui::types::message::Message;
use crate::translations::translations::hide_translation;
use crate::utils::types::file_info::FileInfo;
use crate::utils::types::icon::Icon;
use crate::{Language, StyleType};
pub fn button_hide<'a>(message: Message, language: Language) -> Tooltip<'a, Message, StyleType> {
Tooltip::new(
button(
Text::new("×")
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(15)
.line_height(LineHeight::Relative(1.0)),
)
.padding(2)
.height(20)
.width(20)
.on_press(message),
Text::new(hide_translation(language)),
Position::Right,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
pub fn button_open_file<'a>(
old_file: String,
file_info: FileInfo,
language: Language,
is_editable: bool,
action: fn(String) -> Message,
) -> Tooltip<'a, Message, StyleType> {
let mut tooltip_str = "";
let mut tooltip_style = ContainerType::Standard;
let mut button = button(
Icon::File
.to_text()
.align_y(Alignment::Center)
.align_x(Alignment::Center)
.size(16.0),
)
.padding(0)
.height(25)
.width(40);
if is_editable {
tooltip_str = file_info.action_info(language);
tooltip_style = ContainerType::Tooltip;
button = button.on_press(Message::OpenFile(old_file, file_info, action));
}
Tooltip::new(button, Text::new(tooltip_str), Position::Right)
.gap(5)
.class(tooltip_style)
.delay(TOOLTIP_DELAY)
}
pub fn row_open_link_tooltip<'a>(str: &'static str) -> Row<'a, Message, StyleType> {
let text = if str.is_empty() {
None
} else {
Some(Text::new(str))
};
Row::new()
.align_y(Alignment::Center)
.spacing(10)
.push(text)
.push(Icon::OpenLink.to_text().size(16).class(TextType::Title))
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/footer.rs | src/gui/components/footer.rs | //! GUI bottom footer
use iced::widget::Space;
use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Column, Container, Row, Text, Tooltip, button, rich_text, span};
use iced::{Alignment, Length, Padding};
use crate::gui::components::button::row_open_link_tooltip;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::{FONT_SIZE_FOOTER, FONT_SIZE_SUBTITLE, TOOLTIP_DELAY};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::styles::types::style_type::StyleType;
use crate::gui::types::message::Message;
use crate::translations::translations_2::new_version_available_translation;
use crate::utils::formatted_strings::APP_VERSION;
use crate::utils::types::icon::Icon;
use crate::utils::types::web_page::WebPage;
use crate::{Language, SNIFFNET_TITLECASE};
pub fn footer<'a>(
thumbnail: bool,
language: Language,
color_gradient: GradientType,
newer_release_available: Option<bool>,
dots_pulse: &(String, u8),
) -> Container<'a, Message, StyleType> {
if thumbnail {
return thumbnail_footer();
}
let release_details_row = get_release_details(language, newer_release_available);
let heart_size = match dots_pulse.1 {
1 => 17.0,
2 => 20.0,
_ => 14.0,
};
let footer_row = Row::new()
.spacing(10)
.padding([0, 20])
.align_y(Alignment::Center)
.push(release_details_row)
.push(get_button_roadmap())
.push(get_button_wiki())
.push(get_button_github())
.push(get_button_news())
.push(get_button_sponsor())
.push(
Column::new()
.width(Length::Fill)
.align_x(Alignment::End)
.push(
Row::new()
.height(Length::Fill)
.align_y(Alignment::Center)
.push(Text::new("Made with").size(FONT_SIZE_FOOTER))
.push(
Text::new("❤")
.size(heart_size)
.width(25)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.push(Text::new("by ").size(FONT_SIZE_FOOTER))
.push(
Tooltip::new(
rich_text![span("Giuliano Bellini").underline(true).link(())]
.on_link_click(|()| Message::OpenWebPage(WebPage::MyGitHub))
.size(FONT_SIZE_FOOTER),
row_open_link_tooltip(""),
Position::FollowCursor,
)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY),
),
),
);
Container::new(footer_row)
.height(45)
.align_y(Alignment::Center)
.class(ContainerType::Gradient(color_gradient))
}
fn get_button_roadmap<'a>() -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::Roadmap
.to_text()
.size(15)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.padding(Padding::ZERO.top(2))
.height(30)
.width(30)
.on_press(Message::OpenWebPage(WebPage::Roadmap));
Tooltip::new(content, row_open_link_tooltip("Roadmap"), Position::Top)
.gap(10)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn get_button_wiki<'a>() -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::Book
.to_text()
.size(19)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.padding(Padding::ZERO.top(1))
.height(35)
.width(35)
.on_press(Message::OpenWebPage(WebPage::Wiki));
Tooltip::new(content, row_open_link_tooltip("Wiki"), Position::Top)
.gap(7.5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn get_button_github<'a>() -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::GitHub
.to_text()
.size(26)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.height(40)
.width(40)
.on_press(Message::OpenWebPage(WebPage::Repo));
Tooltip::new(content, row_open_link_tooltip("GitHub"), Position::Top)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn get_button_news<'a>() -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::News
.to_text()
.size(16)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.height(35)
.width(35)
.on_press(Message::OpenWebPage(WebPage::WebsiteNews));
Tooltip::new(content, row_open_link_tooltip("News"), Position::Top)
.gap(7.5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn get_button_sponsor<'a>() -> Tooltip<'a, Message, StyleType> {
let content = button(
Text::new('❤'.to_string())
.size(23)
.class(TextType::Sponsor)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.padding(Padding::ZERO.top(2))
.height(30)
.width(30)
.on_press(Message::OpenWebPage(WebPage::WebsiteSponsor));
Tooltip::new(content, row_open_link_tooltip("Sponsor"), Position::Top)
.gap(10)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
fn get_release_details<'a>(
language: Language,
newer_release_available: Option<bool>,
) -> Row<'a, Message, StyleType> {
let mut ret_val = Row::new()
.align_y(Alignment::Center)
.height(Length::Fill)
.width(Length::Fill)
.push(Text::new(format!("{SNIFFNET_TITLECASE} {APP_VERSION}")).size(FONT_SIZE_FOOTER));
if let Some(boolean_response) = newer_release_available {
if boolean_response {
// a newer release is available on GitHub
let button = button(
Icon::NewerVersion
.to_text()
.size(23)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(0.8)),
)
.padding(0)
.height(35)
.width(35)
.class(ButtonType::Alert)
.on_press(Message::OpenWebPage(WebPage::WebsiteDownload));
let tooltip = Tooltip::new(
button,
row_open_link_tooltip(new_version_available_translation(language)),
Position::Top,
)
.gap(7.5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY);
ret_val = ret_val.push(Space::new().width(10)).push(tooltip);
} else {
// this is the latest release
ret_val = ret_val.push(Text::new(" ✔").size(FONT_SIZE_SUBTITLE));
}
}
ret_val
}
fn thumbnail_footer<'a>() -> Container<'a, Message, StyleType> {
Container::new(Space::new().width(Length::Fill)).height(0)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/header.rs | src/gui/components/header.rs | //! GUI upper header
use iced::widget::text::LineHeight;
use iced::widget::tooltip::Position;
use iced::widget::{Container, Row, Space, Text, Tooltip, button};
use iced::{Alignment, Length};
use crate::gui::components::tab::notifications_badge;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::sniffer::Sniffer;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::TOOLTIP_DELAY;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::gui::types::settings::Settings;
use crate::translations::translations::{quit_analysis_translation, settings_translation};
use crate::translations::translations_3::thumbnail_mode_translation;
use crate::translations::translations_4::{pause_translation, resume_translation};
use crate::utils::types::icon::Icon;
use crate::{Language, SNIFFNET_TITLECASE, StyleType};
pub fn header(sniffer: &Sniffer) -> Container<'_, Message, StyleType> {
let thumbnail = sniffer.thumbnail;
let Settings {
language,
color_gradient,
..
} = sniffer.conf.settings;
if thumbnail {
let unread_notifications = sniffer.unread_notifications;
return thumbnail_header(
language,
color_gradient,
unread_notifications,
sniffer.frozen,
);
}
let last_opened_setting = sniffer.conf.last_opened_setting;
let is_running = sniffer.running_page.is_some();
let logo = Icon::Sniffnet
.to_text()
.align_y(Alignment::Center)
.height(Length::Fill)
.line_height(LineHeight::Relative(0.7))
.size(80);
Container::new(
Row::new()
.padding([0, 20])
.align_y(Alignment::Center)
.push(if is_running {
Container::new(get_button_reset(language))
} else {
Container::new(Space::new().width(60))
})
.push(Space::new().width(Length::Fill))
.push(Container::new(Space::new().width(80)))
.push(Space::new().width(20))
.push(logo)
.push(Space::new().width(20))
.push(if is_running {
Container::new(get_button_freeze(language, sniffer.frozen, false))
} else {
Container::new(Space::new().width(40))
})
.push(if is_running {
Container::new(get_button_minimize(language, false))
} else {
Container::new(Space::new().width(40))
})
.push(Space::new().width(Length::Fill))
.push(get_button_settings(language, last_opened_setting)),
)
.height(70)
.align_y(Alignment::Center)
.class(ContainerType::Gradient(color_gradient))
}
fn get_button_reset<'a>(language: Language) -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::ArrowBack
.to_text()
.size(20)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.line_height(LineHeight::Relative(1.0)),
)
.padding(10)
.height(40)
.width(60)
.on_press(Message::ResetButtonPressed);
Tooltip::new(
content,
Text::new(quit_analysis_translation(language)),
Position::Right,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
pub fn get_button_settings<'a>(
language: Language,
open_overlay: SettingsPage,
) -> Tooltip<'a, Message, StyleType> {
let content = button(
Icon::Settings
.to_text()
.size(20)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(0)
.height(40)
.width(60)
.on_press(Message::OpenSettings(open_overlay));
Tooltip::new(
content,
Text::new(settings_translation(language)),
Position::Left,
)
.gap(5)
.class(ContainerType::Tooltip)
.delay(TOOLTIP_DELAY)
}
pub fn get_button_minimize<'a>(
language: Language,
thumbnail: bool,
) -> Tooltip<'a, Message, StyleType> {
let size = if thumbnail { 20 } else { 24 };
let button_size = if thumbnail { 30 } else { 40 };
let icon = if thumbnail {
Icon::ThumbnailClose
} else {
Icon::ThumbnailOpen
};
let tooltip = if thumbnail {
""
} else {
thumbnail_mode_translation(language)
};
let tooltip_style = if thumbnail {
ContainerType::Standard
} else {
ContainerType::Tooltip
};
let content = button(
icon.to_text()
.size(size)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(0)
.height(button_size)
.width(button_size)
.class(ButtonType::Thumbnail)
.on_press(Message::ToggleThumbnail(false));
Tooltip::new(content, Text::new(tooltip), Position::FollowCursor)
.gap(0)
.class(tooltip_style)
.delay(TOOLTIP_DELAY)
}
pub fn get_button_freeze<'a>(
language: Language,
frozen: bool,
thumbnail: bool,
) -> Tooltip<'a, Message, StyleType> {
let size = if thumbnail { 19 } else { 23 };
let button_size = if thumbnail { 30 } else { 40 };
let icon = if frozen { Icon::Resume } else { Icon::Pause };
let tooltip = if thumbnail {
""
} else if frozen {
resume_translation(language)
} else {
pause_translation(language)
};
let tooltip_style = if thumbnail {
ContainerType::Standard
} else {
ContainerType::Tooltip
};
let content = button(
icon.to_text()
.size(size)
.align_x(Alignment::Center)
.align_y(Alignment::Center),
)
.padding(0)
.height(button_size)
.width(button_size)
.class(ButtonType::Thumbnail)
.on_press(Message::Freeze);
Tooltip::new(content, Text::new(tooltip), Position::FollowCursor)
.gap(0)
.class(tooltip_style)
.delay(TOOLTIP_DELAY)
}
fn thumbnail_header<'a>(
language: Language,
color_gradient: GradientType,
unread_notifications: usize,
frozen: bool,
) -> Container<'a, Message, StyleType> {
Container::new(
Row::new()
.align_y(Alignment::Center)
.push(Space::new().width(Length::Fill))
.push(Space::new().width(110))
.push(Text::new(SNIFFNET_TITLECASE))
.push(Space::new().width(10))
.push(get_button_freeze(language, frozen, true))
.push(get_button_minimize(language, true))
.push(Space::new().width(Length::Fill))
.push(if unread_notifications > 0 {
Container::new(
notifications_badge(unread_notifications)
.class(ContainerType::HighlightedOnHeader),
)
.width(40)
.align_x(Alignment::Center)
} else {
Container::new(Space::new().width(40))
}),
)
.height(30)
.align_y(Alignment::Center)
.class(ContainerType::Gradient(color_gradient))
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/mod.rs | src/gui/components/mod.rs | pub mod button;
pub mod footer;
pub mod header;
pub mod modal;
pub mod tab;
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/gui/components/modal.rs | src/gui/components/modal.rs | use iced::alignment::Alignment;
use iced::widget::{
Column, Container, Row, Space, Text, button, center, mouse_area, opaque, stack,
};
use iced::{Element, Length};
use crate::gui::components::button::button_hide;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::FONT_SIZE_TITLE;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::translations::translations::{
ask_clear_all_translation, ask_quit_translation, clear_all_translation,
quit_analysis_translation, yes_translation,
};
use crate::{Language, StyleType};
pub fn get_exit_overlay<'a>(
message: Message,
color_gradient: GradientType,
language: Language,
) -> Container<'a, Message, StyleType> {
let row_buttons = confirm_button_row(language, message);
let content = Column::new()
.align_x(Alignment::Center)
.width(Length::Fill)
.push(get_modal_header(
color_gradient,
language,
quit_analysis_translation(language),
))
.push(Space::new().height(20))
.push(ask_quit_translation(language).align_x(Alignment::Center))
.push(row_buttons);
Container::new(content)
.height(160)
.width(450)
.class(ContainerType::Modal)
}
pub fn get_clear_all_overlay<'a>(
color_gradient: GradientType,
language: Language,
) -> Container<'a, Message, StyleType> {
let row_buttons = confirm_button_row(language, Message::ClearAllNotifications);
let content = Column::new()
.align_x(Alignment::Center)
.width(Length::Fill)
.push(get_modal_header(
color_gradient,
language,
clear_all_translation(language),
))
.push(Space::new().height(20))
.push(ask_clear_all_translation(language).align_x(Alignment::Center))
.push(row_buttons);
Container::new(content)
.height(160)
.width(450)
.class(ContainerType::Modal)
}
fn get_modal_header<'a>(
color_gradient: GradientType,
language: Language,
title: &'static str,
) -> Container<'a, Message, StyleType> {
Container::new(
Row::new()
.push(Space::new().width(Length::Fill))
.push(
Text::new(title)
.size(FONT_SIZE_TITLE)
.width(Length::FillPortion(6))
.align_x(Alignment::Center),
)
.push(
Container::new(button_hide(Message::HideModal, language))
.width(Length::Fill)
.align_x(Alignment::Center),
),
)
.align_x(Alignment::Center)
.align_y(Alignment::Center)
.height(40)
.width(Length::Fill)
.class(ContainerType::Gradient(color_gradient))
}
fn confirm_button_row<'a>(language: Language, message: Message) -> Row<'a, Message, StyleType> {
Row::new()
.height(Length::Fill)
.align_y(Alignment::Center)
.push(
button(
yes_translation(language)
.align_y(Alignment::Center)
.align_x(Alignment::Center),
)
.padding(5)
.height(40)
.width(80)
.class(ButtonType::Alert)
.on_press(message),
)
}
pub fn modal<'a>(
base: Element<'a, Message, StyleType>,
content: Element<'a, Message, StyleType>,
on_blur: Message,
) -> Element<'a, Message, StyleType> {
stack![
base,
opaque(
mouse_area(center(opaque(content)).class(ContainerType::ModalBackground))
.on_press(on_blur)
)
]
.into()
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/tab.rs | src/gui/components/tab.rs | //! Tab buttons to be used in the various pages just under the header
use iced::widget::text::LineHeight;
use iced::widget::{Button, Container, Row, Space, Text, button};
use iced::{Alignment, Length, alignment};
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::style_constants::FONT_SIZE_SUBTITLE;
use crate::gui::styles::text::TextType;
use crate::gui::types::message::Message;
use crate::{Language, RunningPage, StyleType};
pub fn get_settings_tabs<'a>(
active: SettingsPage,
language: Language,
) -> Row<'a, Message, StyleType> {
let mut tabs = Row::new()
.width(Length::Fill)
.align_y(Alignment::Start)
.spacing(2)
.padding([0, 3]);
for page in &SettingsPage::ALL {
let active = page.eq(&active);
tabs = tabs.push(new_settings_tab(*page, active, language));
}
tabs
}
pub fn get_pages_tabs<'a>(
active: RunningPage,
language: Language,
unread_notifications: usize,
) -> Row<'a, Message, StyleType> {
let mut tabs = Row::new()
.width(Length::Fill)
.align_y(Alignment::Start)
.spacing(2)
.padding([0, 3]);
for page in &RunningPage::ALL {
let active = page.eq(&active);
let unread = if page.eq(&RunningPage::Notifications) {
Some(unread_notifications)
} else {
None
};
tabs = tabs.push(new_page_tab(*page, active, language, unread));
}
tabs
}
fn new_page_tab<'a>(
page: RunningPage,
active: bool,
language: Language,
unread: Option<usize>,
) -> Button<'a, Message, StyleType> {
let mut content = Row::new()
.height(Length::Fill)
.align_y(Alignment::Center)
.push(Space::new().width(Length::Fill))
.push(
page.icon()
.size(15)
.class(if active {
TextType::Title
} else {
TextType::Standard
})
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
)
.push(Space::new().width(10))
.push(
Text::new(page.get_tab_label(language).to_string())
.size(FONT_SIZE_SUBTITLE)
.class(if active {
TextType::Title
} else {
TextType::Standard
})
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
);
if let Some(num) = unread
&& num > 0
{
content = content
.push(Space::new().width(7))
.push(notifications_badge(num));
}
content = content.push(Space::new().width(Length::Fill));
button(content)
.height(if active { 35 } else { 30 })
.padding(0)
.width(Length::Fill)
.class(if active {
ButtonType::TabActive
} else {
ButtonType::TabInactive
})
.on_press(page.action())
}
fn new_settings_tab<'a>(
page: SettingsPage,
active: bool,
language: Language,
) -> Button<'a, Message, StyleType> {
let content = Row::new()
.height(Length::Fill)
.align_y(Alignment::Center)
.push(Space::new().width(Length::Fill))
.push(
page.icon()
.size(15)
.class(if active {
TextType::Title
} else {
TextType::Standard
})
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
)
.push(Space::new().width(10))
.push(
Text::new(page.get_tab_label(language).to_string())
.size(FONT_SIZE_SUBTITLE)
.class(if active {
TextType::Title
} else {
TextType::Standard
})
.align_x(alignment::Alignment::Center)
.align_y(alignment::Alignment::Center),
)
.push(Space::new().width(Length::Fill));
button(content)
.height(if active { 35 } else { 30 })
.padding(0)
.width(Length::Fill)
.class(if active {
ButtonType::TabActive
} else {
ButtonType::TabInactive
})
.on_press(page.action())
}
pub fn notifications_badge<'a>(num: usize) -> Container<'a, Message, StyleType> {
Container::new(
Text::new(num.to_string())
.size(14)
.line_height(LineHeight::Relative(1.0)),
)
.align_y(Alignment::Center)
.padding([2, 4])
.height(20)
.class(ContainerType::Highlighted)
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/types/my_modal.rs | src/gui/components/types/my_modal.rs | use crate::networking::types::address_port_pair::AddressPortPair;
/// This enum defines the currently displayed modal.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MyModal {
/// Reset modal.
Reset,
/// Quit modal.
Quit,
/// Clear all modal.
ClearAll,
/// Connection details modal.
ConnectionDetails(AddressPortPair),
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/components/types/mod.rs | src/gui/components/types/mod.rs | pub mod my_modal;
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/types/settings.rs | src/gui/types/settings.rs | use serde::{Deserialize, Serialize};
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::conf::deserialize_or_default;
use crate::notifications::types::notifications::Notifications;
use crate::{Language, StyleType};
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[serde(default)]
pub struct Settings {
#[serde(deserialize_with = "deserialize_or_default")]
pub color_gradient: GradientType,
#[serde(deserialize_with = "deserialize_or_default")]
pub style_path: String,
#[serde(deserialize_with = "deserialize_or_default")]
pub language: Language,
#[serde(deserialize_with = "deserialize_or_default")]
pub scale_factor: f32,
#[serde(deserialize_with = "deserialize_or_default")]
pub mmdb_country: String,
#[serde(deserialize_with = "deserialize_or_default")]
pub mmdb_asn: String,
// ---------------------------------------------------------------------------------------------
#[serde(deserialize_with = "deserialize_or_default")]
pub notifications: Notifications,
#[serde(deserialize_with = "deserialize_or_default")]
pub style: StyleType,
}
impl Default for Settings {
fn default() -> Self {
Settings {
color_gradient: GradientType::default(),
language: Language::default(),
scale_factor: 1.0,
mmdb_country: String::new(),
mmdb_asn: String::new(),
style_path: String::new(),
notifications: Notifications::default(),
style: StyleType::default(),
}
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/types/export_pcap.rs | src/gui/types/export_pcap.rs | use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::gui::types::conf::deserialize_or_default;
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
#[serde(default)]
pub struct ExportPcap {
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) enabled: bool,
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) file_name: String,
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) directory: String,
}
impl ExportPcap {
pub const DEFAULT_FILE_NAME: &'static str = "sniffnet.pcap";
pub fn toggle(&mut self) {
self.enabled = !self.enabled;
}
pub fn set_file_name(&mut self, file_name: &str) {
// remove forward and backward slashes to avoid directory traversal
self.file_name = file_name.replace(['/', '\\'], "");
}
pub fn set_directory(&mut self, directory: String) {
self.directory = directory;
}
pub fn enabled(&self) -> bool {
self.enabled
}
pub fn file_name(&self) -> &str {
&self.file_name
}
pub fn directory(&self) -> &str {
&self.directory
}
pub fn full_path(&self) -> Option<String> {
if self.enabled {
let mut full_path = PathBuf::from(&self.directory);
let file_name = if self.file_name.is_empty() {
Self::DEFAULT_FILE_NAME
} else {
&self.file_name
};
full_path.push(file_name);
Some(full_path.to_string_lossy().to_string())
} else {
None
}
}
}
impl Default for ExportPcap {
fn default() -> Self {
ExportPcap {
enabled: false,
file_name: String::from(Self::DEFAULT_FILE_NAME),
directory: std::env::var("HOME").unwrap_or_default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let export_pcap = ExportPcap::default();
assert_eq!(export_pcap.enabled(), false);
assert_eq!(export_pcap.file_name(), "sniffnet.pcap");
assert_eq!(
export_pcap.directory(),
std::env::var("HOME").unwrap_or_default()
);
}
#[test]
fn test_toggle() {
let mut export_pcap = ExportPcap::default();
assert_eq!(export_pcap.enabled(), false);
export_pcap.toggle();
assert_eq!(export_pcap.enabled(), true);
export_pcap.toggle();
assert_eq!(export_pcap.enabled(), false);
}
#[test]
fn test_set_file_name() {
let mut export_pcap = ExportPcap::default();
assert_eq!(export_pcap.file_name(), "sniffnet.pcap");
export_pcap.set_file_name("test.pcap");
assert_eq!(export_pcap.file_name(), "test.pcap");
export_pcap.set_file_name("./ciao/test\\hello.pcap");
assert_eq!(export_pcap.file_name(), ".ciaotesthello.pcap");
export_pcap.set_file_name("");
assert_eq!(export_pcap.file_name(), "");
}
#[test]
fn test_set_directory() {
let mut export_pcap = ExportPcap::default();
assert_eq!(
export_pcap.directory(),
std::env::var("HOME").unwrap_or_default()
);
export_pcap.set_directory("/tmp".to_string());
assert_eq!(export_pcap.directory(), "/tmp");
}
#[test]
fn test_full_path() {
let mut dir = std::env::var("HOME").unwrap_or_default();
if !dir.is_empty() {
dir.push('/');
}
let mut export_pcap = ExportPcap::default();
assert_eq!(export_pcap.full_path(), None);
export_pcap.toggle();
assert_eq!(
export_pcap.full_path(),
Some(format!("{dir}sniffnet.pcap",))
);
export_pcap.set_file_name("test.pcap");
assert_eq!(export_pcap.full_path(), Some(format!("{dir}test.pcap",)));
let mut full_path = PathBuf::from("/tmp");
full_path.push("test.pcap");
export_pcap.set_directory("/tmp".to_string());
assert_eq!(
export_pcap.full_path(),
Some(full_path.to_string_lossy().to_string())
);
export_pcap.toggle();
assert_eq!(export_pcap.full_path(), None);
export_pcap.toggle();
assert_eq!(
export_pcap.full_path(),
Some(full_path.to_string_lossy().to_string())
);
let mut full_path = PathBuf::from("/tmp");
full_path.push("sniffnet.pcap");
export_pcap.set_file_name("");
assert_eq!(
export_pcap.full_path(),
Some(full_path.to_string_lossy().to_string())
);
export_pcap.set_directory("".to_string());
assert_eq!(export_pcap.full_path(), Some("sniffnet.pcap".to_string()));
}
}
| rust | Apache-2.0 | a748d0a04dfc6f6c3be206d79c5df4f6beeeab85 | 2026-01-04T15:32:49.059067Z | false |
GyulyVGC/sniffnet | https://github.com/GyulyVGC/sniffnet/blob/a748d0a04dfc6f6c3be206d79c5df4f6beeeab85/src/gui/types/filters.rs | src/gui/types/filters.rs | use crate::gui::types::conf::deserialize_or_default;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
#[serde(default)]
pub struct Filters {
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) expanded: bool,
#[serde(deserialize_with = "deserialize_or_default")]
pub(crate) bpf: String,
}
impl Filters {
pub fn toggle(&mut self) {
self.expanded = !self.expanded;
}
pub fn set_bpf(&mut self, bpf: String) {
self.bpf = bpf;
}
pub fn expanded(&self) -> bool {
self.expanded
}
pub fn bpf(&self) -> &str {
&self.bpf
}
pub fn is_some_filter_active(&self) -> bool {
self.expanded && !self.bpf.trim().is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let filters = Filters::default();
assert_eq!(filters.expanded(), false);
assert_eq!(filters.bpf(), "");
}
#[test]
fn test_toggle() {
let mut filters = Filters::default();
assert_eq!(filters.expanded(), false);
filters.toggle();
assert_eq!(filters.expanded(), true);
filters.toggle();
assert_eq!(filters.expanded(), false);
}
#[test]
fn test_set_bpf() {
let mut filters = Filters::default();
assert_eq!(filters.bpf(), "");
filters.set_bpf("tcp port 80".to_string());
assert_eq!(filters.bpf(), "tcp port 80");
filters.set_bpf(" udp port 53 ".to_string());
assert_eq!(filters.bpf(), " udp port 53 ");
}
#[test]
fn test_is_some_filter_active() {
let mut filters = Filters::default();
assert_eq!(filters.is_some_filter_active(), false);
filters.toggle();
assert_eq!(filters.is_some_filter_active(), false);
filters.set_bpf("tcp port 80".to_string());
assert_eq!(filters.is_some_filter_active(), true);
filters.toggle();
assert_eq!(filters.is_some_filter_active(), false);
filters.toggle();
assert_eq!(filters.is_some_filter_active(), true);
filters.set_bpf(" \t \n ".to_string());
assert_eq!(filters.is_some_filter_active(), false);
}
}
| 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.