]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.browsing.ui.graph.impl/src/org/simantics/browsing/ui/graph/impl/GraphStringIndexModifier.java
Use Consumer interface instead of deprecated Callback interface
[simantics/platform.git] / bundles / org.simantics.browsing.ui.graph.impl / src / org / simantics / browsing / ui / graph / impl / GraphStringIndexModifier.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.browsing.ui.graph.impl;
13
14 import java.util.concurrent.Semaphore;
15
16 import org.simantics.browsing.ui.BuiltinKeys;
17 import org.simantics.browsing.ui.NodeContext;
18 import org.simantics.browsing.ui.content.Labeler.Modifier;
19 import org.simantics.db.ReadGraph;
20 import org.simantics.db.Resource;
21 import org.simantics.db.Session;
22 import org.simantics.db.WriteGraph;
23 import org.simantics.db.common.request.ReadRequest;
24 import org.simantics.db.common.request.WriteRequest;
25 import org.simantics.db.exception.DatabaseException;
26 import org.simantics.db.layer0.adapter.StringIndexModifier;
27 import org.simantics.db.layer0.adapter.StringModifier;
28 import org.simantics.db.layer0.adapter.TObjectIntPair;
29 import org.simantics.layer0.utils.representation.StringRepresentation2;
30 import org.simantics.utils.ui.ErrorLogger;
31
32 /**
33  * Please implement:
34  * <ul>
35  * <li>{@link #createModifierInput(String)} - constructs an input for
36  * {@link org.simantics.db.layer0.adapter.Modifier#modify(WriteGraph, Object)}
37  * from the specified label given by the user.
38  * <li>{@link #doModify(WriteGraph, String)} - perform the requested modification
39  * into the graph.</li>
40  * </ul>
41  * 
42  * <p>
43  * Other points of customization:
44  * </p>
45  * <ul>
46  * <li>{@link #getInitialValue(ReadGraph)} - returns the value that should be shown
47  * initially when editing. The default implementation just adapts the input to
48  * its String representation, but you may want to customize this.</li>
49  * <li>{@link #initializeGraphModifier(ReadGraph)} - allows you to perform custom
50  * initialization of the modifier which uses the graph</li>
51  * <li>{@link #getResourceToModify()} - allows you to customize the way in which
52  * the input INodeContext is resolved into a Resource. The default
53  * implementation uses the IAdaptable interface of INodeContext to get the
54  * Resource.</li>
55  * <li>{@link #verifyModification(String)} - allows for last chance denial of
56  * the modification after the user has signalled approval of the modification.</li>
57  * </ul>
58  * 
59  * @author Tuukka Lehtonen
60  * 
61  * @param <T> the input class of the used
62  *        {@link org.simantics.db.layer0.adapter.Modifier}
63  */
64 public abstract class GraphStringIndexModifier implements Modifier {
65
66     protected NodeContext        context;
67
68     protected Session             session;
69
70     protected int                 index;
71
72     protected String              initialValue;
73
74     protected StringIndexModifier modifier;
75
76     /**
77      * Used to synchronize {@link #isValid(String)} and {@link #modify(String)}
78      * with the asynchronous modifier fetch.
79      */
80     protected Semaphore           modifierReady = new Semaphore(0);
81
82     /**
83      * If <code>non-null</code>, the modifier could not be fetched, e.g. adapted
84      * from the specified INodeContext.
85      */
86     protected Throwable           modifierFailed;
87
88
89     /**
90      * @param context
91      * @param session
92      */
93     public GraphStringIndexModifier(NodeContext context, Session session, int index) throws DatabaseException {
94         this.context = context;
95         this.session = session;
96         this.index = index;
97
98         final Resource r = getResourceToModify();
99         if (r == null)
100             throw new IllegalArgumentException("This modifier does not work for INodeContexts that are not adaptable to a Resource. The context input is: " + context.getConstant(BuiltinKeys.INPUT));
101
102         session.syncRequest(new ReadRequest() {
103             @Override
104             public void run(ReadGraph g) throws DatabaseException {
105                 initialValue = getInitialValue(g);
106                 GraphStringIndexModifier.this.modifier = g.adapt(r, StringIndexModifier.class);
107                 initializeGraphModifier(g);
108                 modifierReady.release();
109             }
110         });
111
112     }
113
114     /**
115      * @param g
116      * @return the value that shall be returned by {@link #getValue()}
117      */
118     protected String getInitialValue(ReadGraph g) throws DatabaseException {
119         StringRepresentation2 sr = g.adapt(getResourceToModify(), StringRepresentation2.class);
120         String s = sr.get(g, index);
121         return s;
122     }
123
124     /**
125      * Override to perform graph-based initialization actions for this modifier.
126      * 
127      * @param g the graph handle
128      */
129     protected void initializeGraphModifier(ReadGraph g) {
130     }
131
132     /**
133      * @return the Resource to modify based on the input INodeContext. This
134      *         resource must be adaptable to a {@link StringModifier} in order
135      *         for this modifier to work.
136      */
137     protected Resource getResourceToModify() {
138         Resource r = (Resource) context.getAdapter(Resource.class);
139         if (r == null)
140             throw new AssertionError("context.getAdapter(Resource.class) returned null");
141         return r;
142     }
143
144     /**
145      * @return the modifier or <code>null</code> if the StringModifier adaption
146      *         has not completed yet.
147      */
148     protected StringIndexModifier getModifier() {
149         return modifier;
150     }
151
152     @Override
153     public String getValue() {
154         return initialValue;
155     }
156
157     @Override
158     public String isValid(String label) {
159         if (modifierFailed != null)
160             return "Could not resolve validator for this value, modification denied. Reason: " + modifierFailed.getMessage();
161         if (modifier == null)
162             // Cannot validate yet, the validator has not been resolved.
163             // For the time being, consider the value invalid for no
164             // apparent reason to the user.
165             return "";
166         TObjectIntPair<String> t = createModifierInput(label);
167         return modifier.isValid(t);
168     }
169
170     @Override
171     public final void modify(String label) {
172         if (modifier == null) {
173             try {
174                 modifierReady.acquire();
175             } catch (InterruptedException e) {
176                 // TODO: throw exception?
177                 return;
178             }
179         }
180         if (modifierFailed != null)
181             // TODO: throw exception?
182             return;
183         final TObjectIntPair<String> t = createModifierInput(label);
184         if (!verifyModification(t))
185             return;
186         session.asyncRequest(new WriteRequest() {
187             @Override
188             public void perform(WriteGraph graph) throws DatabaseException {
189                 doModify(graph, t);
190             }
191         }, parameter -> {
192             if (parameter != null)
193                 ErrorLogger.defaultLogError(parameter);
194         });
195     }
196
197     /**
198      * Called one last time before actually performing the modifying write
199      * transaction to verify whether this is really desired or not.
200      * 
201      * <p>
202      * This default implementation will always allow the modification to proceed.
203      * </p>
204      * 
205      * @param label the label to be given to the modifier
206      * @return <code>true</code> to go forward with the transaction,
207      *         <code>false</code> to bail out
208      */
209     protected boolean verifyModification(TObjectIntPair<String> label) {
210         return true;
211     }
212
213     public abstract void doModify(WriteGraph graph, TObjectIntPair<String> label) throws DatabaseException;
214
215     /**
216      * Constructs T from the specified label which is then given to
217      * {@link #doModify(WriteGraph, Object)} as the class T argument.
218      * 
219      * @param fromLabel the modified label specified by the user
220      * @return the
221      *         {@link org.simantics.db.layer0.adapter.Modifier#modify(WriteGraph, Object)}
222      *         input
223      */
224     public abstract TObjectIntPair<String> createModifierInput(String fromLabel);
225
226 };