]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/GraphDebugger.java
Predicate by label request into Layer0Utils
[simantics/platform.git] / bundles / org.simantics.debug.ui / src / org / simantics / debug / ui / GraphDebugger.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.debug.ui;
13
14 import java.io.File;
15 import java.io.FileNotFoundException;
16 import java.io.IOException;
17 import java.lang.reflect.Array;
18 import java.net.URI;
19 import java.net.URISyntaxException;
20 import java.net.URL;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30 import java.util.concurrent.CopyOnWriteArrayList;
31
32 import org.eclipse.core.runtime.Assert;
33 import org.eclipse.core.runtime.FileLocator;
34 import org.eclipse.core.runtime.IPath;
35 import org.eclipse.core.runtime.Path;
36 import org.eclipse.jface.action.IStatusLineManager;
37 import org.eclipse.jface.dialogs.Dialog;
38 import org.eclipse.jface.dialogs.IDialogConstants;
39 import org.eclipse.jface.dialogs.IDialogSettings;
40 import org.eclipse.jface.dialogs.IInputValidator;
41 import org.eclipse.jface.dialogs.InputDialog;
42 import org.eclipse.jface.dialogs.MessageDialog;
43 import org.eclipse.jface.layout.GridDataFactory;
44 import org.eclipse.jface.resource.ColorDescriptor;
45 import org.eclipse.jface.resource.JFaceResources;
46 import org.eclipse.jface.resource.LocalResourceManager;
47 import org.eclipse.swt.SWT;
48 import org.eclipse.swt.SWTError;
49 import org.eclipse.swt.browser.Browser;
50 import org.eclipse.swt.browser.LocationAdapter;
51 import org.eclipse.swt.browser.LocationEvent;
52 import org.eclipse.swt.dnd.DND;
53 import org.eclipse.swt.dnd.DropTarget;
54 import org.eclipse.swt.dnd.DropTargetAdapter;
55 import org.eclipse.swt.dnd.DropTargetEvent;
56 import org.eclipse.swt.dnd.TextTransfer;
57 import org.eclipse.swt.dnd.Transfer;
58 import org.eclipse.swt.events.DisposeEvent;
59 import org.eclipse.swt.events.DisposeListener;
60 import org.eclipse.swt.events.FocusEvent;
61 import org.eclipse.swt.events.FocusListener;
62 import org.eclipse.swt.events.KeyAdapter;
63 import org.eclipse.swt.events.KeyEvent;
64 import org.eclipse.swt.events.ModifyEvent;
65 import org.eclipse.swt.events.ModifyListener;
66 import org.eclipse.swt.events.SelectionEvent;
67 import org.eclipse.swt.events.SelectionListener;
68 import org.eclipse.swt.graphics.Color;
69 import org.eclipse.swt.graphics.Point;
70 import org.eclipse.swt.graphics.RGB;
71 import org.eclipse.swt.layout.GridData;
72 import org.eclipse.swt.layout.GridLayout;
73 import org.eclipse.swt.widgets.Button;
74 import org.eclipse.swt.widgets.Composite;
75 import org.eclipse.swt.widgets.Label;
76 import org.eclipse.swt.widgets.Text;
77 import org.eclipse.ui.IWorkbenchSite;
78 import org.simantics.databoard.Bindings;
79 import org.simantics.databoard.Databoard;
80 import org.simantics.databoard.binding.Binding;
81 import org.simantics.databoard.binding.error.BindingException;
82 import org.simantics.databoard.serialization.Serializer;
83 import org.simantics.databoard.type.ArrayType;
84 import org.simantics.databoard.type.Datatype;
85 import org.simantics.databoard.type.StringType;
86 import org.simantics.databoard.util.ObjectUtils;
87 import org.simantics.db.AsyncRequestProcessor;
88 import org.simantics.db.ReadGraph;
89 import org.simantics.db.Resource;
90 import org.simantics.db.Session;
91 import org.simantics.db.Statement;
92 import org.simantics.db.VirtualGraph;
93 import org.simantics.db.WriteGraph;
94 import org.simantics.db.common.ResourceArray;
95 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
96 import org.simantics.db.common.request.Queries;
97 import org.simantics.db.common.request.ReadRequest;
98 import org.simantics.db.common.request.WriteRequest;
99 import org.simantics.db.common.uri.ResourceToPossibleURI;
100 import org.simantics.db.common.utils.ListUtils;
101 import org.simantics.db.common.utils.NameUtils;
102 import org.simantics.db.common.utils.OrderedSetUtils;
103 import org.simantics.db.event.ChangeEvent;
104 import org.simantics.db.event.ChangeListener;
105 import org.simantics.db.exception.AdaptionException;
106 import org.simantics.db.exception.DatabaseException;
107 import org.simantics.db.exception.ResourceNotFoundException;
108 import org.simantics.db.exception.ValidationException;
109 import org.simantics.db.layer0.adapter.StringModifier;
110 import org.simantics.db.layer0.variable.RVI;
111 import org.simantics.db.layer0.variable.Variable;
112 import org.simantics.db.layer0.variable.Variables;
113 import org.simantics.db.service.ClusteringSupport;
114 import org.simantics.db.service.GraphChangeListenerSupport;
115 import org.simantics.db.service.SerialisationSupport;
116 import org.simantics.db.service.VirtualGraphSupport;
117 import org.simantics.db.service.XSupport;
118 import org.simantics.debug.ui.internal.Activator;
119 import org.simantics.debug.ui.internal.DebugUtils;
120 import org.simantics.debug.ui.internal.HashMultiMap;
121 import org.simantics.layer0.Layer0;
122 import org.simantics.ui.dnd.LocalObjectTransfer;
123 import org.simantics.ui.dnd.ResourceReferenceTransfer;
124 import org.simantics.ui.dnd.ResourceTransferUtils;
125 import org.simantics.ui.utils.ResourceAdaptionUtils;
126 import org.simantics.utils.Container;
127 import org.simantics.utils.FileUtils;
128 import org.simantics.utils.datastructures.BijectionMap;
129 import org.simantics.utils.datastructures.Callback;
130 import org.simantics.utils.strings.AlphanumComparator;
131 import org.simantics.utils.ui.ErrorLogger;
132 import org.simantics.utils.ui.PathUtils;
133 import org.simantics.utils.ui.workbench.WorkbenchUtils;
134
135
136 public class GraphDebugger extends Composite {
137
138     public interface HistoryListener {
139         void historyChanged();
140     }
141
142     private static final String                         STATEMENT_PART_SEPARATOR  = ",";
143     private final static String                         DEFAULT_DEBUGGER_CSS_FILE = "debugger.css";
144     private final static String                         DEFAULT_DEBUGGER_CSS_PATH = "css/" + DEFAULT_DEBUGGER_CSS_FILE;
145
146     private static int                                  RESOURCE_NAME_MAX_LENGTH  = 1000;
147     private static int                                  RESOURCE_VALUE_MAX_SIZE = 16384;
148
149     private final LocalResourceManager                  resourceManager;
150
151     private String                                      cssPath;
152
153     private Browser                                     browser;
154     private final ColorDescriptor                       green = ColorDescriptor.createFrom(new RGB(0x57, 0xbc, 0x95));
155
156     private final boolean                               displayClusters           = true;
157
158     private final BijectionMap<String, Resource>        links                     = new BijectionMap<String, Resource>();
159     private final LinkedList<Resource>                  backHistory               = new LinkedList<Resource>();
160     private final LinkedList<Resource>                  forwardHistory            = new LinkedList<Resource>();
161     private Resource                                    currentElement            = null;
162
163     /**
164      * The Session used to access the graph. Received from outside of this
165      * class and therefore it is not disposed here, just used.
166      */
167     private final Session                               session;
168
169     private final CopyOnWriteArrayList<HistoryListener> historyListeners          = new CopyOnWriteArrayList<HistoryListener>();
170
171     private final AsyncRequestProcessor                 updater;
172
173     protected Layer0                                    L0;
174
175     protected IWorkbenchSite                            site;
176
177     private final ChangeListener changeListener = new ChangeListener() {
178         @Override
179         public void graphChanged(ChangeEvent e) {
180             // This makes sure that the transaction for updating this
181             // GraphDebugger get executed in a serialized fashion.
182             updater.asyncRequest(new ReadRequest() {
183
184                 @Override
185                 public void run(ReadGraph graph) throws DatabaseException {
186                     updateContent(graph, currentElement);
187                 }
188
189             });
190
191         }
192     };
193
194     /**
195      * @param parent
196      * @param style
197      * @param session
198      * @param resource the initial resource to debug or <code>null</code> for
199      *        initially blank UI.
200      * @param site the workbench site that contains this debugger, for workbench
201      *        service access
202      */
203     public GraphDebugger(Composite parent, int style, final Session session, Resource resource, IWorkbenchSite site) {
204         this(parent, style, session, resource);
205         this.site = site;
206     }
207
208     /**
209      * @param parent
210      * @param style
211      * @param session
212      * @param resource the initial resource to debug or <code>null</code> for
213      *        initially blank UI.
214      */
215     public GraphDebugger(Composite parent, int style, final Session session, Resource resource) {
216         super(parent, style);
217         Assert.isNotNull(session, "session is null");
218         this.session = session;
219         this.currentElement = resource;
220         this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
221
222         updater = session;//.getService(MergingGraphRequestProcessor.class);
223
224         initializeCSS();
225
226         addDisposeListener(new DisposeListener() {
227             @Override
228             public void widgetDisposed(DisposeEvent e) {
229                 GraphChangeListenerSupport support = session.getService(GraphChangeListenerSupport.class);
230                 support.removeListener(changeListener);
231             }
232         });
233     }
234
235     /**
236      * When given to setStatus, indicates that the message shouldn't be touched
237      * since <code>null</code> has a different meaning.
238      */
239     private static final String DONT_TOUCH = "DONT_TOUCH";
240
241     protected void setStatus(String message, String error) {
242         IStatusLineManager status = WorkbenchUtils.getStatusLine(site);
243         if (status != null) {
244             if (message != DONT_TOUCH)
245                 status.setMessage(message);
246             if (error != DONT_TOUCH)
247                 status.setErrorMessage(error);
248         }
249     }
250
251     public void defaultInitializeUI() {
252         setLayout(new GridLayout(2, false));
253         setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
254
255         createResourceText(this);
256         createDropLabel(this);
257         createBrowser(this);
258
259     }
260
261     protected void initializeCSS() {
262         // Extract default css to a temporary location if necessary.
263         try {
264             IPath absolutePath = PathUtils.getAbsolutePath(Activator.PLUGIN_ID, DEFAULT_DEBUGGER_CSS_PATH);
265             if (absolutePath != null) {
266                 cssPath = absolutePath.toFile().toURI().toString();
267             } else {
268                 File tempDir = FileUtils.getOrCreateTemporaryDirectory(false);
269                 File css = new File(tempDir, DEFAULT_DEBUGGER_CSS_FILE);
270                 if (!css.exists()) {
271                     URL url = FileLocator.find(Activator.getDefault().getBundle(), new Path(DEFAULT_DEBUGGER_CSS_PATH), null);
272                     if (url == null)
273                         throw new FileNotFoundException("Could not find '" + DEFAULT_DEBUGGER_CSS_PATH + "' in bundle '" + Activator.PLUGIN_ID + "'");
274                     cssPath = FileUtils.copyResource(url, css, true).toURI().toString();
275                 } else {
276                     cssPath = css.toURI().toString();
277                 }
278             }
279         } catch (IOException e) {
280             // CSS extraction failed, let's just live without it then.
281             ErrorLogger.defaultLogWarning(e);
282         }
283     }
284
285     private static final String PROMPT_TEXT = "Enter resource ID (RID) or URI";
286
287     public void createResourceText(final Composite parent) {
288         final Text text = new Text(parent, SWT.BORDER);
289         text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
290         text.setText(PROMPT_TEXT);
291         GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(text);
292         
293         text.addFocusListener(new FocusListener() {    
294             @Override
295             public void focusLost(FocusEvent e) {
296                 if (text.getText().trim().equals("")) {
297                     text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
298                     text.setText(PROMPT_TEXT);
299                 }
300             }
301             @Override
302             public void focusGained(FocusEvent e) {
303                 if (text.getText().trim().equals(PROMPT_TEXT)) {
304                     text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_BLACK));
305                     text.setText("");
306                 }
307                 text.selectAll();
308             }
309         });
310         text.addKeyListener(new KeyAdapter() {
311             @Override
312             public void keyPressed(KeyEvent e) {
313                 if (e.keyCode == SWT.CR) {
314                     String input = text.getText();
315                     setLookupInput(input);
316                 }
317             }
318         });
319
320         final Button button = new Button(parent, SWT.FLAT);
321         button.setText("&Lookup");
322         button.setEnabled(false);
323         GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(false, false).applyTo(button);
324
325         text.addKeyListener(new KeyAdapter() {
326             
327             @Override
328             public void keyPressed(KeyEvent e) {
329                 if (e.keyCode == 13) {
330                     String input = text.getText();
331                     setLookupInput(input);
332                     button.setFocus();
333                 }
334             }
335         });
336         
337         button.addSelectionListener(new SelectionListener() {
338             @Override
339             public void widgetDefaultSelected(SelectionEvent e) {
340                 widgetSelected(e);
341             }
342             @Override
343             public void widgetSelected(SelectionEvent e) {
344                 String input = text.getText();
345                 setLookupInput(input);
346             }
347         });
348         
349         text.addModifyListener(new ModifyListener() {
350             @Override
351             public void modifyText(ModifyEvent e) {
352                 String input = text.getText().trim();
353                 if (!input.equals(PROMPT_TEXT) && !input.equals(""))
354                     button.setEnabled(true);
355                 else
356                     button.setEnabled(false);
357             }
358         });
359     }
360
361     public void setLookupInput(String input) {
362         // There's no harm in trimming out spaces from both ends of the input.
363         input = input.trim();
364
365         SerialisationSupport support = session.getService(SerialisationSupport.class);
366         if (input.startsWith("$")) {
367             try {
368                 Resource r = support.getResource(Long.parseLong(input.substring(1)));
369                 changeLocation(r);
370             } catch (NumberFormatException e1) {
371                 // Ignore, may happen for crap input
372                 setStatus(DONT_TOUCH, "Invalid '$'-prefixed input, expected resource ID");
373             } catch (Exception e1) {
374                 ErrorLogger.defaultLogError(e1);
375                 setStatus(DONT_TOUCH, "Resource ID lookup failed. See Error Log.");
376             }
377             return;
378         }
379
380         String[] parts = input.split("-");
381
382         if (parts.length == 1) {
383             try {
384                 int resourceKey = Integer.parseInt(parts[0].trim());
385                 Resource r = support.getResource(resourceKey);
386                 // Some validation, not enough though
387                 ClusteringSupport cs = session.getService(ClusteringSupport.class);
388                 long cluster = cs.getCluster(r);
389                 if(cluster > 0) {
390                     changeLocation(r);
391                 }
392             } catch (NumberFormatException e1) {
393                 // Ignore, may happen for crap input
394                 setStatus(DONT_TOUCH, "Invalid input, expected transient resource ID");
395             } catch (Exception e1) {
396                 ErrorLogger.defaultLogError(e1);
397                 setStatus(DONT_TOUCH, "Transient resource ID lookup failed. See Error Log.");
398             }
399         } else if (parts.length == 2) {
400             try {
401                 int resourceIndex = Integer.parseInt(parts[1]);
402                 long clusterId = Long.parseLong(parts[0]);
403                 ClusteringSupport cs = session.getService(ClusteringSupport.class);
404                 Resource r = cs.getResourceByIndexAndCluster(resourceIndex, clusterId);
405                 changeLocation(r);
406             } catch (NumberFormatException e1) {
407                 // Ignore, may happen for crap input
408                 setStatus(DONT_TOUCH, "Invalid input, expected index & cluster IDs");
409             } catch (Exception e1) {
410                 ErrorLogger.defaultLogError(e1);
411                 setStatus(DONT_TOUCH, "Index & cluster -based lookup failed. See Error Log.");
412             }
413         }
414
415         // Try to see if the input data is an URI reference
416         try {
417             // First check that the input really is a proper URI.
418             String uri = input;
419             if (!input.equals("http:/") && input.endsWith("/"))
420                 uri = input.substring(0, input.length() - 1);
421             new URI(uri);
422             Resource r = session.syncRequest( Queries.resource( uri ) );
423             changeLocation(r);
424             return;
425         } catch (URISyntaxException e) {
426             // Ignore, this is not a proper URI at all.
427         } catch (ResourceNotFoundException e1) {
428             // Ok, this was an URI, but no resource was found.
429             setStatus(DONT_TOUCH, "Resource for URI '" + input + "' not found");
430             return;
431         } catch (DatabaseException e1) {
432             setStatus(DONT_TOUCH, "URI lookup failed. See Error Log.");
433             ErrorLogger.defaultLogError(e1);
434         }
435
436         setStatus(DONT_TOUCH, "Invalid input, resource ID or URI expected");
437     }
438
439     public Label createDropLabel(Composite parent) {
440         final Label label = new Label(parent, SWT.BORDER);
441         label.setAlignment(SWT.CENTER);
442         label.setText("Drag a resource here to examine it in this debugger!");
443         label.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
444         GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(SWT.DEFAULT, 20).span(2, 1).grab(true, false).applyTo(label);
445
446         // Add resource id drop support to the drop-area.
447         DropTarget dropTarget = new DropTarget(label, DND.DROP_LINK | DND.DROP_COPY);
448         dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), ResourceReferenceTransfer.getInstance(), LocalObjectTransfer.getTransfer() });
449         dropTarget.addDropListener(new DropTargetAdapter() {
450             @Override
451             public void dragEnter(DropTargetEvent event) {
452                 event.detail = DND.DROP_LINK;
453                 label.setBackground((Color) resourceManager.get(green));
454                 return;
455             }
456             @Override
457             public void dragLeave(DropTargetEvent event) {
458                 label.setBackground(null);
459             }
460
461             @Override
462             public void drop(DropTargetEvent event) {
463                 label.setBackground(null);
464                 ResourceArray[] data = parseEventData(event);
465                 if (data == null || data.length != 1) {
466                     event.detail = DND.DROP_NONE;
467                     return;
468                 }
469                 final ResourceArray array = data[0];
470                 final Resource r = array.resources[array.resources.length - 1];
471
472                 changeLocation(r);
473             }
474
475             private ResourceArray[] parseEventData(DropTargetEvent event) {
476                 //System.out.println("DATA: " + event.data);
477                 if (event.data instanceof String) {
478                     try {
479                         SerialisationSupport support = session.getService(SerialisationSupport.class);
480                         return ResourceTransferUtils.readStringTransferable(support, (String) event.data).toResourceArrayArray();
481                     } catch (IllegalArgumentException e) {
482                         ErrorLogger.defaultLogError(e);
483                     } catch (DatabaseException e) {
484                         ErrorLogger.defaultLogError(e);
485                     }
486                 }
487                 ResourceArray[] ret = ResourceAdaptionUtils.toResourceArrays(event.data);
488                 if (ret.length > 0)
489                     return ret;
490                 return null;
491             }
492         });
493
494         return label;
495     }
496
497     public Browser createBrowser(Composite parent) {
498         try {
499             browser = new Browser(parent, SWT.MOZILLA);
500         } catch (SWTError e) {
501             //System.out.println("Could not instantiate Browser: " + e.getMessage());
502             browser = new Browser(parent, SWT.NONE);
503         }
504         GridDataFactory.fillDefaults().span(2, 1).grab(true, true).applyTo(browser);
505
506         // Left/right arrows for back/forward
507         browser.addKeyListener(new KeyAdapter() {
508 //              
509 //              @Override
510 //            public void keyPressed(KeyEvent e) {
511 //                      if (e.keyCode == SWT.F5) {
512 //                      refreshBrowser();
513 //                      }
514 //              }
515 //          }
516             @Override
517             public void keyReleased(KeyEvent e) {
518 //                System.out.println("key, char: " + e.keyCode + ", " + (int) e.character + " (" + e.character + ")");
519                 if (e.keyCode == SWT.BS) {
520                     back();
521                 }
522                 
523                 if (e.keyCode == SWT.F5) {
524                         refreshBrowser();
525                 }
526                 
527                 if ((e.stateMask & SWT.ALT) != 0) {
528                     if (e.keyCode == SWT.ARROW_RIGHT)
529                         forward();
530                     if (e.keyCode == SWT.ARROW_LEFT)
531                         back();
532                 }
533             }
534         });
535
536         // Add listener for debugging functionality
537         browser.addLocationListener(new LocationAdapter() {
538             @Override
539             public void changing(LocationEvent event) {
540                 String location = event.location;
541                 if (location.startsWith("simantics:browser"))
542                     location = "about:" + location.substring(17);
543                 //System.out.println("changing: location=" + location);
544
545                 // Do not follow links that are meant as actions that are
546                 // handled below.
547                 event.doit = false;
548                 if ("about:blank".equals(location)) {
549                     // Just changing to the same old blank url is ok since it
550                     // allows the browser to refresh itself.
551                     event.doit = true;
552                 }
553
554                 if (location.startsWith("about:-link")) {
555                     String target = location.replace("about:-link", "");
556                     Resource element = links.getRight(target);
557                     if (element == currentElement) {
558                         event.doit = false;
559                         return;
560                     }
561                     changeLocation(element);
562                 } else if (location.startsWith("about:-remove")) {
563                     String target = location.replace("about:-remove", "");
564                     String n[] = target.split(STATEMENT_PART_SEPARATOR);
565                     if (n.length != 3)
566                         return;
567
568                     final Resource s = links.getRight(n[0]);
569                     final Resource p = links.getRight(n[1]);
570                     final Resource o = links.getRight(n[2]);
571
572                     // Make sure this is what the use wants.
573                     MessageDialog md = new MessageDialog(
574                             getShell(),
575                             "Confirm action...",
576                             null,
577                             "This action will remove the selected statement.\nAre you sure you want to proceed with this action?",
578                             MessageDialog.QUESTION, new String[] { "Cancel", "Continue" }, 0);
579                     if (md.open() != 1) {
580                         return;
581                     }
582
583                     session.asyncRequest(new WriteRequest() {
584
585                         @Override
586                         public void perform(WriteGraph g) throws DatabaseException {
587                                 try {
588                                         List<Resource> ls = OrderedSetUtils.toList(g, s);
589                                         if(ls.contains(o))
590                                                 OrderedSetUtils.remove(g, s, o);
591                                 } catch (DatabaseException e) {
592                                         
593                                 }
594                                 try {
595                                         List<Resource> ls = ListUtils.toList(g, s);
596                                         if(ls.contains(o))
597                                                 ListUtils.removeElement(g, s, o);
598                                 } catch (DatabaseException e) {
599                                         
600                                 }
601                             g.denyStatement(s, p, o);
602                         }
603
604                     }, new Callback<DatabaseException>() {
605
606                         @Override
607                         public void run(DatabaseException parameter) {
608                             refreshBrowser();
609                         }
610
611                     });
612                 } else if (location.startsWith("about:-edit-value")) {
613                     String target = location.replace("about:-edit-value", "");
614                     final Resource o = links.getRight(target);
615
616                     session.asyncRequest(new ReadRequest() {
617
618                         String previousValue;
619
620                         @Override
621                         public void run(ReadGraph graph) throws DatabaseException {
622
623                             previousValue = getResourceName(graph, o);
624                             final StringModifier modifier = graph.adapt(o, StringModifier.class);
625                             getDisplay().asyncExec(new Runnable() {
626                                 @Override
627                                 public void run() {
628                                     InputDialog dialog = new InputDialog(
629                                             getShell(),
630                                             "Edit Value",
631                                             null,
632                                             previousValue,
633                                             new IInputValidator() {
634                                                 @Override
635                                                 public String isValid(String newText) {
636                                                     return modifier.isValid(newText);
637                                                 }
638                                             }) {
639                                         private static final String DIALOG = "DebuggerEditValueDialog"; //$NON-NLS-1$
640                                         private IDialogSettings dialogBoundsSettings;
641                                         @Override
642                                         protected IDialogSettings getDialogBoundsSettings() {
643                                             if (dialogBoundsSettings == null) {
644                                                 IDialogSettings settings = Activator.getDefault().getDialogSettings();
645                                                 dialogBoundsSettings = settings.getSection(DIALOG);
646                                                 if (dialogBoundsSettings == null)
647                                                     dialogBoundsSettings = settings.addNewSection(DIALOG);
648                                             }
649                                             return dialogBoundsSettings;
650                                         }
651                                         @Override
652                                         protected Point getInitialSize() {
653                                             Point defaultSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
654                                             Point result = super.getInitialSize();
655                                             if (defaultSize.equals(result))
656                                                 return new Point(600, 400);
657                                             return result;
658                                         }
659                                         protected int getShellStyle() {
660                                             return super.getShellStyle() | SWT.RESIZE;
661                                         }
662                                         protected org.eclipse.swt.widgets.Control createDialogArea(Composite parent) {
663                                             Composite composite = (Composite) super.createDialogArea(parent);
664                                             getText().setLayoutData(
665                                                     new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL
666                                                             | GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
667                                             {
668                                                 Label label = new Label(composite, SWT.NONE);
669                                                 label.moveAbove(getText());
670                                                 label.setText("Input new property value. For numeric vector values, separate numbers with comma (',').");
671                                                 GridData data = new GridData(GridData.GRAB_HORIZONTAL
672                                                         | GridData.HORIZONTAL_ALIGN_FILL
673                                                         | GridData.VERTICAL_ALIGN_CENTER);
674                                                 data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
675                                                 label.setLayoutData(data);
676                                                 label.setFont(parent.getFont());
677                                             }
678                                             return composite;
679                                         }
680                                         protected int getInputTextStyle() {
681                                             return SWT.MULTI | SWT.BORDER;
682                                         }
683                                     };
684                                     int ok = dialog.open();
685                                     if (ok != Dialog.OK)
686                                         return;
687
688                                     final String value = dialog.getValue();
689                                     session.asyncRequest(new WriteRequest() {
690                                         @Override
691                                         public void perform(WriteGraph g) throws DatabaseException {
692                                             //modifier.modify( g, htmlEscape( value ) );
693                                             modifier.modify( g, value );
694                                         }
695                                     }, new Callback<DatabaseException>() {
696                                         @Override
697                                         public void run(DatabaseException parameter) {
698                                             if (parameter != null)
699                                                 ErrorLogger.defaultLogError(parameter);
700                                             refreshBrowser();
701                                         }
702                                     });
703                                     return;
704                                 }
705                             });
706                         }
707
708                     }, new ProcedureAdapter<Object>() {
709                         @Override
710                         public void exception(Throwable t) {
711                             ErrorLogger.defaultLogError(t);
712                         }
713                     });
714
715                 }
716             }
717         });
718
719         // Schedule a request that updates the browser content.
720         refreshBrowser();
721         GraphChangeListenerSupport support = session.getService(GraphChangeListenerSupport.class);
722         support.removeListener(changeListener);
723
724         return browser;
725     }
726
727     public void refreshBrowser() {
728         if (currentElement == null)
729             return;
730
731         // Schedule a request that updates the browser content.
732         updater.asyncRequest(new ReadRequest() {
733
734             @Override
735             public void run(ReadGraph graph) throws DatabaseException {
736                 updateContent(graph, currentElement);
737             }
738
739         });
740
741     }
742
743     public Resource getDebuggerLocation() {
744         return currentElement;
745     }
746
747     public void changeLocation(Resource element) {
748         if (currentElement != null) {
749             backHistory.addLast(currentElement);
750         }
751         currentElement = element;
752         forwardHistory.clear();
753
754         refreshBrowser();
755         setStatus(DONT_TOUCH, null);
756         fireHistoryChanged();
757     }
758
759     public void addHistoryListener(HistoryListener l) {
760         historyListeners.add(l);
761     }
762
763     public void removeHistoryListener(HistoryListener l) {
764         historyListeners.remove(l);
765     }
766
767     private void fireHistoryChanged() {
768         for (HistoryListener l : historyListeners)
769             l.historyChanged();
770     }
771
772     public boolean hasBackHistory() {
773         return backHistory.isEmpty();
774     }
775
776     public boolean hasForwardHistory() {
777         return forwardHistory.isEmpty();
778     }
779
780     public void back() {
781         if (backHistory.isEmpty())
782             return;
783
784         forwardHistory.addFirst(currentElement);
785         currentElement = backHistory.removeLast();
786
787         refreshBrowser();
788         fireHistoryChanged();
789     }
790
791     public void forward() {
792         if (forwardHistory.isEmpty())
793             return;
794
795         backHistory.addLast(currentElement);
796         currentElement = forwardHistory.removeFirst();
797
798         refreshBrowser();
799         fireHistoryChanged();
800     }
801
802     protected String toName(Object o) {
803         Class<?> clazz = o.getClass();
804         if (clazz.isArray()) {
805             int length = Array.getLength(o);
806             if (length > RESOURCE_NAME_MAX_LENGTH) {
807                 if (o instanceof byte[]) {
808                     byte[] arr = (byte[]) o;
809                     byte[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
810                     return truncated("byte", Arrays.toString(arr2), arr.length);
811                 } else if (o instanceof int[]) {
812                     int[] arr = (int[]) o;
813                     int[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
814                     return truncated("int", Arrays.toString(arr2), arr.length);
815                 } else if (o instanceof long[]) {
816                     long[] arr = (long[]) o;
817                     long[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
818                     return truncated("long", Arrays.toString(arr2), arr.length);
819                 } else if (o instanceof float[]) {
820                     float[] arr = (float[]) o;
821                     float[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
822                     return truncated("float", Arrays.toString(arr2), arr.length);
823                 } else if (o instanceof double[]) {
824                     double[] arr = (double[]) o;
825                     double[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
826                     return truncated("double", Arrays.toString(arr2), arr.length);
827                 } else if (o instanceof boolean[]) {
828                     boolean[] arr = (boolean[]) o;
829                     boolean[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
830                     return truncated("boolean", Arrays.toString(arr2), arr.length);
831                 } else if (o instanceof Object[]) {
832                     Object[] arr = (Object[]) o;
833                     Object[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
834                     return truncated("Object", Arrays.toString(arr2), arr.length);
835                 } else {
836                     return "Unknown big array " + o.getClass();
837                 }
838             } else {
839                 return o.getClass().getComponentType() + "[" + length + "] = " + ObjectUtils.toString(o);
840             }
841         }
842         return null;
843     }
844
845     protected String truncated(String type, String string, int originalLength) {
846         return type + "[" + RESOURCE_NAME_MAX_LENGTH + "/" + originalLength + "] = " + string;
847     }
848     
849     public static String htmlEscape(String s)
850     {
851         return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n", "<br/>");
852     }
853
854     /**
855      * Get resource name(?) 
856      * 
857      * @param graph
858      * @param r
859      * @return
860      */
861     protected String getResourceName(ReadGraph graph, Resource r) {
862         try {
863
864             String name = null;
865             //System.out.println("hasValue(" + NameUtils.getSafeName(graph, r, true));
866             if (graph.hasValue(r)) {
867                 // too large array may cause application to run out of memory.
868                 //System.out.println("getValue(" + NameUtils.getSafeName(graph, r, true));
869                 Datatype type = graph.getPossibleRelatedValue(r, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
870                 if (type!=null) {
871                         Binding rviBinding = graph.getService(Databoard.class).getBindingUnchecked( RVI.class );
872                         if (type.equals( rviBinding.type() )) {
873                                 RVI rvi = graph.getValue(r, rviBinding);
874                                                                 
875                                 try {
876                                         Variable v = Variables.getConfigurationContext( graph, currentElement );
877                                         name = rvi.asString(graph, v);
878 //                                      name = rvi.resolve(graph, v).getURI(graph);
879                                 } catch (DatabaseException dbe ) {
880                                         name = rvi.toString( graph );
881                                 }
882                         } else {
883                                 long valueSize = NameUtils.getPossibleValueSize(graph, r);
884                                 if (valueSize > RESOURCE_NAME_MAX_LENGTH) {
885 //                                      Binding b = Bindings.getBinding(type);
886 //                                      Object v = graph.getValue(r, b);
887 //                                      Serializer s = Bindings.getSerializerUnchecked(b);
888 //                                      int size = s.getSize(v);
889                                     name = "Approx. " + valueSize + " byte literal of type " + type.toSingleLineString();
890                                 } else {                                        
891                                         Binding b = Bindings.getBinding(type);
892                                         Object v = graph.getValue(r, b);
893                                         if (b.type() instanceof StringType) {
894                                                 name = (String) graph.getValue(r, b);
895                                         } else {
896                                             name = b.toString(v, false);
897                                         }
898                                     if (type instanceof ArrayType){
899                                         name = name.substring(1, name.length()-1);
900                                     }
901                                 }
902                         }
903                 } else {
904                     Object o = graph.getValue(r);
905                     name = toName(o);
906                 }
907                 
908                 if(name.isEmpty()) {
909                         name = "<empty value>";
910                 }
911                 
912             }
913             // Does resource have a file ??
914             if (name == null) {
915 //                try {
916 //                    Accessor accessor = graph.getAccessor(r);
917 //                    name = "File of type " + accessor.type().toSingleLineString();
918 //                } catch (DatabaseException e) {
919 //                    // No file, try next alternative.
920 //                }
921             }
922             if (name == null) {
923                 //name = graph.adapt(r, String.class);
924                 //if(name.isEmpty())
925                 name = DebugUtils.getSafeLabel(graph, r);
926                 if (name.isEmpty())
927                     name = "<empty name>";
928             }
929 //            ClusteringSupport support = graph.getSession().getService(ClusteringSupport.class);
930 //            if(name == null)
931 //                return "[" + r.getResourceId() + " - " + support.getCluster(r) + "]";
932             if(displayClusters) {
933 //                SessionDebug debug = graph.getSession().getDebug();
934 //                name += " (" + debug.getCluster(r) + ")";
935             }
936             return name;
937         } catch (AdaptionException e) {
938 //            e.printStackTrace();
939             String name = safeReadableString(graph, r);
940 //          try {
941 //                MessageService.defaultLog(new DetailStatus(IDetailStatus.DEBUG, Activator.PLUGIN_ID, 0, NLS.bind(Messages.Name_adaption_problem, MessageUtil.resource(session, r, "this resource")), e));
942 //            } catch (ReferenceSerializationException e1) {
943 //                e1.printStackTrace();
944 //                ErrorLogger.defaultLogWarning(e1);
945 //            }
946             return name;
947         } catch (Exception e) {
948             ErrorLogger.defaultLogError(e);
949             String name = safeReadableString(graph, r);
950 //          try {
951 //                MessageService.defaultLog(new DetailStatus(IDetailStatus.DEBUG, Activator.PLUGIN_ID, 0, NLS.bind(Messages.Name_formulation_problem, MessageUtil.resource(session, r, "this resource")), e));
952 //            } catch (ReferenceSerializationException e1) {
953 //                e1.printStackTrace();
954 //                ErrorLogger.defaultLogWarning(e1);
955 //            }
956             return name;
957         }
958     }
959
960     private String getResourceRef(ReadGraph graph, Resource r) throws DatabaseException {
961         String name;
962         try {
963             Layer0 L0 = Layer0.getInstance(graph);
964             if (graph.isInstanceOf(r, L0.Assertion)) {
965                 Resource pred = graph.getSingleObject(r, L0.HasPredicate);
966                 // Don't know how I encountered this but it seems to be possible in some cases..
967                 // Resource obj = graph.getSingleObject(r, L0.HasObject);
968                 Resource obj = graph.getPossibleObject(r, L0.HasObject);
969                 String tmp = htmlEscape( getResourceName(graph, pred) + " -> " + (obj == null ? "No object ?" : getResourceName(graph, obj)) + " (Assertion)" );
970                 name = tmp.substring(0, Math.min(80, tmp.length()));
971             } else {
972                 String resourceName = getResourceName(graph, r);
973                 if(resourceName.equals("Inverse")) {
974                     Resource inverse = graph.getPossibleInverse(r);
975                     if(inverse != null && graph.hasStatement(inverse, L0.ConsistsOf, r))
976                         resourceName = getResourceName(graph, inverse) + "/Inverse";
977                 }
978                 String tmp = htmlEscape( resourceName );
979                 name = tmp.substring(0, Math.min(80, tmp.length()));
980             }
981             
982         } catch (OutOfMemoryError e) {
983             name = "OutOfMemoryError";
984         }
985         String ret = "<a href=\"simantics:browser-link" + getLinkString(r) + "\">"
986         + name
987         + "</a>";
988         if (graph.isInstanceOf(r, L0.Literal)) {
989             ret += "&nbsp;<a class=\"edit-link\" href=\"simantics:browser-edit-value" + getLinkString(r) + "\">"
990             + "(edit)"
991             + "</a>";
992         }
993         return ret;
994     }
995
996     private String getStatementRemoveRef(Resource s, Resource p, Resource o) {
997         return "<a href=\"simantics:browser-remove" + getStatementString(s, p, o)
998         + "\" title=\"Remove this statement\">X</a>";
999     }
1000
1001     private void updatePred(StringBuffer content, ReadGraph graph, Resource subj, Resource pred, List<Resource[]> stats) throws DatabaseException {
1002         // Generate output content from statements
1003         String[][] objects = new String[stats.size()][];
1004         for (int i = 0; i < stats.size(); ++i) {
1005             Resource stmSubject = stats.get(i)[0];
1006             Resource object = stats.get(i)[1];
1007
1008             objects[i] = new String[4];
1009             objects[i][0] = getLinkString(object);
1010             objects[i][1] = htmlEscape( getResourceName(graph, object) );
1011             objects[i][2] = getResourceRef(graph, object);
1012
1013             // Make a note if the statement was acquired.
1014             if(!stmSubject.equals(subj)) {
1015                 objects[i][3] = " (in " + getResourceRef(graph, stmSubject) + ")";
1016             }
1017         }
1018
1019         // Sort statements by object name
1020         Arrays.sort(objects, new Comparator<String[]>() {
1021             @Override
1022             public int compare(String[] o1, String[] o2) {
1023                 return AlphanumComparator.CASE_INSENSITIVE_COMPARATOR.compare(o1[1], o2[1]);
1024             }
1025         });
1026
1027         // Output table rows
1028         for (int i = 0; i < objects.length; ++i) {
1029             content.append("<tr>");
1030             // Predicate column
1031             if (i == 0)
1032                 content.append("<td rowspan=\"").append(objects.length).append("\" valign=\"top\">").append(getResourceRef(graph, pred)).append("</td>");
1033
1034             // Object column
1035             if (objects[i][3] == null) content.append("<td>");
1036             else content.append("<td class=\"acquired\">");
1037
1038             content.append(objects[i][2]);
1039             if (objects[i][3] != null)
1040                 content.append(objects[i][3]);
1041
1042             content.append("</td>");
1043             
1044             VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
1045             VirtualGraph vg = vgs.getGraph(graph, subj, pred, links.getRight(objects[i][0]));
1046             
1047             if(vg != null) {
1048                 content.append("<td>").append(vg.toString()).append("</td>");
1049             } else {
1050                 content.append("<td>DB</td>");
1051             }
1052             
1053
1054             // Statement remove -link column
1055             // Only allowed for non-acquired statements.
1056             if (objects[i][3] == null) {
1057                 content.append("<td class=\"remove\">");
1058                 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1059                 content.append("</td>");
1060             }
1061             content.append("</tr>");
1062         }
1063     }
1064
1065     private void updateTag(StringBuffer content, ReadGraph graph, Resource subj, Resource tag) throws DatabaseException {
1066
1067         // Generate output content from statements
1068         String ref = getResourceRef(graph, tag);
1069
1070         content.append("<tr>");
1071         content.append("<td rowspan=\"1\" colspan=\"3\" valign=\"top\">").append(ref).append("</td>");
1072         //content.append("<td>" + name + "</td>");
1073         content.append("<td class=\"remove\">");
1074         content.append(getStatementRemoveRef(subj, tag, subj));
1075         content.append("</td>");
1076         content.append("</tr>");
1077
1078     }
1079
1080     private void updateOrderedSet(StringBuffer content, ReadGraph graph, Resource subj) throws DatabaseException {
1081         //List<Resource> list = OrderedSetUtils.toList(graph, subj);
1082         /*
1083         // Generate output content from statements
1084         String[][] objects = new String[stats.size()][];
1085         for (int i = 0; i < stats.size(); ++i) {
1086             Resource stmSubject = stats.get(i)[0];
1087             Resource object = stats.get(i)[1];
1088
1089             objects[i] = new String[4];
1090             objects[i][0] = getLinkString(object);
1091             objects[i][1] = getResourceName(graph, object);
1092             objects[i][2] = getResourceRef(graph, object);
1093
1094             // Make a note if the statement was acquired.
1095             if(!stmSubject.equals(subj)) {
1096                 objects[i][3] = " (acquired from " + getResourceRef(graph, stmSubject) + ")";
1097             }
1098         }
1099
1100         // Sort statements by object name
1101         Arrays.sort(objects, new Comparator<String[]>() {
1102             @Override
1103             public int compare(String[] o1, String[] o2) {
1104                 return o1[1].compareTo(o2[1]);
1105             }
1106         });*/
1107
1108         List<String> list = new ArrayList<String>();
1109         Resource cur = subj;
1110         while(true) {
1111             try {
1112                 cur = OrderedSetUtils.next(graph, subj, cur);
1113             } catch(DatabaseException e) {
1114                 list.add("<span style=\"color:red;font-weight:bold\">BROKEN ORDERED SET:<br/></span><span style=\"color:red\">" + e.getMessage() + "</span>");
1115                 Resource inv = graph.getPossibleInverse(subj);
1116                 for(Statement stat : graph.getStatements(cur, L0.IsRelatedTo)) {
1117                     if(stat.getSubject().equals(cur)) {
1118                         if(stat.getPredicate().equals(subj)) {
1119                             list.add("next " + getResourceRef(graph, stat.getObject()));
1120                         }
1121                         else if(stat.getPredicate().equals(inv)) {
1122                             list.add("prev " + getResourceRef(graph, stat.getObject()));
1123                         }
1124                     }
1125                 }
1126                 break;
1127             }
1128             if(cur.equals(subj))
1129                 break;
1130             list.add(getResourceRef(graph, cur));
1131         }
1132
1133         // Output table rows
1134         for (int i = 0; i < list.size() ; ++i) {
1135             content.append("<tr>");
1136             // Predicate column
1137             if (i == 0)
1138                 content.append("<td rowspan=\"").append(list.size()).append("\" valign=\"top\">Ordered Set Elements</td>");
1139
1140             // Object column
1141             content.append("<td>");
1142             content.append(list.get(i));
1143             content.append("</td>");
1144
1145             // Statement remove -link column
1146             // Only allowed for non-acquired statements.
1147             /*if (objects[i][3] == null) {
1148                 content.append("<td class=\"remove\">");
1149                 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1150                 content.append("</td>");
1151             }*/
1152             content.append("</tr>");
1153         }
1154     }
1155
1156     private void updateLinkedList(StringBuffer content, ReadGraph graph, Resource subj) throws DatabaseException {
1157
1158         List<String> list = new ArrayList<String>();
1159         
1160         try {
1161                 List<Resource> resources = ListUtils.toList(graph, subj);
1162                 for(Resource element : resources) {
1163                     list.add(getResourceRef(graph, element));
1164                 }
1165         } catch (DatabaseException e) {
1166                 throw new ValidationException(e);
1167         }
1168
1169         // Output table rows
1170         for (int i = 0; i < list.size() ; ++i) {
1171             content.append("<tr>");
1172             // Predicate column
1173             if (i == 0)
1174                 content.append("<td rowspan=\"").append(list.size()).append("\" valign=\"top\">Linked List Elements</td>");
1175
1176             // Object column
1177             content.append("<td>");
1178             content.append(list.get(i));
1179             content.append("</td><td>DB</td>");
1180
1181             // Statement remove -link column
1182             // Only allowed for non-acquired statements.
1183             /*if (objects[i][3] == null) {
1184                 content.append("<td class=\"remove\">");
1185                 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1186                 content.append("</td>");
1187             }*/
1188             content.append("</tr>");
1189         }
1190     }
1191
1192     protected synchronized void updateContent(final ReadGraph graph, Resource... resources) throws DatabaseException {
1193         L0 = Layer0.getInstance(graph);
1194
1195         links.clear();
1196         StringBuffer content = new StringBuffer();
1197
1198         // Generate HTML -page
1199         content.append("<html>\n<head>\n")
1200         .append(getHead())
1201         .append("\n</head>\n")
1202         .append("<body>\n")
1203         .append("<div id=\"mainContent\">\n\n");
1204
1205         for (Resource r : resources) {
1206             if (r == null)
1207                 continue;
1208
1209             String uri = null;
1210             try {
1211                 uri = graph.syncRequest(new ResourceToPossibleURI(r));
1212             } catch (Exception e) {
1213                 ErrorLogger.defaultLogError(e);
1214                 uri = "Cannot get URI: " + e.getMessage();
1215             }
1216
1217             // Top DIV
1218             content.append("<div id=\"top\">\n");
1219             content.append("<table class=\"top\">\n");
1220             if (uri != null) {
1221                 content.append("<tr><td class=\"top_key\">URI</td><td class=\"top_value\"><span id=\"uri\">").append(uri).append("</span></td></tr>\n");
1222             }
1223
1224             XSupport xs = graph.getService(XSupport.class);
1225             boolean immutable = xs.getImmutable(r);
1226
1227             Collection<Statement> statements = graph.getStatements(r, L0.IsWeaklyRelatedTo);
1228             HashMultiMap<Resource, Resource[]> map = new HashMultiMap<Resource, Resource[]>();
1229             for(org.simantics.db.Statement statement : statements) {
1230                 Resource predicate = null;
1231                 Resource subject = null;
1232                 Resource obj = null;
1233                 try {
1234                     predicate = statement.getPredicate();
1235                     subject = statement.getSubject();
1236                     obj = statement.getObject();
1237                     map.add(predicate, new Resource[] {subject, obj});
1238                 } catch (Throwable e) {
1239                     ErrorLogger.defaultLogError("Cannot find statement " + subject + " " + predicate + " " + obj, e);
1240                 }
1241             }
1242             SerialisationSupport ss = graph.getSession().getService(SerialisationSupport.class);
1243             ClusteringSupport support = graph.getSession().getService(ClusteringSupport.class);
1244             content.append("<tr><td class=\"top_key\">Identifiers</td><td class=\"top_value\">");
1245             content.append("<span id=\"resource_id\">")
1246             .append(" RID = $").append(r.getResourceId())
1247             .append(" Resource Key = ").append(ss.getTransientId(r))
1248             .append(" CID = ").append(support.getCluster(r));
1249             content.append("</span></td>");
1250             if (immutable)
1251                 content.append("<td class=\"remove\">[IMMUTABLE]</td>");
1252             content.append("</tr>\n");
1253  
1254             boolean isClusterSet = support.isClusterSet(r);
1255             Resource parentSet = support.getClusterSetOfCluster(r);
1256             String parentSetURI = parentSet != null ? graph.getPossibleURI(parentSet) : null;
1257             
1258             content.append("<tr><td class=\"top_key\">Clustering</td><td class=\"top_value\">");
1259             content.append("<span id=\"resource_id\">");
1260             
1261             if(parentSetURI != null)
1262                 content.append(" Containing cluster set = ").append(parentSetURI);
1263             else if (parentSet != null)
1264                 content.append(" Containing cluster set = ").append(parentSet.toString());
1265             else 
1266                 content.append(" Not in any cluster set ");
1267             
1268             content.append("</span></td>");
1269             if (isClusterSet)
1270                 content.append("<td class=\"remove\">[CLUSTER SET]</td>");
1271             content.append("</tr>\n");
1272             
1273             // If the resource has a value, show it.
1274             String resourceValue = getResourceValue(graph, r);
1275             if (resourceValue != null) {
1276                 content
1277                 .append("<tr><td class=\"top_key\">Attached value</td><td class=\"top_value\">")
1278                 .append(htmlEscape(resourceValue))
1279                 .append("</td></tr>\n");
1280             }
1281
1282             // Close #top
1283             content.append("</table>\n");
1284             content.append("</div>\n");
1285
1286             content.append("\n<div id=\"data\">\n");
1287             content.append("<table>\n")
1288             .append("<tr><th>Predicate</th><th>Object</th><th>Graph</th></tr>")
1289             .append("<tr><td class=\"subtitle\" colspan=\"3\">Basic information</td></tr>");
1290
1291             boolean isOrderedSet = graph.isInstanceOf(r, L0.OrderedSet);
1292             boolean isLinkedList = graph.isInstanceOf(r, L0.List);
1293 //            map.remove(r);
1294
1295             // BASIC INFORMATION:
1296             for (Resource pred :
1297                 new Resource[] {L0.HasName, L0.InstanceOf,
1298                     L0.Inherits, L0.SubrelationOf,
1299                     L0.PartOf, L0.ConsistsOf})
1300                 if (map.containsKey(pred))
1301                     updatePred(content, graph, r, pred, map.remove(pred));
1302
1303             // TAGS
1304             content.append("<tr><td class=\"subtitle\" colspan=\"3\">Tags</td></tr>");
1305             for(Statement stm : statements) {
1306                 if(stm.getSubject().equals(stm.getObject())) {
1307                     updateTag(content, graph, r, stm.getPredicate());
1308                     map.remove(stm.getPredicate());
1309                 }
1310             }
1311
1312             // ORDERED SETS
1313             content.append("<tr><td class=\"subtitle\" colspan=\"3\">Ordered Sets</td></tr>");
1314             for(Statement stm : statements) {
1315                 Resource predicate = stm.getPredicate();
1316                 if(graph.isInstanceOf(stm.getPredicate(), L0.OrderedSet)) {
1317                     updateTag(content, graph, r, stm.getPredicate());
1318                     if(map.get(stm.getPredicate()) != null && map.get(stm.getPredicate()).size() == 1)
1319                         map.remove(stm.getPredicate());
1320                 }
1321                 Resource inverse = graph.getPossibleInverse(predicate);
1322                 if (inverse != null) {
1323                     if(graph.isInstanceOf(inverse, L0.OrderedSet)) {
1324                         if(map.get(stm.getPredicate()) != null && map.get(stm.getPredicate()).size() == 1)
1325                             map.remove(stm.getPredicate());
1326                     }
1327                 } else {
1328                     // FIXME : should we infor missing inverse
1329                 }
1330             }
1331
1332             // IS RELATED TO
1333             content.append("<tr><td class=\"subtitle\" colspan=\"3\">Is Related To</td></tr>");
1334
1335             // ELEMENTS OF ORDERED SET
1336             if(isOrderedSet) {
1337                 //content.append("<tr><td class=\"subtitle\" colspan=\"2\">Ordered set</td></tr>");
1338                 try {
1339                     updateOrderedSet(content, graph, r);
1340                 } catch (ValidationException e) {
1341                     content.append("<td colspan=\"3\"><span style=\"color:red;font-weight:bold\">BROKEN ORDERED SET:<br/></span><span style=\"color:red\">").append(e.getMessage()).append("</span></td>");
1342                 }
1343             }
1344
1345             // ELEMENTS OF LINKED LIST
1346             if(isLinkedList) {
1347                 //content.append("<tr><td class=\"subtitle\" colspan=\"2\">Ordered set</td></tr>");
1348                 try {
1349                     updateLinkedList(content, graph, r);
1350                 } catch (ValidationException e) {
1351                     content.append("<td colspan=\"3\"><span style=\"color:red;font-weight:bold\">BROKEN LINKED LIST:<br/></span><span style=\"color:red\">").append(e.getMessage()).append("</span></td>");
1352                 }
1353             }
1354
1355             // IS RELATED TO (other)
1356             Resource[] preds = map.keySet().toArray(new Resource[0]);
1357             final Map<Resource, String> strmap = new HashMap<Resource, String>(preds.length);
1358             for(Resource pred : preds) {
1359                 String str = htmlEscape( getResourceName(graph, pred) );
1360                 if(str == null)
1361                     str = "<null>";
1362                 strmap.put(pred, str);
1363             }
1364             Arrays.sort(preds, new Comparator<Resource>() {
1365                 @Override
1366                 public int compare(Resource o1, Resource o2) {
1367                     return AlphanumComparator.CASE_INSENSITIVE_COMPARATOR.compare(strmap.get(o1), strmap.get(o2));
1368                 }
1369             });
1370             for(Resource pred : preds)
1371                 if(graph.isSubrelationOf(pred, L0.IsRelatedTo))
1372                     updatePred(content, graph, r, pred, map.get(pred));
1373
1374             // OTHER STATEMENTS
1375             content.append("<tr><td class=\"subtitle\" colspan=\"3\">Other statements</td></tr>");
1376             for(Resource pred : preds)
1377                 if(!graph.isSubrelationOf(pred, L0.IsRelatedTo))
1378                     updatePred(content, graph, r, pred, map.get(pred));
1379             content.append("</table>\n");
1380         }
1381         // Close #data
1382         content.append("</div>\n\n");
1383         // Close #mainContent
1384         content.append("</div>\n");
1385         content.append("</body>\n</html>\n");
1386
1387         // Update content
1388         final String finalContent = content.toString();
1389         if (!isDisposed()) {
1390             getDisplay().asyncExec(new Runnable() {
1391                 @Override
1392                 public void run() {
1393                     if (!browser.isDisposed())
1394                         browser.setText(finalContent);
1395                 }
1396             });
1397         }
1398     }
1399
1400     private String getResourceValue(ReadGraph graph, Resource r) {
1401         try {
1402             if (graph.hasValue(r)) {
1403                 // too large array may cause application to run out of memory.
1404                 //System.out.println("getValue(" + NameUtils.getSafeName(graph, r, true));
1405                 Datatype type = graph.getPossibleRelatedValue(r, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
1406                 if (type != null) {
1407                     Binding rviBinding = graph.getService(Databoard.class).getBindingUnchecked( RVI.class );
1408                     if (type.equals( rviBinding.type() )) {
1409                         RVI rvi = graph.getValue(r, rviBinding);
1410                         try {
1411                             Variable v = Variables.getConfigurationContext( graph, r );
1412                             return rvi.asString(graph, v);
1413                         } catch (DatabaseException dbe ) {
1414                             return rvi.toString( graph );
1415                         }
1416                     } else {
1417                         Binding b = Bindings.getBinding(type);
1418                         Object v = graph.getValue(r, b);
1419                         Serializer s = Bindings.getSerializerUnchecked(b);
1420                         int size = s.getSize(v);
1421                         if (size > RESOURCE_VALUE_MAX_SIZE) {
1422                             return "Approx. " + size + " byte literal of type " + type.toSingleLineString();
1423                         } else {
1424                             return b.toString(v, false);
1425                         }
1426                     }
1427                 } else {
1428                     Object o = graph.getValue(r);
1429                     return toName(o);
1430                 }
1431             }
1432             return null;
1433         } catch (DatabaseException e) {
1434             return e.getMessage();
1435         } catch (IOException e) {
1436             return e.getMessage();
1437         } catch (BindingException e) {
1438             return e.getMessage();
1439         }
1440     }
1441
1442     private static String safeReadableString(ReadGraph g, Resource r) {
1443         try {
1444             return NameUtils.getSafeName(g, r);
1445         } catch(Throwable throwable) {
1446             ErrorLogger.defaultLogError(throwable);
1447             return "<font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font>";
1448         }
1449     }
1450
1451 //    private static String safeReadableString(IEntity t) {
1452 //        try {
1453 //            return ResourceDebugUtils.getReadableNameForEntity(t);
1454 //        } catch(Throwable throwable) {
1455 //            throwable.printStackTrace();
1456 //            return "<font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font>";
1457 //        }
1458 //    }
1459
1460     private String getLinkString(Container<Resource> t) {
1461         String link = links.getLeft(t.get());
1462         if(link == null) {
1463             link = UUID.randomUUID().toString();
1464             links.map(link, t.get());
1465         }
1466         return link;
1467     }
1468
1469 //    private String getPropertyEditString(Container<Resource> t) {
1470 //        String link = links.getLeft(t.get());
1471 //        if(link == null) {
1472 //            link = UUID.randomUUID().toString();
1473 //            links.map(link, t.get());
1474 //        }
1475 //        return link;
1476 //    }
1477
1478     private String getStatementString(Resource _s, Resource _p, Resource _o) {
1479         String s = getLinkString(_s);
1480         String p = getLinkString(_p);
1481         String o = getLinkString(_o);
1482         return s + STATEMENT_PART_SEPARATOR + p + STATEMENT_PART_SEPARATOR + o;
1483     }
1484
1485 //    private String getStatementString(Statement stm) {
1486 //        String s = getLinkString(stm.getSubject());
1487 //        String p = getLinkString(stm.getPredicate());
1488 //        String o = getLinkString(stm.getObject());
1489 //        return s + STATEMENT_PART_SEPARATOR + p + STATEMENT_PART_SEPARATOR + o;
1490 //    }
1491
1492 //    private String toOutgoingTableRow(IEntity subject, Statement stm) {
1493 //        boolean isAcquired = !subject.equals(stm.getSubject());
1494 //
1495 //        String plainCell = "%s";
1496 //        String hrefCell = "<a href=\"%s\">%s</a>";
1497 //        String formatTemplate = isAcquired
1498 //                ? "<tr>\n<td class=\"acquired\">{0}</td>\n<td class=\"acquired\">{1}</td>\n<td class=\"acquired\">{1}</td>\n<td class=\"acquired\">{1}</td>\n</tr>"
1499 //                : "<tr>\n<td>{1}</td>\n<td>{1}</td>\n<td>{1}</td>\n<td>{1}</td>\n</tr>";
1500 //        String format = NLS.bind(formatTemplate, plainCell, hrefCell);
1501 ////        System.out.println("format: " + format);
1502 //
1503 //        IEntity s = stm.getSubject();
1504 //        IEntity p = stm.getPredicate();
1505 //        IEntity o = stm.getObject();
1506 //
1507 ////        String timePart = "[" + timeToString(t.getBegin()) + ", " + timeToString(t.getEnd()) + "]";
1508 //
1509 //        try {
1510 //            return !isAcquired
1511 //                ? String.format(format,
1512 //                    "about:blank-remove" + getStatementString(stm), "Remove",
1513 //                    "about:blank-link" + getLinkString(s), safeReadableString(s),
1514 //                    "about:blank-link" + getLinkString(p), safeReadableString(p),
1515 //                    "about:blank-link" + getLinkString(o), safeReadableString(o))
1516 //                : String.format(format,
1517 //                    "Acquired",
1518 //                    "about:blank-link" + getLinkString(s), safeReadableString(s),
1519 //                    "about:blank-link" + getLinkString(p), safeReadableString(p),
1520 //                    "about:blank-link" + getLinkString(o), safeReadableString(o)
1521 //            );
1522 //        } catch (Throwable throwable) {
1523 //            return "<tr><td colspan=\"4\"><font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font></td></tr>";
1524 //        }
1525 //    }
1526
1527 //    private String intervalToString(Interval time) {
1528 //        return timeToString(time.getBegin()) + ", " + timeToString(time.getEnd());
1529 //    }
1530 //
1531 //    DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
1532 //
1533 //    private String timeToString(long time) {
1534 //        if (time == Long.MIN_VALUE)
1535 //            return "-&infin;";
1536 //        if (time == Long.MAX_VALUE)
1537 //            return "+&infin;";
1538 //        //return String.valueOf(time);
1539 //        Date d = new Date(time);
1540 //        return dateTimeFormat.format(d);
1541 //    }
1542
1543     private String getHead() {
1544         String result = "";
1545         if (cssPath != null) {
1546             result = "<link href=\"" + cssPath + "\" rel=\"stylesheet\" type=\"text/css\">";
1547         }
1548         return result;
1549     }
1550
1551 }