feat: pairing via applet's agent

This commit is contained in:
Ashley Wulber 2023-02-09 20:09:31 -05:00 committed by Ashley Wulber
parent 000ac7b8b4
commit 7a003389b8
8 changed files with 421 additions and 97 deletions

1
Cargo.lock generated
View file

@ -591,6 +591,7 @@ dependencies = [
"log", "log",
"once_cell", "once_cell",
"pretty_env_logger", "pretty_env_logger",
"rand",
"rust-embed", "rust-embed",
"slotmap", "slotmap",
"smithay-client-toolkit", "smithay-client-toolkit",

View file

@ -6,7 +6,7 @@ license = "GPL-3.0-or-later"
[dependencies] [dependencies]
once_cell = "1.16.0" once_cell = "1.16.0"
bluer = { version = "0.15", features = ["bluetoothd"] } bluer = { version = "0.15", features = ["bluetoothd", "id"] }
futures-util = "0.3.21" futures-util = "0.3.21"
libcosmic = { git = "https://github.com/pop-os/libcosmic/", branch = "master", default-features = false, features = ["wayland", "applet", "tokio"] } libcosmic = { git = "https://github.com/pop-os/libcosmic/", branch = "master", default-features = false, features = ["wayland", "applet", "tokio"] }
sctk = { package = "smithay-client-toolkit", git = "https://github.com/Smithay/client-toolkit", rev = "3776d4a" } sctk = { package = "smithay-client-toolkit", git = "https://github.com/Smithay/client-toolkit", rev = "3776d4a" }
@ -21,3 +21,4 @@ anyhow = "1.0"
i18n-embed = { version = "0.13.4", features = ["fluent-system", "desktop-requester"] } i18n-embed = { version = "0.13.4", features = ["fluent-system", "desktop-requester"] }
i18n-embed-fl = "0.6.4" i18n-embed-fl = "0.6.4"
rust-embed = "6.3.0" rust-embed = "6.3.0"
rand = "0.8"

View file

@ -2,7 +2,7 @@
Name=Cosmic Applet Network Name=Cosmic Applet Network
Comment=Write a GTK + Rust application Comment=Write a GTK + Rust application
Type=Application Type=Application
Exec=cosmic-applet-network Exec=cosmic-applet-bluetooth
Terminal=false Terminal=false
Categories=GNOME;GTK; Categories=GNOME;GTK;
Keywords=Gnome;GTK; Keywords=Gnome;GTK;

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/com/System76/CosmicDockAppList/">
<!-- see https://gtk-rs.org/gtk4-rs/git/docs/gtk4/struct.Application.html#automatic-resources -->
</gresource>
</gresources>

View file

@ -1,9 +1,6 @@
use std::f32::consts::E;
use crate::bluetooth::{BluerDeviceStatus, BluerRequest, BluerState}; use crate::bluetooth::{BluerDeviceStatus, BluerRequest, BluerState};
use cosmic::applet::APPLET_BUTTON_THEME; use cosmic::applet::APPLET_BUTTON_THEME;
use cosmic::iced_style; use cosmic::iced_style;
use cosmic::widget::ListColumn;
use cosmic::{ use cosmic::{
applet::CosmicAppletHelper, applet::CosmicAppletHelper,
iced::{ iced::{
@ -11,7 +8,7 @@ use cosmic::{
popup::{destroy_popup, get_popup}, popup::{destroy_popup, get_popup},
SurfaceIdWrapper, SurfaceIdWrapper,
}, },
widget::{column, container, row, scrollable, text, text_input, Column}, widget::{column, container, row, scrollable, text, Column},
Alignment, Application, Color, Command, Length, Subscription, Alignment, Application, Color, Command, Length, Subscription,
}, },
iced_native::{ iced_native::{
@ -25,9 +22,11 @@ use cosmic::{
widget::{button, divider, icon, toggler}, widget::{button, divider, icon, toggler},
Element, Theme, Element, Theme,
}; };
use std::collections::HashMap;
use std::time::Duration;
use tokio::sync::mpsc::Sender; use tokio::sync::mpsc::Sender;
use crate::bluetooth::{bluetooth_subscription, BluerEvent}; use crate::bluetooth::{bluetooth_subscription, BluerDevice, BluerEvent};
use crate::{config, fl}; use crate::{config, fl};
pub fn run() -> cosmic::iced::Result { pub fn run() -> cosmic::iced::Result {
@ -35,13 +34,6 @@ pub fn run() -> cosmic::iced::Result {
CosmicBluetoothApplet::run(helper.window_settings()) CosmicBluetoothApplet::run(helper.window_settings())
} }
#[derive(Debug)]
enum NewConnectionState {
EnterPassword { device: (), password: String },
Waiting(()),
Failure(()),
}
// impl Into<()> for NewConnectionState { // impl Into<()> for NewConnectionState {
// fn into(self) -> AccessPoint { // fn into(self) -> AccessPoint {
// match self { // match self {
@ -66,7 +58,7 @@ struct CosmicBluetoothApplet {
bluer_sender: Option<Sender<BluerRequest>>, bluer_sender: Option<Sender<BluerRequest>>,
// UI state // UI state
show_visible_devices: bool, show_visible_devices: bool,
new_connection: Option<NewConnectionState>, request_confirmation: Option<(BluerDevice, String, Sender<bool>)>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -77,6 +69,8 @@ enum Message {
Ignore, Ignore,
BluetoothEvent(BluerEvent), BluetoothEvent(BluerEvent),
Request(BluerRequest), Request(BluerRequest),
Cancel,
Confirm,
} }
impl Application for CosmicBluetoothApplet { impl Application for CosmicBluetoothApplet {
@ -123,56 +117,113 @@ impl Application for CosmicBluetoothApplet {
.min_width(1) .min_width(1)
.max_height(800) .max_height(800)
.max_width(400); .max_width(400);
return get_popup(popup_settings); let tx = self.bluer_sender.as_ref().cloned();
return Command::batch(vec![
Command::perform(
async {
if let Some(tx) = tx {
let _ = tx.send(BluerRequest::StateUpdate).await;
}
},
|_| Message::Ignore,
),
get_popup(popup_settings),
]);
} }
} }
Message::Errored(_) => todo!(), Message::Errored(_) => todo!(),
Message::Ignore => {} Message::Ignore => {}
// Message::SelectDevice(device) => {
// let tx = if let Some(tx) = self.nm_sender.as_ref() {
// tx
// } else {
// return Command::none();
// };
// let _ = tx.unbounded_send(NetworkManagerRequest::SelectAccessPoint(
// access_point.ssid.clone(),
// ));
// self.new_connection
// .replace(NewConnectionState::EnterPassword {
// access_point,
// password: String::new(),
// });
// }
Message::ToggleVisibleDevices(enabled) => { Message::ToggleVisibleDevices(enabled) => {
self.new_connection.take();
self.show_visible_devices = enabled; self.show_visible_devices = enabled;
} }
Message::BluetoothEvent(e) => match e { Message::BluetoothEvent(e) => match e {
BluerEvent::RequestResponse { BluerEvent::RequestResponse {
req: _req, req,
state, state,
err_msg, err_msg,
} => { } => {
if let Some(err_msg) = err_msg { if let Some(err_msg) = err_msg {
eprintln!("bluetooth request error: {}", err_msg); eprintln!("bluetooth request error: {}", err_msg);
} }
dbg!(&state);
self.bluer_state = state; self.bluer_state = state;
// TODO special handling for some requests // TODO special handling for some requests
match req {
BluerRequest::StateUpdate
if self.popup.is_some() && self.bluer_sender.is_some() =>
{
for device in &self.bluer_state.devices {
dbg!((&device.name, &device.status));
}
let tx = self.bluer_sender.as_ref().cloned().unwrap();
return Command::perform(
async move {
// sleep for a bit before requesting state update again
tokio::time::sleep(Duration::from_millis(3000)).await;
let _ = tx.send(BluerRequest::StateUpdate).await;
},
|_| Message::Ignore,
);
}
_ => {}
};
} }
BluerEvent::Init { sender, state } => { BluerEvent::Init { sender, state } => {
self.bluer_sender.replace(sender); self.bluer_sender.replace(sender);
self.bluer_state = state; self.bluer_state = state;
} }
BluerEvent::DevicesChanged { state } => { BluerEvent::DevicesChanged { state } => {
for device in &state.devices {
dbg!(&device.name);
}
self.bluer_state = state; self.bluer_state = state;
} }
BluerEvent::Finished => { BluerEvent::Finished => {
// TODO exit? eprintln!("bluetooth subscription finished. exiting...");
todo!() std::process::exit(0);
} }
// TODO handle agent events
BluerEvent::AgentEvent(event) => match event {
crate::bluetooth::BluerAgentEvent::DisplayPinCode(d, code) => {
dbg!((d.name, code));
}
crate::bluetooth::BluerAgentEvent::DisplayPasskey(d, code) => {
dbg!((d.name, code));
}
crate::bluetooth::BluerAgentEvent::RequestPinCode(d) => {
// TODO anything to be done here?
dbg!("request pin code", d.name);
}
crate::bluetooth::BluerAgentEvent::RequestPasskey(d) => {
// TODO anything to be done here?
dbg!("request passkey", d.name);
}
crate::bluetooth::BluerAgentEvent::RequestConfirmation(d, code, tx) => {
dbg!("request confirmation", &d.name, &code);
self.request_confirmation.replace((d, code, tx));
// let _ = tx.send(false);
}
crate::bluetooth::BluerAgentEvent::RequestDeviceAuthorization(d, _tx) => {
// TODO anything to be done here?
dbg!("request device authorization", d.name);
// let_ = tx.send(false);
}
crate::bluetooth::BluerAgentEvent::RequestServiceAuthorization(
d,
service,
_tx,
) => {
// my headphones seem to always request this
// doesn't seem to be defined in the UX mockups
dbg!(
"request service authorization",
d.name,
bluer::id::Service::try_from(service)
.map(|s| s.to_string())
.unwrap_or_else(|_| "unknown".to_string())
);
}
},
}, },
Message::Request(r) => { Message::Request(r) => {
match &r { match &r {
@ -220,6 +271,26 @@ impl Application for CosmicBluetoothApplet {
); );
} }
} }
Message::Cancel => {
if let Some((_, _, tx)) = self.request_confirmation.take() {
return Command::perform(
async move {
let _ = tx.send(false).await;
},
|_| Message::Ignore,
);
}
}
Message::Confirm => {
if let Some((_, _, tx)) = self.request_confirmation.take() {
return Command::perform(
async move {
let _ = tx.send(true).await;
},
|_| Message::Ignore,
);
}
}
} }
Command::none() Command::none()
} }
@ -344,9 +415,62 @@ impl Application for CosmicBluetoothApplet {
.style(button_style.clone()) .style(button_style.clone())
.on_press(Message::ToggleVisibleDevices(!self.show_visible_devices)); .on_press(Message::ToggleVisibleDevices(!self.show_visible_devices));
content = content.push(available_connections_btn); content = content.push(available_connections_btn);
if self.show_visible_devices { let mut list_column = Vec::with_capacity(self.bluer_state.devices.len());
let mut list_column = Vec::with_capacity(self.bluer_state.devices.len());
if let Some((device, pin, _)) = self.request_confirmation.as_ref() {
let row = column![
text(&device.name)
.horizontal_alignment(Horizontal::Left)
.vertical_alignment(Vertical::Center)
.width(Length::Fill),
text(fl!(
"confirm-pin",
HashMap::from_iter(vec![("deviceName", device.name.clone())])
))
.horizontal_alignment(Horizontal::Left)
.vertical_alignment(Vertical::Center)
.width(Length::Fill),
text(pin)
.horizontal_alignment(Horizontal::Center)
.vertical_alignment(Vertical::Center)
.width(Length::Fill)
.size(24),
row![
button(Button::Secondary)
.custom(
vec![text(fl!("cancel"))
.size(14)
.width(Length::Fill)
.height(Length::Units(24))
.vertical_alignment(Vertical::Center)
.into(),]
.into(),
)
.padding([8, 24])
.style(button_style.clone())
.on_press(Message::Cancel)
.width(Length::Fill),
button(Button::Secondary)
.custom(
vec![text(fl!("confirm"))
.size(14)
.width(Length::Fill)
.height(Length::Units(24))
.vertical_alignment(Vertical::Center)
.into(),]
.into(),
)
.padding([8, 24])
.style(button_style.clone())
.on_press(Message::Confirm)
.width(Length::Fill),
]
]
.padding([0, 24])
.spacing(8);
list_column.push(row.into());
}
if self.show_visible_devices {
if self.bluer_state.bluetooth_enabled { if self.bluer_state.bluetooth_enabled {
let mut visible_devices = column![]; let mut visible_devices = column![];
for dev in self.bluer_state.devices.iter().filter(|d| { for dev in self.bluer_state.devices.iter().filter(|d| {
@ -370,15 +494,14 @@ impl Application for CosmicBluetoothApplet {
} }
list_column.push(visible_devices.into()); list_column.push(visible_devices.into());
} }
let num_dev = list_column.len(); }
if num_dev > 5 { let num_dev = list_column.len();
content = content.push( if num_dev > 5 {
scrollable(Column::with_children(list_column)) content = content.push(
.height(Length::Units(300)), scrollable(Column::with_children(list_column)).height(Length::Units(300)),
); );
} else { } else {
content = content.push(Column::with_children(list_column)); content = content.push(Column::with_children(list_column));
}
} }
self.applet_helper.popup_container(content).into() self.applet_helper.popup_container(content).into()
} }

View file

@ -1,9 +1,13 @@
use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Duration}; use std::{collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Duration};
use bluer::{Adapter, AdapterProperty, Address, DeviceProperty, Session}; use bluer::{
agent::{Agent, AgentHandle},
Adapter, Address, DeviceProperty, Session, Uuid,
};
use cosmic::iced::{self, subscription}; use cosmic::iced::{self, subscription};
use futures::StreamExt; use futures::StreamExt;
use rand::Rng;
use tokio::{ use tokio::{
spawn, spawn,
sync::{ sync::{
@ -20,7 +24,6 @@ pub fn bluetooth_subscription<I: 'static + Hash + Copy + Send + Sync + Debug>(
subscription::unfold(id, State::Ready, move |state| start_listening(id, state)) subscription::unfold(id, State::Ready, move |state| start_listening(id, state))
} }
#[derive(Debug)]
pub enum State { pub enum State {
Ready, Ready,
Waiting { session_state: BluerSessionState }, Waiting { session_state: BluerSessionState },
@ -88,6 +91,7 @@ async fn start_listening<I: Copy + Debug>(id: I, state: State) -> (Option<(I, Bl
err_msg, err_msg,
}, },
)), )),
BluerSessionEvent::AgentEvent(e) => Some((id, BluerEvent::AgentEvent(e))),
_ => None, _ => None,
} }
} else { } else {
@ -108,6 +112,7 @@ pub enum BluerRequest {
ConnectDevice(Address), ConnectDevice(Address),
DisconnectDevice(Address), DisconnectDevice(Address),
CancelConnect(Address), CancelConnect(Address),
StateUpdate,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -124,6 +129,7 @@ pub enum BluerEvent {
DevicesChanged { DevicesChanged {
state: BluerState, state: BluerState,
}, },
AgentEvent(BluerAgentEvent),
Finished, Finished,
} }
@ -140,6 +146,8 @@ pub enum BluerDeviceStatus {
Paired, Paired,
Connecting, Connecting,
Disconnecting, Disconnecting,
/// Pairing is in progress, maybe with a passkey or pincode
/// passkey or pincode will be 000000 - 999999
Pairing, Pairing,
} }
@ -151,6 +159,32 @@ pub struct BluerDevice {
pub properties: Vec<DeviceProperty>, pub properties: Vec<DeviceProperty>,
} }
impl BluerDevice {
pub async fn from_device(device: &bluer::Device) -> Self {
let name = device
.name()
.await
.unwrap_or_default()
.unwrap_or_else(|| "Unknown".to_string());
let is_paired = device.is_paired().await.unwrap_or_default();
let is_connected = device.is_connected().await.unwrap_or_default();
let properties = device.all_properties().await.unwrap_or_default();
let status = if is_connected {
BluerDeviceStatus::Connected
} else if is_paired {
BluerDeviceStatus::Paired
} else {
BluerDeviceStatus::Disconnected
};
Self {
name,
address: device.address(),
status,
properties,
}
}
}
pub enum BluerSessionEvent { pub enum BluerSessionEvent {
RequestResponse { RequestResponse {
req: BluerRequest, req: BluerRequest,
@ -159,15 +193,27 @@ pub enum BluerSessionEvent {
}, },
ChangesProcessed(BluerState), ChangesProcessed(BluerState),
ChangeStreamEnded, // TODO can we just restart the stream in a new task? ChangeStreamEnded, // TODO can we just restart the stream in a new task?
AgentEvent(BluerAgentEvent),
}
#[derive(Debug, Clone)]
pub enum BluerAgentEvent {
DisplayPinCode(BluerDevice, String),
DisplayPasskey(BluerDevice, String),
RequestPinCode(BluerDevice),
RequestPasskey(BluerDevice),
RequestConfirmation(BluerDevice, String, Sender<bool>), // Note mpsc channel is used bc the sender must be cloned in the iced Message machinery
RequestDeviceAuthorization(BluerDevice, Sender<bool>),
RequestServiceAuthorization(BluerDevice, Uuid, Sender<bool>),
} }
#[derive(Debug)]
pub struct BluerSessionState { pub struct BluerSessionState {
session: Session, _session: Session,
_agent_handle: AgentHandle,
pub adapter: Adapter, pub adapter: Adapter,
pub devices: Arc<Mutex<Vec<BluerDevice>>>, pub devices: Arc<Mutex<Vec<BluerDevice>>>,
pub rx: Option<Receiver<BluerSessionEvent>>, pub rx: Option<Receiver<BluerSessionEvent>>,
tx: Option<Sender<BluerSessionEvent>>, tx: Sender<BluerSessionEvent>,
active_requests: Arc<Mutex<HashMap<BluerRequest, JoinHandle<anyhow::Result<()>>>>>, active_requests: Arc<Mutex<HashMap<BluerRequest, JoinHandle<anyhow::Result<()>>>>>,
} }
@ -178,43 +224,205 @@ impl BluerSessionState {
) -> anyhow::Result<Self> { ) -> anyhow::Result<Self> {
let adapter = session.default_adapter().await?; let adapter = session.default_adapter().await?;
let devices = build_device_list(&adapter).await; let devices = build_device_list(&adapter).await;
let (tx, rx) = tokio::sync::mpsc::channel(100);
let tx_clone_1 = tx.clone();
let tx_clone_2 = tx.clone();
let tx_clone_3 = tx.clone();
let tx_clone_4 = tx.clone();
let tx_clone_5 = tx.clone();
let tx_clone_6 = tx.clone();
let tx_clone_7 = tx.clone();
let adapter_clone_1 = adapter.clone();
let adapter_clone_2 = adapter.clone();
let adapter_clone_3 = adapter.clone();
let adapter_clone_4 = adapter.clone();
let adapter_clone_5 = adapter.clone();
let adapter_clone_6 = adapter.clone();
let adapter_clone_7 = adapter.clone();
let _agent = Agent {
request_default: true, // TODO which agent should eventually become the default? Maybe the one in the settings app?
request_pin_code: Some(Box::new(move |req| {
let agent_clone = adapter_clone_1.clone();
let tx_clone = tx_clone_1.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::RequestPinCode(
BluerDevice::from_device(&device).await,
),
))
.await;
let mut rng = rand::thread_rng();
let pin_code = rng.gen_range(0..999999);
Ok(format!("{:06}", pin_code))
})
})),
display_pin_code: Some(Box::new(move |req| {
let agent_clone = adapter_clone_2.clone();
let tx_clone = tx_clone_2.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::DisplayPinCode(
BluerDevice::from_device(&device).await,
req.pincode,
),
))
.await;
Ok(())
})
})),
request_passkey: Some(Box::new(move |req| {
let agent_clone = adapter_clone_3.clone();
let tx_clone = tx_clone_3.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::RequestPasskey(
BluerDevice::from_device(&device).await,
),
))
.await;
let mut rng = rand::thread_rng();
let pin_code = rng.gen_range(0..999999);
Ok(pin_code)
})
})),
display_passkey: Some(Box::new(move |req| {
let agent_clone = adapter_clone_4.clone();
let tx_clone = tx_clone_4.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::DisplayPasskey(
BluerDevice::from_device(&device).await,
format!("{:06}", req.passkey),
),
))
.await;
Ok(())
})
})),
request_confirmation: Some(Box::new(move |req| {
let agent_clone = adapter_clone_5.clone();
let tx_clone = tx_clone_5.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let (tx, mut rx) = channel(1);
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::RequestConfirmation(
BluerDevice::from_device(&device).await,
format!("{:06}", req.passkey),
tx,
),
))
.await;
let res = rx.recv().await;
dbg!(res);
match res {
Some(res) if res => Ok(()),
_ => Err(bluer::agent::ReqError::Rejected),
}
})
})),
request_authorization: Some(Box::new(move |req| {
let agent_clone = adapter_clone_6.clone();
let tx_clone = tx_clone_6.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let (tx, mut rx) = channel(1);
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::RequestDeviceAuthorization(
BluerDevice::from_device(&device).await,
tx,
),
))
.await;
let res = rx.recv().await;
match res {
Some(res) if res => Ok(()),
_ => Err(bluer::agent::ReqError::Rejected),
}
})
})),
authorize_service: Some(Box::new(move |req| {
let agent_clone = adapter_clone_7.clone();
let tx_clone = tx_clone_7.clone();
Box::pin(async move {
let device = match agent_clone.device(req.device) {
Ok(d) => d,
Err(_) => return Err(bluer::agent::ReqError::Rejected),
};
let (tx, mut rx) = channel(1);
// TODO better describe the service to the user
let _ = tx_clone
.send(BluerSessionEvent::AgentEvent(
BluerAgentEvent::RequestServiceAuthorization(
BluerDevice::from_device(&device).await,
req.service,
tx,
),
))
.await;
let res = rx.recv().await;
match res {
Some(res) if res => Ok(()),
_ => Err(bluer::agent::ReqError::Rejected),
}
})
})),
_non_exhaustive: (),
};
let _agent_handle = session.register_agent(_agent).await?;
let mut self_ = Self { let mut self_ = Self {
session, _agent_handle,
adapter: adapter, _session: session,
adapter,
devices: Arc::new(Mutex::new(devices)), devices: Arc::new(Mutex::new(devices)),
rx: None, rx: Some(rx),
tx: None, tx,
active_requests: Arc::new(Mutex::new(HashMap::new())), active_requests: Arc::new(Mutex::new(HashMap::new())),
}; };
self_.process_changes(); self_.process_changes();
self_.process_requests(request_rx); self_.process_requests(request_rx);
Ok(self_) Ok(self_)
} }
pub(crate) async fn devices(&self) -> Vec<BluerDevice> { // Note: For some reason, this doesn't actually seem to work so well. it seems unreliable...
self.devices.lock().await.clone()
}
pub(crate) async fn clear(&mut self) {
self.devices.lock().await.clear();
}
pub(crate) fn start_monitoring(&mut self) {
self.process_changes();
}
pub(crate) fn process_changes(&mut self) { pub(crate) fn process_changes(&mut self) {
let (tx, rx) = tokio::sync::mpsc::channel(100); let tx = self.tx.clone();
self.tx = Some(tx.clone());
let devices_clone = self.devices.clone(); let devices_clone = self.devices.clone();
let adapter_clone = self.adapter.clone(); let adapter_clone = self.adapter.clone();
let _monitor_devices: tokio::task::JoinHandle<Result<(), anyhow::Error>> = let _monitor_devices: tokio::task::JoinHandle<Result<(), anyhow::Error>> =
spawn(async move { spawn(async move {
let mut change_stream = adapter_clone.discover_devices_with_changes().await?; let mut change_stream = adapter_clone.discover_devices_with_changes().await?;
let mut cur = None;
let mut devices_changed = false; let mut devices_changed = false;
let mut milli_timeout = 10; let mut milli_timeout = 10;
'outer: loop { 'outer: loop {
@ -233,7 +441,7 @@ impl BluerSessionState {
Err(_) => continue, Err(_) => continue,
}; };
let mut status = if device.is_connected().await? { let status = if device.is_connected().await? {
BluerDeviceStatus::Connected BluerDeviceStatus::Connected
} else if device.is_paired().await? { } else if device.is_paired().await? {
BluerDeviceStatus::Paired BluerDeviceStatus::Paired
@ -241,10 +449,7 @@ impl BluerSessionState {
BluerDeviceStatus::Disconnected BluerDeviceStatus::Disconnected
}; };
if let Some(pos) = if devices.iter().any(|device| device.address == address) {
devices.iter().position(|device| device.address == address)
{
cur = Some(pos);
continue; continue;
}; };
// only send a DevicesChanged event if we have actually added a device // only send a DevicesChanged event if we have actually added a device
@ -260,29 +465,22 @@ impl BluerSessionState {
status, status,
properties: Vec::new(), properties: Vec::new(),
}); });
cur = Some(devices.len() - 1);
} }
bluer::AdapterEvent::DeviceRemoved(address) => { bluer::AdapterEvent::DeviceRemoved(address) => {
if let Some(pos) = if let Some(pos) =
devices.iter().position(|device| device.address == address) devices.iter().position(|device| device.address == address)
{ {
devices_changed = true; devices_changed = true;
cur = None;
devices.remove(pos); devices.remove(pos);
}; };
} }
bluer::AdapterEvent::PropertyChanged(prop) => { bluer::AdapterEvent::PropertyChanged(_) => {
let bluer_device = match cur.and_then(|i| devices.get_mut(i)) {
Some(d) => d,
None => continue,
};
devices_changed = true; devices_changed = true;
} }
} }
} }
if devices_changed { if devices_changed {
devices_changed = false; devices_changed = false;
dbg!(&devices_clone);
let _ = tx let _ = tx
.send(BluerSessionEvent::ChangesProcessed(BluerState { .send(BluerSessionEvent::ChangesProcessed(BluerState {
devices: build_device_list(&adapter_clone).await, devices: build_device_list(&adapter_clone).await,
@ -299,14 +497,13 @@ impl BluerSessionState {
eprintln!("Change stream ended"); eprintln!("Change stream ended");
Ok(()) Ok(())
}); });
self.rx.replace(rx);
} }
pub(crate) fn process_requests(&self, request_rx: Receiver<BluerRequest>) { pub(crate) fn process_requests(&self, request_rx: Receiver<BluerRequest>) {
let active_requests = self.active_requests.clone(); let active_requests = self.active_requests.clone();
let adapter = self.adapter.clone(); let adapter = self.adapter.clone();
let devices = self.devices.clone(); let tx = self.tx.clone();
let tx = self.tx.clone().unwrap(); // TODO error handling
let _handle: JoinHandle<anyhow::Result<()>> = spawn(async move { let _handle: JoinHandle<anyhow::Result<()>> = spawn(async move {
let mut request_rx = request_rx; let mut request_rx = request_rx;
@ -314,7 +511,6 @@ impl BluerSessionState {
let req_clone = req.clone(); let req_clone = req.clone();
let req_clone_2 = req.clone(); let req_clone_2 = req.clone();
let active_requests_clone = active_requests.clone(); let active_requests_clone = active_requests.clone();
let devices_clone = devices.clone();
let tx_clone = tx.clone(); let tx_clone = tx.clone();
let adapter_clone = adapter.clone(); let adapter_clone = adapter.clone();
let handle = spawn(async move { let handle = spawn(async move {
@ -373,6 +569,7 @@ impl BluerSessionState {
err_msg = Some("No active connection request found".to_string()); err_msg = Some("No active connection request found".to_string());
} }
} }
BluerRequest::StateUpdate => {}
}; };
let state = BluerState { let state = BluerState {

1
debian/control vendored
View file

@ -9,6 +9,7 @@ Build-Depends:
cargo, cargo,
libgtk-4-dev, libgtk-4-dev,
libadwaita-1-dev, libadwaita-1-dev,
libdbus-1-dev,
libpulse-dev, libpulse-dev,
just, just,
pkg-config, pkg-config,

View file

@ -16,6 +16,7 @@ bindir := rootdir + prefix + '/bin'
app_list_id := 'com.system76.CosmicAppList' app_list_id := 'com.system76.CosmicAppList'
audio_id := 'com.system76.CosmicAppletAudio' audio_id := 'com.system76.CosmicAppletAudio'
battery_id := 'com.system76.CosmicAppletBattery' battery_id := 'com.system76.CosmicAppletBattery'
bluetooth_id := 'com.system76.CosmicAppletBluetooth'
graphics_id := 'com.system76.CosmicAppletGraphics' graphics_id := 'com.system76.CosmicAppletGraphics'
network_id := 'com.system76.CosmicAppletNetwork' network_id := 'com.system76.CosmicAppletNetwork'
notifications_id := 'com.system76.CosmicAppletNotifications' notifications_id := 'com.system76.CosmicAppletNotifications'
@ -88,6 +89,12 @@ install:
install -Dm0644 cosmic-applet-battery/data/{{battery_id}}.desktop {{sharedir}}/applications/{{battery_id}}.desktop install -Dm0644 cosmic-applet-battery/data/{{battery_id}}.desktop {{sharedir}}/applications/{{battery_id}}.desktop
install -Dm0755 target/release/cosmic-applet-battery {{bindir}}/cosmic-applet-battery install -Dm0755 target/release/cosmic-applet-battery {{bindir}}/cosmic-applet-battery
# battery
install -Dm0644 cosmic-applet-bluetooth/data/icons/{{bluetooth_id}}.svg {{iconsdir}}/{{bluetooth_id}}.svg
install -Dm0644 cosmic-applet-bluetooth/data/{{bluetooth_id}}.desktop {{sharedir}}/applications/{{bluetooth_id}}.desktop
install -Dm0755 target/release/cosmic-applet-bluetooth {{bindir}}/cosmic-applet-bluetooth
# Extracts vendored dependencies if vendor=1 # Extracts vendored dependencies if vendor=1
_extract_vendor: _extract_vendor:
#!/usr/bin/env sh #!/usr/bin/env sh