clipboard.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. #[cfg(target_os = "linux")]
  19. use std::sync::{Arc, Mutex};
  20. #[cfg(target_os = "linux")]
  21. use std::time::Duration;
  22. #[cfg(target_os = "linux")]
  23. static X11_CLIPBOARD: Mutex<Option<Arc<x11_clipboard::Clipboard>>> = Mutex::new(None);
  24. #[cfg(target_os = "linux")]
  25. fn get_clipboard() -> Option<Arc<x11_clipboard::Clipboard>> {
  26. let mut clipboard = X11_CLIPBOARD.lock().unwrap();
  27. if clipboard.is_none() {
  28. *clipboard = x11_clipboard::Clipboard::new().ok().map(Arc::new);
  29. }
  30. clipboard.clone()
  31. }
  32. pub fn get() -> Option<String> {
  33. #[cfg(target_os = "linux")]
  34. if let Some(clipboard) = get_clipboard() {
  35. if let Ok(bytes) = clipboard.load(
  36. clipboard.getter.atoms.clipboard,
  37. clipboard.getter.atoms.utf8_string,
  38. clipboard.getter.atoms.property,
  39. Duration::from_secs(2),
  40. ) {
  41. if let Ok(text) = String::from_utf8(bytes) {
  42. return Some(text)
  43. }
  44. }
  45. }
  46. miniquad::window::clipboard_get()
  47. }
  48. pub fn set(text: &str) {
  49. #[cfg(target_os = "linux")]
  50. if let Some(clipboard) = get_clipboard() {
  51. if clipboard.store(
  52. clipboard.setter.atoms.clipboard,
  53. clipboard.setter.atoms.utf8_string,
  54. text,
  55. ).is_ok() {
  56. return
  57. }
  58. }
  59. miniquad::window::clipboard_set(text);
  60. }