Files
Graphite/graphene/src/layers/mod.rs
Azeem Bande-Ali 91543d530d Add support for saving and opening files (#325)
* Add support for saving a document

This is similar to the "export" functionality, except that
we store all metadata needed to open the file again.

Currently we store the internal representation of the layer
which is probably pretty fragile.

Example document:

```json
{
    "nodes": {},
    "root": {
        "blend_mode": "Normal",
        "cache": "...",
        "cache_dirty": false,
        "data": {
            "Folder": {
                "layer_ids": [
                    3902938778642561358
                ],
                "layers": [
                    {
                        "blend_mode": "Normal",
                        "cache": "...",
                        "cache_dirty": false,
                        "data": {
                            "Shape": {
                                "path": [
                                    {
                                        "MoveTo": {
                                            "x": 0.0,
                                            "y": 0.0
                                        }
                                    },
                                    {
                                        "LineTo": {
                                            "x": 1.0,
                                            "y": 0.0
                                        }
                                    },
                                    {
                                        "LineTo": {
                                            "x": 1.0,
                                            "y": 1.0
                                        }
                                    },
                                    {
                                        "LineTo": {
                                            "x": 0.0,
                                            "y": 1.0
                                        }
                                    },
                                    "ClosePath"
                                ],
                                "render_index": 1,
                                "solid": true,
                                "style": {
                                    "fill": {
                                        "color": {
                                            "alpha": 1.0,
                                            "blue": 0.0,
                                            "green": 0.0,
                                            "red": 0.0
                                        }
                                    },
                                    "stroke": null
                                }
                            }
                        },
                        "name": null,
                        "opacity": 1.0,
                        "thumbnail_cache": "...",
                        "transform": {
                            "matrix2": [
                                223.0,
                                0.0,
                                -0.0,
                                348.0
                            ],
                            "translation": [
                                -188.0,
                                -334.0
                            ]
                        },
                        "visible": true
                    }
                ],
                "next_assignment_id": 3902938778642561359
            }
        },
        "name": null,
        "opacity": 1.0,
        "thumbnail_cache": "...",
        "transform": {
            "matrix2": [
                1.0,
                0.0,
                0.0,
                1.0
            ],
            "translation": [
                479.0,
                563.0
            ]
        },
        "visible": true
    },
    "version": 0
}
```

* Add support for opening a saved document

User can select a file using the browser's file input selector.
We parse it as JSON and load it into the internal representation.

Concerns:
- The file format is fragile
- Loading data directly into internal data structures usually creates
security vulnerabilities
- Error handling: The user is not informed of errors

* Serialize Document and skip "cache" fields in Layer

Instead of serializing the root layer, we serialize the
Document struct directly. Additionally, we mark the
"cache" fields in layer as "skip" fields so they
don't get serialized.

* Opened files use the filename as the tab title

* Split "new document" and "open document" handling

Open document needs name and content to be provided so having a
different interface is cleaner. Also did some refactoring to reuse code.

* Show error to user when a file fails to open

* Clean up code: better variable naming and structure

* Use document name for saved and exported files

We pass through the document name in the export and save
messages. Additionally, we check if the appropriate file
suffixes (.graphite and .svg) need to be added before
passing it to the frontend.

* Refactor document name generation

* Don't assign a default of 1 to Documents that start with something
  other than DEFAULT_DOCUMENT_NAME
* Improve runtime complexity by using binary instead of linear search

* Update Layer panel upon document selection

* Add File>Open/Ctrl+O; File>Save (As)/Ctrl+(Shift)+S; browse filters extension; split out download()/upload() into files.ts; change unsaved close dialog text

Co-authored-by: Dennis Kobert <dennis@kobert.dev>
Co-authored-by: Keavon Chambers <keavon@keavon.com>
2021-08-14 00:56:52 -07:00

172 lines
4.1 KiB
Rust

pub mod style;
use glam::DAffine2;
use glam::{DMat2, DVec2};
pub mod blend_mode;
pub use blend_mode::BlendMode;
pub mod simple_shape;
pub use simple_shape::Shape;
pub mod folder;
use crate::LayerId;
use crate::{DocumentError, Quad};
pub use folder::Folder;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
pub trait LayerData {
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>);
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>);
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]>;
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub enum LayerDataType {
Folder(Folder),
Shape(Shape),
}
impl LayerDataType {
pub fn inner(&self) -> &dyn LayerData {
match self {
LayerDataType::Shape(s) => s,
LayerDataType::Folder(f) => f,
}
}
pub fn inner_mut(&mut self) -> &mut dyn LayerData {
match self {
LayerDataType::Shape(s) => s,
LayerDataType::Folder(f) => f,
}
}
}
impl LayerData for LayerDataType {
fn render(&mut self, svg: &mut String, transforms: &mut Vec<glam::DAffine2>) {
self.inner_mut().render(svg, transforms)
}
fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
self.inner().intersects_quad(quad, path, intersections)
}
fn bounding_box(&self, transform: glam::DAffine2) -> Option<[DVec2; 2]> {
self.inner().bounding_box(transform)
}
}
#[derive(Serialize, Deserialize)]
#[serde(remote = "glam::DAffine2")]
struct DAffine2Ref {
pub matrix2: DMat2,
pub translation: DVec2,
}
fn return_true() -> bool {
true
}
#[derive(Debug, PartialEq, Deserialize, Serialize)]
pub struct Layer {
pub visible: bool,
pub name: Option<String>,
pub data: LayerDataType,
#[serde(with = "DAffine2Ref")]
pub transform: glam::DAffine2,
#[serde(skip)]
pub cache: String,
#[serde(skip)]
pub thumbnail_cache: String,
#[serde(skip, default = "return_true")]
pub cache_dirty: bool,
pub blend_mode: BlendMode,
pub opacity: f64,
}
impl Layer {
pub fn new(data: LayerDataType, transform: [f64; 6]) -> Self {
Self {
visible: true,
name: None,
data,
transform: glam::DAffine2::from_cols_array(&transform),
cache: String::new(),
thumbnail_cache: String::new(),
cache_dirty: true,
blend_mode: BlendMode::Normal,
opacity: 1.,
}
}
pub fn render(&mut self, transforms: &mut Vec<DAffine2>) -> &str {
if !self.visible {
return "";
}
if self.cache_dirty {
transforms.push(self.transform);
self.thumbnail_cache.clear();
self.data.render(&mut self.thumbnail_cache, transforms);
self.cache.clear();
let _ = writeln!(self.cache, r#"<g transform="matrix("#);
self.transform.to_cols_array().iter().enumerate().for_each(|(i, f)| {
let _ = self.cache.write_str(&(f.to_string() + if i != 5 { "," } else { "" }));
});
let _ = write!(
self.cache,
r#")" style="mix-blend-mode: {}; opacity: {}">{}</g>"#,
self.blend_mode.to_svg_style_name(),
self.opacity,
self.thumbnail_cache.as_str()
);
transforms.pop();
self.cache_dirty = false;
}
self.cache.as_str()
}
pub fn intersects_quad(&self, quad: Quad, path: &mut Vec<LayerId>, intersections: &mut Vec<Vec<LayerId>>) {
if !self.visible {
return;
}
let transformed_quad = self.transform.inverse() * quad;
self.data.intersects_quad(transformed_quad, path, intersections)
}
pub fn current_bounding_box(&self) -> Option<[DVec2; 2]> {
self.data.bounding_box(self.transform)
}
pub fn as_folder_mut(&mut self) -> Result<&mut Folder, DocumentError> {
match &mut self.data {
LayerDataType::Folder(f) => Ok(f),
_ => Err(DocumentError::NotAFolder),
}
}
pub fn as_folder(&self) -> Result<&Folder, DocumentError> {
match &self.data {
LayerDataType::Folder(f) => Ok(f),
_ => Err(DocumentError::NotAFolder),
}
}
}
impl Clone for Layer {
fn clone(&self) -> Self {
Self {
visible: self.visible,
name: self.name.clone(),
data: self.data.clone(),
transform: self.transform,
cache: String::new(),
thumbnail_cache: String::new(),
cache_dirty: true,
blend_mode: self.blend_mode,
opacity: self.opacity,
}
}
}