[go: up one dir, main page]

Struct Position

Source
pub struct Position {
    pub x: u16,
    pub y: u16,
}
Expand description

Position in the terminal

The position is relative to the top left corner of the terminal window, with the top left corner being (0, 0). The x axis is horizontal increasing to the right, and the y axis is vertical increasing downwards.

§Examples

use ratatui::layout::{Position, Rect};

// the following are all equivalent
let position = Position { x: 1, y: 2 };
let position = Position::new(1, 2);
let position = Position::from((1, 2));
let position = Position::from(Rect::new(1, 2, 3, 4));

// position can be converted back into the components when needed
let (x, y) = position.into();

Fields§

§x: u16

The x coordinate of the position

The x coordinate is relative to the left edge of the terminal window, with the left edge being 0.

§y: u16

The y coordinate of the position

The y coordinate is relative to the top edge of the terminal window, with the top edge being 0.

Implementations§

Source§

impl Position

Source

pub const ORIGIN: Self

Position at the origin, the top left edge at 0,0

Source

pub const fn new(x: u16, y: u16) -> Self

Create a new position

Examples found in repository?
examples/canvas.rs (line 126)
121    fn handle_mouse_event(&mut self, event: event::MouseEvent) {
122        match event.kind {
123            MouseEventKind::Down(_) => self.is_drawing = true,
124            MouseEventKind::Up(_) => self.is_drawing = false,
125            MouseEventKind::Drag(_) => {
126                self.points.push(Position::new(event.column, event.row));
127            }
128            _ => {}
129        }
130    }
More examples
Hide additional examples
examples/colors_rgb.rs (line 218)
206    fn render(self, area: Rect, buf: &mut Buffer) {
207        self.setup_colors(area);
208        let colors = &self.colors;
209        for (xi, x) in (area.left()..area.right()).enumerate() {
210            // animate the colors by shifting the x index by the frame number
211            let xi = (xi + self.frame_count) % (area.width as usize);
212            for (yi, y) in (area.top()..area.bottom()).enumerate() {
213                // render a half block character for each row of pixels with the foreground color
214                // set to the color of the pixel and the background color set to the color of the
215                // pixel below it
216                let fg = colors[yi * 2][xi];
217                let bg = colors[yi * 2 + 1][xi];
218                buf[Position::new(x, y)].set_char('▀').set_fg(fg).set_bg(bg);
219            }
220        }
221        self.frame_count += 1;
222    }
examples/user_input.rs (lines 217-223)
169    fn draw(&self, frame: &mut Frame) {
170        let vertical = Layout::vertical([
171            Constraint::Length(1),
172            Constraint::Length(3),
173            Constraint::Min(1),
174        ]);
175        let [help_area, input_area, messages_area] = vertical.areas(frame.area());
176
177        let (msg, style) = match self.input_mode {
178            InputMode::Normal => (
179                vec![
180                    "Press ".into(),
181                    "q".bold(),
182                    " to exit, ".into(),
183                    "e".bold(),
184                    " to start editing.".bold(),
185                ],
186                Style::default().add_modifier(Modifier::RAPID_BLINK),
187            ),
188            InputMode::Editing => (
189                vec![
190                    "Press ".into(),
191                    "Esc".bold(),
192                    " to stop editing, ".into(),
193                    "Enter".bold(),
194                    " to record the message".into(),
195                ],
196                Style::default(),
197            ),
198        };
199        let text = Text::from(Line::from(msg)).patch_style(style);
200        let help_message = Paragraph::new(text);
201        frame.render_widget(help_message, help_area);
202
203        let input = Paragraph::new(self.input.as_str())
204            .style(match self.input_mode {
205                InputMode::Normal => Style::default(),
206                InputMode::Editing => Style::default().fg(Color::Yellow),
207            })
208            .block(Block::bordered().title("Input"));
209        frame.render_widget(input, input_area);
210        match self.input_mode {
211            // Hide the cursor. `Frame` does this by default, so we don't need to do anything here
212            InputMode::Normal => {}
213
214            // Make the cursor visible and ask ratatui to put it at the specified coordinates after
215            // rendering
216            #[allow(clippy::cast_possible_truncation)]
217            InputMode::Editing => frame.set_cursor_position(Position::new(
218                // Draw the cursor at the current position in the input field.
219                // This position is can be controlled via the left and right arrow key
220                input_area.x + self.character_index as u16 + 1,
221                // Move one line down, from the border to the input line
222                input_area.y + 1,
223            )),
224        }
225
226        let messages: Vec<ListItem> = self
227            .messages
228            .iter()
229            .enumerate()
230            .map(|(i, m)| {
231                let content = Line::from(Span::raw(format!("{i}: {m}")));
232                ListItem::new(content)
233            })
234            .collect();
235        let messages = List::new(messages).block(Block::bordered().title("Messages"));
236        frame.render_widget(messages, messages_area);
237    }

Trait Implementations§

Source§

impl Clone for Position

Source§

fn clone(&self) -> Position

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Position

Source§

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

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

impl Default for Position

Source§

fn default() -> Position

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

impl<'de> Deserialize<'de> for Position

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Position

Source§

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

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

impl From<(u16, u16)> for Position

Source§

fn from((x, y): (u16, u16)) -> Self

Converts to this type from the input type.
Source§

impl From<Position> for (u16, u16)

Source§

fn from(position: Position) -> Self

Converts to this type from the input type.
Source§

impl From<Rect> for Position

Source§

fn from(rect: Rect) -> Self

Converts to this type from the input type.
Source§

impl Hash for Position

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Position

Source§

fn cmp(&self, other: &Position) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Position

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Position

Source§

fn partial_cmp(&self, other: &Position) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Position

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 Copy for Position

Source§

impl Eq for Position

Source§

impl StructuralPartialEq for Position

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
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, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
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<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
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<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
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, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToCompactString for T
where T: Display,

Source§

impl<T> ToLine for T
where T: Display,

Source§

fn to_line(&self) -> Line<'_>

Converts the value to a Line.
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> ToSpan for T
where T: Display,

Source§

fn to_span(&self) -> Span<'_>

Converts the value to a Span.
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> ToText for T
where T: Display,

Source§

fn to_text(&self) -> Text<'_>

Converts the value to a Text.
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> RuleType for T
where T: Copy + Debug + Eq + Hash + Ord,