Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2c2299c1f5b926d37b9d92677f923c2e4b5c0cae (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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/*******************************************************************************
 * Copyright (c) 2006, 2007 Wind River Systems, Inc. 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:
 *    Markus Schorn - initial API and implementation
 *    Ed Swartz (Nokia)
 *******************************************************************************/ 

package org.eclipse.cdt.internal.ui.includebrowser;

import java.util.ArrayList;
import java.util.Arrays;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
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.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.actions.OpenFileAction;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexFileLocation;
import org.eclipse.cdt.core.index.IndexLocationFactory;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.ui.CUIPlugin;

import org.eclipse.cdt.internal.ui.CPluginImages;
import org.eclipse.cdt.internal.ui.navigator.OpenCElementAction;
import org.eclipse.cdt.internal.ui.util.Messages;
import org.eclipse.cdt.internal.ui.viewsupport.EditorOpener;
import org.eclipse.cdt.internal.ui.viewsupport.ExtendedTreeViewer;
import org.eclipse.cdt.internal.ui.viewsupport.IndexUI;
import org.eclipse.cdt.internal.ui.viewsupport.TreeNavigator;
import org.eclipse.cdt.internal.ui.viewsupport.WorkingSetFilterUI;

/**
 * The view part for the include browser.
 */
public class IBViewPart extends ViewPart 
        implements IShowInSource, IShowInTarget, IShowInTargetList {

	private static final int MAX_HISTORY_SIZE = 10;
    private static final String TRUE = String.valueOf(true);
    private static final String KEY_WORKING_SET_FILTER = "workingSetFilter"; //$NON-NLS-1$
    private static final String KEY_FILTER_SYSTEM = "systemFilter"; //$NON-NLS-1$
    private static final String KEY_FILTER_INACTIVE = "inactiveFilter"; //$NON-NLS-1$
    private static final String KEY_INPUT_PATH= "inputPath"; //$NON-NLS-1$
    
    private IMemento fMemento;
    private boolean fShowsMessage;
    private IBNode fLastNavigationNode;
	private ArrayList fHistoryEntries= new ArrayList(MAX_HISTORY_SIZE);

    // widgets
    private PageBook fPagebook;
    private Composite fViewerPage;
    private Label fInfoText;

    // treeviewer
    private IBContentProvider fContentProvider;
    private IBLabelProvider fLabelProvider;
    private ExtendedTreeViewer fTreeViewer;

    // filters, sorter
    private IBWorkingSetFilter fWorkingSetFilter;
    private ViewerFilter fInactiveFilter;
    private ViewerFilter fSystemFilter;
    private ViewerComparator fSorterAlphaNumeric;
    private ViewerComparator fSorterReferencePosition;

    // actions
    private Action fIncludedByAction;
    private Action fIncludesToAction;
    private Action fFilterInactiveAction;
    private Action fFilterSystemAction;
    private Action fShowFolderInLabelsAction;
    private Action fNextAction;
    private Action fPreviousAction;
    private Action fRefreshAction;
	private Action fHistoryAction;
	private IContextActivation fContextActivation;
	private WorkingSetFilterUI fWorkingSetFilterUI;
	private IBSetInputJob fSetInputJob;

    
    public void setFocus() {
        fPagebook.setFocus();
    }

    public void setMessage(String msg) {
        fInfoText.setText(msg);
        fPagebook.showPage(fInfoText);
        fShowsMessage= true;
        updateActionEnablement();
        updateDescription();
    }
    
    public void setInput(ITranslationUnit input) {
    	if (fPagebook.isDisposed()) {
    		return;
    	}
    	if (input instanceof IWorkingCopy) {
    		input= ((IWorkingCopy) input).getOriginalElement();
    	}
    	fSetInputJob.cancel();
    	if (input == null) {
    		setMessage(IBMessages.IBViewPart_instructionMessage);
    		fTreeViewer.setInput(null);
    		return;
    	}
    	
    	if (CCorePlugin.getIndexManager().isIndexerIdle()) {
    		setInputIndexerIdle(input);
    	}
    	else {
    		setMessage(IBMessages.IBViewPart_waitingOnIndexerMessage);
    		fSetInputJob.setInput(input);
    		fSetInputJob.schedule();
    	}
    }

	private void setInputIndexerIdle(final ITranslationUnit input) {
		fShowsMessage= false;
        boolean isHeader= input.isHeaderUnit();
        
        fTreeViewer.setInput(null);
        if (!isHeader) {
        	fContentProvider.setComputeIncludedBy(isHeader);
        	fIncludedByAction.setChecked(isHeader);
        	fIncludesToAction.setChecked(!isHeader);
        	fIncludedByAction.setEnabled(false);
        	updateSorter();
        }
        else {
        	fIncludedByAction.setEnabled(true);
        }
        fTreeViewer.setInput(input);
        fPagebook.showPage(fViewerPage);
        updateHistory(input);

        updateActionEnablement();
        updateDescription();
        final Display display= Display.getCurrent();
        Job job= new Job(IBMessages.IBViewPart_jobCheckInput) {
			protected IStatus run(IProgressMonitor monitor) {
				try {
					IIndex index= CCorePlugin.getIndexManager().getIndex(input.getCProject());
					index.acquireReadLock();
					try {
						if (!IndexUI.isIndexed(index, input)) {
							final String msg = IndexUI
									.getFleNotIndexedMessage(input);
							display.asyncExec(new Runnable() {
								public void run() {
									if (fTreeViewer.getInput() == input) {
										setMessage(msg);
										fTreeViewer.setInput(null);
									}
								}
							});
						}
						return Status.OK_STATUS;
					} finally {
						index.releaseReadLock();
					}
				} catch (CoreException e) {
					return Status.OK_STATUS;
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
					return Status.CANCEL_STATUS;
				} 
			}
        };
        job.setSystem(true);
        job.schedule();
	}

	private void updateActionEnablement() {
		fHistoryAction.setEnabled(!fHistoryEntries.isEmpty());
		fNextAction.setEnabled(!fShowsMessage);
		fPreviousAction.setEnabled(!fShowsMessage);
		fRefreshAction.setEnabled(!fShowsMessage);
	}

	public void createPartControl(Composite parent) {
		fSetInputJob= new IBSetInputJob(this, Display.getCurrent());
		
        fPagebook = new PageBook(parent, SWT.NULL);
        fPagebook.setLayoutData(new GridData(GridData.FILL_BOTH));
        createInfoPage();
        createViewerPage();
                
        initDragAndDrop();
        createActions();
        createContextMenu();

        getSite().setSelectionProvider(fTreeViewer);
        setMessage(IBMessages.IBViewPart_instructionMessage);
        
        initializeActionStates();
        restoreInput();
        fMemento= null;

    	IContextService ctxService = (IContextService) getSite().getService(IContextService.class);
    	if (ctxService != null) {
    		fContextActivation= ctxService.activateContext(CUIPlugin.CVIEWS_SCOPE);
    	}
    }
	
	public void dispose() {
		if (fContextActivation != null) {
			IContextService ctxService = (IContextService)getSite().getService(IContextService.class);
	    	if (ctxService != null) {
	    		ctxService.deactivateContext(fContextActivation);
	    	}
		}
		if (fWorkingSetFilterUI != null) {
			fWorkingSetFilterUI.dispose();
		}
	}
	
    private void initializeActionStates() {
        boolean includedBy= true;
        boolean filterSystem= false;
        boolean filterInactive= false;
        
        if (fMemento != null) {
            filterSystem= TRUE.equals(fMemento.getString(KEY_FILTER_SYSTEM));
            filterInactive= TRUE.equals(fMemento.getString(KEY_FILTER_INACTIVE));
        }
        
        fIncludedByAction.setChecked(includedBy);
        fIncludesToAction.setChecked(!includedBy);
        fContentProvider.setComputeIncludedBy(includedBy);
        
        fFilterInactiveAction.setChecked(filterInactive);
        fFilterInactiveAction.run();
        fFilterSystemAction.setChecked(filterSystem);
        fFilterSystemAction.run();
        updateSorter();
    }
    
    private void restoreInput() {
        if (fMemento != null) {
            String pathStr= fMemento.getString(KEY_INPUT_PATH);
            if (pathStr != null) {
                IPath path= Path.fromPortableString(pathStr);
                if (path.segmentCount() > 1) {
                    String name= path.segment(0);
                    ICProject project= CoreModel.getDefault().getCModel().getCProject(name);
                    if (project != null) {
                        ICElement celement;
                        try {
                            celement = project.findElement(path);
                            if (celement instanceof ITranslationUnit) {
                                setInput((ITranslationUnit) celement);
                            }
                        } catch (CModelException e) {
                            // ignore
                        }
                    }
                }
            }
        }
    }


    public void init(IViewSite site, IMemento memento) throws PartInitException {
        fMemento= memento;
        super.init(site, memento);
    }


    public void saveState(IMemento memento) {
        if (fWorkingSetFilter != null) {
            fWorkingSetFilter.getUI().saveState(memento, KEY_WORKING_SET_FILTER);
        }
        memento.putString(KEY_FILTER_INACTIVE, String.valueOf(fFilterInactiveAction.isChecked()));
        memento.putString(KEY_FILTER_SYSTEM, String.valueOf(fFilterSystemAction.isChecked()));
        ITranslationUnit input= getInput();
        if (input != null) {
            IPath path= input.getPath();
            if (path != null) {
                memento.putString(KEY_INPUT_PATH, path.toPortableString());
            }
        }
        super.saveState(memento);
    }

    private void createContextMenu() {
        MenuManager manager = new MenuManager();
        manager.setRemoveAllWhenShown(true);
        manager.addMenuListener(new IMenuListener() {
            public void menuAboutToShow(IMenuManager m) {
                onContextMenuAboutToShow(m);
            }
        });
        Menu menu = manager.createContextMenu(fTreeViewer.getControl());
        fTreeViewer.getControl().setMenu(menu);
        IWorkbenchPartSite site = getSite();
        site.registerContextMenu(CUIPlugin.ID_INCLUDE_BROWSER, manager, fTreeViewer); 
    }

    private void createViewerPage() {
        Display display= getSite().getShell().getDisplay();
        fViewerPage = new Composite(fPagebook, SWT.NULL);
        fViewerPage.setLayoutData(new GridData(GridData.FILL_BOTH));
        fViewerPage.setSize(100, 100);
        fViewerPage.setLayout(new FillLayout());

        fContentProvider= new IBContentProvider(display); 
        fLabelProvider= new IBLabelProvider(display, fContentProvider);
        fTreeViewer= new ExtendedTreeViewer(fViewerPage);
        fTreeViewer.setUseHashlookup(true);
        fTreeViewer.setContentProvider(fContentProvider);
        fTreeViewer.setLabelProvider(fLabelProvider);
        fTreeViewer.setAutoExpandLevel(2);     
        fTreeViewer.addOpenListener(new IOpenListener() {
            public void open(OpenEvent event) {
                onShowInclude(event.getSelection());
            }
        });
    }
    
    private void createInfoPage() {
    	fInfoText = new Label(fPagebook, SWT.TOP | SWT.LEFT | SWT.WRAP);
    }

    private void initDragAndDrop() {
        IBDropTargetListener dropListener= new IBDropTargetListener(this);
        Transfer[] dropTransfers= new Transfer[] {
                LocalSelectionTransfer.getTransfer(),
                ResourceTransfer.getInstance(), 
                FileTransfer.getInstance()};
        DropTarget dropTarget = new DropTarget(fPagebook, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT);
        dropTarget.setTransfer(dropTransfers);
        dropTarget.addDropListener(dropListener);

        Transfer[] dragTransfers= new Transfer[] {
                ResourceTransfer.getInstance(), 
                FileTransfer.getInstance()};
        IBDragSourceListener dragListener= new IBDragSourceListener(fTreeViewer);
        dragListener.setDependentDropTargetListener(dropListener);
        fTreeViewer.addDragSupport(DND.DROP_COPY, dragTransfers, dragListener);
    }

    private void createActions() {
        fWorkingSetFilterUI= new WorkingSetFilterUI(this, fMemento, KEY_WORKING_SET_FILTER) {
            protected void onWorkingSetChange() {
                updateWorkingSetFilter(this);
            }
            protected void onWorkingSetNameChange() {
                updateDescription();
            }
        }; 

        fIncludedByAction= 
            new Action(IBMessages.IBViewPart_showIncludedBy_label, IAction.AS_RADIO_BUTTON) { 
                public void run() {
                    if (isChecked()) {
                        onSetDirection(true);
                    }
                }
        };
        fIncludedByAction.setToolTipText(IBMessages.IBViewPart_showIncludedBy_tooltip);
        CPluginImages.setImageDescriptors(fIncludedByAction, CPluginImages.T_LCL, CPluginImages.IMG_ACTION_SHOW_REF_BY);       

        fIncludesToAction= 
            new Action(IBMessages.IBViewPart_showIncludesTo_label, IAction.AS_RADIO_BUTTON) { 
                public void run() {
                    if (isChecked()) {
                        onSetDirection(false);
                    }
                }
        };
        fIncludesToAction.setToolTipText(IBMessages.IBViewPart_showIncludesTo_tooltip);
        CPluginImages.setImageDescriptors(fIncludesToAction, CPluginImages.T_LCL, CPluginImages.IMG_ACTION_SHOW_RELATES_TO);       

        fInactiveFilter= new ViewerFilter() {
            public boolean select(Viewer viewer, Object parentElement, Object element) {
                if (element instanceof IBNode) {
                    IBNode node= (IBNode) element;
                    return node.isActiveCode();
                }
                return true;
            }
        };
        fFilterInactiveAction= new Action(IBMessages.IBViewPart_hideInactive_label, IAction.AS_CHECK_BOX) {
            public void run() {
                if (isChecked()) {
                    fTreeViewer.addFilter(fInactiveFilter);
                }
                else {
                    fTreeViewer.removeFilter(fInactiveFilter);
                }
            }
        };
        fFilterInactiveAction.setToolTipText(IBMessages.IBViewPart_hideInactive_tooltip);
        CPluginImages.setImageDescriptors(fFilterInactiveAction, CPluginImages.T_LCL, CPluginImages.IMG_ACTION_HIDE_INACTIVE);       

        fSystemFilter= new ViewerFilter() {
            public boolean select(Viewer viewer, Object parentElement, Object element) {
                if (element instanceof IBNode) {
                    IBNode node= (IBNode) element;
                    return !node.isSystemInclude();
                }
                return true;
            }
        };
        fFilterSystemAction= new Action(IBMessages.IBViewPart_hideSystem_label, IAction.AS_CHECK_BOX) {
            public void run() {
                if (isChecked()) {
                    fTreeViewer.addFilter(fSystemFilter);
                }
                else {
                    fTreeViewer.removeFilter(fSystemFilter);
                }
            }
        };
        fFilterSystemAction.setToolTipText(IBMessages.IBViewPart_hideSystem_tooltip);
        CPluginImages.setImageDescriptors(fFilterSystemAction, CPluginImages.T_LCL, CPluginImages.IMG_ACTION_HIDE_SYSTEM);       
        
        fSorterAlphaNumeric= new ViewerComparator();
        fSorterReferencePosition= new ViewerComparator() {
            public int category(Object element) {
                if (element instanceof IBNode) {
                    return 0;
                }
                return 1;
            }
            public int compare(Viewer viewer, Object e1, Object e2) {
                if (!(e1 instanceof IBNode)) {
                    if (!(e2 instanceof IBNode)) {
                        return 0;
                    }
                    return -1;
                }
                if (!(e2 instanceof IBNode)) {
                    return 1;
                }
                IBNode n1= (IBNode) e1;
                IBNode n2= (IBNode) e2;
                return n1.getDirectiveCharacterOffset() - n2.getDirectiveCharacterOffset();
            }
        };
        
        fShowFolderInLabelsAction= new Action(IBMessages.IBViewPart_showFolders_label, IAction.AS_CHECK_BOX) {
            public void run() {
                onShowFolderInLabels(isChecked());
            }
        };
        fShowFolderInLabelsAction.setToolTipText(IBMessages.IBViewPart_showFolders_tooltip);
        fNextAction = new Action(IBMessages.IBViewPart_nextMatch_label) {
            public void run() {
                onNextOrPrevious(true);
            }
        };
        fNextAction.setToolTipText(IBMessages.IBViewPart_nextMatch_tooltip); 
        CPluginImages.setImageDescriptors(fNextAction, CPluginImages.T_LCL, CPluginImages.IMG_SHOW_NEXT);       

        fPreviousAction = new Action(IBMessages.IBViewPart_previousMatch_label) {
            public void run() {
                onNextOrPrevious(false);
            }
        };
        fPreviousAction.setToolTipText(IBMessages.IBViewPart_previousMatch_tooltip); 
        CPluginImages.setImageDescriptors(fPreviousAction, CPluginImages.T_LCL, CPluginImages.IMG_SHOW_PREV);       

        fRefreshAction = new Action(IBMessages.IBViewPart_refresh_label) {
            public void run() {
                onRefresh();
            }
        };
        fRefreshAction.setToolTipText(IBMessages.IBViewPart_refresh_tooltip); 
        CPluginImages.setImageDescriptors(fRefreshAction, CPluginImages.T_LCL, CPluginImages.IMG_REFRESH);       

        fHistoryAction= new IBHistoryDropDownAction(this);
        
        // setup action bar
        // global action hooks
        IActionBars actionBars = getViewSite().getActionBars();
        actionBars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAction);
        actionBars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAction);
        actionBars.setGlobalActionHandler(ActionFactory.REFRESH.getId(), fRefreshAction);
        actionBars.updateActionBars();
        
        // local toolbar
        IToolBarManager tm = actionBars.getToolBarManager();
        tm.add(fNextAction);
        tm.add(fPreviousAction);
        tm.add(new Separator());
        tm.add(fFilterSystemAction);
        tm.add(fFilterInactiveAction);
        tm.add(new Separator());
        tm.add(fIncludedByAction);
        tm.add(fIncludesToAction);
        tm.add(fHistoryAction);
        tm.add(fRefreshAction);

        // local menu
        IMenuManager mm = actionBars.getMenuManager();

        fWorkingSetFilterUI.fillActionBars(actionBars);
        mm.add(fIncludedByAction);
        mm.add(fIncludesToAction);
        mm.add(new Separator());
        mm.add(fShowFolderInLabelsAction);
        mm.add(new Separator());
        mm.add(fFilterSystemAction);
        mm.add(fFilterInactiveAction);
    }
    
    private IBNode getNextNode(boolean forward) {
    	TreeNavigator navigator= new TreeNavigator(fTreeViewer.getTree(), IBNode.class);
    	TreeItem selectedItem= navigator.getSelectedItemOrFirstOnLevel(1, forward);
    	if (selectedItem == null) {
    		return null;
    	}
    	
        if (selectedItem.getData().equals(fLastNavigationNode)) {
        	selectedItem= navigator.getNextSibbling(selectedItem, forward);
        }
        
        return selectedItem == null ? null : (IBNode) selectedItem.getData();
    }
        
    protected void onNextOrPrevious(boolean forward) {
    	IBNode nextItem= getNextNode(forward);
        if (nextItem != null) {
            StructuredSelection sel= new StructuredSelection(nextItem);
            fTreeViewer.setSelection(sel);
            onShowInclude(sel);
        }
    }

    protected void onRefresh() {
        fContentProvider.recompute();
    }
    
    protected void onShowFolderInLabels(boolean show) {
        fLabelProvider.setShowFolders(show);
        fTreeViewer.refresh();
    }

    private void updateHistory(ITranslationUnit input) {
    	if (input != null) {
    		fHistoryEntries.remove(input);
    		fHistoryEntries.add(0, input);
    		if (fHistoryEntries.size() > MAX_HISTORY_SIZE) {
    			fHistoryEntries.remove(MAX_HISTORY_SIZE-1);
    		}
    	}
	}

    private void updateSorter() {
        if (fIncludedByAction.isChecked()) {
            fTreeViewer.setComparator(fSorterAlphaNumeric);
        }
        else {
            fTreeViewer.setComparator(fSorterReferencePosition);
        }
    }
    
    private void updateDescription() {
        String message= ""; //$NON-NLS-1$
        if (!fShowsMessage) {
        	ITranslationUnit tu= getInput();
            if (tu != null) {
                IPath path= tu.getPath();
                if (path != null) {
                    String format, file, scope;
                    
                    file= path.lastSegment() + "(" + path.removeLastSegments(1) + ")";  //$NON-NLS-1$//$NON-NLS-2$
                    if (fWorkingSetFilter == null) {
                        scope= IBMessages.IBViewPart_workspaceScope;
                    }
                    else {
                        scope= fWorkingSetFilter.getLabel();
                    }
                    
                    if (fIncludedByAction.isChecked()) {
                        format= IBMessages.IBViewPart_IncludedByContentDescription;
                    }
                    else {
                        format= IBMessages.IBViewPart_IncludesToContentDescription;
                    }
                    message= Messages.format(format, file, scope);
                }
            }
        }
        setContentDescription(message);
    }

    private void updateWorkingSetFilter(WorkingSetFilterUI filterUI) {
        if (filterUI.getWorkingSet() == null) {
            if (fWorkingSetFilter != null) {
                fTreeViewer.removeFilter(fWorkingSetFilter);
                fWorkingSetFilter= null;
            }
        }
        else {
            if (fWorkingSetFilter != null) {
                fTreeViewer.refresh();
            }
            else {
                fWorkingSetFilter= new IBWorkingSetFilter(filterUI);
                fTreeViewer.addFilter(fWorkingSetFilter);
            }
        }
    }
    
    public void onSetDirection(boolean includedBy) {
        if (includedBy != fContentProvider.getComputeIncludedBy()) {
            Object input= fTreeViewer.getInput();
            fTreeViewer.setInput(null);
            fContentProvider.setComputeIncludedBy(includedBy);
            updateSorter();
            fTreeViewer.setInput(input);
            updateDescription();
        }
    }

    protected void onContextMenuAboutToShow(IMenuManager m) {
        final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection();
        final IBNode node= IBConversions.selectionToNode(selection);
        
        if (node != null) {
            final IWorkbenchPage page = getSite().getPage();
            
            // open include
            if (node.getParent() != null && node.getDirectiveFile() != null) {
                m.add(new Action(IBMessages.IBViewPart_showInclude_label) {
                    public void run() {
                        onShowInclude(selection);
                    }
                });
            }

            final ITranslationUnit tu= node.getRepresentedTranslationUnit();
            if (tu != null) {
                // open
                OpenCElementAction ofa= new OpenCElementAction(page);
                ofa.selectionChanged(selection);
                m.add(ofa);

                // open with
                // keep the menu shorter, no open with support
//                final IResource r= tu.getResource();
//                if (r != null) {
//                    IMenuManager submenu= new MenuManager(IBMessages.IBViewPart_OpenWithMenu_label); 
//                    submenu.add(new OpenWithMenu(page, r));
//                    m.add(submenu);
//                }

                // show in
                IMenuManager submenu= new MenuManager(IBMessages.IBViewPart_ShowInMenu_label);
                submenu.add(ContributionItemFactory.VIEWS_SHOW_IN.create(getSite().getWorkbenchWindow()));
                m.add(submenu);
            	if (node.getParent() != null) {
                    m.add(new Separator());
            		m.add(new Action(Messages.format(IBMessages.IBViewPart_FocusOn_label, tu.getPath().lastSegment())) {
            			public void run() {
            				setInput(tu);
            			}
            		});
            	}

            }
        }
        m.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
    }
    
    protected void onShowInclude(ISelection selection) {
        IBNode node= IBConversions.selectionToNode(selection);
        if (node != null) {
        	fLastNavigationNode= node;

            IWorkbenchPage page= getSite().getPage();
        	IBFile ibf= node.getDirectiveFile();
            if (ibf != null) {
                IRegion region= new Region(node.getDirectiveCharacterOffset(), node.getDirectiveLength());
                long timestamp= node.getTimestamp();

                IFile f= ibf.getResource();
                if (f != null) {
                	EditorOpener.open(page, f, region, timestamp);
                }
                else {
                    IIndexFileLocation ifl = ibf.getLocation();
                    if (ifl != null) {
                    	IPath location= IndexLocationFactory.getAbsolutePath(ifl);
                    	if (location != null) {
                    		EditorOpener.openExternalFile(page, location, region, timestamp);
                    	}
                    }
                }
            }
            else {
            	ITranslationUnit tu= IBConversions.selectionToTU(selection);
            	if (tu != null) {
            		IResource r= tu.getResource();
            		if (r != null) {
            			OpenFileAction ofa= new OpenFileAction(page);
            			ofa.selectionChanged((IStructuredSelection) selection);
            			ofa.run();
            		}
            	}
            }
        }
    }

    public ShowInContext getShowInContext() {
        return new ShowInContext(null, IBConversions.nodeSelectionToRepresentedTUSelection(fTreeViewer.getSelection()));
    }

    public boolean show(ShowInContext context) {
        ITranslationUnit tu= IBConversions.selectionToTU(context.getSelection());
        if (tu == null) {
            tu= IBConversions.objectToTU(context.getInput());
            if (tu == null) {
                setMessage(IBMessages.IBViewPart_falseInputMessage);
                return false;
            }
        }

        setInput(tu);
        return true;
    }
    
    public String[] getShowInTargetIds() {
        return new String[] {
        		CUIPlugin.CVIEW_ID, 
        		IPageLayout.ID_RES_NAV
        };
    }

    // access for tests
	public TreeViewer getTreeViewer() {
		return fTreeViewer;
	}

	public ITranslationUnit[] getHistoryEntries() {
		return (ITranslationUnit[]) fHistoryEntries.toArray(new ITranslationUnit[fHistoryEntries.size()]);
	}

	public void setHistoryEntries(ITranslationUnit[] remaining) {
		fHistoryEntries.clear();
		fHistoryEntries.addAll(Arrays.asList(remaining));
	}

	public ITranslationUnit getInput() {
        Object input= fTreeViewer.getInput();
        if (input instanceof ITranslationUnit) {
        	return (ITranslationUnit) input;
        }
        return null;
	}
}

Back to the top