ltk/
channel.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! [`ChannelSender`], which delivers an app's messages into the run loop.

use std::fmt;
use std::sync::mpsc::SendError;

/// Delivers messages into the run loop from any thread and wakes it. Given to the app by [`crate::App::set_channel_sender`].
pub struct ChannelSender<T>
{
	#[ cfg( not( queued_sources ) ) ]
	inner: calloop::channel::Sender<T>,
	#[ cfg( queued_sources ) ]
	inner: std::sync::mpsc::Sender<T>,
}

impl<T> ChannelSender<T>
{
	/// Fails once the run loop has ended.
	pub fn send( &self, msg: T ) -> Result<(), SendError<T>>
	{
		self.inner.send( msg )?;
		#[ cfg( queued_sources ) ]
		wake();
		Ok( () )
	}

	#[ cfg( not( queued_sources ) ) ]
	pub( crate ) fn from_calloop( inner: calloop::channel::Sender<T> ) -> Self
	{
		Self { inner }
	}
}

impl<T> Clone for ChannelSender<T>
{
	fn clone( &self ) -> Self
	{
		Self { inner: self.inner.clone() }
	}
}

impl<T> fmt::Debug for ChannelSender<T>
{
	fn fmt( &self, f: &mut fmt::Formatter<'_> ) -> fmt::Result
	{
		f.debug_struct( "ChannelSender" ).finish_non_exhaustive()
	}
}

#[ cfg( queued_sources ) ]
static WAKE: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();

/// A sender and the receiver the run loop drains; `wake` is called after every message sent.
#[ cfg( queued_sources ) ]
pub( crate ) fn channel<T>( wake: fn() ) -> ( ChannelSender<T>, std::sync::mpsc::Receiver<T> )
{
	let _ = WAKE.set( wake );
	let ( inner, rx ) = std::sync::mpsc::channel();
	( ChannelSender { inner }, rx )
}

#[ cfg( queued_sources ) ]
fn wake()
{
	if let Some( wake ) = WAKE.get() { wake(); }
}