Skip to content

Commit

Permalink
Warning/clippy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ids1024 committed Mar 25, 2024
1 parent cd67415 commit ea7dd9b
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 128 deletions.
7 changes: 5 additions & 2 deletions src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ pub(crate) struct AccessDialogOptions {
grant_label: Option<String>,
icon: Option<String>,
//(ID returned with the response, choices (ID, label), label, initial selection or "" meaning the portal should choose)
#[allow(clippy::type_complexity)]
choices: Option<Vec<(String, String, Vec<(String, String)>, String)>>,
}

pub static ACCESS_ID: Lazy<window::Id> = Lazy::new(|| window::Id::unique());
pub static ACCESS_ID: Lazy<window::Id> = Lazy::new(window::Id::unique);

#[derive(zvariant::SerializeDict, zvariant::Type, Debug, Clone)]
#[zvariant(signature = "a{sv}")]
Expand All @@ -52,6 +53,7 @@ impl Access {

#[zbus::dbus_interface(name = "")]
impl Access {
#[allow(clippy::too_many_arguments)]
async fn access_dialog(
&self,
handle: zvariant::ObjectPath<'_>,
Expand Down Expand Up @@ -252,7 +254,8 @@ pub fn update_args(
tokio::spawn(async move {
let _ = args
.tx
.send(PortalResponse::Cancelled::<AccessDialogResult>);
.send(PortalResponse::Cancelled::<AccessDialogResult>)
.await;
});
}

Expand Down
3 changes: 2 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,10 @@ impl cosmic::Application for CosmicPortal {
}
}

#[allow(clippy::collapsible_match)]
fn subscription(&self) -> cosmic::iced_futures::Subscription<Self::Message> {
Subscription::batch(vec![
subscription::portal_subscription(self.wayland_helper.clone()).map(|e| Msg::Portal(e)),
subscription::portal_subscription(self.wayland_helper.clone()).map(Msg::Portal),
listen_with(|e, _| match e {
cosmic::iced_core::Event::PlatformSpecific(
cosmic::iced_core::event::PlatformSpecific::Wayland(w_e),
Expand Down
2 changes: 1 addition & 1 deletion src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn create_memfd(width: u32, height: u32) -> OwnedFd {
// TODO: BSD support using shm_open
let name = unsafe { CStr::from_bytes_with_nul_unchecked(b"pipewire-screencopy\0") };
let fd = rustix::fs::memfd_create(name, rustix::fs::MemfdFlags::CLOEXEC).unwrap(); // XXX
rustix::fs::ftruncate(&fd, (width * height * 4) as _);
rustix::fs::ftruncate(&fd, (width * height * 4) as _).unwrap();
fd
}

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cosmic::cosmic_theme::palette::Srgba;
use std::collections::HashMap;
use zbus::zvariant::{self, Array, Dict, OwnedValue, Value};
use zbus::zvariant::{self, OwnedValue};

mod access;
mod app;
Expand Down
22 changes: 11 additions & 11 deletions src/screencast_thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,12 @@ use pipewire::{
stream::{StreamRef, StreamState},
sys::pw_buffer,
};
use std::{
ffi::c_void,
io, iter,
os::fd::{BorrowedFd, IntoRawFd},
slice,
};
use std::{ffi::c_void, io, iter, os::fd::IntoRawFd, slice};
use tokio::sync::oneshot;
use wayland_client::protocol::{wl_buffer, wl_output, wl_shm};

use crate::{
buffer::{self, Dmabuf, Plane},
buffer,
wayland::{CaptureSource, DmabufHelper, Session, WaylandHelper},
};

Expand Down Expand Up @@ -169,7 +164,7 @@ impl StreamData {
// Similar to xdg-desktop-portal-wlr
let modifiers = iter::once(default)
.chain(alternatives)
.filter_map(|x| gbm::Modifier::try_from(*x as u64).ok())
.map(|x| gbm::Modifier::from(*x as u64))
.collect::<Vec<_>>();
if let Some((modifier, plane_count)) = self.choose_modifier(&modifiers) {
self.modifier = modifier;
Expand All @@ -185,7 +180,9 @@ impl StreamData {
.iter()
.map(|x| Pod::from_bytes(x.as_slice()).unwrap())
.collect();
stream.update_params(&mut params);
if let Err(err) = stream.update_params(&mut params) {
log::error!("failed to update pipewire params: {}", err);
}
}
}
}
Expand Down Expand Up @@ -271,7 +268,10 @@ impl StreamData {
let buffer = unsafe { stream.dequeue_raw_buffer() };
if !buffer.is_null() {
let wl_buffer = unsafe { &*((*buffer).user_data as *const wl_buffer::WlBuffer) };
block_on(self.session.capture_wl_buffer(&wl_buffer));
if let Err(err) = block_on(self.session.capture_wl_buffer(wl_buffer)) {
log::error!("screencopy failed: {:?}", err);
// TODO terminate screencasting?
}
unsafe { stream.queue_raw_buffer(buffer) };
}
}
Expand All @@ -293,7 +293,7 @@ fn start_stream(
let context = pipewire::context::Context::new(&loop_)?;
let core = context.connect(None)?;

let name = format!("cosmic-screenshot"); // XXX randomize?
let name = "cosmic-screenshot".to_string(); // XXX randomize?

let (node_id_tx, node_id_rx) = oneshot::channel();

Expand Down
180 changes: 88 additions & 92 deletions src/screenshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ impl Screenshot {
.capture_output_toplevels_shm(&output, false)
.await
.into_iter()
.filter_map(|img| img.image().ok().map(|img| Arc::new(img)))
.filter_map(|img| img.image().ok())
.map(Arc::new)
.collect();
map.insert(name.clone(), frame);
}
Expand Down Expand Up @@ -153,7 +154,7 @@ impl Screenshot {

pub fn save_rgba(img: &RgbaImage, path: &PathBuf) -> anyhow::Result<()> {
let mut encoder =
png::Encoder::new(std::fs::File::create(&path)?, img.width(), img.height());
png::Encoder::new(std::fs::File::create(path)?, img.width(), img.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header()?;
Expand Down Expand Up @@ -277,7 +278,7 @@ impl Screenshot {
],
)
.await?;
let doc_id = doc_ids.get(0).unwrap();
let doc_id = doc_ids.first().unwrap();

let mut doc_path = mount_point.as_ref().to_path_buf();
doc_path.push(&**doc_id);
Expand Down Expand Up @@ -465,7 +466,7 @@ pub(crate) fn view(portal: &CosmicPortal, id: window::Id) -> cosmic::Element<Msg
output,
id,
Msg::OutputChanged,
|c| Msg::Choice(c),
Msg::Choice,
Msg::DragCommand,
&args.toplevel_images,
Msg::WindowChosen,
Expand Down Expand Up @@ -565,7 +566,7 @@ pub fn update_msg(portal: &mut CosmicPortal, msg: Msg) -> cosmic::Command<crate:
.get(&output)
.and_then(|imgs| imgs.get(window_i))
{
if let Err(err) = Screenshot::save_rgba(&img, &image_path) {
if let Err(err) = Screenshot::save_rgba(img, &image_path) {
log::error!("Failed to capture screenshot: {:?}", err);
success = false;
};
Expand Down Expand Up @@ -640,7 +641,7 @@ pub fn update_msg(portal: &mut CosmicPortal, msg: Msg) -> cosmic::Command<crate:
}
Msg::DragCommand(DndCommand(cmd)) => {
let action = cmd();
return data_device::action(action);
data_device::action(action)
}
Msg::WindowChosen(name, i) => {
if let Some(args) = portal.screenshot_args.as_mut() {
Expand Down Expand Up @@ -670,94 +671,89 @@ pub fn update_msg(portal: &mut CosmicPortal, msg: Msg) -> cosmic::Command<crate:
}
}

pub fn update_args(portal: &mut CosmicPortal, msg: Args) -> cosmic::Command<crate::app::Msg> {
match msg {
args => {
let Args {
handle,
app_id,
parent_window,
options,
output_images: images,
tx,
choice,
action,
location,
toplevel_images,
} = &args;

if portal.outputs.len() != images.len() {
log::error!(
"Screenshot output count mismatch: {} != {}",
portal.outputs.len(),
images.len()
);
log::warn!("Screenshot outputs: {:?}", portal.outputs);
log::warn!("Screenshot images: {:?}", images.keys().collect::<Vec<_>>());
return cosmic::Command::none();
}

// update output bg sources
if let Ok(c) = cosmic::cosmic_config::Config::new_state(
cosmic_bg_config::NAME,
cosmic_bg_config::state::State::version(),
) {
let bg_state = match cosmic_bg_config::state::State::get_entry(&c) {
Ok(state) => state,
Err((err, s)) => {
log::error!("Failed to get bg config state: {:?}", err);
s
}
};
for o in &mut portal.outputs {
let source = bg_state.wallpapers.iter().find(|s| s.0 == o.name);
o.bg_source = Some(source.cloned().map(|s| s.1).unwrap_or_else(|| {
cosmic_bg_config::Source::Path(
"/usr/share/backgrounds/pop/kate-hazen-COSMIC-desktop-wallpaper.png"
.into(),
)
}));
}
} else {
log::error!("Failed to get bg config state");
for o in &mut portal.outputs {
o.bg_source = Some(cosmic_bg_config::Source::Path(
"/usr/share/backgrounds/pop/kate-hazen-COSMIC-desktop-wallpaper.png".into(),
));
}
}
portal.location_options = vec![fl!("save-to", "pictures"), fl!("save-to", "documents")];
pub fn update_args(portal: &mut CosmicPortal, args: Args) -> cosmic::Command<crate::app::Msg> {
let Args {
handle,
app_id,
parent_window,
options,
output_images: images,
tx,
choice,
action,
location,
toplevel_images,
} = &args;

if portal.outputs.len() != images.len() {
log::error!(
"Screenshot output count mismatch: {} != {}",
portal.outputs.len(),
images.len()
);
log::warn!("Screenshot outputs: {:?}", portal.outputs);
log::warn!("Screenshot images: {:?}", images.keys().collect::<Vec<_>>());
return cosmic::Command::none();
}

if portal.screenshot_args.replace(args).is_none() {
// iterate over outputs and create a layer surface for each
let cmds: Vec<_> = portal
.outputs
.iter()
.filter_map(
|OutputState {
output, id, name, ..
}| {
Some(get_layer_surface(SctkLayerSurfaceSettings {
id: *id,
layer: Layer::Overlay,
keyboard_interactivity: KeyboardInteractivity::Exclusive,
pointer_interactivity: true,
anchor: Anchor::all(),
output: IcedOutput::Output(output.clone()),
namespace: "screenshot".to_string(),
size: Some((None, None)),
exclusive_zone: -1,
size_limits: Limits::NONE.min_height(1.0).min_width(1.0),
..Default::default()
}))
},
)
.collect();
cosmic::Command::batch(cmds)
} else {
log::info!("Existing screenshot args updated");
cosmic::Command::none()
// update output bg sources
if let Ok(c) = cosmic::cosmic_config::Config::new_state(
cosmic_bg_config::NAME,
cosmic_bg_config::state::State::version(),
) {
let bg_state = match cosmic_bg_config::state::State::get_entry(&c) {
Ok(state) => state,
Err((err, s)) => {
log::error!("Failed to get bg config state: {:?}", err);
s
}
};
for o in &mut portal.outputs {
let source = bg_state.wallpapers.iter().find(|s| s.0 == o.name);
o.bg_source = Some(source.cloned().map(|s| s.1).unwrap_or_else(|| {
cosmic_bg_config::Source::Path(
"/usr/share/backgrounds/pop/kate-hazen-COSMIC-desktop-wallpaper.png".into(),
)
}));
}
} else {
log::error!("Failed to get bg config state");
for o in &mut portal.outputs {
o.bg_source = Some(cosmic_bg_config::Source::Path(
"/usr/share/backgrounds/pop/kate-hazen-COSMIC-desktop-wallpaper.png".into(),
));
}
}
portal.location_options = vec![fl!("save-to", "pictures"), fl!("save-to", "documents")];

if portal.screenshot_args.replace(args).is_none() {
// iterate over outputs and create a layer surface for each
let cmds: Vec<_> = portal
.outputs
.iter()
.map(
|OutputState {
output, id, name, ..
}| {
get_layer_surface(SctkLayerSurfaceSettings {
id: *id,
layer: Layer::Overlay,
keyboard_interactivity: KeyboardInteractivity::Exclusive,
pointer_interactivity: true,
anchor: Anchor::all(),
output: IcedOutput::Output(output.clone()),
namespace: "screenshot".to_string(),
size: Some((None, None)),
exclusive_zone: -1,
size_limits: Limits::NONE.min_height(1.0).min_width(1.0),
..Default::default()
})
},
)
.collect();
cosmic::Command::batch(cmds)
} else {
log::info!("Existing screenshot args updated");
cosmic::Command::none()
}
}
Loading

0 comments on commit ea7dd9b

Please sign in to comment.