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
//! # bwdraw
//!
//! `bwdraw` is a Rust library designed for simple black and white 2D drawing in the terminal. It uses half-filled characters as pixels, allowing for a square-shaped representation without stretching the y-axis. The library provides a convenient way to draw with half-filled ASCII characters by representing the canvas as a grid of booleans and converting them into characters accordingly.
//!
//! ## Pixel Representation
//!
//! The library uses the concept of `DuoPixel`, where each pixel has upper and lower states. These states are converted into character representations using the [`Into<char>`] trait. The available characters for representation are:
//! - `FULL_C`: Full-filled character ('█')
//! - `UPPER_C`: Upper half-filled character ('▀')
//! - `LOWER_C`: Lower half-filled character ('▄')
//! - `EMPTY_C`: Empty character (' ')
//!
//! ## Examples
//!
//! ```rust
//! use bwdraw::Canvas;
//!    // Draw a 10x10 square
//!    let height: usize = 10;
//!    let width: usize = 10;
//!
//!    let mut square = Canvas::new(width, height);
//!    for i in 0..height {
//!        for j in 0..width {
//!            if i == 0 || i == height - 1 || j == 0 || j == width - 1 {
//!                square.set(j, i, true);
//!            }
//!        }
//!    }
//!    println!("{}", square.to_string());
//! ```
//!
//! ## Drawing Functions
//!
//! The library also provides a `clear` function, which clears the console screen using ANSI escape codes.

use std::ops::Deref;

#[cfg(test)]
mod tests;

pub const FULL_C: char = '\u{2588}';
pub const LOWER_C: char = '\u{2584}';
pub const UPPER_C: char = '\u{2580}';
pub const EMPTY_C: char = ' ';

/// Represents a single pixel in the drawing canvas.
///
/// Each pixel can have an upper and lower state, to be converted into a character
/// representation based on its state using the [`Into<char>`] trait.
#[derive(Debug, Clone)]
pub struct DuoPixel {
    upper: bool,
    lower: bool,
}

impl From<(bool, bool)> for DuoPixel {
    fn from(value: (bool, bool)) -> Self {
        DuoPixel {
            upper: value.0,
            lower: value.1,
        }
    }
}

impl Into<(bool, bool)> for DuoPixel {
    fn into(self) -> (bool, bool) {
        (self.upper, self.lower)
    }
}

impl Into<char> for DuoPixel {
    fn into(self) -> char {
        match (self.lower, self.upper) {
            (true, true) => FULL_C,
            (false, true) => UPPER_C,
            (true, false) => LOWER_C,
            (false, false) => EMPTY_C,
        }
    }
}

impl PartialEq for DuoPixel {
    fn eq(&self, other: &Self) -> bool {
        self.upper == other.upper && self.lower == other.lower
    }
}

/// Represents a row of pixels in the drawing canvas.
///
/// Each row is composed of a vector of `Pixel` instances and
/// can be converted into a string using the `Into<String>` trait.
#[derive(Debug, Clone)]
pub struct Row(Vec<DuoPixel>);

impl Deref for Row {
    type Target = Vec<DuoPixel>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<(Vec<bool>, Vec<bool>)> for Row {
    fn from(value: (Vec<bool>, Vec<bool>)) -> Self {
        let pixels: Vec<DuoPixel> = value
            .0
            .iter()
            .zip(value.1.iter())
            .map(|(&u, &l)| DuoPixel { upper: u, lower: l })
            .collect();
        Row(pixels)
    }
}

impl Into<(Vec<bool>, Vec<bool>)> for Row {
    fn into(self) -> (Vec<bool>, Vec<bool>) {
        self.0
            .into_iter()
            .map(|pixel| (pixel.upper, pixel.lower))
            .unzip()
    }
}

impl Into<String> for Row {
    fn into(self) -> String {
        self.0
            .iter()
            .cloned()
            .map(|p| {
                let c: char = p.into();
                c
            })
            .collect()
    }
}

impl PartialEq for Row {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

/// Represents the drawing canvas, composed of rows of pixels.
///
/// The canvas can be initialized with a specified width and height, and it provides methods
/// for modifying and converting its content.
#[derive(Debug, Clone)]
pub struct Canvas(Vec<Row>);

impl Canvas {
    /// Creates new empty [`Canvas`] with set `width` and `height`
    pub fn new(width: usize, height: usize) -> Self {
        Canvas::from(vec![vec![false; width]; height])
    }

    /// Sets a [`DuoPixel`] on [`Canvas`] to specified one and return [`DuoPixel`] which was previously there.
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn mut_set_duopixel(&mut self, x: usize, y: usize, pixel: DuoPixel) -> Option<DuoPixel> {
        let original = self.0.get_mut(y)?.0.get_mut(x)?;
        let orig = original.clone();
        *original = pixel;
        Some(orig)
    }

    /// Get [`DuoPixel`] at `(x,y)`
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn get_duopixel(&self, x: usize, y: usize) -> Option<DuoPixel> {
        let pix = self.0.get(y)?.0.get(x)?;
        Some(pix.clone())
    }

    /// Inverts state of pixel at `(x,y)` on existing Canvas and returns resulting Canvas
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn mut_invert_pixel(&mut self, x: usize, y: usize) -> Option<Canvas> {
        let mut subpixeled: Vec<Vec<bool>> = self.clone().into();
        let orig = subpixeled.get_mut(y)?.get_mut(x)?;
        *orig = !orig.clone();

        let new_pic = Canvas::from(subpixeled);

        *self = new_pic.clone();
        Some(new_pic)
    }

    /// Returns new Canvas with inverted pixel at `(x,y)`
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn invert_pixel(&self, x: usize, y: usize) -> Option<Canvas> {
        let mut subpixeled: Vec<Vec<bool>> = self.clone().into();
        let orig = subpixeled.get_mut(y)?.get_mut(x)?;
        *orig = !orig.clone();

        let new_pic = Canvas::from(subpixeled);

        Some(new_pic)
    }

    /// Sets a state of square pixel on existing [`Canvas`] and returns the resulting [`Canvas`].
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn mut_set(&mut self, x: usize, y: usize, state: bool) -> Option<Self> {
        let mut subpixeled: Vec<Vec<bool>> = self.clone().into();
        *subpixeled.get_mut(y)?.get_mut(x)? = state;

        let new_pic = Canvas::from(subpixeled);

        *self = new_pic.clone();
        Some(new_pic)
    }

    /// Returns a new canvas with set state of square pixel at `(x,y)`
    /// Returns [`None`] if `(x,y)` is out of bounds
    pub fn set(&self, x: usize, y: usize, state: bool) -> Option<Self> {
        let mut subpixeled: Vec<Vec<bool>> = self.clone().into();
        *subpixeled.get_mut(y)?.get_mut(x)? = state;
        let new_pic = Canvas::from(subpixeled);
        Some(new_pic)
    }

    /// Gets state of square pixel at `(x,y)`.
    /// Returns [`None`] if `(x,y)` is out of bounds.
    pub fn get(&self, x: usize, y: usize) -> Option<bool> {
        let subpixeled: Vec<Vec<bool>> = self.clone().into();
        Some(subpixeled.get(y)?.get(x)?.clone())
    }

    /// Parse canvas from string specifying chars representing active and inactive pixels.
    /// Any unspecified chars will be interpreted as active
    pub fn parse(str_pic: &str, active: char, inactive: char) -> Self {
        str_pic
            .lines()
            .map(|l| {
                l.chars()
                    .map(|c| {
                        if c == active {
                            true
                        } else if c == inactive {
                            false
                        } else {
                            true
                        }
                    })
                    .collect::<Vec<bool>>()
            })
            .collect::<Vec<Vec<bool>>>()
            .into()
    }

    /// Inverts existing [`Canvas`]
    pub fn invert(&mut self) {
        let subpixeled: Vec<Vec<bool>> = self.clone().into();
        let inverted: Vec<Vec<bool>> = subpixeled
            .iter()
            .map(|r| r.iter().map(|p| !p).collect())
            .collect();
        *self = inverted.into();
    }

    /// Returns inverted [`Canvas`]
    pub fn inverted(&self) -> Self {
        let subpixeled: Vec<Vec<bool>> = self.clone().into();
        let inverted: Vec<Vec<bool>> = subpixeled
            .iter()
            .map(|r| r.iter().map(|p| !p).collect())
            .collect();
        inverted.into()
    }
}

impl Deref for Canvas {
    type Target = Vec<Row>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl ToString for Canvas {
    fn to_string(&self) -> String {
        let s: String = self.clone().into();
        s
    }
}

impl Into<Vec<Vec<bool>>> for Canvas {
    fn into(self) -> Vec<Vec<bool>> {
        self.0
            .into_iter()
            .flat_map(|row| {
                let t: (Vec<bool>, Vec<bool>) = row.into();
                vec![t.0, t.1]
            })
            .collect()
    }
}

impl From<Vec<Vec<bool>>> for Canvas {
    fn from(value: Vec<Vec<bool>>) -> Self {
        // add a vec of falses if number of subpixels is false
        let longed = if value.len() % 2 == 0 {
            value
        } else {
            let inner_len = if let Some(inner) = value.get(0) {
                inner.len()
            } else {
                0
            };
            let falses_vec: Vec<bool> = vec![false; inner_len];
            let mut new_value = value.clone();
            new_value.push(falses_vec);
            new_value
        };
        let paired: Vec<(Vec<bool>, Vec<bool>)> = longed
            .chunks(2)
            .map(|chunk| (chunk[0].clone(), chunk[1].clone()))
            .collect();
        let rows = paired.iter().map(|p| Row::from(p.clone())).collect();
        Canvas(rows)
    }
}

impl Into<Vec<Row>> for Canvas {
    fn into(self) -> Vec<Row> {
        self.0
    }
}

impl Into<String> for Canvas {
    fn into(self) -> String {
        self.0
            .iter()
            .cloned()
            .map(|r| {
                let s: String = r.into();
                s + "\n"
            })
            .collect()
    }
}

impl PartialEq for Canvas {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

/// Clears the console screen.
///
/// This function sends ANSI escape codes to clear the console screen.
pub fn clear() {
    print!("{}[2J", 27 as char);
    print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
}