Skip to content

Commit

Permalink
feat: new sway-mode module (#671)
Browse files Browse the repository at this point in the history
* feat: add sway-mode module

* refactor: Avoid making multiple connections to SwayIPC

Now `sway::Client` is store in `ironbar.clients`, and allow dynamically
registering event listeners, instead of hardcoding events for Workspace
updates.

Remove the use of `swayipc::Connection` from `sway-mode` module, and
replace it with the new event listener system.

#671
  • Loading branch information
Rodrigodd authored Aug 5, 2024
1 parent 4f2f890 commit e307e15
Show file tree
Hide file tree
Showing 11 changed files with 411 additions and 72 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,11 @@ volume = ["libpulse-binding"]

workspaces = ["futures-lite"]
"workspaces+all" = ["workspaces", "workspaces+sway", "workspaces+hyprland"]
"workspaces+sway" = ["workspaces", "swayipc-async"]
"workspaces+sway" = ["workspaces", "sway"]
"workspaces+hyprland" = ["workspaces", "hyprland"]

sway = ["swayipc-async"]

schema = ["dep:schemars"]

[dependencies]
Expand Down
1 change: 1 addition & 0 deletions docs/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
- [Network Manager](network-manager)
- [Notifications](notifications)
- [Script](script)
- [Sway-mode](sway-mode)
- [Sys_Info](sys-info)
- [Tray](tray)
- [Upower](upower)
Expand Down
78 changes: 78 additions & 0 deletions docs/modules/Sway-mode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
Displays the current sway mode in a label. If the current sway mode is
"default", nothing is displayed.

> [!NOTE]
> This module only works under the [Sway](https://swaywm.org/) compositor.
## Configuration

> Type: `sway-mode`
| Name | Type | Default | Description |
| --------------------- | ------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `truncate` | `'start'` or `'middle'` or `'end'` or `Map` | `null` | The location of the ellipses and where to truncate text from. Leave null to avoid truncating. Use the long-hand `Map` version if specifying a length. |
| `truncate.mode` | `'start'` or `'middle'` or `'end'` | `null` | The location of the ellipses and where to truncate text from. Leave null to avoid truncating. |
| `truncate.length` | `integer` | `null` | The fixed width (in chars) of the widget. Leave blank to let GTK automatically handle. |
| `truncate.max_length` | `integer` | `null` | The maximum number of characters before truncating. Leave blank to let GTK automatically handle. |

<details>
<summary>JSON</summary>

```json
{
"end": [
{
"type": "sway-mode",
"truncate": "start"
}
]
}
```

</details>

<details>
<summary>TOML</summary>

```toml
[[end]]
type = "sway-mode"
truncate = "start"
```

</details>

<details>
<summary>YAML</summary>

```yaml
end:
- type: "sway-mode"
truncate: "start"
```
</details>
<details>
<summary>Corn</summary>
```corn
{
end = [
{
type = "sway-mode"
truncate = "start"
}
]
}
```

</details>

## Styling

| Selector | Description |
| ------------ | ---------------------- |
| `.sway_mode` | Sway mode label widget |

For more information on styling, please see the [styling guide](styling-guide).
11 changes: 7 additions & 4 deletions src/clients/compositor/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{await_sync, register_fallible_client};
use crate::register_fallible_client;
use cfg_if::cfg_if;
use color_eyre::{Help, Report, Result};
use std::fmt::{Debug, Display, Formatter};
Expand Down Expand Up @@ -56,13 +56,16 @@ impl Compositor {

/// Creates a new instance of
/// the workspace client for the current compositor.
pub fn create_workspace_client() -> Result<Arc<dyn WorkspaceClient + Send + Sync>> {
pub fn create_workspace_client(
clients: &mut super::Clients,
) -> Result<Arc<dyn WorkspaceClient + Send + Sync>> {
let current = Self::get_current();
debug!("Getting workspace client for: {current}");
match current {
#[cfg(feature = "workspaces+sway")]
Self::Sway => await_sync(async { sway::Client::new().await })
.map(|client| Arc::new(client) as Arc<dyn WorkspaceClient + Send + Sync>),
Self::Sway => clients
.sway()
.map(|client| client as Arc<dyn WorkspaceClient + Send + Sync>),
#[cfg(feature = "workspaces+hyprland")]
Self::Hyprland => Ok(Arc::new(hyprland::Client::new())),
Self::Unsupported => Err(Report::msg("Unsupported compositor")
Expand Down
90 changes: 24 additions & 66 deletions src/clients/compositor/sway.rs
Original file line number Diff line number Diff line change
@@ -1,85 +1,43 @@
use super::{Visibility, Workspace, WorkspaceClient, WorkspaceUpdate};
use crate::{await_sync, send, spawn};
use color_eyre::{Report, Result};
use futures_lite::StreamExt;
use std::sync::Arc;
use swayipc_async::{Connection, Event, EventType, Node, WorkspaceChange, WorkspaceEvent};
use tokio::sync::broadcast::{channel, Receiver, Sender};
use tokio::sync::Mutex;
use tracing::{info, trace};

#[derive(Debug)]
pub struct Client {
client: Arc<Mutex<Connection>>,
workspace_tx: Sender<WorkspaceUpdate>,
_workspace_rx: Receiver<WorkspaceUpdate>,
}

impl Client {
pub(crate) async fn new() -> Result<Self> {
// Avoid using `arc_mut!` here because we need tokio Mutex.
let client = Arc::new(Mutex::new(Connection::new().await?));
info!("Sway IPC subscription client connected");

let (workspace_tx, workspace_rx) = channel(16);

{
// create 2nd client as subscription takes ownership
let client = Connection::new().await?;
let workspace_tx = workspace_tx.clone();

spawn(async move {
let event_types = [EventType::Workspace];
let mut events = client.subscribe(event_types).await?;

while let Some(event) = events.next().await {
trace!("event: {:?}", event);
if let Event::Workspace(event) = event? {
let event = WorkspaceUpdate::from(*event);
if !matches!(event, WorkspaceUpdate::Unknown) {
workspace_tx.send(event)?;
}
};
}

Ok::<(), Report>(())
});
}
use crate::{await_sync, send};
use color_eyre::Result;
use swayipc_async::{Node, WorkspaceChange, WorkspaceEvent};
use tokio::sync::broadcast::{channel, Receiver};

Ok(Self {
client,
workspace_tx,
_workspace_rx: workspace_rx,
})
}
}
use crate::clients::sway::Client;

impl WorkspaceClient for Client {
fn focus(&self, id: String) -> Result<()> {
await_sync(async move {
let mut client = self.client.lock().await;
let mut client = self.connection().lock().await;
client.run_command(format!("workspace {id}")).await
})?;
Ok(())
}

fn subscribe_workspace_change(&self) -> Receiver<WorkspaceUpdate> {
let rx = self.workspace_tx.subscribe();
let (tx, rx) = channel(16);

{
let tx = self.workspace_tx.clone();
let client = self.client.clone();
let client = self.connection().clone();

await_sync(async {
let mut client = client.lock().await;
let workspaces = client.get_workspaces().await.expect("to get workspaces");
await_sync(async {
let mut client = client.lock().await;
let workspaces = client.get_workspaces().await.expect("to get workspaces");

let event =
WorkspaceUpdate::Init(workspaces.into_iter().map(Workspace::from).collect());
let event =
WorkspaceUpdate::Init(workspaces.into_iter().map(Workspace::from).collect());

send!(tx, event);
});
}
send!(tx, event);

drop(client);

self.add_listener::<swayipc_async::WorkspaceEvent>(move |event| {
let update = WorkspaceUpdate::from(event.clone());
send!(tx, update);
})
.await
.expect("to add listener");
});

rx
}
Expand Down
21 changes: 20 additions & 1 deletion src/clients/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub mod lua;
pub mod music;
#[cfg(feature = "network_manager")]
pub mod networkmanager;
#[cfg(feature = "sway")]
pub mod sway;
#[cfg(feature = "notifications")]
pub mod swaync;
#[cfg(feature = "tray")]
Expand All @@ -31,6 +33,8 @@ pub struct Clients {
wayland: Option<Arc<wayland::Client>>,
#[cfg(feature = "workspaces")]
workspaces: Option<Arc<dyn compositor::WorkspaceClient>>,
#[cfg(feature = "sway")]
sway: Option<Arc<sway::Client>>,
#[cfg(feature = "clipboard")]
clipboard: Option<Arc<clipboard::Client>>,
#[cfg(feature = "cairo")]
Expand Down Expand Up @@ -76,7 +80,7 @@ impl Clients {
let client = match &self.workspaces {
Some(workspaces) => workspaces.clone(),
None => {
let client = compositor::Compositor::create_workspace_client()?;
let client = compositor::Compositor::create_workspace_client(self)?;
self.workspaces.replace(client.clone());
client
}
Expand All @@ -85,6 +89,21 @@ impl Clients {
Ok(client)
}

#[cfg(feature = "sway")]
pub fn sway(&mut self) -> ClientResult<sway::Client> {
let client = match &self.sway {
Some(client) => client.clone(),
None => {
let client = await_sync(async { sway::Client::new().await })?;
let client = Arc::new(client);
self.sway.replace(client.clone());
client
}
};

Ok(client)
}

#[cfg(feature = "cairo")]
pub fn lua(&mut self, config_dir: &Path) -> Rc<lua::LuaEngine> {
self.lua
Expand Down
Loading

0 comments on commit e307e15

Please sign in to comment.