1use crate::default_instance;
18use crate::dispatch::fmt::*;
19use crate::error::HyprError;
20use crate::shared::*;
21use derive_more::Display;
22use std::string::ToString;
23
24#[derive(Debug, Clone, Display)]
26pub enum WindowIdentifier<'a> {
27 #[display("address:{_0}")]
29 Address(Address),
30 #[display("class:{_0}")]
32 ClassRegularExpression(&'a str),
33 #[display("title:{_0}")]
35 Title(&'a str),
36 #[display("tag:{_0}")]
38 Tag(&'a str),
39 #[display("pid:{_0}")]
41 ProcessId(u32),
42 #[display("activewindow")]
44 ActiveWindow,
45 #[display("floating")]
47 Floating,
48 #[display("tiled")]
50 Tiled,
51}
52
53#[derive(Debug, Clone, Display)]
55pub enum FullscreenType {
56 #[display("0")]
58 Real,
59 #[display("1")]
61 Maximize,
62 #[display("")]
64 NoParam,
65}
66
67#[allow(missing_docs)]
69#[derive(Debug, Clone, Copy)]
70pub enum FullscreenState {
71 Current = -1,
72 None = 0,
73 Maximize = 1,
74 Fullscreen = 2,
75 MaximizeFullscreen = 3,
76}
77
78impl std::fmt::Display for FullscreenState {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 write!(f, "{}", *self as i8)
81 }
82}
83
84#[derive(Debug, Clone, Display)]
86#[allow(missing_docs)]
87pub enum Direction {
88 #[display("u")]
89 Up,
90 #[display("d")]
91 Down,
92 #[display("r")]
93 Right,
94 #[display("l")]
95 Left,
96}
97
98#[derive(Debug, Clone, Display)]
100pub enum Position {
101 #[display("{_0} {_0}")]
103 Delta(i16, i16),
104 #[display("exact {_0} {_0}")]
106 Exact(i16, i16),
107 #[display("{_0}% {_0}%")]
109 DeltaFraction(i16, i16),
110 #[display("exact {_0}% {_0}%")]
112 ExactFraction(i16, i16),
113}
114
115#[allow(missing_docs)]
117#[derive(Debug, Clone, Display)]
118pub enum CycleDirection {
119 #[display("")]
120 Next,
121 #[display("prev")]
122 Previous,
123}
124
125#[allow(missing_docs)]
127#[derive(Debug, Clone, Display)]
128pub enum WindowSwitchDirection {
129 #[display("b")]
130 Back,
131 #[display("f")]
132 Forward,
133 #[display("{}", _0)]
134 Index(i32),
135}
136
137#[derive(Debug, Clone)]
139pub enum MonitorIdentifier<'a> {
140 Direction(Direction),
142 Id(MonitorId),
144 Name(&'a str),
146 Current,
148 Relative(i32),
150}
151
152impl std::fmt::Display for MonitorIdentifier<'_> {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 let out = match self {
155 MonitorIdentifier::Direction(dir) => dir.to_string(),
156 MonitorIdentifier::Id(id) => id.to_string(),
157 MonitorIdentifier::Name(name) => name.to_string(),
158 MonitorIdentifier::Current => "current".to_string(),
159 MonitorIdentifier::Relative(int) => format_relative(*int, ""),
160 };
161 write!(f, "{out}")
162 }
163}
164
165#[allow(missing_docs)]
167#[derive(Debug, Clone)]
168pub enum Corner {
169 BottomLeft = 0,
170 BottomRight = 1,
171 TopRight = 2,
172 TopLeft = 3,
173}
174
175#[derive(Debug, Clone, Display)]
177pub enum WorkspaceOptions {
178 #[display("allfloat")]
180 AllPseudo,
181 #[display("allpseudo")]
183 AllFloat,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub struct FirstEmpty {
189 pub on_monitor: bool,
191 pub next: bool,
193}
194
195impl std::fmt::Display for FirstEmpty {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 let mut s = String::new();
198 if self.on_monitor {
199 s.push('m');
200 }
201 if self.next {
202 s.push('n');
203 }
204 write!(f, "{s}")
205 }
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
210pub enum WorkspaceIdentifierWithSpecial<'a> {
211 Id(WorkspaceId),
213 #[display("{}", format_relative(*_0, ""))]
215 Relative(i32),
216 #[display("{}", format_relative(*_0, "m"))]
218 RelativeMonitor(i32),
219 #[display("{}", format_relative(*_0, "r"))]
221 RelativeMonitorIncludingEmpty(i32),
222 #[display("{}", format_relative(*_0, "e"))]
224 RelativeOpen(i32),
225 #[display("previous")]
227 Previous,
228 #[display("previous_per_monitor")]
230 PreviousPerMonitor,
231 #[display("{}", format!("empty{}", _0))]
233 Empty(FirstEmpty),
234 #[display("name:{_0}")]
236 Name(&'a str),
237 #[display("special{}", format_special_workspace_ident(_0))]
239 Special(Option<&'a str>),
240}
241
242pub(super) mod fmt {
243 #[inline(always)]
244 pub(super) fn format_special_workspace_ident<'a>(opt: &'a Option<&'a str>) -> String {
245 match opt {
246 Some(o) => ":".to_owned() + o,
247 None => String::new(),
248 }
249 }
250
251 #[inline(always)]
252 pub(super) fn format_relative(int: i32, extra: &'_ str) -> String {
253 if int.is_positive() {
254 format!("{extra}+{int}")
255 } else if int.is_negative() {
256 format!("{extra}-{}", int.abs())
257 } else {
258 "+0".to_owned()
259 }
260 }
261}
262
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub enum WorkspaceIdentifier<'a> {
266 Id(WorkspaceId),
268 Relative(i32),
270 RelativeMonitor(i32),
272 RelativeMonitorIncludingEmpty(i32),
274 RelativeOpen(i32),
276 Previous,
278 Empty,
280 Name(&'a str),
282}
283
284impl std::fmt::Display for WorkspaceIdentifier<'_> {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 use WorkspaceIdentifier::*;
287 let out = match self {
288 Id(id) => format!("{id}"),
289 Name(name) => format!("name:{name}"),
290 Relative(int) => format_relative(*int, ""),
291 RelativeMonitor(int) => format_relative(*int, "m"),
292 RelativeMonitorIncludingEmpty(int) => format_relative(*int, "r"),
293 RelativeOpen(int) => format_relative(*int, "e"),
294 Previous => "previous".to_string(),
295 Empty => "empty".to_string(),
296 };
297
298 write!(f, "{out}")
299 }
300}
301
302#[derive(Debug, Clone)]
304pub enum WindowMove<'a> {
305 Monitor(MonitorIdentifier<'a>),
307 Direction(Direction),
309}
310
311#[derive(Debug, Clone, Display)]
313#[allow(missing_docs)]
314pub enum TagAction {
315 #[display("+")]
316 Add,
317 #[display("-")]
318 Remove,
319 #[display("")]
320 Toggle,
321}
322
323#[derive(Debug, Clone, Copy)]
325pub enum SignalType {
326 SIGHUP = 1,
328 SIGINT = 2,
330 SIGQUIT = 3,
332 SIGILL = 4,
334 SIGTRAP = 5,
336 SIGABRT = 6,
338 SIGBUS = 7,
340 SIGFPE = 8,
342 SIGKILL = 9,
344 SIGUSR1 = 10,
346 SIGSEGV = 11,
348 SIGUSR2 = 12,
350 SIGPIPE = 13,
352 SIGALRM = 14,
354 SIGTERM = 15,
356 SIGSTKFLT = 16,
358 SIGCHLD = 17,
360 SIGCONT = 18,
362 SIGSTOP = 19,
364 SIGTSTP = 20,
366 SIGTTIN = 21,
368 SIGTTOU = 22,
370 SIGURG = 23,
372 SIGXCPU = 24,
374 SIGXFSZ = 25,
376 SIGVTALRM = 26,
378 SIGPROF = 27,
380 SIGWINCH = 28,
382 SIGIO = 29,
384 SIGPWR = 30,
386 SIGSYS = 31,
388}
389
390impl std::fmt::Display for SignalType {
391 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
392 write!(f, "{}", *self as u8)
393 }
394}
395
396#[derive(Debug, Clone, Copy, Display)]
397pub enum MoveToRootParam {
399 #[display("")]
401 Stable,
402 #[display("unstable")]
404 Unstable,
405}
406
407#[derive(Debug, Clone, Copy, Display)]
409pub enum ZOrder {
410 #[display("top")]
412 Top,
413 #[display("bottom")]
415 Bottom,
416}
417
418#[derive(Debug, Clone, Copy, Display)]
420pub enum SubmapParam<'a> {
421 #[display("reset")]
423 Reset,
424 #[display("{}", _0)]
426 Name(&'a str),
427}
428
429#[derive(Debug, Clone)]
431pub enum DispatchType<'a> {
432 Custom(
435 &'a str,
437 &'a str,
439 ),
440 SetCursor(
442 &'a str,
444 u16,
446 ),
447 Exec(&'a str),
449 ExecRaw(&'a str),
451 Pass(WindowIdentifier<'a>),
454 Global(&'a str),
456 KillActiveWindow,
458 ForceKillActiveWindow,
460 CloseWindow(WindowIdentifier<'a>),
462 Workspace(WorkspaceIdentifierWithSpecial<'a>),
464 MoveToWorkspace(
466 WorkspaceIdentifierWithSpecial<'a>,
467 Option<WindowIdentifier<'a>>,
468 ),
469 MoveToWorkspaceSilent(
472 WorkspaceIdentifierWithSpecial<'a>,
473 Option<WindowIdentifier<'a>>,
474 ),
475 ToggleFloating(Option<WindowIdentifier<'a>>),
477 SetFloating(Option<WindowIdentifier<'a>>),
479 SetTiled(Option<WindowIdentifier<'a>>),
481 ToggleFullscreen(FullscreenType),
483 ToggleFullscreenState(FullscreenState, FullscreenState),
485 ToggleFakeFullscreen,
488 ToggleDPMS(bool, Option<&'a str>),
490 TogglePseudo,
492 TogglePin,
494 TogglePinWindow(WindowIdentifier<'a>),
496 SendShortcut(
498 &'a [crate::shared::Mod],
500 &'a str,
502 Option<WindowIdentifier<'a>>,
504 ),
505 Signal(SignalType),
507 SignalWindow(WindowIdentifier<'a>, SignalType),
509 MoveFocus(Direction),
511 MoveWindow(WindowMove<'a>),
513 CenterWindow,
515 ResizeActive(Position),
517 MoveActive(Position),
519 ResizeWindowPixel(Position, WindowIdentifier<'a>),
521 MoveWindowPixel(Position, WindowIdentifier<'a>),
523 CycleWindow(CycleDirection),
525 SwapNext(CycleDirection),
527 SwapWindow(Direction),
529 TagWindow(TagAction, &'a str, Option<WindowIdentifier<'a>>),
531 FocusWindow(WindowIdentifier<'a>),
533 FocusMonitor(MonitorIdentifier<'a>),
535 ChangeSplitRatio(FloatValue),
537 ToggleOpaque,
539 MoveCursorToCorner(Corner),
541 MoveCursor(i64, i64),
544 WorkspaceOption(WorkspaceOptions),
546 RenameWorkspace(WorkspaceId, Option<&'a str>),
548 Exit,
550 ForceRendererReload,
552 MoveCurrentWorkspaceToMonitor(MonitorIdentifier<'a>),
554 MoveWorkspaceToMonitor(WorkspaceIdentifier<'a>, MonitorIdentifier<'a>),
556 SwapActiveWorkspaces(MonitorIdentifier<'a>, MonitorIdentifier<'a>),
558 BringActiveToTop,
560 AlterZOrder(ZOrder, Option<WindowIdentifier<'a>>),
562 ToggleSpecialWorkspace(Option<String>),
564 FocusUrgentOrLast,
566 FocusCurrentOrLast,
568 ToggleSwallow,
570 Submap(SubmapParam<'a>),
572
573 ToggleSplit,
577 SwapSplit,
579 PreSelect(Direction),
581 MoveToRoot(Option<WindowIdentifier<'a>>, MoveToRootParam),
583
584 SwapWithMaster(SwapWithMasterParam),
589 FocusMaster(FocusMasterParam),
591 CycleNextMaster(MasterLoopParam),
593 CyclePrevMaster(MasterLoopParam),
595 SwapNextMaster(MasterLoopParam),
597 SwapPrevMaster(MasterLoopParam),
599 AddMaster,
602 RemoveMaster,
605 OrientationLeft,
608 OrientationRight,
611 OrientationTop,
614 OrientationBottom,
617 OrientationCenter,
620 OrientationNext,
622 OrientationPrev,
624 OrientationCycle(OrientationParam),
626 Mfact(FloatValue),
628 RollNext,
630 RollPrev,
632
633 ToggleGroup,
636 ChangeGroupActive(WindowSwitchDirection),
638 LockGroups(LockType),
640 LockActiveGroup(LockType),
642 MoveIntoGroup(Direction),
644 MoveWindowOrGroup(Direction),
646 MoveOutOfGroup,
648 MoveGroupWindow(WindowSwitchDirection),
650 DenyWindowFromGroup(BinaryState),
652 SetIgnoreGroupLock(BinaryState),
654}
655
656#[allow(missing_docs)]
658#[derive(Debug, Clone, Copy, Display, PartialEq, Eq, PartialOrd, Ord)]
659pub enum BinaryState {
660 #[display("on")]
661 On,
662 #[display("off")]
663 Off,
664 #[display("toggle")]
665 Toggle,
666}
667
668#[derive(Debug, Clone, Copy, Display, PartialEq, Eq, PartialOrd, Ord)]
670pub enum LockType {
671 #[display("lock")]
673 Lock,
674 #[display("unlock")]
676 Unlock,
677 #[display("toggle")]
679 ToggleLock,
680}
681
682#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
684pub enum SwapWithMasterParam {
685 #[display("master")]
687 Master,
688 #[display("child")]
690 Child,
691 #[display("auto")]
693 Auto,
694 #[display("ignoremaster")]
696 IgnoreMaster,
697}
698
699#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
701pub enum FocusMasterParam {
702 #[display("master")]
704 Master,
705 #[display("auto")]
707 Auto,
708 #[display("previous")]
710 Previous,
711}
712
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
715pub enum MasterLoopParam {
716 #[display("loop")]
718 Loop,
719 #[display("noloop")]
721 NoLoop,
722}
723
724#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
726pub enum OrientationParam {
727 #[display("left")]
729 Left,
730 #[display("right")]
732 Right,
733 #[display("bottom")]
735 Bottom,
736 #[display("top")]
738 Top,
739 #[display("center")]
741 Center,
742}
743
744#[derive(Debug, Clone, Copy, PartialEq, Display)]
746pub enum FloatValue {
747 #[display("{}", _0)]
749 Relative(f32),
750 #[display("exact {}", _0)]
752 Exact(f32),
753}
754
755pub(crate) fn gen_dispatch_str(cmd: DispatchType, dispatch: bool) -> crate::Result<CommandContent> {
756 use DispatchType::*;
757 let sep = if dispatch { " " } else { "," };
758 let string_to_pass = match &cmd {
759 Custom(name, args) => format!("{name}{sep}{args}"),
760 Exec(sh) => format!("exec{sep}{sh}"),
761 ExecRaw(sh) => format!("execr{sep}{sh}"),
762 Pass(win) => format!("pass{sep}{win}"),
763 Global(name) => format!("global{sep}{name}"),
764 KillActiveWindow => "killactive".to_string(),
765 ForceKillActiveWindow => "forcekillactive".to_string(),
766 CloseWindow(win) => format!("closewindow{sep}{win}"),
767 Workspace(work) => format!("workspace{sep}{work}"),
768 MoveToWorkspace(work, Some(win)) => format!("movetoworkspace{sep}{work},{win}"),
769 MoveToWorkspace(work, None) => format!("movetoworkspace{sep}{work}"),
770 MoveToWorkspaceSilent(work, Some(win)) => format!("movetoworkspacesilent{sep}{work},{win}"),
771 MoveToWorkspaceSilent(work, None) => format!("movetoworkspacesilent{sep}{work}"),
772 ToggleFloating(Some(v)) => format!("togglefloating{sep}{v}"),
773 ToggleFloating(None) => "togglefloating".to_string(),
774 SetFloating(Some(v)) => format!("setfloating{sep}{v}"),
775 SetFloating(None) => "setfloating".to_string(),
776 SetTiled(Some(v)) => format!("settiled{sep}{v}"),
777 SetTiled(None) => "settiled".to_string(),
778 ToggleFullscreen(ftype) => format!("fullscreen{sep}{ftype}"),
779 ToggleFullscreenState(int, cl) => format!("fullscreenstate{sep}{int} {cl}"),
780 ToggleFakeFullscreen => "fakefullscreen".to_string(),
781 ToggleDPMS(stat, mon) => {
782 format!(
783 "dpms{sep}{} {}",
784 if *stat { "on" } else { "off" },
785 mon.unwrap_or_default()
786 )
787 }
788 TogglePseudo => "pseudo".to_string(),
789 TogglePin => "pin".to_string(),
790 TogglePinWindow(win) => format!("pin{sep}{win}"),
791 SendShortcut(mods, key, win_opt) => {
792 let mods_str: String = mods.iter().map(|m| m.to_string()).collect();
793 match win_opt {
794 Some(win) => format!("sendshortcut{sep}{mods_str},{key},{win}"),
795 None => format!("sendshortcut{sep}{mods_str},{key},"),
796 }
797 }
798 MoveFocus(dir) => format!("movefocus{sep}{dir}",),
799 MoveWindow(ident) => format!(
800 "movewindow{sep}{}",
801 match ident {
802 WindowMove::Direction(dir) => dir.to_string(),
803 WindowMove::Monitor(mon) => format!("mon:{mon}"),
804 }
805 ),
806 CenterWindow => "centerwindow".to_string(),
807 ResizeActive(pos) => format!("resizeactive{sep}{pos}"),
808 MoveActive(pos) => format!("moveactive {pos}"),
809 ResizeWindowPixel(pos, win) => format!("resizewindowpixel{sep}{pos},{win}"),
810 MoveWindowPixel(pos, win) => format!("movewindowpixel{sep}{pos},{win}"),
811 CycleWindow(dir) => format!("cyclenext{sep}{dir}"),
812 SwapNext(dir) => format!("swapnext{sep}{dir}"),
813 SwapWindow(dir) => format!("swapwindow{sep}{dir}"),
814 TagWindow(act, tag, Some(win)) => format!("tagwindow{sep}{act}{tag} {win}"),
815 TagWindow(act, tag, None) => format!("tagwindow{sep}{act}{tag}"),
816 FocusWindow(win) => format!("focuswindow{sep}{win}"),
817 FocusMonitor(mon) => format!("focusmonitor{sep}{mon}"),
818 ChangeSplitRatio(fv) => format!("splitratio {fv}"),
819 ToggleOpaque => "toggleopaque".to_string(),
820 MoveCursorToCorner(corner) => format!("movecursortocorner{sep}{}", corner.clone() as u8),
821 MoveCursor(x, y) => format!("movecursor{sep}{x} {y}"),
822 WorkspaceOption(opt) => format!("workspaceopt{sep}{opt}"),
823 Exit => "exit".to_string(),
824 ForceRendererReload => "forcerendererreload".to_string(),
825 MoveCurrentWorkspaceToMonitor(mon) => format!("movecurrentworkspacetomonitor{sep}{mon}"),
826 MoveWorkspaceToMonitor(work, mon) => format!("moveworkspacetomonitor{sep}{work} {mon}"),
827 ToggleSpecialWorkspace(Some(name)) => format!("togglespecialworkspace {name}"),
828 ToggleSpecialWorkspace(None) => "togglespecialworkspace".to_string(),
829 RenameWorkspace(id, name) => {
830 format!(
831 "renameworkspace{sep}{id} {}",
832 name.unwrap_or(&id.to_string())
833 )
834 }
835 SwapActiveWorkspaces(mon, mon2) => format!("swapactiveworkspaces{sep}{mon} {mon2}",),
836 BringActiveToTop => "bringactivetotop".to_string(),
837 AlterZOrder(z, Some(win)) => format!("alterzorder{sep}{z},{win}"),
838 AlterZOrder(z, None) => format!("alterzorder{sep}{z}"),
839 SetCursor(theme, size) => format!("{theme} {}", *size),
840 Signal(sig) => format!("signal{sep}{sig}"),
841 SignalWindow(win, sig) => format!("signalwindow{sep}{win},{sig}"),
842 FocusUrgentOrLast => "focusurgentorlast".to_string(),
843 FocusCurrentOrLast => "focuscurrentorlast".to_string(),
844 ToggleSwallow => "toggleswallow".to_string(),
845 ToggleSplit => format!("layoutmsg{sep}togglesplit"),
846 SwapSplit => format!("layoutmsg{sep}swapsplit"),
847 PreSelect(dir) => format!("layoutmsg{sep}preselect {dir}"),
848 MoveToRoot(Some(win), param) => format!("layoutmsg{sep}movetoroot {win} {param}"),
849 MoveToRoot(None, _) => format!("layoutmsg{sep}movetoroot"),
850 Submap(param) => format!("submap{sep}{param}"),
851 SwapWithMaster(param) => format!("layoutmsg{sep}swapwithmaster {param}"),
852 FocusMaster(param) => format!("layoutmsg{sep}focusmaster {param}"),
853 CycleNextMaster(param) => format!("layoutmsg{sep}cyclenext {param}"),
854 CyclePrevMaster(param) => format!("layoutmsg{sep}cycleprev {param}"),
855 SwapNextMaster(param) => format!("layoutmsg{sep}swapnext {param}"),
856 SwapPrevMaster(param) => format!("layoutmsg{sep}swapprev {param}"),
857 AddMaster => format!("layoutmsg{sep}addmaster"),
858 RemoveMaster => format!("layoutmsg{sep}removemaster"),
859 OrientationLeft => format!("layoutmsg{sep}orientationleft"),
860 OrientationRight => format!("layoutmsg{sep}orientationright"),
861 OrientationTop => format!("layoutmsg{sep}orientationtop"),
862 OrientationBottom => format!("layoutmsg{sep}orientationbottom"),
863 OrientationCenter => format!("layoutmsg{sep}orientationcenter"),
864 OrientationNext => format!("layoutmsg{sep}orientationnext"),
865 OrientationPrev => format!("layoutmsg{sep}orientationprev"),
866 OrientationCycle(param) => format!("layoutmsg{sep}orientationcycle {param}"),
867 Mfact(fv) => format!("layoutmsg{sep}mfact {fv}"),
868 RollNext => format!("layoutmsg{sep}rollnext"),
869 RollPrev => format!("layoutmsg{sep}rollprev"),
870 ToggleGroup => "togglegroup".to_string(),
871 ChangeGroupActive(dir) => format!("changegroupactive{sep}{dir}"),
872 LockGroups(how) => format!("lockgroups{sep}{how}"),
873 LockActiveGroup(how) => format!("lockactivegroups{sep}{how}"),
874 MoveIntoGroup(dir) => format!("moveintogroup{sep}{dir}"),
875 MoveWindowOrGroup(dir) => format!("movewindoworgroup{sep}{dir}"),
876 MoveOutOfGroup => "moveoutofgroup".to_string(),
877 MoveGroupWindow(dir) => format!("movegroupwindow{sep}{dir}"),
878 DenyWindowFromGroup(state) => format!("denywindowfromgroup{sep}{state}"),
879 SetIgnoreGroupLock(state) => format!("setignoregrouplock{sep}{state}"),
880 };
881
882 if let SetCursor(_, _) = cmd {
883 Ok(command!(JSON, "setcursor {string_to_pass}"))
884 } else if dispatch {
885 Ok(command!(JSON, "dispatch {string_to_pass}"))
886 } else {
887 Ok(command!(Empty, "{string_to_pass}"))
888 }
889}
890
891pub struct Dispatch;
893
894impl Dispatch {
895 pub fn call(dispatch_type: DispatchType) -> crate::Result<()> {
906 Self::instance_call(default_instance()?, dispatch_type)
907 }
908
909 pub fn instance_call(
921 instance: &crate::instance::Instance,
922 dispatch_type: DispatchType,
923 ) -> crate::Result<()> {
924 let output = instance.write_to_socket(gen_dispatch_str(dispatch_type, true)?);
925 match output {
926 Ok(msg) => match msg.as_str() {
927 "ok" => Ok(()),
928 msg => Err(HyprError::NotOkDispatch(msg.to_string())),
929 },
930 Err(error) => Err(error),
931 }
932 }
933
934 #[cfg(any(feature = "async-lite", feature = "tokio"))]
947 pub async fn call_async(dispatch_type: DispatchType<'_>) -> crate::Result<()> {
948 Self::instance_call_async(default_instance()?, dispatch_type).await
949 }
950
951 #[cfg(any(feature = "async-lite", feature = "tokio"))]
964 pub async fn instance_call_async(
965 instance: &crate::instance::Instance,
966 dispatch_type: DispatchType<'_>,
967 ) -> crate::Result<()> {
968 let output = instance
969 .write_to_socket_async(gen_dispatch_str(dispatch_type, true)?)
970 .await;
971 match output {
972 Ok(msg) => match msg.as_str() {
973 "ok" => Ok(()),
974 msg => Err(HyprError::NotOkDispatch(msg.to_string())),
975 },
976 Err(error) => Err(error),
977 }
978 }
979}
980
981#[macro_export]
983macro_rules! dispatch {
984 (async; $dis:ident) => {
985 $crate::dispatch::Dispatch::call_async($crate::dispatch::DispatchType::$dis)
986 };
987 (async; $dis:ident, $( $arg:expr ), *) => {
988 $crate::dispatch::Dispatch::call_async($crate::dispatch::DispatchType::$dis($($arg), *))
989 };
990 (async; $instance:expr; $dis:ident) => {
991 $crate::dispatch::Dispatch::instance_call_async($instance, $crate::dispatch::DispatchType::$dis)
992 };
993 (async; $instance:expr; $dis:ident, $( $arg:expr ), *) => {
994 $crate::dispatch::Dispatch::instance_call_async($instance, $crate::dispatch::DispatchType::$dis($($arg), *))
995 };
996 ($dis:ident) => {
997 $crate::dispatch::Dispatch::call($crate::dispatch::DispatchType::$dis)
998 };
999 ($dis:ident, $( $arg:expr ), *) => {
1000 $crate::dispatch::Dispatch::call($crate::dispatch::DispatchType::$dis($($arg), *))
1001 };
1002 ($instance:expr; $dis:ident) => {
1003 $crate::dispatch::Dispatch::instance_call($instance, $crate::dispatch::DispatchType::$dis)
1004 };
1005 ($instance:expr; $dis:ident, $( $arg:expr ), *) => {
1006 $crate::dispatch::Dispatch::instance_call($instance, $crate::dispatch::DispatchType::$dis($($arg), *))
1007 };
1008}