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