1use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::future::Future;
6use std::path::PathBuf;
7
8use crate::{
9 Command, Error, NewPane, ObjectKind, OptionMap, OptionScope, OptionValue, Pane,
10 ResizeDirection, Result, Server, Session, SessionId, SessionTarget, SparseOptionMap, SplitPane,
11 TmuxText, WindowId, WindowLink, WindowSnapshot, WindowTarget,
12};
13
14#[derive(Clone, Debug, Eq, Hash, PartialEq)]
16pub enum Layout {
17 EvenHorizontal,
19 EvenVertical,
21 MainHorizontal,
23 MainVertical,
25 Tiled,
27 Custom(String),
29}
30
31impl std::fmt::Display for Layout {
32 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 formatter.write_str(match self {
34 Self::EvenHorizontal => "even-horizontal",
35 Self::EvenVertical => "even-vertical",
36 Self::MainHorizontal => "main-horizontal",
37 Self::MainVertical => "main-vertical",
38 Self::Tiled => "tiled",
39 Self::Custom(value) => value,
40 })
41 }
42}
43
44#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
46pub enum Rotation {
47 Up,
49 Down,
51}
52
53#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
55pub enum WindowPosition {
56 Before,
58 After,
60}
61
62#[derive(Clone, Debug, Default, Eq, PartialEq)]
64pub struct WindowResize {
65 adjustment: Option<(ResizeDirection, u32)>,
66 width: Option<u32>,
67 height: Option<u32>,
68 expand: bool,
69 shrink: bool,
70}
71
72impl WindowResize {
73 #[must_use]
75 pub fn new() -> Self {
76 Self::default()
77 }
78
79 pub fn adjustment(mut self, direction: ResizeDirection, cells: u32) -> Result<Self> {
81 if cells == 0 {
82 return Err(Error::InvalidArgument {
83 argument: "window resize adjustment",
84 message: "must be non-zero".to_owned(),
85 });
86 }
87 self.adjustment = Some((direction, cells));
88 Ok(self)
89 }
90
91 pub fn width(mut self, width: u32) -> Result<Self> {
93 if width == 0 {
94 return Err(Error::InvalidArgument {
95 argument: "window width",
96 message: "must be non-zero".to_owned(),
97 });
98 }
99 self.width = Some(width);
100 Ok(self)
101 }
102
103 pub fn height(mut self, height: u32) -> Result<Self> {
105 if height == 0 {
106 return Err(Error::InvalidArgument {
107 argument: "window height",
108 message: "must be non-zero".to_owned(),
109 });
110 }
111 self.height = Some(height);
112 Ok(self)
113 }
114
115 #[must_use]
117 pub const fn expand(mut self, enabled: bool) -> Self {
118 self.expand = enabled;
119 self
120 }
121
122 #[must_use]
124 pub const fn shrink(mut self, enabled: bool) -> Self {
125 self.shrink = enabled;
126 self
127 }
128}
129
130#[derive(Clone, Debug, Default)]
132pub struct RespawnWindow {
133 command: Option<OsString>,
134 cwd: Option<PathBuf>,
135 environment: BTreeMap<String, OsString>,
136 kill: bool,
137}
138
139impl RespawnWindow {
140 #[must_use]
142 pub fn new() -> Self {
143 Self::default()
144 }
145
146 #[must_use]
148 pub fn command(mut self, command: impl Into<OsString>) -> Self {
149 self.command = Some(command.into());
150 self
151 }
152
153 #[must_use]
155 pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
156 self.cwd = Some(cwd.into());
157 self
158 }
159
160 pub fn environment(
162 mut self,
163 name: impl Into<String>,
164 value: impl Into<OsString>,
165 ) -> Result<Self> {
166 let name = name.into();
167 crate::server::validate_name("environment name", &name)?;
168 self.environment.insert(name, value.into());
169 Ok(self)
170 }
171
172 #[must_use]
174 pub const fn kill(mut self, enabled: bool) -> Self {
175 self.kill = enabled;
176 self
177 }
178}
179
180#[derive(Clone, Debug)]
182pub struct NewWindow {
183 name: Option<OsString>,
184 cwd: Option<PathBuf>,
185 index: Option<u32>,
186 detached: bool,
187 kill_existing: bool,
188 shell_command: Option<OsString>,
189 environment: BTreeMap<String, OsString>,
190 relative_to: Option<WindowTarget>,
191 position: Option<WindowPosition>,
192 select_existing: bool,
193}
194
195impl Default for NewWindow {
196 fn default() -> Self {
197 Self {
198 name: None,
199 cwd: None,
200 index: None,
201 detached: true,
202 kill_existing: false,
203 shell_command: None,
204 environment: BTreeMap::new(),
205 relative_to: None,
206 position: None,
207 select_existing: false,
208 }
209 }
210}
211
212impl NewWindow {
213 #[must_use]
215 pub fn new() -> Self {
216 Self::default()
217 }
218
219 #[must_use]
221 pub fn name(mut self, name: impl Into<OsString>) -> Self {
222 self.name = Some(name.into());
223 self
224 }
225
226 #[must_use]
228 pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
229 self.cwd = Some(cwd.into());
230 self
231 }
232
233 #[must_use]
235 pub const fn index(mut self, index: u32) -> Self {
236 self.index = Some(index);
237 self
238 }
239
240 #[must_use]
242 pub const fn detached(mut self, detached: bool) -> Self {
243 self.detached = detached;
244 self
245 }
246
247 #[must_use]
249 pub const fn kill_existing(mut self, enabled: bool) -> Self {
250 self.kill_existing = enabled;
251 self
252 }
253
254 #[must_use]
256 pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
257 self.shell_command = Some(command.into());
258 self
259 }
260
261 pub fn environment(
263 mut self,
264 name: impl Into<String>,
265 value: impl Into<OsString>,
266 ) -> Result<Self> {
267 let name = name.into();
268 crate::server::validate_name("environment name", &name)?;
269 self.environment.insert(name, value.into());
270 Ok(self)
271 }
272
273 #[must_use]
275 pub fn relative_to(
276 mut self,
277 target: impl Into<WindowTarget>,
278 position: WindowPosition,
279 ) -> Self {
280 self.relative_to = Some(target.into());
281 self.position = Some(position);
282 self
283 }
284
285 #[must_use]
287 pub const fn select_existing(mut self, enabled: bool) -> Self {
288 self.select_existing = enabled;
289 self
290 }
291}
292
293#[derive(Clone, Debug)]
295pub struct Window {
296 server: Server,
297 id: WindowId,
298 session_id: SessionId,
299 link: WindowLink,
300 snapshot: WindowSnapshot,
301}
302
303impl Window {
304 pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
305 let snapshot = WindowSnapshot::new(row);
306 let id = snapshot.id()?.ok_or_else(|| Error::Decode {
307 context: "window row",
308 message: "window_id was empty".to_owned(),
309 })?;
310 let session_id = snapshot
311 .get("session_id")
312 .ok_or_else(|| Error::Decode {
313 context: "window row",
314 message: "session_id was absent".to_owned(),
315 })?
316 .to_str()
317 .map_err(|source| Error::Decode {
318 context: "window session ID",
319 message: source.to_string(),
320 })?
321 .parse()?;
322 let index = snapshot.index()?.ok_or_else(|| Error::Decode {
323 context: "window row",
324 message: "window_index was empty".to_owned(),
325 })?;
326 Ok(Self {
327 server,
328 id,
329 session_id,
330 link: WindowLink::new(session_id, index),
331 snapshot,
332 })
333 }
334
335 pub async fn from_environment() -> Result<Self> {
337 Server::from_environment()?
338 .pane_from_environment()
339 .await?
340 .window()
341 .await
342 }
343
344 pub(crate) async fn create(session: &Session, options: NewWindow) -> Result<Self> {
345 let target = options.relative_to.as_ref().map_or_else(
346 || {
347 options.index.map_or_else(
348 || session.id().to_string(),
349 |index| format!("{}:{index}", session.id()),
350 )
351 },
352 ToString::to_string,
353 );
354 let mut command = Command::new("new-window")
355 .arg("-P")
356 .arg("-F")
357 .arg("#{window_id}")
358 .arg("-t")
359 .arg(target);
360 if options.detached {
361 command = command.arg("-d");
362 }
363 if options.kill_existing {
364 command = command.arg("-k");
365 }
366 if options.select_existing {
367 command = command.arg("-S");
368 }
369 if let Some(position) = options.position {
370 command = command.arg(match position {
371 WindowPosition::Before => "-b",
372 WindowPosition::After => "-a",
373 });
374 }
375 if let Some(name) = options.name {
376 command = command.arg("-n").arg(name);
377 }
378 if let Some(cwd) = options.cwd {
379 command = command.arg("-c").arg(cwd);
380 }
381 for (name, value) in options.environment {
382 command =
383 command
384 .arg("-e")
385 .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
386 }
387 if let Some(shell_command) = options.shell_command {
388 command = command.sensitive_arg(shell_command);
389 }
390 let result = session.server().checked("create window", command).await?;
391 let id: WindowId =
392 crate::server::single_line(result.stdout(), "new-window window ID")?.parse()?;
393 session.window(id).await
394 }
395
396 #[must_use]
398 pub const fn id(&self) -> WindowId {
399 self.id
400 }
401
402 #[must_use]
404 pub const fn link(&self) -> &WindowLink {
405 &self.link
406 }
407
408 #[must_use]
410 pub const fn session_id(&self) -> SessionId {
411 self.session_id
412 }
413
414 #[must_use]
416 pub const fn snapshot(&self) -> &WindowSnapshot {
417 &self.snapshot
418 }
419
420 #[must_use]
422 pub const fn server(&self) -> &Server {
423 &self.server
424 }
425
426 pub async fn refresh(&mut self) -> Result<()> {
428 let link = self.link.clone();
429 *self = self
430 .server
431 .windows()
432 .await?
433 .into_iter()
434 .find(|window| window.link == link)
435 .ok_or_else(|| Error::ObjectNotFound {
436 kind: ObjectKind::Window,
437 target: link.to_string(),
438 })?;
439 Ok(())
440 }
441
442 pub async fn session(&self) -> Result<Session> {
444 self.server.session(self.session_id()).await
445 }
446
447 pub async fn linked_sessions(&self) -> Result<Vec<Session>> {
449 let mut ids = self
450 .server
451 .windows()
452 .await?
453 .into_iter()
454 .filter(|window| window.id == self.id)
455 .map(|window| window.session_id)
456 .collect::<std::collections::BTreeSet<_>>();
457 let mut sessions = Vec::with_capacity(ids.len());
458 while let Some(id) = ids.pop_first() {
459 sessions.push(self.server.session(id).await?);
460 }
461 Ok(sessions)
462 }
463
464 pub async fn panes(&self) -> Result<Vec<Pane>> {
466 Ok(self
467 .server
468 .panes()
469 .await?
470 .into_iter()
471 .filter(|pane| pane.window_id() == self.id && pane.session_id() == self.session_id())
472 .collect())
473 }
474
475 pub async fn panes_or_empty(&self) -> Vec<Pane> {
477 self.panes().await.unwrap_or_default()
478 }
479
480 pub async fn active_pane(&self) -> Result<Pane> {
482 for pane in self.panes().await? {
483 if pane.snapshot().active()? == Some(true) {
484 return Ok(pane);
485 }
486 }
487 Err(Error::ObjectNotFound {
488 kind: ObjectKind::Pane,
489 target: format!("active pane in {}", self.link),
490 })
491 }
492
493 pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
495 self.server.cmd(command.target(&self.link)).await
496 }
497
498 pub async fn split(&self, options: SplitPane) -> Result<Pane> {
500 let pane = self.active_pane().await?;
501 pane.split(options).await
502 }
503
504 pub async fn new_pane(&self, options: NewPane) -> Result<Pane> {
506 self.active_pane().await?.new_pane(options).await
507 }
508
509 pub async fn new_window(&self, options: NewWindow, position: WindowPosition) -> Result<Window> {
511 self.session()
512 .await?
513 .new_window(options.relative_to(self.link.clone(), position))
514 .await
515 }
516
517 pub async fn select_pane(&self, pane: crate::PaneId) -> Result<Pane> {
519 self.server
520 .checked(
521 "select window pane",
522 Command::new("select-pane").target(pane),
523 )
524 .await?;
525 self.server.pane(pane).await
526 }
527
528 pub async fn last_pane(&self) -> Result<Pane> {
530 self.last_pane_with(None, false).await
531 }
532
533 pub async fn last_pane_with(
535 &self,
536 input_enabled: Option<bool>,
537 keep_zoom: bool,
538 ) -> Result<Pane> {
539 let mut command = Command::new("last-pane").target(&self.link);
540 if let Some(enabled) = input_enabled {
541 command = command.arg(if enabled { "-e" } else { "-d" });
542 }
543 if keep_zoom {
544 command = command.arg("-Z");
545 }
546 self.server.checked("last pane", command).await?;
547 self.active_pane().await
548 }
549
550 pub async fn with_pane<F, Fut, T>(&self, options: SplitPane, operation: F) -> Result<T>
552 where
553 F: FnOnce(Pane) -> Fut,
554 Fut: Future<Output = Result<T>>,
555 {
556 let pane = self.split(options).await?;
557 let cleanup = pane.clone();
558 let outcome = operation(pane).await;
559 let cleanup_result = cleanup.kill().await;
560 match (outcome, cleanup_result) {
561 (Ok(value), Ok(())) => Ok(value),
562 (Ok(_), Err(source)) => Err(Error::Cleanup {
563 operation: "with_pane",
564 source: Box::new(source),
565 }),
566 (Err(source), _) => Err(source),
567 }
568 }
569
570 pub async fn select(&self) -> Result<()> {
572 self.server
573 .checked(
574 "select window",
575 Command::new("select-window").target(&self.link),
576 )
577 .await
578 .map(|_| ())
579 }
580
581 pub async fn rename(&mut self, name: impl Into<OsString>) -> Result<()> {
583 self.server
584 .checked(
585 "rename window",
586 Command::new("rename-window").target(&self.link).arg(name),
587 )
588 .await?;
589 self.refresh().await
590 }
591
592 pub async fn select_layout(&mut self, layout: &Layout) -> Result<()> {
594 self.server
595 .checked(
596 "select layout",
597 Command::new("select-layout")
598 .target(&self.link)
599 .arg(layout.to_string()),
600 )
601 .await?;
602 self.refresh().await
603 }
604
605 pub async fn next_layout(&mut self) -> Result<()> {
607 self.server
608 .checked(
609 "next layout",
610 Command::new("next-layout").target(&self.link),
611 )
612 .await?;
613 self.refresh().await
614 }
615
616 pub async fn previous_layout(&mut self) -> Result<()> {
618 self.server
619 .checked(
620 "previous layout",
621 Command::new("previous-layout").target(&self.link),
622 )
623 .await?;
624 self.refresh().await
625 }
626
627 pub async fn spread_layout(&mut self) -> Result<()> {
629 self.server
630 .checked(
631 "spread layout",
632 Command::new("select-layout").arg("-E").target(&self.link),
633 )
634 .await?;
635 self.refresh().await
636 }
637
638 pub async fn resize(&mut self, width: Option<u32>, height: Option<u32>) -> Result<()> {
640 if width.is_none() && height.is_none() {
641 return Err(Error::InvalidArgument {
642 argument: "window size",
643 message: "width or height is required".to_owned(),
644 });
645 }
646 if width == Some(0) || height == Some(0) {
647 return Err(Error::InvalidArgument {
648 argument: "window size",
649 message: "dimensions must be non-zero".to_owned(),
650 });
651 }
652 let mut command = Command::new("resize-window").target(&self.link);
653 if let Some(width) = width {
654 command = command.arg("-x").arg(width.to_string());
655 }
656 if let Some(height) = height {
657 command = command.arg("-y").arg(height.to_string());
658 }
659 self.server.checked("resize window", command).await?;
660 self.refresh().await
661 }
662
663 pub async fn resize_with(&mut self, options: WindowResize) -> Result<()> {
665 let modes = usize::from(options.adjustment.is_some())
666 + usize::from(options.width.is_some() || options.height.is_some())
667 + usize::from(options.expand)
668 + usize::from(options.shrink);
669 if modes != 1 {
670 return Err(Error::InvalidArgument {
671 argument: "window resize mode",
672 message: "choose exactly one of adjustment, absolute size, expand, or shrink"
673 .to_owned(),
674 });
675 }
676 let mut command = Command::new("resize-window").target(&self.link);
677 if let Some((direction, cells)) = options.adjustment {
678 command = command.arg(direction.flag()).arg(cells.to_string());
679 }
680 if let Some(width) = options.width {
681 command = command.arg("-x").arg(width.to_string());
682 }
683 if let Some(height) = options.height {
684 command = command.arg("-y").arg(height.to_string());
685 }
686 if options.expand {
687 command = command.arg("-A");
688 }
689 if options.shrink {
690 command = command.arg("-a");
691 }
692 self.server.checked("resize window", command).await?;
693 self.refresh().await
694 }
695
696 pub async fn rotate(&self, direction: Rotation) -> Result<()> {
698 let mut command = Command::new("rotate-window");
699 if direction == Rotation::Down {
700 command = command.arg("-D");
701 }
702 self.server
703 .checked("rotate window", command.target(&self.link))
704 .await
705 .map(|_| ())
706 }
707
708 pub async fn rotate_keep_zoom(&self, direction: Rotation) -> Result<()> {
710 let direction = match direction {
711 Rotation::Up => "-U",
712 Rotation::Down => "-D",
713 };
714 self.server
715 .checked(
716 "rotate window",
717 Command::new("rotate-window")
718 .arg(direction)
719 .arg("-Z")
720 .target(&self.link),
721 )
722 .await
723 .map(|_| ())
724 }
725
726 pub async fn swap_with(
728 &self,
729 destination: impl Into<WindowTarget>,
730 detached: bool,
731 ) -> Result<()> {
732 let mut command = Command::new("swap-window")
733 .arg("-s")
734 .arg(self.link.to_string());
735 if detached {
736 command = command.arg("-d");
737 }
738 command = command.arg("-t").arg(destination.into().to_string());
739 self.server
740 .checked("swap window", command)
741 .await
742 .map(|_| ())
743 }
744
745 pub async fn link_to(
747 &self,
748 session: impl Into<SessionTarget>,
749 index: Option<u32>,
750 kill_existing: bool,
751 ) -> Result<Window> {
752 self.link_to_with(session, index, kill_existing, None, true)
753 .await
754 }
755
756 pub async fn link_to_with(
758 &self,
759 session: impl Into<SessionTarget>,
760 index: Option<u32>,
761 kill_existing: bool,
762 position: Option<WindowPosition>,
763 detached: bool,
764 ) -> Result<Window> {
765 let session = session.into();
766 let destination_session_id = match &session {
767 SessionTarget::Id(id) => *id,
768 SessionTarget::Name(name) => self.server.session_by_name(name).await?.id(),
769 };
770 let destination =
771 index.map_or_else(|| session.to_string(), |index| format!("{session}:{index}"));
772 let mut command = Command::new("link-window")
773 .arg("-s")
774 .arg(self.link.to_string())
775 .arg("-t")
776 .arg(&destination);
777 if kill_existing {
778 command = command.arg("-k");
779 }
780 if let Some(position) = position {
781 command = command.arg(match position {
782 WindowPosition::Before => "-b",
783 WindowPosition::After => "-a",
784 });
785 }
786 if detached {
787 command = command.arg("-d");
788 }
789 self.server.checked("link window", command).await?;
790 self.server
791 .windows()
792 .await?
793 .into_iter()
794 .find(|window| {
795 window.id == self.id
796 && window.session_id == destination_session_id
797 && index.is_none_or(|index| window.link.index() == index)
798 })
799 .ok_or(Error::ObjectNotFound {
800 kind: ObjectKind::Window,
801 target: destination,
802 })
803 }
804
805 pub async fn move_to(
807 &self,
808 session: impl Into<SessionTarget>,
809 index: Option<u32>,
810 kill_existing: bool,
811 ) -> Result<()> {
812 self.move_to_with(session, index, kill_existing, None, true)
813 .await
814 }
815
816 pub async fn move_to_with(
818 &self,
819 session: impl Into<SessionTarget>,
820 index: Option<u32>,
821 kill_existing: bool,
822 position: Option<WindowPosition>,
823 detached: bool,
824 ) -> Result<()> {
825 let session = session.into();
826 let destination =
827 index.map_or_else(|| session.to_string(), |index| format!("{session}:{index}"));
828 let mut command = Command::new("move-window")
829 .arg("-s")
830 .arg(self.link.to_string())
831 .arg("-t")
832 .arg(destination);
833 if kill_existing {
834 command = command.arg("-k");
835 }
836 if let Some(position) = position {
837 command = command.arg(match position {
838 WindowPosition::Before => "-b",
839 WindowPosition::After => "-a",
840 });
841 }
842 if detached {
843 command = command.arg("-d");
844 }
845 self.server
846 .checked("move window", command)
847 .await
848 .map(|_| ())
849 }
850
851 pub async fn unlink(&self, kill_if_last: bool) -> Result<()> {
853 let mut command = Command::new("unlink-window");
854 if kill_if_last {
855 command = command.arg("-k");
856 }
857 self.server
858 .checked("unlink window", command.target(&self.link))
859 .await
860 .map(|_| ())
861 }
862
863 pub async fn respawn(
865 &self,
866 command: Option<OsString>,
867 cwd: Option<PathBuf>,
868 kill: bool,
869 ) -> Result<()> {
870 let mut tmux = Command::new("respawn-window").target(&self.link);
871 if kill {
872 tmux = tmux.arg("-k");
873 }
874 if let Some(cwd) = cwd {
875 tmux = tmux.arg("-c").arg(cwd);
876 }
877 if let Some(command) = command {
878 tmux = tmux.sensitive_arg(command);
879 }
880 self.server
881 .checked("respawn window", tmux)
882 .await
883 .map(|_| ())
884 }
885
886 pub async fn respawn_with(&self, options: RespawnWindow) -> Result<()> {
888 let mut command = Command::new("respawn-window").target(&self.link);
889 if options.kill {
890 command = command.arg("-k");
891 }
892 if let Some(cwd) = options.cwd {
893 command = command.arg("-c").arg(cwd);
894 }
895 for (name, value) in options.environment {
896 command =
897 command
898 .arg("-e")
899 .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
900 }
901 if let Some(shell_command) = options.command {
902 command = command.sensitive_arg(shell_command);
903 }
904 self.server
905 .checked("respawn window", command)
906 .await
907 .map(|_| ())
908 }
909
910 pub async fn kill(&self) -> Result<()> {
912 self.server
913 .checked("kill window", Command::new("kill-window").target(self.id))
914 .await
915 .map(|_| ())
916 }
917
918 pub async fn kill_others(&self) -> Result<()> {
920 self.server
921 .checked(
922 "kill other windows",
923 Command::new("kill-window").arg("-a").target(&self.link),
924 )
925 .await
926 .map(|_| ())
927 }
928
929 pub async fn options(&self) -> Result<OptionMap> {
931 self.server
932 .show_options(OptionScope::Window, Some(&self.link.to_string()))
933 .await
934 }
935
936 pub async fn sparse_options(&self) -> Result<SparseOptionMap> {
938 self.server
939 .show_sparse_options(OptionScope::Window, Some(&self.link.to_string()))
940 .await
941 }
942
943 pub async fn set_option(&self, name: &str, value: &OptionValue, append: bool) -> Result<()> {
945 self.server
946 .set_option(
947 OptionScope::Window,
948 Some(&self.link.to_string()),
949 name,
950 value,
951 append,
952 )
953 .await
954 }
955
956 pub async fn unset_option(&self, name: &str) -> Result<()> {
958 self.server
959 .unset_option(OptionScope::Window, Some(&self.link.to_string()), name)
960 .await
961 }
962}
963
964impl PartialEq for Window {
965 fn eq(&self, other: &Self) -> bool {
966 self.id == other.id
967 && self.link == other.link
968 && self.server.config() == other.server.config()
969 }
970}
971
972impl Eq for Window {}