/src/clipboard/linux.rs

https://github.com/federico-terzi/espanso · Rust · 98 lines · 64 code · 16 blank · 18 comment · 10 complexity · 2f035fd373397c8d40319212e3ed1f2a MD5 · raw file

  1. /*
  2. * This file is part of espanso.
  3. *
  4. * Copyright (C) 2019 Federico Terzi
  5. *
  6. * espanso is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * espanso is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with espanso. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. use log::error;
  20. use std::io::Write;
  21. use std::path::Path;
  22. use std::process::{Command, Stdio};
  23. pub struct LinuxClipboardManager {}
  24. impl super::ClipboardManager for LinuxClipboardManager {
  25. fn get_clipboard(&self) -> Option<String> {
  26. let res = Command::new("xclip").args(&["-o", "-sel", "clip"]).output();
  27. if let Ok(output) = res {
  28. if output.status.success() {
  29. let s = String::from_utf8_lossy(&output.stdout);
  30. return Some((*s).to_owned());
  31. }
  32. }
  33. None
  34. }
  35. fn set_clipboard(&self, payload: &str) {
  36. let res = Command::new("xclip")
  37. .args(&["-sel", "clip"])
  38. .stdin(Stdio::piped())
  39. .spawn();
  40. if let Ok(mut child) = res {
  41. let stdin = child.stdin.as_mut();
  42. if let Some(output) = stdin {
  43. let res = output.write_all(payload.as_bytes());
  44. if let Err(e) = res {
  45. error!("Could not set clipboard: {}", e);
  46. }
  47. let res = child.wait();
  48. if let Err(e) = res {
  49. error!("Could not set clipboard: {}", e);
  50. }
  51. }
  52. }
  53. }
  54. fn set_clipboard_image(&self, image_path: &Path) {
  55. let extension = image_path.extension();
  56. let mime = match extension {
  57. Some(ext) => {
  58. let ext = ext.to_string_lossy().to_lowercase();
  59. match ext.as_ref() {
  60. "png" => "image/png",
  61. "jpg" | "jpeg" => "image/jpeg",
  62. "gif" => "image/gif",
  63. "svg" => "image/svg",
  64. _ => "image/png",
  65. }
  66. }
  67. None => "image/png",
  68. };
  69. let image_path = image_path.to_string_lossy().into_owned();
  70. let res = Command::new("xclip")
  71. .args(&["-selection", "clipboard", "-t", mime, "-i", &image_path])
  72. .spawn();
  73. if let Err(e) = res {
  74. error!("Could not set image clipboard: {}", e);
  75. }
  76. }
  77. }
  78. impl LinuxClipboardManager {
  79. pub fn new() -> LinuxClipboardManager {
  80. LinuxClipboardManager {}
  81. }
  82. }