libtmux 0.1.0-alpha.1

Async typed tmux client and object model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! Window handles and their snapshot getters.

use std::ffi::{OsStr, OsString};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use crate::formats::TmuxText;
use crate::internal::core::Core;
use crate::internal::listing::{self, Pushdown as _};
use crate::internal::options;
use crate::pane::Pane;
use crate::query::Filterable;
use crate::session::Session;
use crate::snapshot::{WindowFields, WindowInfo, WindowProjection};
use crate::target::{ServerIdentity, SessionId, WindowId};
use crate::{Command, Error, ObjectKind, OptionValue};

/// One tmux window, as reached through one session that links it.
///
/// A window is not owned by a single session. `link-window` makes the same
/// underlying window appear in several sessions at once, so discovery returns
/// one `Window` per link rather than per window. Two handles for the same
/// window reached through different sessions are **not** equal: they describe
/// different places in the hierarchy.
///
/// Getters that describe the window itself, such as [`Window::name`], read the
/// window. Getters that describe its place in a session, such as
/// [`Window::index`] and [`Window::is_active`], read the link.
#[derive(Clone)]
pub struct Window {
    core: Arc<Core>,
    projection: WindowProjection,
}

impl Window {
    /// Build a handle from a hydrated projection.
    pub(crate) const fn new(core: Arc<Core>, projection: WindowProjection) -> Self {
        Self { core, projection }
    }

    /// Find the window this process is running in.
    ///
    /// Resolved through the pane named by `TMUX_PANE`, which is the only
    /// value tmux gives a process that identifies exactly where it is.
    ///
    /// `Ok(None)` means tmux no longer has that pane.
    ///
    /// # Errors
    ///
    /// Returns an error when `TMUX_PANE` is absent or is not a pane ID, or
    /// when the listing fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::Window;
    ///
    /// let session = server.new_session("locating-window").await?;
    /// let pane = session.try_panes().await?.remove(0);
    ///
    /// // Standing in for the environment tmux gives a process it starts.
    /// let found = Window::from_env_value(server, Some(pane.id().as_ref())).await?;
    ///
    /// assert_eq!(found.expect("the window exists").id(), pane.window_id());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_env(server: &crate::Server) -> Result<Option<Self>, Error> {
        Self::from_env_value(server, std::env::var_os("TMUX_PANE")).await
    }

    /// Find a window from an explicit `TMUX_PANE` value.
    ///
    /// # Errors
    ///
    /// Returns an error when the value is absent or is not a pane ID, or when
    /// the listing fails.
    pub async fn from_env_value(
        server: &crate::Server,
        value: Option<impl AsRef<OsStr>>,
    ) -> Result<Option<Self>, Error> {
        let Some(pane) = Pane::from_env_value(server, value).await? else {
            return Ok(None);
        };

        server.window_by_id(pane.window_id()).await
    }

    /// Return the tmux window identity.
    ///
    /// This is the `@`-prefixed id, which is shared by every link to the same
    /// window.
    #[must_use]
    pub const fn id(&self) -> &WindowId {
        self.projection.window().window_id()
    }

    /// Return the session this handle reached the window through.
    #[must_use]
    pub const fn session_id(&self) -> &SessionId {
        self.projection.link().identity().session_id()
    }

    /// Return the window's index within [`Window::session_id`].
    ///
    /// A linked window can hold a different index in each session, so this is
    /// a property of the link rather than of the window.
    #[must_use]
    pub const fn index(&self) -> i32 {
        self.projection.link().identity().window_index()
    }

    /// Return the window name.
    #[must_use]
    pub fn name(&self) -> &TmuxText {
        self.projection.window().window_name()
    }

    /// Return how many panes the window contains.
    #[must_use]
    pub fn pane_count(&self) -> u32 {
        *self.projection.window().window_panes()
    }

    /// Return the window width in cells.
    #[must_use]
    pub fn width(&self) -> u32 {
        *self.projection.window().window_width()
    }

    /// Return the window height in cells.
    #[must_use]
    pub fn height(&self) -> u32 {
        *self.projection.window().window_height()
    }

    /// Return the window's pane layout string.
    #[must_use]
    pub fn layout(&self) -> &TmuxText {
        self.projection.window().window_layout()
    }

    /// Report whether this window is the active one in its session.
    #[must_use]
    pub const fn is_active(&self) -> bool {
        self.projection.link().is_active()
    }

    /// Report whether the window is linked into more than one session.
    #[must_use]
    pub const fn is_linked(&self) -> bool {
        self.projection.link().is_linked()
    }

    /// Report whether the window has unseen activity in this session.
    #[must_use]
    pub const fn has_activity(&self) -> bool {
        self.projection.link().has_activity()
    }

    /// Report whether the window rang a bell in this session.
    #[must_use]
    pub const fn has_bell(&self) -> bool {
        self.projection.link().has_bell()
    }

    /// Report whether one of the window's panes is zoomed to fill it.
    ///
    /// This is the window's own flag rather than the pane's, because tmux
    /// only reports `pane_zoomed_flag` from 3.7 onwards.
    #[must_use]
    pub fn is_zoomed(&self) -> bool {
        *self.projection.window().window_zoomed_flag()
    }

    /// Return the identity of the server this window belongs to.
    pub(crate) fn server_identity(&self) -> &ServerIdentity {
        self.core.configuration().identity()
    }

    /// List this window's panes, in tmux's own order.
    ///
    /// This is the lenient form; use [`Window::try_panes`] when the reason for
    /// an empty result matters.
    pub async fn panes(&self) -> Vec<Pane> {
        self.try_panes().await.unwrap_or_default()
    }

    /// List this window's panes, preserving any failure.
    ///
    /// Panes are addressed by window id rather than by session and index, so
    /// this returns the same panes through every link to the window.
    ///
    /// # Errors
    ///
    /// Returns an error when the list command cannot run, or when its output
    /// cannot be decoded into snapshots.
    pub async fn try_panes(&self) -> Result<Vec<Pane>, Error> {
        let target = self.id().to_string();
        let projections = listing::panes(&self.core, listing::Scope::Target(&target), None).await?;

        Ok(projections
            .into_iter()
            .map(|projection| Pane::new(Arc::clone(&self.core), projection))
            .collect())
    }

    /// Return the window's active pane.
    ///
    /// # Errors
    ///
    /// Returns an error when the pane listing fails. A window always has an
    /// active pane, so `Ok(None)` means the window disappeared between the
    /// snapshot and this call.
    pub async fn active_pane(&self) -> Result<Option<Pane>, Error> {
        Ok(self.try_panes().await?.into_iter().find(Pane::is_active))
    }

    /// Return the session this window was reached through.
    ///
    /// This re-reads tmux rather than the snapshot, so a session renamed or
    /// removed since discovery is reported as it is now. `Ok(None)` means the
    /// session no longer exists.
    ///
    /// # Errors
    ///
    /// Returns an error when the session listing fails.
    pub async fn session(&self) -> Result<Option<Session>, Error> {
        let infos = listing::sessions(&self.core, None).await?;

        Ok(infos
            .into_iter()
            .find(|info| info.session_id() == self.session_id())
            .map(|info| Session::new(Arc::clone(&self.core), info)))
    }

    /// Replace this handle's snapshot with the window's current state.
    ///
    /// The handle keeps following the same link, so a window that moved to a
    /// different index in the same session is found at its new index.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when this session no longer links the
    /// window, or a listing error when tmux could not be read.
    pub async fn refresh(&mut self) -> Result<&mut Self, Error> {
        let session = self.session_id().to_string();
        let projection = listing::windows(&self.core, listing::Scope::Target(&session), None)
            .await?
            .into_iter()
            .find(|projection| projection.window().window_id() == self.id())
            .ok_or_else(|| Error::ObjectGone {
                kind: ObjectKind::Window,
                id: self.id().to_string(),
            })?;

        self.projection = projection;
        Ok(self)
    }

    /// Return a new handle holding the window's current state.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when this session no longer links the
    /// window, or a listing error when tmux could not be read.
    pub async fn refreshed(&self) -> Result<Self, Error> {
        let mut refreshed = self.clone();
        refreshed.refresh().await?;
        Ok(refreshed)
    }

    /// Split this window and return the new pane.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the split, which includes a target
    /// pane that is too small to divide.
    pub async fn split(&self, options: impl Into<SplitOptions>) -> Result<Pane, Error> {
        let options = options.into();
        let window = self.id().to_string();
        let projection =
            listing::create_pane(&self.core, |format| options.into_command(&window, format))
                .await?;

        Ok(Pane::new(Arc::clone(&self.core), projection))
    }

    /// Rename the window and update this handle.
    ///
    /// The name belongs to the window, so every session linking it sees the
    /// change.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the name.
    pub async fn rename(&mut self, name: impl Into<OsString>) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "rename-window",
            Command::new("rename-window")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(name.into()),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Make this window active in the session it was reached through.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn select(&mut self) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "select-window",
            Command::new("select-window").arg("-t").arg(format!(
                "{}:{}",
                self.session_id(),
                self.index()
            )),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Set the window's pane layout.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the layout name or specification.
    pub async fn select_layout(&mut self, layout: impl Into<OsString>) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "select-layout",
            Command::new("select-layout")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(layout.into()),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Kill the window, closing it in every session that links it.
    ///
    /// This consumes the handle. Use [`Window::unlink`] to remove only this
    /// session's link while leaving the window alive elsewhere.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn kill(self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "kill-window",
            Command::new("kill-window")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Remove this session's link to the window, leaving other links intact.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command, which includes
    /// unlinking a window that only one session holds.
    pub async fn unlink(self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "unlink-window",
            Command::new("unlink-window").arg("-t").arg(format!(
                "{}:{}",
                self.session_id(),
                self.index()
            )),
        )
        .await
    }

    /// Read one option's exact stored value.
    ///
    /// A user option, whose name begins with `@`, exists only while it is
    /// set, so an unset one reports `None`. A built-in option always exists,
    /// so an unset one also reports `None`. An unrecognized built-in name is
    /// an error.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux does not recognize the option name.
    pub async fn get_option(&self, name: &str) -> Result<Option<TmuxText>, Error> {
        let target = self.id().to_string();
        options::get(&self.core, options::Scope::Window(&target), name).await
    }

    /// List the option names set at this window's scope.
    ///
    /// Values are not included: tmux renders them for display with three
    /// different quoting styles, so re-parsing them would be guesswork. Read
    /// each value with [`Self::get_option`], which returns exact bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the listing.
    pub async fn option_names(&self) -> Result<Vec<String>, Error> {
        let target = self.id().to_string();
        options::names(&self.core, options::Scope::Window(&target)).await
    }

    /// Set one option.
    ///
    /// The value is marked sensitive, so it never reaches `Debug`, an error,
    /// or a tracing span.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name or value.
    pub async fn set_option(&self, name: &str, value: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set(
            &self.core,
            options::Scope::Window(&target),
            name,
            value,
            false,
        )
        .await
    }

    /// Append to one option rather than replacing it.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name or value.
    pub async fn append_option(&self, name: &str, value: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set(
            &self.core,
            options::Scope::Window(&target),
            name,
            value,
            true,
        )
        .await
    }

    /// Remove one option, restoring whatever it inherits.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name.
    pub async fn unset_option(&self, name: &str) -> Result<(), Error> {
        let target = self.id().to_string();
        options::unset(&self.core, options::Scope::Window(&target), name).await
    }

    /// Set one hook to a tmux command.
    ///
    /// Hooks live in the same option tables, so a hook is an array option and
    /// [`Self::get_option`] reads it under an indexed name such as
    /// `after-new-window[0]`.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the hook name or command.
    pub async fn set_hook(&self, name: &str, command: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set_hook(&self.core, options::Scope::Window(&target), name, command).await
    }

    /// Remove one hook.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the hook name.
    pub async fn unset_hook(&self, name: &str) -> Result<(), Error> {
        let target = self.id().to_string();
        options::unset_hook(&self.core, options::Scope::Window(&target), name).await
    }

    /// Create a pane, run an operation with it, then kill it.
    ///
    /// The pane is killed whether the operation succeeded or failed, so a
    /// short-lived task does not leave one behind. A panic still skips
    /// cleanup: `Drop` on these handles is deliberately not destructive.
    ///
    /// Setup and teardown failures convert into the operation's own error
    /// type, so a caller writes one `?` rather than unwrapping twice. When
    /// both the operation and the cleanup fail, the operation's error is
    /// returned, because that is the work the caller was doing; the discarded
    /// cleanup failure is recorded through `tracing` when that feature is on.
    ///
    /// # Errors
    ///
    /// Returns the operation's error, or a converted [`Error`] when the
    /// pane could not be created, or could not be killed after the
    /// operation succeeded.
    pub async fn with_pane<T, E>(
        &self,
        options: impl Into<SplitOptions>,
        operation: impl AsyncFnOnce(&Pane) -> Result<T, E>,
    ) -> Result<T, E>
    where
        E: From<Error>,
    {
        let created = self.split(options).await?;
        let outcome = operation(&created).await;

        match (outcome, created.kill().await) {
            (outcome, Ok(())) => outcome,
            (Ok(_), Err(error)) => Err(error.into()),
            (Err(outcome), Err(cleanup)) => {
                listing::trace_discarded_cleanup(&cleanup);
                Err(outcome)
            }
        }
    }

    /// Swap this window's position with another.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the swap.
    pub async fn swap_with(&mut self, other: &Self) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "swap-window",
            Command::new("swap-window")
                .arg("-s")
                .arg(self.id().to_string())
                .arg("-t")
                .arg(format!("{}:{}", other.session_id(), other.index())),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Move this window to an index, possibly in another session.
    ///
    /// The destination is a session and an index rather than a target string,
    /// because those are the two things tmux needs and a string could express
    /// neither or both.
    ///
    /// # Errors
    ///
    /// Returns an error when the destination is occupied or does not exist.
    pub async fn move_to(&mut self, session: &Session, index: i32) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "move-window",
            Command::new("move-window")
                .arg("-s")
                .arg(self.id().to_string())
                .arg("-t")
                .arg(format!("{}:{index}", session.id())),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Resize the window to an exact size in cells.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the size.
    /// Move one edge of the window by a number of cells.
    ///
    /// This is the form a keybinding uses: "make it two columns wider" rather
    /// than a size computed from the current one.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the resize.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::ResizeDirection;
    ///
    /// let session = server.new_session("resized-window").await?;
    /// let mut window = session.try_windows().await?.remove(0);
    ///
    /// window.resize(80, 24).await?;
    /// window.resize_by(ResizeDirection::Down, 4).await?;
    /// assert_eq!(window.height(), 28);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resize_by(
        &mut self,
        direction: ResizeDirection,
        cells: u32,
    ) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "resize-window",
            Command::new("resize-window")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(direction.flag())
                .arg(cells.to_string()),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Link this window into another session, so both hold the same window.
    ///
    /// A linked window is one window with two winlinks, not a copy: renaming
    /// it or splitting it shows up in both sessions. [`Window::unlink`] takes
    /// one link away again.
    ///
    /// `index` places the link at a window index, or appends when `None`.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the link, which includes an index
    /// that is already taken.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// let source = server.new_session("linking-from").await?;
    /// let target = server.new_session("linking-to").await?;
    /// let window = source.try_windows().await?.remove(0);
    ///
    /// window.link_to(&target, None).await?;
    ///
    /// let linked = target.try_windows().await?;
    /// assert!(linked.iter().any(|other| other.id() == window.id()));
    /// # Ok(())
    /// # }
    /// ```
    pub async fn link_to(&self, session: &Session, index: Option<i32>) -> Result<(), Error> {
        let target = index.map_or_else(
            || session.id().to_string(),
            |index| format!("{}:{index}", session.id()),
        );

        listing::mutate(
            &self.core,
            "link-window",
            Command::new("link-window")
                .arg("-s")
                .arg(self.id().to_string())
                .arg("-t")
                .arg(target),
        )
        .await?;

        Ok(())
    }

    /// Resize the window to an exact size in cells.
    ///
    /// Use [`Window::resize_by`] to move one edge instead.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the size.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// let session = server.new_session("sized").await?;
    /// let mut window = session.try_windows().await?.remove(0);
    ///
    /// window.resize(100, 40).await?;
    /// assert_eq!((window.width(), window.height()), (100, 40));
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resize(&mut self, width: u32, height: u32) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "resize-window",
            Command::new("resize-window")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-x")
                .arg(width.to_string())
                .arg("-y")
                .arg(height.to_string()),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Read one option, decoded according to what tmux declares about it.
    ///
    /// A flag comes back as [`OptionValue::Flag`] and a number as
    /// [`OptionValue::Number`], so a caller does not decide for itself that
    /// `on` means one. Everything else, including user options, stays text.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux does not recognize the option name.
    pub async fn typed_option(&self, name: &str) -> Result<Option<OptionValue>, Error> {
        let target = self.id().to_string();
        Ok(
            options::get(&self.core, options::Scope::Window(&target), name)
                .await?
                .map(|value| OptionValue::decode(name, value)),
        )
    }

    /// Find this window's pane at the given index.
    ///
    /// # Errors
    ///
    /// Returns an error when the pane listing fails.
    pub async fn pane_at(&self, index: u32) -> Result<Option<Pane>, Error> {
        let target = self.id().to_string();
        let projections = listing::panes(
            &self.core,
            listing::Scope::Target(&target),
            Some(&index.predicate("pane_index")),
        )
        .await?;

        Ok(projections
            .into_iter()
            .next()
            .map(|projection| Pane::new(Arc::clone(&self.core), projection)))
    }
}

/// Windows compare by server endpoint, session, index, and window id.
///
/// Equality follows the link, not the window, because a linked window occupies
/// a genuinely different position in each session that holds it. Compare
/// [`Window::id`] directly to ask whether two handles name the same underlying
/// window.
impl PartialEq for Window {
    fn eq(&self, other: &Self) -> bool {
        self.server_identity() == other.server_identity()
            && self.projection.link().identity() == other.projection.link().identity()
    }
}

impl Eq for Window {}

impl Hash for Window {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.server_identity().hash(state);
        self.projection.link().identity().hash(state);
    }
}

/// Renders identity only, never snapshot text.
impl fmt::Debug for Window {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Window")
            .field("id", &self.id())
            .field("session_id", &self.session_id())
            .field("index", &self.index())
            .finish_non_exhaustive()
    }
}

/// Filtering a window uses the same handles as the snapshot beneath it.
///
/// Matching and validation delegate to that snapshot, so an expression can
/// only name fields the catalog knows. The companion is re-parameterized to
/// [`Window`] so the type a listing returns is the type an expression
/// filters.
impl Filterable for Window {
    type Fields = WindowFields<Self>;

    const FILTER_TARGET: &'static str = <WindowInfo as Filterable>::FILTER_TARGET;

    fn filter_fields() -> Self::Fields {
        Self::Fields::for_target(Self::FILTER_TARGET)
    }

    fn __filter_matches(&self, predicate: &crate::query::__private::Predicate) -> bool {
        self.projection.window().__filter_matches(predicate)
    }

    fn __filter_validate(
        predicate: &crate::query::__private::Predicate,
    ) -> Result<(), crate::query::FilterExpressionError> {
        <WindowInfo as Filterable>::__filter_validate(predicate)
    }
}

/// Where a split puts the new pane, relative to the one being divided.
///
/// tmux spells these `-v`, `-v -b`, `-h`, and `-h -b`, where "horizontal"
/// means side by side. Naming the resulting position instead removes a
/// question every tmux user has asked at least once.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SplitDirection {
    /// Above the pane being divided.
    Above,
    /// Below it, which is tmux's default.
    Below,
    /// To its left.
    Left,
    /// To its right.
    Right,
}

impl SplitDirection {
    /// Return the tmux flags that produce this position.
    const fn flags(self) -> (&'static str, bool) {
        match self {
            Self::Above => ("-v", true),
            Self::Below => ("-v", false),
            Self::Left => ("-h", true),
            Self::Right => ("-h", false),
        }
    }
}

/// How much space a new pane gets.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PaneSize {
    /// A number of rows or columns, depending on the split direction.
    Cells(u32),
    /// A share of the space being divided, as a percentage.
    Percent(u32),
}

impl fmt::Display for PaneSize {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cells(cells) => write!(formatter, "{cells}"),
            Self::Percent(percent) => write!(formatter, "{percent}%"),
        }
    }
}

/// Which edge a resize moves.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ResizeDirection {
    /// Move the top edge up, making it taller.
    Up,
    /// Move the bottom edge down.
    Down,
    /// Move the left edge left.
    Left,
    /// Move the right edge right.
    Right,
}

impl ResizeDirection {
    /// Return the tmux flag for this direction.
    pub(crate) const fn flag(self) -> &'static str {
        match self {
            Self::Up => "-U",
            Self::Down => "-D",
            Self::Left => "-L",
            Self::Right => "-R",
        }
    }
}

/// Options for splitting a window or pane into a new pane.
///
/// A bare [`SplitDirection`] is accepted wherever this is:
/// `window.split(SplitDirection::Below)`.
#[must_use = "options describe a split but do not perform one"]
#[derive(Clone, Debug)]
pub struct SplitOptions {
    direction: SplitDirection,
    start_directory: Option<std::path::PathBuf>,
    command: Option<OsString>,
    size: Option<PaneSize>,
    environment: Vec<(OsString, OsString)>,
    full: bool,
    zoom: bool,
    select: bool,
}

impl SplitOptions {
    /// Describe a split placing the new pane in one direction.
    pub const fn new(direction: SplitDirection) -> Self {
        Self {
            direction,
            start_directory: None,
            command: None,
            size: None,
            environment: Vec::new(),
            full: false,
            zoom: false,
            select: false,
        }
    }

    /// Set the new pane's working directory.
    pub fn start_directory(mut self, directory: impl Into<std::path::PathBuf>) -> Self {
        self.start_directory = Some(directory.into());
        self
    }

    /// Run a command instead of the default shell.
    pub fn command(mut self, command: impl Into<OsString>) -> Self {
        self.command = Some(command.into());
        self
    }

    /// Give the new pane a size, in cells or as a share of the space.
    pub const fn size(mut self, size: PaneSize) -> Self {
        self.size = Some(size);
        self
    }

    /// Set an environment variable for the process the new pane starts.
    ///
    /// Call this more than once for more than one variable. tmux applies
    /// these to the new process only, not to the session.
    pub fn environment(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
        self.environment.push((name.into(), value.into()));
        self
    }

    /// Span the full width or height of the window rather than of the pane.
    pub const fn full(mut self) -> Self {
        self.full = true;
        self
    }

    /// Zoom the new pane, filling the window until it is unzoomed.
    pub const fn zoom(mut self) -> Self {
        self.zoom = true;
        self
    }

    /// Make the new pane active.
    pub const fn select(mut self) -> Self {
        self.select = true;
        self
    }

    /// Lower these options into a `split-window` command for one target.
    ///
    /// `print_format` is placed with the other flags because tmux stops
    /// parsing flags at the first positional, and the shell command is one.
    pub(crate) fn into_command(self, target: &str, print_format: &str) -> Command {
        let (axis, before) = self.direction.flags();
        let mut command = Command::new("split-window")
            .arg("-P")
            .arg("-F")
            .arg(print_format)
            .arg("-t")
            .arg(target)
            .arg(axis);
        if before {
            command = command.arg("-b");
        }
        if !self.select {
            command = command.arg("-d");
        }
        if self.full {
            command = command.arg("-f");
        }
        if self.zoom {
            command = command.arg("-Z");
        }
        if let Some(size) = self.size {
            command = command.arg("-l").arg(size.to_string());
        }
        if let Some(directory) = self.start_directory {
            command = command.arg("-c").arg(directory.into_os_string());
        }
        for (name, value) in self.environment {
            command = command.arg("-e").arg(assignment(&name, &value));
        }
        if let Some(shell_command) = self.command {
            command = command.arg(shell_command);
        }
        command
    }
}

impl From<SplitDirection> for SplitOptions {
    fn from(direction: SplitDirection) -> Self {
        Self::new(direction)
    }
}

/// Render one `NAME=VALUE` pair for tmux's `-e` flag.
///
/// Built from bytes because tmux accepts environment values that are not
/// valid UTF-8, and rejecting them here would be stricter than tmux is.
pub(crate) fn assignment(name: &OsStr, value: &OsStr) -> OsString {
    use std::os::unix::ffi::{OsStrExt as _, OsStringExt as _};

    let mut bytes = name.as_bytes().to_vec();
    bytes.push(b'=');
    bytes.extend_from_slice(value.as_bytes());

    OsString::from_vec(bytes)
}

/// Renders `session:index`, the form tmux targets a window by.
///
/// The id alone would be ambiguous about which link is meant, and this is
/// the spelling that can be pasted into a tmux command.
impl fmt::Display for Window {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}", self.session_id(), self.index())
    }
}