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
//! GDL is a graphic design crate that allows developers to rapidly design and create 2D graphics natively and for the web.
//! 
//! This crate contains built-in templates for rapid graphic creation, resizing for social media, and utils for design, but also 
//! provides more low-level access to developers who wish to work with the elements directly, and create their
//! own designs from the elements available.
//! 
//! To view a full demo of templates available, visit the [official website](https://silvia-odwyer.github.io/gdl).
//! 

extern crate image;
use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, ImageData, HtmlCanvasElement};
use wasm_bindgen::Clamped;
use image::{GenericImageView, GenericImage, ImageBuffer, DynamicImage, RgbaImage, Rgba};
use palette::{Lch, Srgb, Srgba, Hue, Gradient};
use palette::rgb::LinSrgba;
use palette::encoding::pixel::Pixel;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

/// Provides the image's height, width, and contains the image's raw pixels.
/// For use when communicating between JS and WASM, and also natively. 
#[wasm_bindgen]
#[derive(Debug)]
pub struct PhotonImage {
    raw_pixels: Vec<u8>,
    width: u32, 
    height: u32,
}

#[wasm_bindgen]
impl PhotonImage {
    pub fn height(self) -> u32 {
        self.height
    }

    pub fn width(self) -> u32 {
        self.width
    }
    
    pub fn new_from_rawpixels(raw_pixels: Vec<u8>, width: u32, height: u32) -> PhotonImage {
        return PhotonImage {raw_pixels: raw_pixels, width: width, height: height}
    }
    
    pub fn new_from_imgdata(&mut self, img_data: ImageData, width: u32, height: u32) -> PhotonImage {
        let _raw_pixels = to_raw_pixels(img_data);
        let new_vec = Vec::new();
        return PhotonImage {raw_pixels: new_vec, width: width, height: height}
    }

    pub fn new_with_background(width: u32, height: u32, background_color: &Rgb) -> PhotonImage {
        // create a pixel 
        let pixel =  image::Rgba([background_color.r, background_color.g, background_color.b, 255]);
        let image_buffer = ImageBuffer::from_pixel(width, height, pixel);
        let rgba_img = image::ImageRgba8(image_buffer);

        let raw_pixels = rgba_img.raw_pixels();
        return PhotonImage { raw_pixels: raw_pixels, width: width, height: height};
    }

    // pub fn new_with_pattern(width: u32, height: u32, background_color: Rgb) {
    //     // create a pixel 
    //     // let pixel =  image::Rgba([background_color.r, background_color.g, background_color.b, 255]);
    //     // let image_buffer = ImageBuffer::from_pixel(width, height, pixel);
    //     // let rgba_img = image::ImageRgba8(image_buffer);


    //     // let raw_pixels = rgba_img.raw_pixels();
    //     // return PhotonImage { raw_pixels: raw_pixels, width: width, height: height};
    // }

    pub fn new_with_gradient(width: u32, height: u32) -> PhotonImage {
        // create a pixel 
        let mut image = RgbaImage::new(width, height);
        let grad1 = Gradient::new(vec![
            LinSrgba::new(1.0, 0.1, 0.1, 1.0),
            LinSrgba::new(0.1, 0.1, 1.0, 1.0),
            LinSrgba::new(0.1, 1.0, 0.1, 1.0),
        ]);

        //The same colors and offsets as in grad1, but in a color space where the hue
        // is a component
        let _grad3 = Gradient::new(vec![
            Lch::from(LinSrgba::new(1.0, 0.1, 0.1, 1.0)),
            Lch::from(LinSrgba::new(0.1, 0.1, 1.0, 1.0)),
            Lch::from(LinSrgba::new(0.1, 1.0, 0.1, 1.0)),
        ]);


        for (i, c1) in grad1
        .take(width as usize)
        .enumerate()
    {
        let c1 = Srgba::from_linear(c1).into_format().into_raw();
        {
            let mut sub_image = image.sub_image(i as u32, 0, 1, height);
            let (width, height) = sub_image.dimensions();
            for x in 0..width {
                for y in 0..height {
                    sub_image.put_pixel(x, y, image::Rgba {
                        data: c1
                    });
                }
            }
        }
    }
        let rgba_img = image::ImageRgba8(image);
        let raw_pixels = rgba_img.raw_pixels();
        return PhotonImage { raw_pixels: raw_pixels, width: width, height: height};
    }
    
    /// Create a new social media graphic. 
    /// Available types include: linkedin_banner, pinterest, fb_ad, fb_post, instagram_post, 
    /// twitter_header, twitter_post.
    pub fn new_socialmedia_graphic(name: &str) -> PhotonImage {
        let (width, height) = match name {
            "linkedin_banner" => (1400, 425),
            "pinterest" => (735, 1102),
            "fb_ad" => (1200, 628), 
            "fb_post" => (940, 788),
            "instagram_post" => (1080, 1080),
            "twitter_post" => (1024, 512),
            "twitter_header" => (1500, 500),
            _ => (192, 120)
        };
        let new_vec = Vec::new();
        return PhotonImage {raw_pixels: new_vec, width: width, height: height}
    }

    pub fn raw_pix(self) -> Vec<u8> {
        self.raw_pixels
    } 
}


/// Generate color schemes from a single input color. 
#[wasm_bindgen]
#[derive(Debug)]
pub struct ColorScheme {
    main_color: Rgb,
    analogous_swatch: Vec<Lch>,
}

#[wasm_bindgen]
impl ColorScheme {
    pub fn new(main_color: Rgb) -> ColorScheme {
        let distance = 120.0;

        let primary: Lch = Srgb::new(main_color.r, main_color.g, main_color.b)
        .into_format::<f32>()
        .into_linear()
        .into();

        let an_shift = 180.0 - (distance / 2.0);

        let analogous_swatch = vec![
            primary.shift_hue(an_shift), 
            primary.shift_hue(-an_shift)
        ];

        // gen secondary swatch

        
        // gen rectangular swatch
        return ColorScheme {main_color: main_color, analogous_swatch: analogous_swatch}
    }

    /// Create a swatch image in PNG format of the colour swatches generated
    /// from the main colour.
    pub fn create_swatch_image() {

    }
}


/// Provides the image's height, width, and contains the image's raw pixels.
/// For use when communicating between JS and WASM, and also natively. 
#[wasm_bindgen]
#[derive(Debug)]
pub struct Font {
    name: String,
    size: u8,
    color: Rgb
}

#[wasm_bindgen]
impl Font {
    pub fn new(name: &str, size: u8, color: Rgb) -> Font {
        return Font {name: name.to_string(), size: size, color: color};
    }
}

/// Rgb color type.
#[wasm_bindgen]
#[derive(Debug)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8
}

#[wasm_bindgen]
impl Rgb {
    /// Create a new Rgb color.
    pub fn new(&mut self, r: u8, g: u8, b: u8) -> Rgb {
        return Rgb {r: r, g: g, b: b}
    }
}

#[wasm_bindgen]
pub fn draw_rect_web(ctx: CanvasRenderingContext2d) {
    ctx.rect(10.0, 20.0, 50.0, 50.0);
    ctx.stroke();
}

// Called by the JS entry point to ensure that everything is working as expected
#[wasm_bindgen]
pub fn run() -> Result<(), JsValue> {
    set_panic_hook();

    let window = web_sys::window().expect("No Window found, should have a Window");
    let document = window.document().expect("No Document found, should have a Document");

    let p: web_sys::Node = document.create_element("p")?.into();
    p.set_text_content(Some("You're successfully running WASM!"));

    let body = document.body().expect("ERR: No body found, should have a body");
    let body: &web_sys::Node = body.as_ref();
    body.append_child(&p)?;
    Ok(())
}

/// Place the ImageData onto the 2D context.
#[wasm_bindgen]
pub fn put_image_data(canvas: HtmlCanvasElement, ctx: CanvasRenderingContext2d, mut new_image: PhotonImage) {
    // Convert the raw pixels back to an ImageData object.
    let new_imgdata = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&mut new_image.raw_pixels), canvas.width(), canvas.height());

    // Place the new imagedata onto the canvas
    ctx.put_image_data(&new_imgdata.unwrap(), 0.0, 0.0);
}

pub fn new_with_background(width: u32, height: u32, background_color: &Rgb) -> DynamicImage {
    let pixel =  image::Rgba([background_color.r, background_color.g, background_color.b, 255]);
    let image_buffer = ImageBuffer::from_pixel(width, height, pixel);
    let rgba_img = image::ImageRgba8(image_buffer);
    return rgba_img;
}

/// Convert the ImageData found in the canvas context to a PhotonImage,
/// which can be used to filter or apply effects to the image
#[wasm_bindgen]
#[no_mangle]
pub fn open_image(canvas: HtmlCanvasElement, ctx: CanvasRenderingContext2d) -> PhotonImage {
    let imgdata = get_image_data(&canvas, &ctx);
    let raw_pixels = to_raw_pixels(imgdata);
    return PhotonImage {raw_pixels: raw_pixels, width: canvas.width(), height: canvas.height() }
}

/// Create a new RGB colour. TODO Will be using struct impl soon. 
#[wasm_bindgen]
pub fn new_rgb(r:u8, g:u8, b:u8) -> Rgb {
    let rgb = Rgb{r, g, b};
    return rgb;
}

/// Convert ImageData to raw pixels.
#[wasm_bindgen]
pub fn to_raw_pixels(imgdata: ImageData) -> Vec<u8> {
    let img_vec = imgdata.data().to_vec();
    return img_vec;
}

/// Convert a PhotonImage to JS-compatible ImageData
#[wasm_bindgen]
pub fn to_image_data(photon_image: PhotonImage) -> ImageData {
    let mut raw_pixels = photon_image.raw_pixels;
    let width = photon_image.width;
    let height = photon_image.height;
    let new_imgdata = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&mut raw_pixels), width, height).unwrap();

    return new_imgdata;
}

/// Get the ImageData from a 2D canvas context
#[wasm_bindgen]
pub fn get_image_data(canvas: &HtmlCanvasElement, ctx: &CanvasRenderingContext2d) -> ImageData {
    let width = canvas.width();
    let height = canvas.height();

    let data = ctx.get_image_data(0.0, 0.0, width as f64, height as f64).unwrap();
    return data;
}

fn set_panic_hook() {
    // When the `console_error_panic_hook` feature is enabled, we can call the
    // `set_panic_hook` function to get better error messages if we ever panic.
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();
}

pub mod text;
pub mod background;
pub mod diagrams;
pub mod collage;
pub mod helpers;
pub mod graphics;
pub mod elements;
pub mod presets;
pub mod resize;