Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c7e697c165e4e593ce6a2e2973373423dbd457fc (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
/**
 * Copyright (c) 2012 Eclipse contributors and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v20.html
 */
package org.eclipse.emf.common.ui.viewer;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import org.eclipse.emf.common.ui.CommonUIPlugin;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.internal.text.InformationControlReplacer;
import org.eclipse.jface.internal.text.html.BrowserInformationControl;
import org.eclipse.jface.internal.text.html.BrowserInformationControlInput;
import org.eclipse.jface.internal.text.html.HTMLPrinter;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.AbstractHoverInformationControlManager;
import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IInformationControlExtension;
import org.eclipse.jface.text.IInformationControlExtension2;
import org.eclipse.jface.text.IInformationControlExtension3;
import org.eclipse.jface.text.IInformationControlExtension4;
import org.eclipse.jface.text.IInformationControlExtension5;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.viewers.ViewerRow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;


/**
 * A utility class for showing rich JDT-style HTML content in tool tip hovers.
 * This class is final to avoid long term API commitments.
 * If you feel the need to specialize it, please open a bugzilla to explain what your use case and requirements.
 *
 * @since 2.9
 */
@SuppressWarnings("restriction")
public final class ColumnViewerInformationControlToolTipSupport
{
  /**
   * The default font used within the hovers.
   * It will be the same as JDT's Javadoc font, if available, or the default {@link JFaceResources#DIALOG_FONT dialog} otherwise.
   */
  protected static final String DEFAULT_FONT = JFaceResources.getFontRegistry().hasValueFor("org.eclipse.jdt.ui.javadocfont") ? "org.eclipse.jdt.ui.javadocfont" : JFaceResources.DIALOG_FONT;

  /**
   * A listener that's "path URI" aware.
   * I.e., a URI of the form "path:{/<index>}+" will be interpreted to
   * {@link StructuredViewer#setSelection(org.eclipse.jface.viewers.ISelection, boolean) select} and reveal the {@link StructuredViewer}'s content tree's corresponding object.
   */
  public static class PathLocationListener implements LocationListener
  {
    protected StructuredViewer viewer;

    public PathLocationListener(StructuredViewer viewer)
    {
      this.viewer = viewer;
    }

    public URI getURI(Object object)
    {
      IContentProvider contentProvider = viewer.getContentProvider();
      if (contentProvider instanceof IStructuredContentProvider)
      {
        IStructuredContentProvider structuredContentProvider = (IStructuredContentProvider)contentProvider;
        List<Object> elements = Arrays.asList(structuredContentProvider.getElements(viewer.getInput()));
        if (structuredContentProvider instanceof ITreeContentProvider)
        {
          return traverse(elements, (ITreeContentProvider)structuredContentProvider, object);
        }
        else
        {
          int index = elements.indexOf(object);
          if (index != -1)
          {
            return URI.createURI("path:/" + index);
          }
        }
      }
      return null;
    }

    protected URI traverse(List<Object> elements, ITreeContentProvider treeContentProvider, Object object)
    {
      int index = elements.indexOf(object);
      if (index != -1)
      {
        return URI.createURI("path:/" + index);
      }
      Object parent = treeContentProvider.getParent(object);
      if (parent != null)
      {
        URI uri = traverse(elements, treeContentProvider, parent);
        if (uri != null)
        {
          List<Object> children = Arrays.asList(treeContentProvider.getChildren(parent));
          index = children.indexOf(object);
          if (index != -1)
          {
            return uri.appendSegment(Integer.toString(index));
          }
        }
      }
      return null;
    }

    public void changing(LocationEvent event)
    {
      URI uri = URI.createURI(event.location);
      if ("path".equals(uri.scheme()))
      {
        IContentProvider contentProvider = viewer.getContentProvider();
        if (contentProvider instanceof IStructuredContentProvider)
        {
          IStructuredContentProvider structuredContentProvider = (IStructuredContentProvider)contentProvider;
          traverse(structuredContentProvider, uri.segments(), 0);
        }
        event.doit = false;
      }
    }

    protected void traverse(IStructuredContentProvider structuredContentProvider, String[] segments, int index)
    {
      Object[] elements = structuredContentProvider.getElements(viewer.getInput());
      int i = Integer.parseInt(segments[index++]);
      Object object = elements[i];
      if (index != segments.length && structuredContentProvider instanceof ITreeContentProvider)
      {
        ITreeContentProvider treeContentProvider = (ITreeContentProvider)structuredContentProvider;
        traverse(treeContentProvider, object, segments, index);
      }
      else
      {
        setSelection(object);
      }
    }

    protected void traverse(ITreeContentProvider treeContentProvider, Object object, String[] segments, int index)
    {
      Object[] children = treeContentProvider.getChildren(object);
      int i = Integer.parseInt(segments[index++]);
      Object child = children[i];
      if (index != segments.length)
      {
        traverse(treeContentProvider, child, segments, index);
      }
      else
      {
        setSelection(child);
      }
    }

    protected void setSelection(Object object)
    {
      viewer.setSelection(new StructuredSelection(object), true);
      viewer.getControl().setFocus();
    }

    public void changed(LocationEvent event)
    {
      // Ignore.
    }
  }

  static protected String defaultStyleSheet;

  protected ColumnViewer viewer;
  protected Control control;
  protected LocationListener locationListener;
  protected ViewerCell currentCell;
  protected String text;
  protected Font font;
  protected Color backgroundColor;
  protected Color foregroundColor;

  /**
   * An interface that provides access to the underlying control so that we're able give it focus.
   */
  public interface AccessibleInformationControl extends IInformationControl, IInformationControlExtension, IInformationControlExtension2, IInformationControlExtension3, IInformationControlExtension4, IInformationControlExtension5
  {
    public Control getControl();
  }

  protected AbstractReusableInformationControlCreator replacementInformationControlCreator =
    new AbstractReusableInformationControlCreator()
    {
      @Override
      protected IInformationControl doCreateInformationControl(Shell parent)
      {
        IInformationControl informationControl;
        if (BrowserInformationControl.isAvailable(parent))
        {
          BrowserInformationControl browserInformationControl = new BrowserInformationControl(parent, getSymbolicFont(), true);
          browserInformationControl.addLocationListener(locationListener);
          informationControl = browserInformationControl;
        }
        else
        {
          informationControl = new DefaultInformationControl(parent, (ToolBarManager)null);
        }

        if (foregroundColor != null)
        {
          informationControl.setForegroundColor(foregroundColor);
        }
        if (backgroundColor != null)
        {
          informationControl.setBackgroundColor(backgroundColor);
        }

        return informationControl;
      }
    };

   protected AbstractReusableInformationControlCreator reusableInformationControlCreator =
     new AbstractReusableInformationControlCreator()
     {
       @Override
       protected IInformationControl doCreateInformationControl(Shell parent)
       {
         IInformationControl informationControl;
         if (BrowserInformationControl.isAvailable(parent))
         {
           class AccessibleBrowserInformationControl extends BrowserInformationControl implements AccessibleInformationControl
           {
             public AccessibleBrowserInformationControl(Shell parent, String symbolicFontName, String statusFieldText)
             {
               super(parent, symbolicFontName, statusFieldText);
             }

             @Override
             public IInformationControlCreator getInformationPresenterControlCreator()
             {
               return replacementInformationControlCreator;
             }

             public Control getControl()
             {
               return getShell();
             }
           }
           AccessibleBrowserInformationControl accessibleBrowserInformationControl = new AccessibleBrowserInformationControl(parent,  getSymbolicFont(), CommonUIPlugin.INSTANCE.getString("_UI_PressF2ForFocus_label"));
           informationControl = accessibleBrowserInformationControl;
         }
         else
         {
           class AccessibleDefaultInformationControl extends DefaultInformationControl implements AccessibleInformationControl
           {
             public AccessibleDefaultInformationControl(Shell parent, String statusFieldText)
             {
               super(parent, statusFieldText);
             }

             public void setInput(Object input)
             {
               if (input instanceof BrowserInformationControlInput)
               {
                 setInformation(((BrowserInformationControlInput)input).getHtml());
               }
               else
               {
                 setInformation((String)input);
               }
             }

             public Control getControl()
             {
               return getShell();
             }
           }
           informationControl = new AccessibleDefaultInformationControl(parent, CommonUIPlugin.INSTANCE.getString("_UI_PressF2ForFocus_label"));
         }

         if (foregroundColor != null)
         {
           informationControl.setForegroundColor(foregroundColor);
         }
         if (backgroundColor != null)
         {
           informationControl.setBackgroundColor(backgroundColor);
         }

         return informationControl;
       }
     };

  protected AbstractHoverInformationControlManager hoverInformationControlManager =
    new AbstractHoverInformationControlManager(reusableInformationControlCreator)
    {
      protected IInformationControlCloser closer;
      protected InformationControlReplacer replacer;

      {
        replacer =
          new InformationControlReplacer(replacementInformationControlCreator)
          {
            {
              this.setCloser(new Closer());
            }

            class Closer implements IInformationControlCloser, ControlListener, MouseListener, KeyListener, FocusListener, Listener
            {
              protected boolean isActive;
              protected Display display;
              protected Control subjectControl;
              protected IInformationControl informationControl;

              public void setSubjectControl(Control control)
              {
                subjectControl = control;
              }

              public void setInformationControl(IInformationControl control)
              {
                this.informationControl = control;
              }

              public void start(Rectangle informationArea)
              {
                if (!isActive)
                {
                  isActive = true;

                  if (subjectControl != null && !subjectControl.isDisposed())
                  {
                    subjectControl.addControlListener(this);
                    subjectControl.addMouseListener(this);
                    subjectControl.addKeyListener(this);
                  }

                  if (informationControl != null)
                  {
                    informationControl.addFocusListener(this);
                  }

                  display = subjectControl.getDisplay();
                  if (!display.isDisposed())
                  {
                    display.addFilter(SWT.MouseMove, this);
                    display.addFilter(SWT.FocusOut, this);
                  }
                }
              }

              public void stop()
              {
                if (isActive)
                {
                  isActive = false;

                  if (subjectControl != null && !subjectControl.isDisposed())
                  {
                    subjectControl.removeControlListener(this);
                    subjectControl.removeMouseListener(this);
                    subjectControl.removeKeyListener(this);
                  }

                  if (informationControl != null)
                  {
                    informationControl.removeFocusListener(this);
                  }

                  if (display != null && !display.isDisposed())
                  {
                    display.removeFilter(SWT.MouseMove, this);
                    display.removeFilter(SWT.FocusOut, this);
                  }
                  display = null;
                }
              }

              public void controlResized(ControlEvent event)
              {
                hideInformationControl();
              }

              public void controlMoved(ControlEvent event)
              {
                hideInformationControl();
              }

              public void mouseDown(MouseEvent event)
              {
                hideInformationControl();
              }

              public void mouseUp(MouseEvent event)
              {
                // Ignore.
              }

              public void mouseDoubleClick(MouseEvent event)
              {
                hideInformationControl();
              }

              public void keyPressed(KeyEvent event)
              {
                hideInformationControl();
              }

              public void keyReleased(KeyEvent event)
              {
                // Ignore.
              }

              public void focusGained(FocusEvent event)
              {
                // Ignore.
              }

              public void focusLost(FocusEvent event)
              {
                if (display != null && !display.isDisposed())
                {
                  display.asyncExec
                    (new Runnable()
                     {
                       public void run()
                       {
                         hideInformationControl();
                       }
                     });
                }
              }

              public void handleEvent(Event event)
              {
                if (event.type == SWT.MouseMove)
                {
                  if (event.widget instanceof Control && event.widget.isDisposed())
                  {
                    if (informationControl != null && !informationControl.isFocusControl() && informationControl instanceof IInformationControlExtension3)
                    {
                      Rectangle controlBounds =  ((IInformationControlExtension3)informationControl).getBounds();
                      if (controlBounds != null)
                      {
                        Point mouseLocation = event.display.map((Control)event.widget, null, event.x, event.y);
                        if (!controlBounds.contains(mouseLocation))
                        {
                          hideInformationControl();
                        }
                      }
                    }
                    else
                    {
                      if (display != null && !display.isDisposed())
                      {
                        display.removeFilter(SWT.MouseMove, this);
                      }
                    }
                  }
                }
                else if (event.type == SWT.FocusOut)
                {
                  if (informationControl != null && !informationControl.isFocusControl())
                  {
                    hideInformationControl();
                  }
                }
              }
            }
          };

        getInternalAccessor().setInformationControlReplacer(replacer);
      }

      @Override
      protected void setCloser(IInformationControlCloser closer)
      {
        this.closer = closer;
        super.setCloser(closer);
      }

      @Override
      protected boolean canClearDataOnHide()
      {
        return false;
      }

      @Override
      @SuppressWarnings("deprecation")
      protected void computeInformation()
      {
        MouseEvent hoverEvent = getHoverEvent();
        Event event = new Event();
        event.x = hoverEvent.x;
        event.y = hoverEvent.y;
        if (shouldCreateToolTip(event))
        {
          StringBuffer buffer = new StringBuffer(text);
          String styleSheet = getStyleSheet();
          FontData fontData = JFaceResources.getFontRegistry().getFontData(getSymbolicFont())[0];
          styleSheet = HTMLPrinter.convertTopLevelFont(styleSheet, fontData);
          HTMLPrinter.insertPageProlog(buffer, 0, foregroundColor == null ? null : foregroundColor.getRGB(), backgroundColor == null ? null : backgroundColor.getRGB(), styleSheet);
          HTMLPrinter.addPageEpilog(buffer);
          final String html = buffer.toString();

          setInformation
            (new BrowserInformationControlInput(null)
             {
               @Override
               public String getHtml()
               {
                 return html;
               }

               @Override
               public String getInputName()
               {
                 return "";
               }

               @Override
               public Object getInputElement()
               {
                 return text;
               }
             },
             currentCell.getBounds());

          currentCell = null;
        }
        else
        {
          setInformation(null, null);
        }
      }

      protected KeyListener keyListener =
        new KeyListener()
        {
          public void keyReleased(KeyEvent event)
          {
            if (event.keyCode == SWT.F2)
            {
              IInformationControl informationControl = getInformationControl();
              if (informationControl instanceof AccessibleInformationControl)
              {
                Control myControl = ((AccessibleInformationControl)informationControl).getControl();
                Event mouseEvent = new Event();
                mouseEvent.display = control.getDisplay();
                mouseEvent.widget = myControl;
                mouseEvent.type = SWT.MouseUp;
                ((Listener)closer).handleEvent(mouseEvent);
                event.doit = false;
              }
            }
          }

          public void keyPressed(KeyEvent event)
          {
            // Ignore.
          }
        };

      @Override
      public void install(Control subjectControl)
      {
        Control oldSubjectControl = getSubjectControl();

        if (oldSubjectControl != null && !oldSubjectControl.isDisposed())
        {
          oldSubjectControl.removeKeyListener(keyListener);
        }

        if (subjectControl != null)
        {
          subjectControl.addKeyListener(keyListener);
        }

        super.install(subjectControl);
        getInternalAccessor().getInformationControlReplacer().install(subjectControl);
      }

      @Override
      public void dispose()
      {
        Control subjectControl = getSubjectControl();
        if (subjectControl != null && !subjectControl.isDisposed())
        {
          subjectControl.removeKeyListener(keyListener);
        }
        replacer.dispose();
        super.dispose();
      }
    };

  public ColumnViewerInformationControlToolTipSupport(ColumnViewer viewer, LocationListener locationListener)
  {
    this.viewer = viewer;
    this.control = viewer.getControl();
    this.locationListener = locationListener == null ? new PathLocationListener(viewer) : locationListener;
    hoverInformationControlManager.install(control);
  }

  protected String getSymbolicFont()
  {
    if (font == null)
    {
      return DEFAULT_FONT;
    }
    else
    {
      FontData[] fontData = font.getFontData();
      FontRegistry fontRegistry = JFaceResources.getFontRegistry();
      for (Object name : fontRegistry.getKeySet())
      {
        FontData[] registerFontData = fontRegistry.getFontData((String)name);
        if (Arrays.equals(fontData, registerFontData))
        {
          return (String)name;
        }
      }
      return DEFAULT_FONT;
    }
  }

  public void showInformation()
  {
    hoverInformationControlManager.showInformation();
  }

  public String getStyleSheet()
  {
    if (defaultStyleSheet == null)
    {
      URL styleSheetURL = CommonUIPlugin.getPlugin().getBundle().getEntry("EMFCommonUIHoverStyleSheet.css");
      if (styleSheetURL != null)
      {
        BufferedReader reader = null;
        try
        {
          reader = new BufferedReader(new InputStreamReader(styleSheetURL.openStream()));
          StringBuffer buffer = new StringBuffer(1500);
          String line = reader.readLine();
          while (line != null)
          {
            buffer.append(line);
            buffer.append('\n');
            line = reader.readLine();
          }
          defaultStyleSheet = buffer.toString();
        }
        catch (IOException ex)
        {
          return "";
        }
        finally
        {
          try
          {
            if (reader != null)
              reader.close();
          }
          catch (IOException exception)
          {
            // Ignore
          }
        }
      }
    }
    return defaultStyleSheet;
  }

  protected void toolTipShow(Shell tip, Event event)
  {
    if (!tip.isDisposed())
    {
      currentCell = getToolTipArea(event);
      tip.setVisible(true);
    }
  }

  protected ViewerCell getToolTipArea(Event event)
  {
    return viewer.getCell(new Point(event.x, event.y));
  }

  protected boolean shouldCreateToolTip(Event event)
  {
    ViewerCell cell = getToolTipArea(event);
    if (cell != null && !cell.equals(currentCell))
    {
      control.setToolTipText("");
      currentCell = cell;
      ViewerRow row = cell.getViewerRow();
      if (row != null)
      {
        Object element = row.getItem().getData();
        CellLabelProvider labelProvider = viewer.getLabelProvider(cell.getColumnIndex());
        text = labelProvider.getToolTipText(element);
        boolean useNative = labelProvider.useNativeToolTip(element);
        if (useNative || text == null)
        {
          control.setToolTipText(text);
        }
        else
        {
          foregroundColor = labelProvider.getToolTipForegroundColor(element);
          backgroundColor = labelProvider.getToolTipBackgroundColor(element);
          font = labelProvider.getToolTipFont(element);
          return text != null;
        }
      }
    }
    else
    {
      currentCell = cell;
    }

    return false;
  }

  public void dispose()
  {
    hoverInformationControlManager.dispose();
  }
}

Back to the top