Skip to main content

Key

Struct Key 

Source
pub struct Key {
    pub name: String,
    pub text: Option<String>,
    pub ctrl: bool,
    pub alt: bool,
    pub shift: bool,
    pub meta: bool,
}
Expand description

One key press, or a paste (name "paste" with its text).

Fields§

§name: String

The key: a lowercase character ("a", "é"), "space", a named key ("enter", "up", "f5", …) or "paste".

§text: Option<String>

What the key types, when it types something.

§ctrl: bool

Control held.

§alt: bool

Alt (Option) held.

§shift: bool

Shift held.

§meta: bool

Cmd on macOS, Super elsewhere.

Implementations§

Source§

impl Key

Source

pub fn named(name: impl Into<String>) -> Self

A key without modifiers or text.

Source

pub fn is(&self, chord: &str) -> bool

Whether this is the chord chord: modifiers and a name joined by + ("ctrl+c", "shift+tab", "escape", "ctrl++"), every modifier matching exactly.

§Example
use tern_sdk::keys::Key;

let key = Key { ctrl: true, ..Key::named("c") };
assert!(key.is("ctrl+c"));
assert!(!key.is("c"));
Examples found in repository?
examples/progress.rs (line 95)
89fn wait(session: &mut Session, time: Duration) -> Result<bool, tern_sdk::Error> {
90	let until = Instant::now() + time;
91	loop {
92		let left = until.saturating_duration_since(Instant::now());
93		match session.next(Some(left))? {
94			None => return Ok(false),
95			Some(Input::Key(key)) if key.is("ctrl+c") => return Ok(true),
96			Some(_) => {},
97		}
98	}
99}
More examples
Hide additional examples
examples/chat.rs (line 139)
127fn main() -> Result<(), tern_sdk::Error> {
128	let Some(mut session) = Session::connect(Options::new().feature(feature::SEND))? else {
129		println!("chat needs a terminal that speaks TSP (Tern).");
130		return Ok(());
131	};
132	let sf = session.open(SurfaceOptions::inline().title("chat"))?;
133	let mut chat = Chat::default();
134	session.render(sf, chat.view())?;
135	session.focus(sf, Some(EDITOR))?;
136	while let Some(input) = session.next(None)? {
137		match input {
138			Input::Key(key) => {
139				if key.is("escape") || key.is("ctrl+c") || key.is("ctrl+d") {
140					break;
141				}
142				match key.name.as_str() {
143					"enter" if !key.shift && !key.alt => {
144						let text = std::mem::take(&mut chat.draft);
145						chat.cursor = 0;
146						chat.send(text);
147					},
148					"enter" => chat.insert("\n"),
149					"backspace" if chat.cursor > 0 => {
150						let at = chat.byte(chat.cursor - 1);
151						chat.draft.remove(at);
152						chat.cursor -= 1;
153					},
154					"delete" if chat.cursor < chat.draft.chars().count() => {
155						let at = chat.byte(chat.cursor);
156						chat.draft.remove(at);
157					},
158					"left" => chat.cursor = chat.cursor.saturating_sub(1),
159					"right" => chat.cursor = (chat.cursor + 1).min(chat.draft.chars().count()),
160					"home" => chat.cursor = 0,
161					"end" => chat.cursor = chat.draft.chars().count(),
162					"paste" => chat.insert(key.text.as_deref().unwrap_or_default()),
163					_ => match key.typed() {
164						Some(text) => chat.insert(text),
165						None => continue,
166					},
167				}
168			},
169			Input::Msg(Msg::Send(text), _) => chat.send(text),
170			Input::Msg(Msg::Focus, _) => session.focus(sf, Some(EDITOR))?,
171			Input::Event(_) => continue,
172		}
173		session.render(sf, chat.view())?;
174	}
175	session.close()?;
176	println!("Chat closed after {} messages.", chat.transcript.len());
177	Ok(())
178}
Source

pub fn typed(&self) -> Option<&str>

Whether the key types text without Control, Alt or Meta held.

Examples found in repository?
examples/chat.rs (line 163)
127fn main() -> Result<(), tern_sdk::Error> {
128	let Some(mut session) = Session::connect(Options::new().feature(feature::SEND))? else {
129		println!("chat needs a terminal that speaks TSP (Tern).");
130		return Ok(());
131	};
132	let sf = session.open(SurfaceOptions::inline().title("chat"))?;
133	let mut chat = Chat::default();
134	session.render(sf, chat.view())?;
135	session.focus(sf, Some(EDITOR))?;
136	while let Some(input) = session.next(None)? {
137		match input {
138			Input::Key(key) => {
139				if key.is("escape") || key.is("ctrl+c") || key.is("ctrl+d") {
140					break;
141				}
142				match key.name.as_str() {
143					"enter" if !key.shift && !key.alt => {
144						let text = std::mem::take(&mut chat.draft);
145						chat.cursor = 0;
146						chat.send(text);
147					},
148					"enter" => chat.insert("\n"),
149					"backspace" if chat.cursor > 0 => {
150						let at = chat.byte(chat.cursor - 1);
151						chat.draft.remove(at);
152						chat.cursor -= 1;
153					},
154					"delete" if chat.cursor < chat.draft.chars().count() => {
155						let at = chat.byte(chat.cursor);
156						chat.draft.remove(at);
157					},
158					"left" => chat.cursor = chat.cursor.saturating_sub(1),
159					"right" => chat.cursor = (chat.cursor + 1).min(chat.draft.chars().count()),
160					"home" => chat.cursor = 0,
161					"end" => chat.cursor = chat.draft.chars().count(),
162					"paste" => chat.insert(key.text.as_deref().unwrap_or_default()),
163					_ => match key.typed() {
164						Some(text) => chat.insert(text),
165						None => continue,
166					},
167				}
168			},
169			Input::Msg(Msg::Send(text), _) => chat.send(text),
170			Input::Msg(Msg::Focus, _) => session.focus(sf, Some(EDITOR))?,
171			Input::Event(_) => continue,
172		}
173		session.render(sf, chat.view())?;
174	}
175	session.close()?;
176	println!("Chat closed after {} messages.", chat.transcript.len());
177	Ok(())
178}

Trait Implementations§

Source§

impl Clone for Key

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Key

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Key

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Key

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Key

Source§

impl PartialEq for Key

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Key

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Key

Auto Trait Implementations§

§

impl Freeze for Key

§

impl RefUnwindSafe for Key

§

impl Send for Key

§

impl Sync for Key

§

impl Unpin for Key

§

impl UnsafeUnpin for Key

§

impl UnwindSafe for Key

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more