cursive_image/
image_view.rs1use super::{image::*, sizing::*, state::*, vec2f::*};
2
3use {
4 crossterm::terminal::*,
5 cursive::{align::*, *},
6 std::{cell::*, sync::*},
7};
8
9pub struct ImageView {
21 pub(crate) image: Option<Image>,
22 pub(crate) sizing: Sizing,
23 pub(crate) align: Align,
24
25 pub(crate) size: Option<Vec2>,
26 pub(crate) content_offset: Mutex<RefCell<Option<Vec2>>>,
27 pub(crate) state: Mutex<RefCell<State>>,
28
29 pub(crate) cell_size: XY<f64>,
30 pub(crate) cell_aspect_ratio: f64,
31}
32
33impl ImageView {
34 pub fn image(&self) -> Option<&Image> {
36 self.image.as_ref()
37 }
38
39 pub fn set_image(&mut self, image: Image) {
41 self.image = Some(image);
43 self.reset_layout();
44 }
45
46 pub fn with_image(self, image: Image) -> Self {
50 self.with(|self_| self_.set_image(image))
51 }
52
53 pub fn sizing(&self) -> Sizing {
55 self.sizing
56 }
57
58 pub fn set_sizing(&mut self, sizing: Sizing) {
60 if self.sizing != sizing {
61 self.sizing = sizing;
62 self.reset_layout();
63 }
64 }
65
66 pub fn with_sizing(self, sizing: Sizing) -> Self {
70 self.with(|self_| self_.set_sizing(sizing))
71 }
72
73 pub fn align(&self) -> Align {
75 self.align
76 }
77
78 pub fn set_align(&mut self, align: Align) {
80 if self.align != align {
81 self.align = align;
82 self.reset_layout();
83 }
84 }
85
86 pub fn with_align(self, align: Align) -> Self {
90 self.with(|self_| self_.set_align(align))
91 }
92
93 fn reset_layout(&mut self) {
95 self.size = None;
96 self.set_content_offset(None);
97 }
98
99 pub(crate) fn get_state(&self) -> State {
100 *self.state.lock().unwrap().borrow()
101 }
102
103 pub(crate) fn set_state(&self, state: State) {
104 *self.state.lock().unwrap().borrow_mut() = state;
105 }
106
107 pub(crate) fn get_content_offset(&self) -> Option<Vec2> {
108 *self.content_offset.lock().unwrap().borrow()
109 }
110
111 pub(crate) fn set_content_offset(&self, content_offset: Option<Vec2>) {
112 *self.content_offset.lock().unwrap().borrow_mut() = content_offset;
113 }
114}
115
116impl Default for ImageView {
117 fn default() -> Self {
118 let cell_size = cell_size();
119 Self {
120 image: None,
121 sizing: Default::default(),
122 align: Align::center(),
123 size: None,
124 content_offset: Default::default(),
125 state: Default::default(),
126 cell_size,
127 cell_aspect_ratio: cell_size.aspect_ratio(),
128 }
129 }
130}
131
132fn cell_size() -> Vec2f {
136 match window_size() {
137 Ok(size) if size.width != 0 && size.height != 0 && size.columns != 0 && size.rows != 0 => {
138 (size.width as f64 / size.columns as f64, size.height as f64 / size.rows as f64)
139 }
140
141 _ => (8., 8.),
142 }
143 .into()
144}