Skip to content

Add support for saving and opening files #325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Aug 14, 2021
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions editor/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ pub const LINE_ROTATE_SNAP_ANGLE: f64 = 15.;

// SELECT TOOL
pub const SELECTION_TOLERANCE: f64 = 1.0;

pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
pub const FILE_SAVE_SUFFIX: &str = ".graphite";
pub const FILE_EXPORT_SUFFIX: &str = ".svg";
39 changes: 37 additions & 2 deletions editor/src/document/document_file.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
pub use super::layer_panel::*;
use crate::{frontend::layer_panel::*, EditorError};
use crate::{
consts::{FILE_EXPORT_SUFFIX, FILE_SAVE_SUFFIX},
frontend::layer_panel::*,
EditorError,
};
use glam::{DAffine2, DVec2};
use graphene::{document::Document as InternalDocument, LayerId};
use graphene::{document::Document as InternalDocument, DocumentError, LayerId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

Expand Down Expand Up @@ -81,6 +85,7 @@ pub enum DocumentMessage {
AbortTransaction,
CommitTransaction,
ExportDocument,
SaveDocument,
RenderDocument,
Undo,
NudgeSelectedLayers(f64, f64),
Expand Down Expand Up @@ -192,6 +197,18 @@ impl DocumentMessageHandler {
movement_handler: MovementMessageHandler::default(),
}
}
pub fn with_name_and_content(name: String, serialized_content: String) -> Result<Self, EditorError> {
let mut document = Self::with_name(name);
let internal_document = InternalDocument::with_content(&serialized_content);
match internal_document {
Ok(handle) => {
document.document = handle;
Ok(document)
}
Err(DocumentError::InvalidFile(msg)) => Err(EditorError::Document(msg)),
_ => Err(EditorError::Document(String::from("Failed to open file"))),
}
}

pub fn layer_data(&mut self, path: &[LayerId]) -> &mut LayerData {
layer_data(&mut self.layer_data, path)
Expand Down Expand Up @@ -269,6 +286,10 @@ impl MessageHandler<DocumentMessage, &InputPreprocessor> for DocumentMessageHand
ExportDocument => {
let bbox = self.document.visible_layers_bounding_box().unwrap_or([DVec2::ZERO, ipp.viewport_size.as_f64()]);
let size = bbox[1] - bbox[0];
let name = match self.name.ends_with(FILE_SAVE_SUFFIX) {
true => self.name.clone().replace(FILE_SAVE_SUFFIX, FILE_EXPORT_SUFFIX),
false => self.name.clone() + FILE_EXPORT_SUFFIX,
};
responses.push_back(
FrontendMessage::ExportDocument {
document: format!(
Expand All @@ -280,6 +301,20 @@ impl MessageHandler<DocumentMessage, &InputPreprocessor> for DocumentMessageHand
"\n",
self.document.render_root()
),
name,
}
.into(),
)
}
SaveDocument => {
let name = match self.name.ends_with(FILE_SAVE_SUFFIX) {
true => self.name.clone(),
false => self.name.clone() + FILE_SAVE_SUFFIX,
};
responses.push_back(
FrontendMessage::SaveDocument {
document: self.document.serialize_document(),
name,
}
.into(),
)
Expand Down
91 changes: 51 additions & 40 deletions editor/src/document/document_message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use log::warn;
use std::collections::VecDeque;

use super::DocumentMessageHandler;
use crate::consts::DEFAULT_DOCUMENT_NAME;

#[impl_message(Message, Documents)]
#[derive(PartialEq, Clone, Debug)]
Expand All @@ -24,6 +25,7 @@ pub enum DocumentsMessage {
CloseAllDocumentsWithConfirmation,
CloseAllDocuments,
NewDocument,
OpenDocument(String, String),
GetOpenDocumentsList,
NextDocument,
PrevDocument,
Expand All @@ -43,6 +45,45 @@ impl DocumentsMessageHandler {
pub fn active_document_mut(&mut self) -> &mut DocumentMessageHandler {
&mut self.documents[self.active_document_index]
}
fn generate_new_document_name(&self) -> String {
let mut doc_title_numbers = self
.documents
.iter()
.filter_map(|d| {
d.name
.rsplit_once(DEFAULT_DOCUMENT_NAME)
.map(|(prefix, number)| (prefix.is_empty()).then(|| number.trim().parse::<isize>().ok()).flatten().unwrap_or(1))
})
.collect::<Vec<isize>>();
doc_title_numbers.sort_unstable();
doc_title_numbers.iter_mut().enumerate().for_each(|(i, number)| *number = *number - i as isize - 2);
// Uses binary search to find the index of the element where number is bigger than i
let new_doc_title_num = doc_title_numbers.binary_search(&0).map_or_else(|e| e, |v| v) + 1;

let name = match new_doc_title_num {
1 => DEFAULT_DOCUMENT_NAME.to_string(),
_ => format!("{} {}", DEFAULT_DOCUMENT_NAME, new_doc_title_num),
};
name
}

fn load_document(&mut self, new_document: DocumentMessageHandler, responses: &mut VecDeque<Message>) {
self.active_document_index = self.documents.len();
self.documents.push(new_document);

// Send the new list of document tab names
let open_documents = self.documents.iter().map(|doc| doc.name.clone()).collect();
responses.push_back(FrontendMessage::UpdateOpenDocumentsList { open_documents }.into());

responses.push_back(
FrontendMessage::ExpandFolder {
path: Vec::new(),
children: Vec::new(),
}
.into(),
);
responses.push_back(DocumentsMessage::SelectDocument(self.active_document_index).into());
}
}

impl Default for DocumentsMessageHandler {
Expand Down Expand Up @@ -138,48 +179,18 @@ impl MessageHandler<DocumentsMessage, &InputPreprocessor> for DocumentsMessageHa
}
}
NewDocument => {
let digits = ('0'..='9').collect::<Vec<char>>();
let mut doc_title_numbers = self
.documents
.iter()
.map(|d| {
if d.name.ends_with(digits.as_slice()) {
let (_, number) = d.name.split_at(17);
number.trim().parse::<usize>().unwrap()
} else {
1
}
})
.collect::<Vec<usize>>();
doc_title_numbers.sort_unstable();
let mut new_doc_title_num = 1;
while new_doc_title_num <= self.documents.len() {
if new_doc_title_num != doc_title_numbers[new_doc_title_num - 1] {
break;
}
new_doc_title_num += 1;
}
let name = match new_doc_title_num {
1 => "Untitled Document".to_string(),
_ => format!("Untitled Document {}", new_doc_title_num),
};

self.active_document_index = self.documents.len();
let name = self.generate_new_document_name();
let new_document = DocumentMessageHandler::with_name(name);
self.documents.push(new_document);

// Send the new list of document tab names
let open_documents = self.documents.iter().map(|doc| doc.name.clone()).collect();
responses.push_back(FrontendMessage::UpdateOpenDocumentsList { open_documents }.into());

responses.push_back(
FrontendMessage::ExpandFolder {
path: Vec::new(),
children: Vec::new(),
self.load_document(new_document, responses);
}
OpenDocument(name, serialized_contents) => {
let document = DocumentMessageHandler::with_name_and_content(name, serialized_contents);
match document {
Ok(document) => {
self.load_document(document, responses);
}
.into(),
);
responses.push_back(SelectDocument(self.active_document_index).into());
Err(e) => responses.push_back(FrontendMessage::DisplayError { description: e.to_string() }.into()),
}
}
GetOpenDocumentsList => {
// Send the list of document tab names
Expand Down
3 changes: 2 additions & 1 deletion editor/src/frontend/frontend_message_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ pub enum FrontendMessage {
DisplayConfirmationToCloseAllDocuments,
UpdateCanvas { document: String },
UpdateLayer { path: Vec<LayerId>, data: LayerPanelEntry },
ExportDocument { document: String },
ExportDocument { document: String, name: String },
SaveDocument { document: String, name: String },
EnableTextInput,
DisableTextInput,
UpdateWorkingColors { primary: Color, secondary: Color },
Expand Down
20 changes: 15 additions & 5 deletions frontend/src/components/panels/Document.vue
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@
import { defineComponent } from "vue";

import { makeModifiersBitfield } from "@/utilities/input";
import { ResponseType, registerResponseHandler, Response, UpdateCanvas, SetActiveTool, ExportDocument, SetCanvasZoom, SetCanvasRotation } from "@/utilities/response-handler";
import { ResponseType, registerResponseHandler, Response, UpdateCanvas, SetActiveTool, ExportDocument, SetCanvasZoom, SetCanvasRotation, SaveDocument } from "@/utilities/response-handler";
import { SeparatorDirection, SeparatorType } from "@/components/widgets/widgets";
import { comingSoon } from "@/utilities/errors";

Expand Down Expand Up @@ -301,11 +301,15 @@ export default defineComponent({
(await wasm).reset_colors();
},
download(filename: string, fileData: string) {
const svgBlob = new Blob([fileData], { type: "image/svg+xml;charset=utf-8" });
const svgUrl = URL.createObjectURL(svgBlob);
let type = "text/plain;charset=utf-8";
if (filename.endsWith(".svg")) {
type = "image/svg+xml;charset=utf-8";
}
const blob = new Blob([fileData], { type });
const url = URL.createObjectURL(blob);
const element = document.createElement("a");

element.href = svgUrl;
element.href = url;
element.setAttribute("download", filename);
element.style.display = "none";

Expand All @@ -319,7 +323,13 @@ export default defineComponent({
});
registerResponseHandler(ResponseType.ExportDocument, (responseData: Response) => {
const updateData = responseData as ExportDocument;
if (updateData) this.download("canvas.svg", updateData.document);
if (!updateData) return;
this.download(updateData.name, updateData.document);
});
registerResponseHandler(ResponseType.SaveDocument, (responseData: Response) => {
const saveData = responseData as SaveDocument;
if (!saveData) return;
this.download(saveData.name, saveData.document);
});
registerResponseHandler(ResponseType.SetActiveTool, (responseData: Response) => {
const toolData = responseData as SetActiveTool;
Expand Down
24 changes: 22 additions & 2 deletions frontend/src/components/widgets/inputs/MenuBarInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const menuEntries: MenuListEntries = [
children: [
[
{ label: "New", icon: "File", shortcut: ["Ctrl", "N"], shortcutRequiresLock: true, action: async () => (await wasm).new_document() },
{ label: "Open…", shortcut: ["Ctrl", "O"] },
{ label: "Open…", shortcut: ["Ctrl", "O"], action: handleOpenClick },
{
label: "Open Recent",
shortcut: ["Ctrl", "⇧", "O"],
Expand All @@ -90,7 +90,7 @@ const menuEntries: MenuListEntries = [
{ label: "Close All", shortcut: ["Ctrl", "Alt", "W"], action: async () => (await wasm).close_all_documents_with_confirmation() },
],
[
{ label: "Save", shortcut: ["Ctrl", "S"] },
{ label: "Save", shortcut: ["Ctrl", "S"], action: async () => (await wasm).save_document() },
{ label: "Save As…", shortcut: ["Ctrl", "⇧", "S"] },
{ label: "Save All", shortcut: ["Ctrl", "Alt", "S"] },
{ label: "Auto-Save", checkbox: true, checked: true },
Expand Down Expand Up @@ -155,6 +155,26 @@ const menuEntries: MenuListEntries = [
},
];

async function handleOpenClick() {
const element = document.createElement("input");
element.type = "file";
element.style.display = "none";

element.addEventListener(
"change",
async () => {
if (!element.files || !element.files.length) return;
const file = element.files[0];
const filename = file.name;
const content = await file.text();
(await wasm).open_document(filename, content);
},
{ capture: false, once: true }
);

element.click();
}

export default defineComponent({
methods: {
setEntryRefs(menuEntry: MenuListEntry, ref: typeof MenuList) {
Expand Down
18 changes: 17 additions & 1 deletion frontend/src/utilities/response-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const state = reactive({
export enum ResponseType {
UpdateCanvas = "UpdateCanvas",
ExportDocument = "ExportDocument",
SaveDocument = "SaveDocument",
ExpandFolder = "ExpandFolder",
CollapseFolder = "CollapseFolder",
UpdateLayer = "UpdateLayer",
Expand Down Expand Up @@ -72,6 +73,8 @@ function parseResponse(responseType: string, data: any): Response {
return newSetCanvasRotation(data.SetCanvasRotation);
case "ExportDocument":
return newExportDocument(data.ExportDocument);
case "SaveDocument":
return newSaveDocument(data.SaveDocument);
case "UpdateWorkingColors":
return newUpdateWorkingColors(data.UpdateWorkingColors);
case "DisplayError":
Expand Down Expand Up @@ -167,10 +170,23 @@ function newUpdateCanvas(input: any): UpdateCanvas {

export interface ExportDocument {
document: string;
name: string;
}
function newExportDocument(input: any): UpdateCanvas {
function newExportDocument(input: any): ExportDocument {
return {
document: input.document,
name: input.name,
};
}

export interface SaveDocument {
document: string;
name: string;
}
function newSaveDocument(input: any): SaveDocument {
return {
document: input.document,
name: input.name,
};
}

Expand Down
10 changes: 10 additions & 0 deletions frontend/wasm/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ pub fn new_document() -> Result<(), JsValue> {
EDITOR_STATE.with(|editor| editor.borrow_mut().handle_message(DocumentsMessage::NewDocument).map_err(convert_error))
}

#[wasm_bindgen]
pub fn open_document(name: String, content: String) -> Result<(), JsValue> {
EDITOR_STATE.with(|editor| editor.borrow_mut().handle_message(DocumentsMessage::OpenDocument(name, content)).map_err(convert_error))
}

#[wasm_bindgen]
pub fn save_document() -> Result<(), JsValue> {
EDITOR_STATE.with(|editor| editor.borrow_mut().handle_message(DocumentMessage::SaveDocument)).map_err(convert_error)
}

#[wasm_bindgen]
pub fn close_document(document: usize) -> Result<(), JsValue> {
EDITOR_STATE.with(|editor| editor.borrow_mut().handle_message(DocumentsMessage::CloseDocument(document)).map_err(convert_error))
Expand Down
1 change: 1 addition & 0 deletions graphene/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ kurbo = { git = "https://github.com/GraphiteEditor/kurbo.git", features = [
"serde",
] }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
glam = { version = "0.17", features = ["serde"] }
Loading