1 package org.simantics.browsing.ui.swt;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.util.Arrays;
7 import java.util.Collections;
10 import org.simantics.browsing.ui.ExplorerState;
11 import org.simantics.browsing.ui.NodeContext;
12 import org.simantics.browsing.ui.StatePersistor;
13 import org.simantics.databoard.util.StringUtil;
14 import org.simantics.db.common.utils.Logger;
17 * @author Tuukka Lehtonen
19 public class IdentifiedStatePersistor implements StatePersistor {
21 protected final String id;
23 public IdentifiedStatePersistor(String id) {
28 public ExplorerState deserialize(File stateLocation, NodeContext root) {
29 return stateLocation == null ? ExplorerState.EMPTY
30 : deserialize(getMementoPath(stateLocation, root));
34 public void serialize(File stateLocation, NodeContext root, ExplorerState state) {
35 if (stateLocation == null || root == null)
38 GraphExplorerStateBean bean = toStateBean(state, root);
39 Path memento = getMementoPath(stateLocation, root);
40 if (bean != null && memento != null)
41 Files.write(memento, bean.serialize());
42 } catch (Throwable t) {
43 Logger.defaultLogError(t);
47 protected ExplorerState deserialize(Path path) {
48 if (path == null || !Files.exists(path))
49 return ExplorerState.EMPTY;
51 GraphExplorerStateBean stateBean = new GraphExplorerStateBean();
52 stateBean.deserialize( Files.readAllBytes(path) );
53 return toState(stateBean);
54 } catch (Throwable t) {
55 Logger.defaultLogError(t);
56 return ExplorerState.EMPTY;
60 protected NodeContext[] toNodeContexts(GraphExplorerStateNodeBean[] beans) throws Exception {
61 return NodeContext.NONE;
64 protected List<NodeContext> toNodeContextList(GraphExplorerStateNodeBean[] beans) throws Exception {
65 return beans.length == 0 ? Collections.<NodeContext>emptyList()
66 : Arrays.asList(toNodeContexts(beans));
69 protected GraphExplorerStateNodeBean[] toNodeBeans(NodeContext[] contexts) {
70 return GraphExplorerStateNodeBean.NONE;
73 protected ExplorerState toState(GraphExplorerStateBean stateBean) throws Exception {
74 return new ExplorerState(
75 toNodeContexts(stateBean.topNodePath),
76 stateBean.topNodePathChildIndexes,
77 toNodeContextList(stateBean.expandedNodes),
78 stateBean.columnWidths);
83 * the {@link ExplorerState} to transform into a
84 * {@link GraphExplorerStateBean}
86 * the input root node context that was used to initialize the
90 protected GraphExplorerStateBean toStateBean(ExplorerState state, NodeContext root) {
91 GraphExplorerStateBean ib = new GraphExplorerStateBean();
92 ib.topNodePath = toNodeBeans(state.topNodePath);
93 ib.topNodePathChildIndexes = state.topNodePathChildIndex;
94 ib.expandedNodes = toNodeBeans(state.expandedNodes.toArray(NodeContext.NONE));
95 ib.columnWidths = state.columnWidths;
99 protected Path getMementoPath(File stateLocation, NodeContext root) {
100 return stateLocation.toPath().resolve(StringUtil.escapeToFileName(id) + ".ge");