Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Yes/No/Cancel buttons #123

Merged
merged 16 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/target
.idea
4 changes: 2 additions & 2 deletions examples/message-custom-buttons/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"

[dependencies]
rfd = {version = "0.9.0", path = "../..", features=["common-controls-v6"]}
rfd = { version = "0.11.3", path = "../..", features = ["common-controls-v6"] }

[build-dependencies]
embed-resource = "1.6"
embed-resource = "2.1"
4 changes: 2 additions & 2 deletions examples/message-custom-buttons/build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate embed_resource;

fn main() {
#[cfg(target_os = "windows")]
embed_resource::compile("manifest.rc");
#[cfg(target_os = "windows")]
embed_resource::compile("manifest.rc", embed_resource::NONE);
}
35 changes: 16 additions & 19 deletions examples/message-custom-buttons/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
fn main() {
#[cfg(not(feature = "gtk3"))]
let res = "";

#[cfg(any(
target_os = "windows",
target_os = "macos",
all(
any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd"
),
feature = "gtk3"
)
))]
let res = rfd::MessageDialog::new()
.set_title("Msg!")
.set_description("Description!")
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::OkCancelCustom("Got it!".to_string(), "No!".to_string()))
.set_buttons(rfd::MessageButtons::OkCancelCustom(
"Got it!".to_string(),
"No!".to_string(),
))
.show();
println!("{res}");

println!("{}", res);
let res = rfd::MessageDialog::new()
.set_title("Do you want to save the changes you made?")
.set_description("Your changes will be lost if you don't save them.")
.set_level(rfd::MessageLevel::Warning)
.set_buttons(rfd::MessageButtons::YesNoCancelCustom(
"Save".to_string(),
"Don't Save".to_string(),
"Cancel".to_string(),
))
.show();
println!("{res}");
}
5 changes: 3 additions & 2 deletions src/backend.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::message_dialog::MessageDialogResult;
use crate::FileHandle;
use std::future::Future;
use std::path::PathBuf;
Expand Down Expand Up @@ -66,7 +67,7 @@ pub trait FolderPickerDialogImpl {
}

pub trait MessageDialogImpl {
fn show(self) -> bool;
fn show(self) -> MessageDialogResult;
}

//
Expand Down Expand Up @@ -97,5 +98,5 @@ pub trait AsyncFileSaveDialogImpl {
}

pub trait AsyncMessageDialogImpl {
fn show_async(self) -> DialogFutureType<bool>;
fn show_async(self) -> DialogFutureType<MessageDialogResult>;
}
2 changes: 1 addition & 1 deletion src/backend/gtk3/gtk_future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ unsafe fn connect_raw<F>(

unsafe extern "C" fn destroy_closure<F>(ptr: *mut c_void, _: *mut gobject_sys::GClosure) {
// destroy
Box::<F>::from_raw(ptr as *mut _);
let _ = Box::<F>::from_raw(ptr as *mut _);
}
assert_eq!(mem::size_of::<*mut F>(), mem::size_of::<gpointer>());
assert!(trampoline.is_some());
Expand Down
90 changes: 79 additions & 11 deletions src/backend/gtk3/message_dialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use super::utils::wait_for_cleanup;
use super::AsGtkDialog;

use crate::message_dialog::{MessageButtons, MessageDialog, MessageLevel};
use crate::MessageDialogResult;

pub struct GtkMessageDialog {
buttons: MessageButtons,
ptr: *mut gtk_sys::GtkDialog,
}

Expand All @@ -25,22 +27,54 @@ impl GtkMessageDialog {
MessageButtons::Ok => gtk_sys::GTK_BUTTONS_OK,
MessageButtons::OkCancel => gtk_sys::GTK_BUTTONS_OK_CANCEL,
MessageButtons::YesNo => gtk_sys::GTK_BUTTONS_YES_NO,
MessageButtons::YesNoCancel => gtk_sys::GTK_BUTTONS_NONE,
MessageButtons::OkCustom(_) => gtk_sys::GTK_BUTTONS_NONE,
MessageButtons::OkCancelCustom(_, _) => gtk_sys::GTK_BUTTONS_NONE,
MessageButtons::YesNoCancelCustom(_, _, _) => gtk_sys::GTK_BUTTONS_NONE,
};

let custom_buttons = match opt.buttons {
let custom_buttons = match &opt.buttons {
MessageButtons::YesNoCancel => vec![
Some((CString::new("Yes").unwrap(), gtk_sys::GTK_RESPONSE_YES)),
Some((CString::new("No").unwrap(), gtk_sys::GTK_RESPONSE_NO)),
Some((
CString::new("Cancel").unwrap(),
gtk_sys::GTK_RESPONSE_CANCEL,
)),
None,
],
MessageButtons::OkCustom(ok_text) => vec![
Some((CString::new(ok_text).unwrap(), gtk_sys::GTK_RESPONSE_OK)),
Some((
CString::new(ok_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_OK,
)),
None,
],
MessageButtons::OkCancelCustom(ok_text, cancel_text) => vec![
Some((CString::new(ok_text).unwrap(), gtk_sys::GTK_RESPONSE_OK)),
Some((
CString::new(cancel_text).unwrap(),
CString::new(ok_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_OK,
)),
Some((
CString::new(cancel_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_CANCEL,
)),
],
MessageButtons::YesNoCancelCustom(yes_text, no_text, cancel_text) => vec![
Some((
CString::new(yes_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_YES,
)),
Some((
CString::new(no_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_NO,
)),
Some((
CString::new(cancel_text.as_bytes()).unwrap(),
gtk_sys::GTK_RESPONSE_CANCEL,
)),
None,
],
_ => vec![],
};

Expand Down Expand Up @@ -80,13 +114,43 @@ impl GtkMessageDialog {
gtk_sys::gtk_message_dialog_format_secondary_text(ptr as *mut _, description.as_ptr());
}

Self { ptr }
Self {
ptr,
buttons: opt.buttons,
}
}

pub fn run(self) -> bool {
pub fn run(self) -> MessageDialogResult {
let res = unsafe { gtk_sys::gtk_dialog_run(self.ptr) };

res == gtk_sys::GTK_RESPONSE_OK || res == gtk_sys::GTK_RESPONSE_YES
use MessageButtons::*;
match (&self.buttons, res) {
(Ok | OkCancel, gtk_sys::GTK_RESPONSE_OK) => MessageDialogResult::Ok,
(Ok | OkCancel | YesNoCancel, gtk_sys::GTK_RESPONSE_CANCEL) => {
MessageDialogResult::Cancel
}
(YesNo | YesNoCancel, gtk_sys::GTK_RESPONSE_YES) => MessageDialogResult::Yes,
(YesNo | YesNoCancel, gtk_sys::GTK_RESPONSE_NO) => MessageDialogResult::No,
(OkCustom(custom), gtk_sys::GTK_RESPONSE_OK) => {
MessageDialogResult::Custom(custom.to_owned())
}
(OkCancelCustom(custom, _), gtk_sys::GTK_RESPONSE_OK) => {
MessageDialogResult::Custom(custom.to_owned())
}
(OkCancelCustom(_, custom), gtk_sys::GTK_RESPONSE_CANCEL) => {
MessageDialogResult::Custom(custom.to_owned())
}
(YesNoCancelCustom(custom, _, _), gtk_sys::GTK_RESPONSE_YES) => {
MessageDialogResult::Custom(custom.to_owned())
}
(YesNoCancelCustom(_, custom, _), gtk_sys::GTK_RESPONSE_NO) => {
MessageDialogResult::Custom(custom.to_owned())
}
(YesNoCancelCustom(_, _, custom), gtk_sys::GTK_RESPONSE_CANCEL) => {
MessageDialogResult::Custom(custom.to_owned())
}
_ => MessageDialogResult::Cancel,
}
}
}

Expand Down Expand Up @@ -129,7 +193,7 @@ impl AsGtkDialog for GtkMessageDialog {
use crate::backend::MessageDialogImpl;

impl MessageDialogImpl for MessageDialog {
fn show(self) -> bool {
fn show(self) -> MessageDialogResult {
let dialog = GtkMessageDialog::new(self);
dialog.run()
}
Expand All @@ -139,11 +203,15 @@ use crate::backend::AsyncMessageDialogImpl;
use crate::backend::DialogFutureType;

impl AsyncMessageDialogImpl for MessageDialog {
fn show_async(self) -> DialogFutureType<bool> {
fn show_async(self) -> DialogFutureType<MessageDialogResult> {
let builder = move || GtkMessageDialog::new(self);

let future = GtkDialogFuture::new(builder, |_, res| {
res == gtk_sys::GTK_RESPONSE_OK || res == gtk_sys::GTK_RESPONSE_YES
let future = GtkDialogFuture::new(builder, |_, res| match res {
gtk_sys::GTK_RESPONSE_OK => MessageDialogResult::Ok,
gtk_sys::GTK_RESPONSE_CANCEL => MessageDialogResult::Cancel,
gtk_sys::GTK_RESPONSE_YES => MessageDialogResult::Yes,
gtk_sys::GTK_RESPONSE_NO => MessageDialogResult::No,
_ => unreachable!(),
});
Box::pin(future)
}
Expand Down
6 changes: 3 additions & 3 deletions src/backend/gtk3/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl GtkEventHandler {
}

self.request_count.fetch_add(1, Ordering::Relaxed);
IterationRequest ()
IterationRequest()
}

fn iteration_stop(&self) {
Expand All @@ -69,14 +69,14 @@ impl GtkEventHandler {

fn request_iteration_stop(&self) {
self.request_count.fetch_sub(1, Ordering::Release);

if self.request_count.load(Ordering::Acquire) == 0 {
self.iteration_stop();
}
}
}

pub struct IterationRequest ();
pub struct IterationRequest();

impl Drop for IterationRequest {
fn drop(&mut self) {
Expand Down
72 changes: 52 additions & 20 deletions src/backend/linux/zenity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@ use std::{
};

use super::child_stdout::ChildStdout;
use crate::{
file_dialog::Filter,
message_dialog::{MessageButtons, MessageLevel},
FileDialog,
};
use crate::{file_dialog::Filter, message_dialog::{MessageButtons, MessageLevel}, FileDialog, MessageDialogResult};

#[derive(Debug)]
pub enum ZenityError {
Expand Down Expand Up @@ -81,7 +77,7 @@ async fn run(mut command: Command) -> ZenityResult<Option<String>> {
async_io::Timer::after(Duration::from_millis(1)).await;
};

Ok(if status.success() { Some(buffer) } else { None })
Ok(if status.success() || !buffer.is_empty() { Some(buffer) } else { None })
}

#[allow(unused)]
Expand Down Expand Up @@ -154,7 +150,7 @@ pub async fn message(
btns: &MessageButtons,
title: &str,
description: &str,
) -> ZenityResult<bool> {
) -> ZenityResult<MessageDialogResult> {
let cmd = match level {
MessageLevel::Info => "--info",
MessageLevel::Warning => "--warning",
Expand All @@ -174,26 +170,62 @@ pub async fn message(
command.args(["--ok-label", ok]);
}

run(command).await.map(|res| res.is_some())
run(command).await.map(|res| match res {
Some(_) => MessageDialogResult::Ok,
None => MessageDialogResult::Cancel,
})
}

pub async fn question(btns: &MessageButtons, title: &str, description: &str) -> ZenityResult<bool> {
let labels = match btns {
MessageButtons::OkCancel => Some(("Ok", "Cancel")),
MessageButtons::YesNo => None,
MessageButtons::OkCancelCustom(ok, cancel) => Some((ok.as_str(), cancel.as_str())),
_ => None,
};

pub async fn question(btns: &MessageButtons, title: &str, description: &str) -> ZenityResult<MessageDialogResult> {
let mut command = command();
command.args(["--question", "--title", title, "--text", description]);

if let Some((ok, cancel)) = labels {
command.args(["--ok-label", ok]);
command.args(["--cancel-label", cancel]);
match btns {
MessageButtons::OkCancel => {
command.args(["--ok-label", "Ok"]);
command.args(["--cancel-label", "Cancel"]);
}
MessageButtons::OkCancelCustom(ok, cancel) => {
command.args(["--ok-label", ok.as_str()]);
command.args(["--cancel-label", cancel.as_str()]);
},
MessageButtons::YesNoCancel => {
command.args(["--extra-button", "No"]);
command.args(["--cancel-label", "Cancel"]);
},
MessageButtons::YesNoCancelCustom(yes, no, cancel) => {
command.args(["--ok-label", yes.as_str()]);
command.args(["--cancel-label", cancel.as_str()]);
command.args(["--extra-button", no.as_str()]);
},
_ => {}
}

run(command).await.map(|res| res.is_some())
run(command).await.map(|res| match btns {
MessageButtons::OkCancel => match res {
Some(_) => MessageDialogResult::Ok,
None => MessageDialogResult::Cancel,
}
MessageButtons::YesNo => match res {
Some(_) => MessageDialogResult::Yes,
None => MessageDialogResult::No,
}
MessageButtons::OkCancelCustom(ok, cancel) => match res {
Some(_) => MessageDialogResult::Custom(ok.clone()),
None => MessageDialogResult::Custom(cancel.clone()),
}
MessageButtons::YesNoCancel => match res {
Some(output) if output.is_empty() => MessageDialogResult::Yes,
Some(_) => MessageDialogResult::No,
None => MessageDialogResult::Cancel,
}
MessageButtons::YesNoCancelCustom(yes, no, cancel) => match res {
Some(output) if output.is_empty() => MessageDialogResult::Custom(yes.clone()),
Some(_) => MessageDialogResult::Custom(no.clone()),
None => MessageDialogResult::Custom(cancel.clone()),
}
_ => MessageDialogResult::Cancel
})
}

#[cfg(test)]
Expand Down
Loading