Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ae708496ca6ee57fedef12d69992b3c0ea61756c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*******************************************************************************
 * Copyright (c) 2007, 2016 THALES GLOBAL SERVICES and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Obeo - initial API and implementation
 *******************************************************************************/
package org.eclipse.sirius.diagram.ui.business.internal.dialect;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.transaction.RunnableWithResult;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.image.ImageFileFormat;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditDomain;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.parts.DiagramDocumentEditor;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.sirius.business.api.dialect.DialectManager;
import org.eclipse.sirius.business.api.helper.SiriusResourceHelper;
import org.eclipse.sirius.business.api.query.EObjectQuery;
import org.eclipse.sirius.business.api.query.URIQuery;
import org.eclipse.sirius.business.api.session.CustomDataConstants;
import org.eclipse.sirius.business.api.session.Session;
import org.eclipse.sirius.business.api.session.SessionManager;
import org.eclipse.sirius.common.tools.DslCommonPlugin;
import org.eclipse.sirius.common.tools.api.interpreter.IInterpreterSiriusVariables;
import org.eclipse.sirius.common.tools.api.util.StringUtil;
import org.eclipse.sirius.common.ui.tools.api.util.EclipseUIUtil;
import org.eclipse.sirius.diagram.DDiagram;
import org.eclipse.sirius.diagram.DDiagramElement;
import org.eclipse.sirius.diagram.DSemanticDiagram;
import org.eclipse.sirius.diagram.DiagramPlugin;
import org.eclipse.sirius.diagram.business.api.diagramtype.DiagramTypeDescriptorRegistry;
import org.eclipse.sirius.diagram.business.api.diagramtype.IDiagramTypeDescriptor;
import org.eclipse.sirius.diagram.business.api.refresh.CanonicalSynchronizer;
import org.eclipse.sirius.diagram.business.api.refresh.CanonicalSynchronizerFactory;
import org.eclipse.sirius.diagram.description.DescriptionFactory;
import org.eclipse.sirius.diagram.description.DiagramDescription;
import org.eclipse.sirius.diagram.description.DiagramExtensionDescription;
import org.eclipse.sirius.diagram.description.Layer;
import org.eclipse.sirius.diagram.description.concern.provider.ConcernItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.description.filter.provider.FilterItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.description.provider.DescriptionItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.description.style.provider.StyleItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.description.tool.EdgeCreationDescription;
import org.eclipse.sirius.diagram.description.tool.ToolFactory;
import org.eclipse.sirius.diagram.description.tool.provider.ToolItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.provider.DiagramItemProviderAdapterFactory;
import org.eclipse.sirius.diagram.ui.business.api.view.SiriusGMFHelper;
import org.eclipse.sirius.diagram.ui.business.internal.command.CreateAndStoreGMFDiagramCommand;
import org.eclipse.sirius.diagram.ui.edit.api.part.IDDiagramEditPart;
import org.eclipse.sirius.diagram.ui.provider.DiagramUIPlugin;
import org.eclipse.sirius.diagram.ui.provider.Messages;
import org.eclipse.sirius.diagram.ui.tools.api.editor.DDiagramEditor;
import org.eclipse.sirius.diagram.ui.tools.api.part.DiagramEditPartService;
import org.eclipse.sirius.ext.base.Option;
import org.eclipse.sirius.tools.api.profiler.SiriusTasksKey;
import org.eclipse.sirius.ui.business.api.dialect.DialectEditor;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIManager;
import org.eclipse.sirius.ui.business.api.dialect.DialectUIServices;
import org.eclipse.sirius.ui.business.api.dialect.ExportFormat;
import org.eclipse.sirius.ui.business.api.dialect.ExportFormat.ExportDocumentFormat;
import org.eclipse.sirius.ui.business.api.session.SessionEditorInput;
import org.eclipse.sirius.ui.business.api.viewpoint.ViewpointSelectionCallback;
import org.eclipse.sirius.ui.business.internal.commands.ChangeViewpointSelectionCommand;
import org.eclipse.sirius.ui.business.internal.dialect.HierarchyLabelProvider;
import org.eclipse.sirius.ui.tools.api.actions.export.SizeTooLargeException;
import org.eclipse.sirius.viewpoint.DRepresentation;
import org.eclipse.sirius.viewpoint.DRepresentationElement;
import org.eclipse.sirius.viewpoint.DSemanticDecorator;
import org.eclipse.sirius.viewpoint.SiriusPlugin;
import org.eclipse.sirius.viewpoint.description.DescriptionPackage;
import org.eclipse.sirius.viewpoint.description.RepresentationDescription;
import org.eclipse.sirius.viewpoint.description.RepresentationExtensionDescription;
import org.eclipse.sirius.viewpoint.description.Viewpoint;
import org.eclipse.sirius.viewpoint.description.tool.ToolPackage;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * The default diagram ui services.
 *
 * @author cbrun
 */
public class DiagramDialectUIServices implements DialectUIServices {

    /**
     * The label used for the action which refreshes a diagram.
     */
    public static final String REFRESH_DIAGRAM = Messages.DiagramDialectUIServices_refreshDiagram;

    /**
     * {@inheritDoc}
     */
    @Override
    public IEditorPart openEditor(Session session, DRepresentation dRepresentation, IProgressMonitor monitor) {
        DialectEditor result = null;
        try {
            monitor.beginTask(Messages.DiagramDialectUIServices_diagramOpeningMonitorTaskName, 15);
            DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.OPEN_DIAGRAM_KEY);

            if (dRepresentation instanceof DSemanticDiagram) {
                final DSemanticDiagram diag = (DSemanticDiagram) dRepresentation;
                final Collection<EObject> gmfDiags = session.getServices().getCustomData(CustomDataConstants.GMF_DIAGRAMS, diag);

                if (gmfDiags.isEmpty()) {
                    /*
                     * we have our diagrams but not the gmf ones => old aird
                     * version or corrupted file
                     */
                    TransactionalEditingDomain domain = session.getTransactionalEditingDomain();
                    domain.getCommandStack().execute(new CreateAndStoreGMFDiagramCommand(session, diag));

                    gmfDiags.addAll(session.getServices().getCustomData(CustomDataConstants.GMF_DIAGRAMS, diag));
                    monitor.worked(1);
                }

                // If the current DDiagram is shared on a CDO repository and
                // some
                // needed Viewpoints are not activated (for example a
                // contributed
                // activated layer)
                Set<Viewpoint> viewpointsActivated = null;
                if (URIQuery.CDO_URI_SCHEME.equals(diag.eResource().getURI().scheme())) {
                    viewpointsActivated = activateNeededViewpoints(session, diag, monitor);
                }
                for (final EObject object : gmfDiags) {
                    final Diagram gmfDiag = (Diagram) object;
                    if (gmfDiag != null) {
                        result = openEditor(session, gmfDiag, dRepresentation, monitor);
                        new DiagramDialectArrangeOperation().arrange(result, diag);
                        monitor.worked(3);
                    }
                }
                if (viewpointsActivated != null && !viewpointsActivated.isEmpty()) {
                    informOfActivateNeededViewpoints(viewpointsActivated);
                }
            }
            DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.OPEN_DIAGRAM_KEY);
        } finally {
            monitor.done();
        }
        return result;
    }

    private DialectEditor openEditor(Session session, Diagram gmfDiag, DRepresentation dRepresentation, IProgressMonitor monitor) {
        DialectEditor dialectEditor = null;
        URI uri = EcoreUtil.getURI(gmfDiag);
        String editorName = DialectUIManager.INSTANCE.getEditorName(dRepresentation);
        monitor.worked(1);
        final IEditorInput editorInput = new SessionEditorInput(uri, editorName, session);
        monitor.subTask(MessageFormat.format(Messages.DiagramDialectUIServices_diagramEditorOpeningMonitorTaskName, dRepresentation.getName()));
        RunnableWithResult<DialectEditor> runnable = new RunnableWithResult.Impl<DialectEditor>() {

            @Override
            public void run() {
                final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                try {
                    IEditorPart editorPart = page.openEditor(editorInput, DDiagramEditor.EDITOR_ID);
                    if (editorPart instanceof DialectEditor) {
                        setResult((DialectEditor) editorPart);
                    }
                } catch (final PartInitException e) {
                    DiagramPlugin.getDefault().logError(Messages.DiagramDialectUIServices_diagramEditorOpeningError, e);
                }
            }

        };
        EclipseUIUtil.displaySyncExec(runnable);
        monitor.worked(10);
        if (runnable.getResult() != null) {
            dialectEditor = runnable.getResult();
        }
        return dialectEditor;
    }

    private Set<Viewpoint> activateNeededViewpoints(Session session, DDiagram dDiagram, IProgressMonitor monitor) {
        Set<Viewpoint> neededViewpoints = DialectManager.INSTANCE.getRequiredViewpoints(dDiagram);
        Set<Viewpoint> selectedViewpoints = new LinkedHashSet<Viewpoint>();
        for (Viewpoint viewpoint : session.getSelectedViewpoints(false)) {
            selectedViewpoints.add(SiriusResourceHelper.getCorrespondingViewpoint(session, viewpoint));
        }
        neededViewpoints.removeAll(selectedViewpoints);
        if (!neededViewpoints.isEmpty()) {
            Command changeViewpointsSelectionCmd = new ChangeViewpointSelectionCommand(session, new ViewpointSelectionCallback(), neededViewpoints, Collections.<Viewpoint> emptySet(),
                    new SubProgressMonitor(monitor, neededViewpoints.size()));
            session.getTransactionalEditingDomain().getCommandStack().execute(changeViewpointsSelectionCmd);
            monitor.worked(1);
        }
        return neededViewpoints;
    }

    private void informOfActivateNeededViewpoints(Set<Viewpoint> viewpointsActivated) {
        Iterator<Viewpoint> iterator = viewpointsActivated.iterator();
        Viewpoint neededSirius = iterator.next();
        String viewpointsName = neededSirius.getName();
        while (iterator.hasNext()) {
            neededSirius = iterator.next();
            viewpointsName += ", " + neededSirius.getName(); //$NON-NLS-1$
        }
        final String description = viewpointsName;
        EclipseUIUtil.displayAsyncExec(new Runnable() {

            @Override
            public void run() {
                MessageDialog.openInformation(PlatformUI.getWorkbench().getDisplay().getActiveShell(), Messages.DiagramDialectUIServices_requiredViewpointsDialogTitle,
                        MessageFormat.format(Messages.DiagramDialectUIServices_requiredViewpointsDialogMessage, description));
            }

        });
    }

    /**
     * Synchronizes the GMF diagram model according to the viewpoint
     * DSemanticDiagram model.
     *
     * @param diagram
     *            the GMF diagram model to synchronize.
     */
    private void synchronizeDiagram(final Diagram diagram) {
        CanonicalSynchronizer canonicalSynchronizer = CanonicalSynchronizerFactory.INSTANCE.createCanonicalSynchronizer(diagram);
        canonicalSynchronizer.storeViewsToArrange(false);
        canonicalSynchronizer.synchronize();
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#canHandleEditor(org.eclipse.ui.IEditorPart)
     */
    @Override
    public boolean canHandleEditor(final IEditorPart editorPart) {
        return editorPart instanceof DiagramDocumentEditor;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#closeEditor(org.eclipse.ui.IEditorPart,
     *      boolean)
     */
    @Override
    public boolean closeEditor(final IEditorPart editorPart, final boolean save) {
        boolean result = false;
        if (editorPart instanceof DiagramDocumentEditor) {
            try {
                DiagramEditPart diagramEditPart = ((DiagramDocumentEditor) editorPart).getDiagramEditPart();
                if (diagramEditPart != null) {
                    diagramEditPart.deactivate();
                }
            } catch (final NullPointerException e) {
                // we might have an exception closing an editor which is
                // already in trouble
                DiagramPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, DiagramPlugin.ID, Messages.DiagramDialectUIServices_diagramEditPartDeactivationError));
            }

            try {
                ((DiagramDocumentEditor) editorPart).close(save);
            } catch (final NullPointerException e) {
                // we might have an exception closing an editor which is
                // already in trouble
                DiagramUIPlugin.getPlugin().getLog().log(new Status(IStatus.WARNING, DiagramUIPlugin.ID, Messages.DiagramDialectUIServices_diagramEditorClosingError, e));
            }

            // We suppose it is closed.
            result = true;
        }
        return result;
    }

    /**
     *
     * {@inheritDoc}
     */
    @Override
    public Collection<CommandParameter> provideNewChildDescriptors() {
        final Collection<CommandParameter> newChilds = new ArrayList<CommandParameter>();
        newChilds.addAll(this.getDiagramTypesCreation());
        return newChilds;
    }

    /**
     *
     * {@inheritDoc}
     */
    @Override
    public Collection<CommandParameter> provideRepresentationCreationToolDescriptors(final Object feature) {
        final Collection<CommandParameter> newChilds = new ArrayList<CommandParameter>();
        newChilds.add(new CommandParameter(null, feature, ToolFactory.eINSTANCE.createDiagramCreationDescription()));
        return newChilds;
    }

    /**
     *
     * {@inheritDoc}
     */
    @Override
    public Collection<CommandParameter> provideRepresentationNavigationToolDescriptors(final Object feature) {
        final Collection<CommandParameter> newChilds = new ArrayList<CommandParameter>();
        newChilds.add(new CommandParameter(null, feature, ToolFactory.eINSTANCE.createDiagramNavigationDescription()));
        return newChilds;
    }

    /**
     *
     * {@inheritDoc}
     */
    @Override
    public AdapterFactory createAdapterFactory() {
        final ComposedAdapterFactory factory = new ComposedAdapterFactory();
        for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) {
            AdapterFactory aFactory = diagramTypeDescriptor.getDiagramDescriptionProvider().getAdapterFactory();
            if (aFactory != null) {
                factory.addAdapterFactory(aFactory);
            }
        }
        factory.addAdapterFactory(new DescriptionItemProviderAdapterFactory());
        factory.addAdapterFactory(new DiagramItemProviderAdapterFactory());
        factory.addAdapterFactory(new StyleItemProviderAdapterFactory());
        factory.addAdapterFactory(new ToolItemProviderAdapterFactory());
        factory.addAdapterFactory(new FilterItemProviderAdapterFactory());
        factory.addAdapterFactory(new ConcernItemProviderAdapterFactory());
        return factory;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#isRepresentationManagedByEditor(org.eclipse.sirius.viewpoint.DRepresentation,
     *      org.eclipse.ui.IEditorPart)
     */
    @Override
    public boolean isRepresentationManagedByEditor(final DRepresentation representation, final IEditorPart editorPart) {
        boolean isRepresentationManagedByEditor = false;
        if (editorPart instanceof DiagramDocumentEditor) {
            final DiagramDocumentEditor diagramDocumentEditor = (DiagramDocumentEditor) editorPart;
            DiagramEditPart diagramEditPart = diagramDocumentEditor.getDiagramEditPart();
            if (diagramEditPart instanceof IDDiagramEditPart) {
                IDDiagramEditPart idDiagramEditPart = (IDDiagramEditPart) diagramEditPart;
                if (idDiagramEditPart.resolveSemanticElement().equals(representation)) {
                    isRepresentationManagedByEditor = true;
                }
            }
        }
        return isRepresentationManagedByEditor;
    }

    // FXIME unit test this
    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#isRepresentationDescriptionManagedByEditor(org.eclipse.sirius.viewpoint.description.RepresentationDescription,
     *      org.eclipse.ui.IEditorPart)
     */
    @Override
    public boolean isRepresentationDescriptionManagedByEditor(final RepresentationDescription representationDescription, final IEditorPart editor) {
        if (editor instanceof DiagramDocumentEditor) {
            final DiagramDocumentEditor diagramDocumentEditor = (DiagramDocumentEditor) editor;
            final EObject element = diagramDocumentEditor.getDiagram().getElement();
            if (element instanceof DSemanticDiagram) {
                final DSemanticDiagram dSemanticDiagram = (DSemanticDiagram) element;
                final DiagramDescription description = dSemanticDiagram.getDescription();
                return EcoreUtil.equals(description, representationDescription);
            }
        }
        return false;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#canHandle(org.eclipse.sirius.viewpoint.DRepresentation)
     */
    @Override
    public boolean canHandle(final DRepresentation representation) {
        return representation instanceof DSemanticDiagram;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#canHandle(org.eclipse.sirius.viewpoint.description.RepresentationDescription)
     */
    @Override
    public boolean canHandle(final RepresentationDescription description) {
        return description instanceof DiagramDescription;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#canHandle(org.eclipse.sirius.viewpoint.description.RepresentationExtensionDescription)
     *      )
     */
    @Override
    public boolean canHandle(final RepresentationExtensionDescription description) {
        return description instanceof DiagramExtensionDescription;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean canExport(ExportFormat format) {
        if (format.getDocumentFormat().equals(ExportDocumentFormat.NONE) || (format.getDocumentFormat().equals(ExportDocumentFormat.HTML) && DiagramEditPartService.canExportToHtml())) {
            return true;
        }
        return false;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#export(org.eclipse.sirius.viewpoint.DRepresentation,
     *      org.eclipse.sirius.business.api.session.Session)
     */
    @Override
    public void export(final DRepresentation representation, final Session session, final IPath path, final ExportFormat format, final IProgressMonitor monitor) throws SizeTooLargeException {

        final boolean exportToHtml = exportToHtml(format);
        final String imageFileExtension = getImageFileExtension(format);
        final IPath correctPath = getRealPath(path, exportToHtml);

        final Shell shell = new Shell();
        try {

            final Collection<EObject> data = session.getServices().getCustomData(CustomDataConstants.GMF_DIAGRAMS, representation);
            for (final EObject dataElement : data) {
                if (dataElement instanceof Diagram) {
                    final Diagram diagram = (Diagram) dataElement;
                    synchronizeDiagram(diagram);

                    final DiagramEditPartService tool = new DiagramEditPartService();
                    if (exportToHtml) {
                        tool.exportToHtml();
                    }
                    final DiagramEditPart diagramEditPart = tool.createDiagramEditPart(diagram, shell, PreferencesHint.USE_DEFAULTS);

                    try {

                        /* refresh to avoid blank images */
                        diagramEditPart.getRoot().refresh();

                        /* validate to have all nodes in the right position */
                        diagramEditPart.getFigure().validate();
                        /*
                         * In the case of connection on EditParts created during
                         * first Refresh they will not appear until we refresh a
                         * second time Example of such cases are exchanges on
                         * DFI (mch)
                         */
                        diagramEditPart.getRoot().refresh();
                        /*
                         * flush the viewer to have all connections and ports
                         */
                        diagramEditPart.getRoot().getViewer().flush();

                        /* do the effective export */
                        tool.copyToImage(diagramEditPart, correctPath, ImageFileFormat.resolveImageFormat(imageFileExtension), monitor);

                        // We finally ensure that the image has been created
                        if (!new File(correctPath.toOSString()).exists()) {
                            throw new CoreException(new Status(IStatus.ERROR, SiriusPlugin.ID, MessageFormat.format(Messages.DiagramDialectUIServices_exportedDiagramImageCreationError, correctPath)));
                        }
                    } catch (final CoreException exception) {
                        if (exception instanceof SizeTooLargeException) {
                            throw (SizeTooLargeException) exception;
                        }
                        SiriusPlugin.getDefault().error(MessageFormat.format(Messages.DiagramDialectUIServices_exportedDiagramImageCreationError, correctPath), exception);
                    } finally {
                        diagramEditPart.deactivate();
                        // Memory leak : also disposing the
                        // DiagramGraphicalViewer associated to this
                        // DiagramEditPart
                        diagramEditPart.getViewer().flush();
                        diagramEditPart.getViewer().getEditDomain().getCommandStack().flush();
                        diagramEditPart.getViewer().getControl().dispose();
                        ((DiagramEditDomain) diagramEditPart.getViewer().getEditDomain()).removeViewer(diagramEditPart.getViewer());
                    }
                }
            }

        } finally {
            disposeShell(shell);
        }
    }

    private void disposeShell(final Shell shell) {
        Display.getCurrent().asyncExec(new Runnable() {
            @Override
            public void run() {
                shell.dispose();
            }
        });
    }

    private boolean exportToHtml(final ExportFormat format) {
        return format.getDocumentFormat().equals(ExportDocumentFormat.HTML);
    }

    private String getImageFileExtension(final ExportFormat format) {
        return format.getImageFormat().getName();
    }

    private IPath getRealPath(final IPath path, final boolean exportToHtml) {
        if (exportToHtml) {
            return path.removeFileExtension().addFileExtension("html"); //$NON-NLS-1$
        } else {
            return path;
        }
    }

    /**
     * Returns command parameters to create diagram type description.
     *
     * @return command parameters to create diagram type description.
     */
    private Collection<CommandParameter> getDiagramTypesCreation() {
        final Collection<CommandParameter> result = new HashSet<CommandParameter>();
        for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) {
            DiagramDescription specificDiagramDescription = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription();
            specificDiagramDescription.setEnablePopupBars(true);
            if (specificDiagramDescription.getDefaultLayer() == null) {
                Layer layer = DescriptionFactory.eINSTANCE.createLayer();
                layer.setName(Messages.DefaultLayerName);
                specificDiagramDescription.setDefaultLayer(layer);
            }
            final CommandParameter typeCommandParameter = new CommandParameter(null, DescriptionPackage.Literals.VIEWPOINT__OWNED_REPRESENTATIONS, specificDiagramDescription);
            result.add(typeCommandParameter);
        }
        return result;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#getEditorName(org.eclipse.sirius.viewpoint.DRepresentation)
     */
    @Override
    public String getEditorName(final DRepresentation representation) {
        String editorName = representation.getName();
        if (StringUtil.isEmpty(editorName)) {
            editorName = Messages.DiagramDialectUIServices_representationWithEmptyNameEditorName;
        }
        return editorName;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<CommandParameter> provideTools(EObject context) {
        Collection<CommandParameter> toolsParameters = Lists.newArrayList();
        for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) {
            DiagramDescription diagramType = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription();
            if (hasParentOfType(context, diagramType.eClass())) {
                toolsParameters.addAll(diagramTypeDescriptor.getDiagramDescriptionProvider().collectToolCommands(context));
            }
        }
        return toolsParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<CommandParameter> provideAdditionalMappings(EObject context) {
        Collection<CommandParameter> mappings = Lists.newArrayList();
        for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) {
            DiagramDescription diagramType = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription();
            if (hasParentOfType(context, diagramType.eClass())) {
                mappings.addAll(diagramTypeDescriptor.getDiagramDescriptionProvider().collectMappingsCommands());
            }
        }
        return mappings;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#getHierarchyLabelProvider(ILabelProvider)
     *
     */
    @Override
    public ILabelProvider getHierarchyLabelProvider(ILabelProvider currentLabelProvider) {
        return new HierarchyLabelProvider(currentLabelProvider);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setSelection(DialectEditor dialectEditor, List<DRepresentationElement> selection) {
        setSelection(dialectEditor, selection, false);
    }

    @Override
    public void selectAndReveal(DialectEditor dialectEditor, List<DRepresentationElement> selection) {
        setSelection(dialectEditor, selection, true);

    }

    private void setSelection(DialectEditor dialectEditor, List<DRepresentationElement> selection, boolean reveal) {
        if (dialectEditor instanceof DiagramEditor && selection != null) {
            DiagramEditor diagramEditor = (DiagramEditor) dialectEditor;
            List<EditPart> selectedParts = Lists.newArrayList();
            final EditPartViewer graphicalViewer = diagramEditor.getDiagramGraphicalViewer();

            Iterable<DDiagramElement> ddeSelection = Iterables.filter(selection, DDiagramElement.class);
            if (!Iterables.isEmpty(ddeSelection) && graphicalViewer != null) {
                Session session = SessionManager.INSTANCE.getSession(ddeSelection.iterator().next().getTarget());
                for (DDiagramElement dRepresentationElement : ddeSelection) {
                    EditPart selectedEditPart = getEditPart(dRepresentationElement, graphicalViewer, session);
                    if (selectedEditPart != null && selectedEditPart.isSelectable()) {
                        selectedParts.add(selectedEditPart);
                    }
                }
            }
            if (graphicalViewer != null) {
                graphicalViewer.setSelection(new StructuredSelection(selectedParts));
                if (reveal && !selectedParts.isEmpty()) {
                    graphicalViewer.reveal(selectedParts.get(0));
                }
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#getSelection(org.eclipse.sirius.ui.business.api.dialect.DialectEditor)
     */
    @Override
    public Collection<DSemanticDecorator> getSelection(DialectEditor editor) {
        Collection<DSemanticDecorator> selection = Sets.newLinkedHashSet();
        if (editor instanceof DiagramEditor) {
            DiagramEditor dEditor = (DiagramEditor) editor;
            IDiagramGraphicalViewer graphicalViewer = dEditor.getDiagramGraphicalViewer();

            if (graphicalViewer != null) {
                for (IGraphicalEditPart ep : Iterables.filter(graphicalViewer.getSelectedEditParts(), IGraphicalEditPart.class)) {
                    View view = ep.getNotationView();
                    if (view != null && view.getElement() instanceof DSemanticDecorator) {
                        selection.add((DSemanticDecorator) view.getElement());
                    }
                }
            }
        }
        return selection;
    }

    /**
     * Get the editPart corresponding to this diagram element.<BR>
     * The editPart is search in the active editor.
     *
     * @param diagramElement
     *            the diagram element
     * @param graphicalViewer
     *            the editor containing the editPart
     * @param session
     *            the current session
     *
     * @return the editPart corresponding to the diagram element given as
     *         parameter or null if any
     */
    protected IGraphicalEditPart getEditPart(final DDiagramElement diagramElement, final EditPartViewer graphicalViewer, Session session) {
        IGraphicalEditPart result = null;
        final View gmfView = SiriusGMFHelper.getGmfView(diagramElement, session);
        final Map<?, ?> editPartRegistry = graphicalViewer.getEditPartRegistry();
        if (editPartRegistry != null) {
            final Object editPart = editPartRegistry.get(gmfView);
            if (editPart instanceof IGraphicalEditPart) {
                result = (IGraphicalEditPart) editPart;
            }
        }
        return result;
    }

    private boolean hasParentOfType(EObject element, EClass eClass) {
        EObject context = element;
        boolean found = context.eClass() == eClass;
        while (!found && context != null) {
            found = context.eClass() == eClass;
            context = context.eContainer();
        }
        return found;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#completeToolTipText(String,
     *      EObject, EStructuralFeature)
     */
    @Override
    public String completeToolTipText(String toolTipText, EObject eObject, EStructuralFeature feature) {
        String toolTip = toolTipText;
        if (eObject instanceof EdgeCreationDescription) {
            if (feature != null && feature.equals(ToolPackage.Literals.ABSTRACT_TOOL_DESCRIPTION__PRECONDITION)) {
                StringBuilder sb = new StringBuilder();
                sb.append(toolTipText);
                sb.append(MessageFormat.format(Messages.DiagramDialectUIServices_sourceViewPreDescription, IInterpreterSiriusVariables.SOURCE_VIEW_PRE));
                sb.append(MessageFormat.format(Messages.DiagramDialectUIServices_sourcePreDescription, IInterpreterSiriusVariables.SOURCE_PRE));
                sb.append(MessageFormat.format(Messages.DiagramDialectUIServices_targetViewPreDescription, IInterpreterSiriusVariables.TARGET_VIEW_PRE));
                sb.append(MessageFormat.format(Messages.DiagramDialectUIServices_targetPreDescription, IInterpreterSiriusVariables.TARGET_PRE));
                sb.append(MessageFormat.format(Messages.DiagramDialectUIServices_diagramDescription, IInterpreterSiriusVariables.DIAGRAM));
                toolTip = sb.toString();
            }
        }
        EPackage parentPackage = null;
        Option<EObject> parentDiagramDescription = new EObjectQuery(eObject).getFirstAncestorOfType(org.eclipse.sirius.diagram.description.DescriptionPackage.eINSTANCE.getDiagramDescription());
        if (parentDiagramDescription.some()) {
            parentPackage = parentDiagramDescription.get().eClass().getEPackage();
        } else {
            Option<EObject> parentDiagramExtensionDescription = new EObjectQuery(eObject)
                    .getFirstAncestorOfType(org.eclipse.sirius.diagram.description.DescriptionPackage.eINSTANCE.getDiagramExtensionDescription());
            if (parentDiagramExtensionDescription.some()) {
                parentPackage = parentDiagramExtensionDescription.get().eClass().getEPackage();
            }
        }

        if (parentPackage != null) {
            for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) {
                if (diagramTypeDescriptor.getDiagramDescriptionProvider().handles(parentPackage)) {
                    toolTip = diagramTypeDescriptor.getDiagramDescriptionProvider().completeToolTipText(toolTip, eObject, feature);
                }
            }
        }
        return toolTip;
    }

    /**
     * {@inheritDoc}
     *
     * @see org.eclipse.sirius.ui.business.api.dialect.DialectUIServices#completeToolTipText(String,
     *      EObject)
     * @deprecated this method has not access to the feature of eObject. This is
     *             supported in
     *             org.eclipse.sirius.diagram.ui.business.internal.dialect
     *             .DiagramDialectUIServices.completeToolTipText(String,
     *             EObject, EStructuralFeature)
     */
    @Deprecated
    @Override
    public String completeToolTipText(String toolTipText, EObject eObject) {
        return completeToolTipText(toolTipText, eObject, null);
    }

}

Back to the top