bbe202b110848d15a4929ea112858bf8de3b5e33
[Mograsim.git] / net.mograsim.logic.model.editor / src / net / mograsim / logic / model / editor / SaveLoadManager.java
1 package net.mograsim.logic.model.editor;
2
3 import java.io.IOException;
4
5 import org.eclipse.swt.SWT;
6 import org.eclipse.swt.widgets.FileDialog;
7 import org.eclipse.swt.widgets.Shell;
8
9 import net.mograsim.logic.model.model.LogicModelModifiable;
10 import net.mograsim.logic.model.serializing.DeserializedSubmodelComponent;
11 import net.mograsim.logic.model.serializing.IndirectModelComponentCreator;
12 import net.mograsim.logic.model.serializing.SubmodelComponentSerializer;
13
14 public class SaveLoadManager
15 {
16         private String savePath = null;
17         private Editor editor;
18
19         public SaveLoadManager(Editor editor)
20         {
21                 this.editor = editor;
22         }
23
24         public void save()
25         {
26                 if (savePath == null)
27                         openSaveAsDialog();
28                 else
29                         innerSave();
30         }
31
32         public void openSaveAsDialog()
33         {
34                 Shell fdShell = new Shell();
35                 FileDialog fd = new FileDialog(fdShell, SWT.SAVE);
36                 fd.setText("Save as...");
37                 fd.setFilterExtensions(new String[] { "*.json" });
38                 String result = fd.open();
39                 fdShell.dispose();
40                 if (result != null)
41                 {
42                         savePath = result;
43                         innerSave();
44                 }
45         }
46
47         private void innerSave()
48         {
49                 try
50                 {
51                         SubmodelComponentSerializer.serialize(editor.toBeEdited, savePath);
52                 }
53                 catch (IOException e)
54                 {
55                         savePath = null;
56                         System.err.println("Failed to save component!");
57                         e.printStackTrace();
58                 }
59         }
60
61         public static void openLoadDialog() throws IOException
62         {
63                 Shell fdShell = new Shell();
64                 FileDialog fd = new FileDialog(fdShell, SWT.OPEN);
65                 fd.setText("Load component...");
66                 fd.setFilterExtensions(new String[] { "*.json" });
67                 String result = fd.open();
68                 fdShell.dispose();
69                 if (result != null)
70                 {
71                         new Editor((DeserializedSubmodelComponent) IndirectModelComponentCreator.createComponent(new LogicModelModifiable(),
72                                         "jsonfile:" + result));
73                 }
74         }
75 }