This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 217347
Collapse All | Expand All

(-)a/refactoring.api/apichanges.xml (+20 lines)
Lines 49-54 Link Here
49
    <apidef name="refactoring">Refactoring API</apidef>
49
    <apidef name="refactoring">Refactoring API</apidef>
50
</apidefs>
50
</apidefs>
51
<changes>
51
<changes>
52
    <change id="ServerSideQueries">
53
        <api name="refactoring"/>
54
        <summary>Added support for Scope Providers and ExpandableTreeElements.</summary>
55
        <version major="1" minor="30"/>
56
        <date day="31" month="8" year="2012"/>
57
        <author login="ralphbenjamin"/>
58
        <compatibility addition="yes"/>
59
        <description>
60
            <p>
61
                Added an ExpandableTreeElement and a declarative way to add new scopes.
62
            </p>
63
        </description>
64
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ExpandableTreeElement"/>
65
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ScopeProvider"/>
66
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ScopeDescription"/>
67
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ScopeReference"/>
68
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ScopeReferences"/>
69
        <class package="org.netbeans.modules.refactoring.spi.ui" name="ScopePanel"/>
70
        <issue number="217347"/>
71
    </change>
52
    <change id="RefactoringResultsFilters">
72
    <change id="RefactoringResultsFilters">
53
        <api name="refactoring"/>
73
        <api name="refactoring"/>
54
        <summary>Added an API to support filters of the Find Usages results.</summary>
74
        <summary>Added an API to support filters of the Find Usages results.</summary>
(-)a/refactoring.api/nbproject/project.properties (-1 / +1 lines)
Lines 4-8 Link Here
4
javadoc.apichanges=${basedir}/apichanges.xml
4
javadoc.apichanges=${basedir}/apichanges.xml
5
javadoc.title=Refactoring API
5
javadoc.title=Refactoring API
6
6
7
spec.version.base=1.29.0
7
spec.version.base=1.30.0
8
test.config.stableBTD.includes=**/*Test.class
8
test.config.stableBTD.includes=**/*Test.class
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/impl/Bundle.properties (-2 / +3 lines)
Lines 78-85 Link Here
78
LBL_InReadOnlyFile=Error: this occurrence is in a read-only file and cannot be refactored.
78
LBL_InReadOnlyFile=Error: this occurrence is in a read-only file and cannot be refactored.
79
LBL_CannotRefactorGuardedBlock=Read-only block of text cannot be refactored.
79
LBL_CannotRefactorGuardedBlock=Read-only block of text cannot be refactored.
80
LBL_CannotRefactorReadOnlyFile=Read-only files cannot be refactored.
80
LBL_CannotRefactorReadOnlyFile=Read-only files cannot be refactored.
81
LBL_Occurence=occurrence
81
# "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}."
82
LBL_Occurences=occurrences
82
LBL_Occurences={0,choice,0#no occurrences|1#1 occurrence|1<{0,number,integer} occurrences}
83
LBL_OccurencesApproximate=about {0,choice,1#1 occurrence|1<{0,number,integer} occurrences}
83
LBL_Errors=errors
84
LBL_Errors=errors
84
LBL_Hidden=filtered
85
LBL_Hidden=filtered
85
LBL_UsagesWindow=&Find Usages Results
86
LBL_UsagesWindow=&Find Usages Results
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/impl/CheckNode.java (-1 / +52 lines)
Lines 44-59 Link Here
44
package org.netbeans.modules.refactoring.spi.impl;
44
package org.netbeans.modules.refactoring.spi.impl;
45
45
46
import java.io.IOException;
46
import java.io.IOException;
47
import java.util.ArrayList;
47
import java.util.Enumeration;
48
import java.util.Enumeration;
49
import java.util.List;
48
import javax.swing.Icon;
50
import javax.swing.Icon;
51
import javax.swing.SwingUtilities;
49
import javax.swing.tree.*;
52
import javax.swing.tree.*;
50
import org.netbeans.modules.refactoring.spi.ui.TreeElement;
53
import org.netbeans.modules.refactoring.spi.ui.TreeElement;
51
import org.openide.text.PositionBounds;
54
import org.openide.text.PositionBounds;
52
import org.netbeans.modules.refactoring.api.RefactoringElement;
55
import org.netbeans.modules.refactoring.api.RefactoringElement;
56
import org.netbeans.modules.refactoring.spi.ui.ExpandableTreeElement;
53
import org.openide.filesystems.FileObject;
57
import org.openide.filesystems.FileObject;
54
import org.openide.filesystems.FileUtil;
58
import org.openide.filesystems.FileUtil;
55
import org.openide.util.ImageUtilities;
59
import org.openide.util.ImageUtilities;
56
import org.openide.util.NbBundle;
60
import org.openide.util.NbBundle;
61
import org.openide.util.NbCollections;
62
import org.openide.util.RequestProcessor;
57
63
58
/**
64
/**
59
 * @author Pavel Flaska
65
 * @author Pavel Flaska
Lines 65-70 Link Here
65
  
71
  
66
    private int selectionMode;
72
    private int selectionMode;
67
    private boolean isSelected;
73
    private boolean isSelected;
74
    private boolean isQuery;
68
75
69
    private String nodeLabel;
76
    private String nodeLabel;
70
    private Icon icon;
77
    private Icon icon;
Lines 74-82 Link Here
74
    private static Icon found = ImageUtilities.loadImageIcon("org/netbeans/modules/refactoring/api/resources/found_item_orange.png", false);
81
    private static Icon found = ImageUtilities.loadImageIcon("org/netbeans/modules/refactoring/api/resources/found_item_orange.png", false);
75
    
82
    
76
    public CheckNode(Object userObject, String nodeLabel, Icon icon, boolean isQuery) {
83
    public CheckNode(Object userObject, String nodeLabel, Icon icon, boolean isQuery) {
77
        super(userObject, !(userObject instanceof RefactoringElement));
84
        super(userObject, !(userObject instanceof RefactoringElement) || userObject instanceof ExpandableTreeElement);
78
        this.isSelected = true;
85
        this.isSelected = true;
79
        setSelectionMode(DIG_IN_SELECTION);
86
        setSelectionMode(DIG_IN_SELECTION);
87
        this.isQuery = isQuery;
80
        this.nodeLabel = nodeLabel;
88
        this.nodeLabel = nodeLabel;
81
        this.icon = icon;
89
        this.icon = icon;
82
        if (userObject instanceof TreeElement) {
90
        if (userObject instanceof TreeElement) {
Lines 108-113 Link Here
108
                }
116
                }
109
            }
117
            }
110
        }
118
        }
119
120
        if (userObject instanceof ExpandableTreeElement) {
121
            add(new CheckNode("Please wait", "Please wait...", null, isQuery));
122
        }
111
    }
123
    }
112
    
124
    
113
    String getLabel() {
125
    String getLabel() {
Lines 218-221 Link Here
218
        }
230
        }
219
        return l + ":&nbsp;&nbsp;"; //NOI18N
231
        return l + ":&nbsp;&nbsp;"; //NOI18N
220
    }
232
    }
233
    
234
    private static final RequestProcessor WORKER = new RequestProcessor(CheckNode.class.getName(), 1, true, false);
235
    private boolean childrenFilled;
236
    
237
    public synchronized void ensureChildrenFilled(final DefaultTreeModel model) {
238
        if (!childrenFilled) {
239
            childrenFilled = true;
240
241
            if (userObject instanceof ExpandableTreeElement) {
242
                WORKER.post(new Runnable() {
243
                    @Override public void run() {
244
                        final List<TreeElement> subelements = new ArrayList<TreeElement>();
245
                        
246
                        for (TreeElement el : ((ExpandableTreeElement) userObject)) {
247
                            subelements.add(el);
248
                        }
249
250
                        SwingUtilities.invokeLater(new Runnable() {
251
                            @Override public void run() {
252
                                for (TreeElement el : subelements) {
253
                                    insert(new CheckNode(el, el.getText(/*XXX:*/true), el.getIcon(), isQuery), getChildCount() - 1);
254
                                }
255
                                int[] added = new int[getChildCount() - 1];
256
                                for (int i = 0; i < added.length; i++) {
257
                                    added[i] = i;
258
                                }
259
                                model.nodesWereInserted(CheckNode.this, added);
260
                                int childCount = getChildCount();
261
                                Object last = getChildAt(childCount - 1);
262
                                int index = model.getIndexOfChild(CheckNode.this, last);
263
                                remove(index); //remove the please wait node
264
                                model.nodesWereRemoved(CheckNode.this, new int[] {index}, new Object[] {last});
265
                            }
266
                        });
267
                    }
268
                });
269
            }
270
        }
271
    }
221
}
272
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/impl/RefactoringPanel.java (-12 / +32 lines)
Lines 63-72 Link Here
63
import java.util.prefs.Preferences;
63
import java.util.prefs.Preferences;
64
import javax.swing.*;
64
import javax.swing.*;
65
import javax.swing.border.EmptyBorder;
65
import javax.swing.border.EmptyBorder;
66
import javax.swing.event.TreeExpansionEvent;
67
import javax.swing.event.TreeWillExpandListener;
66
import javax.swing.event.ChangeEvent;
68
import javax.swing.event.ChangeEvent;
67
import javax.swing.text.html.HTMLEditorKit;
69
import javax.swing.text.html.HTMLEditorKit;
68
import javax.swing.text.html.parser.ParserDelegator;
70
import javax.swing.text.html.parser.ParserDelegator;
69
import javax.swing.tree.DefaultTreeModel;
71
import javax.swing.tree.DefaultTreeModel;
72
import javax.swing.tree.ExpandVetoException;
70
import javax.swing.tree.TreeNode;
73
import javax.swing.tree.TreeNode;
71
import javax.swing.tree.TreePath;
74
import javax.swing.tree.TreePath;
72
import org.netbeans.api.progress.ProgressHandle;
75
import org.netbeans.api.progress.ProgressHandle;
Lines 75-80 Link Here
75
import org.netbeans.modules.parsing.api.indexing.IndexingManager;
78
import org.netbeans.modules.parsing.api.indexing.IndexingManager;
76
import org.netbeans.modules.refactoring.api.*;
79
import org.netbeans.modules.refactoring.api.*;
77
import org.netbeans.modules.refactoring.api.impl.APIAccessor;
80
import org.netbeans.modules.refactoring.api.impl.APIAccessor;
81
import org.netbeans.modules.refactoring.spi.ui.ExpandableTreeElement;
78
import org.netbeans.modules.refactoring.spi.ui.FiltersDescription;
82
import org.netbeans.modules.refactoring.spi.ui.FiltersDescription;
79
import org.netbeans.modules.refactoring.spi.ui.RefactoringCustomUI;
83
import org.netbeans.modules.refactoring.spi.ui.RefactoringCustomUI;
80
import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
84
import org.netbeans.modules.refactoring.spi.ui.RefactoringUI;
Lines 699-704 Link Here
699
        final RefactoringPanelContainer cont = isQuery ? RefactoringPanelContainer.getUsagesComponent() : RefactoringPanelContainer.getRefactoringComponent();
703
        final RefactoringPanelContainer cont = isQuery ? RefactoringPanelContainer.getUsagesComponent() : RefactoringPanelContainer.getRefactoringComponent();
700
        cont.makeBusy(true);
704
        cont.makeBusy(true);
701
        final AtomicInteger size = new AtomicInteger();
705
        final AtomicInteger size = new AtomicInteger();
706
        final AtomicBoolean sizeIsApproximate = new AtomicBoolean();
702
        initialize();
707
        initialize();
703
        if(showParametersPanel) {
708
        if(showParametersPanel) {
704
            updateFilters();
709
            updateFilters();
Lines 749-756 Link Here
749
                            }
754
                            }
750
                        }
755
                        }
751
                    }
756
                    }
752
                    StringBuffer errorsDesc = getErrorDesc(errorsNum, isQuery?size.get():elements.size(), 0);
757
                    StringBuffer errorsDesc = getErrorDesc(errorsNum, isQuery?size.get():elements.size(), 0, isQuery && sizeIsApproximate.get());
753
                    final CheckNode root = new CheckNode(ui, description + errorsDesc.toString() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",ImageUtilities.loadImageIcon("org/netbeans/modules/refactoring/api/resources/" + (isQuery ? "findusages.png" : "refactoring.gif"), false), isQuery);
758
                    final CheckNode root = new CheckNode(ui, description + errorsDesc.toString() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",ImageUtilities.loadImageIcon("org/netbeans/modules/refactoring/api/resources/" + (isQuery ? "findusages.png" : "refactoring.gif"), false), isQuery);
754
                    final Map<Object, CheckNode> nodes = new HashMap<Object, CheckNode>();
759
                    final Map<Object, CheckNode> nodes = new HashMap<Object, CheckNode>();
755
                    
760
                    
756
                    if (isQuery && showParametersPanel) {
761
                    if (isQuery && showParametersPanel) {
Lines 773-786 Link Here
773
                            // ui.getRefactoring().setClassPath();
778
                            // ui.getRefactoring().setClassPath();
774
                            for (Iterator it = elements.iterator(); it.hasNext();i++) {
779
                            for (Iterator it = elements.iterator(); it.hasNext();i++) {
775
                                final RefactoringElement e = (RefactoringElement) it.next();
780
                                final RefactoringElement e = (RefactoringElement) it.next();
781
                                TreeElement treeElement = null;
776
                                if(e.include(filtersManager)) {
782
                                if(e.include(filtersManager)) {
777
                                    createNode(TreeElementFactory.getTreeElement(e), nodes, root);
783
                                    treeElement = TreeElementFactory.getTreeElement(e);
784
                                    createNode(treeElement, nodes, root);
778
                                } else {
785
                                } else {
779
                                    hidden++;
786
                                    hidden++;
780
                                }
787
                                }
781
                                final int occurrences = i + 1;
788
                                final int occurrences = i + (treeElement instanceof ExpandableTreeElement ? ((ExpandableTreeElement) treeElement).estimateChildCount() : 1);
782
                                final int hiddenOccurrences = hidden;
789
                                final int hiddenOccurrences = hidden;
783
                                size.set(occurrences);
790
                                size.set(occurrences);
791
                                sizeIsApproximate.compareAndSet(false, treeElement instanceof ExpandableTreeElement);
784
                                if (isQuery && showParametersPanel) {
792
                                if (isQuery && showParametersPanel) {
785
                                    if (cancelRequest.get()) {
793
                                    if (cancelRequest.get()) {
786
                                        break;
794
                                        break;
Lines 791-797 Link Here
791
                                        SwingUtilities.invokeLater(new Runnable() {
799
                                        SwingUtilities.invokeLater(new Runnable() {
792
                                            @Override
800
                                            @Override
793
                                            public void run() {
801
                                            public void run() {
794
                                                root.setNodeLabel(description + getErrorDesc(0, occurrences, hiddenOccurrences));
802
                                                root.setNodeLabel(description + getErrorDesc(0, occurrences, hiddenOccurrences, isQuery && sizeIsApproximate.get()));
795
                                                if (last) {
803
                                                if (last) {
796
                                                    tree.repaint();
804
                                                    tree.repaint();
797
                                                }
805
                                                }
Lines 838-856 Link Here
838
                    }
846
                    }
839
                    
847
                    
840
                    if (!(isQuery && showParametersPanel)) {
848
                    if (!(isQuery && showParametersPanel)) {
841
                        root.setNodeLabel(description + getErrorDesc(errorsNum, isQuery ? size.get() : elements.size(), hidden).toString());
849
                        root.setNodeLabel(description + getErrorDesc(errorsNum, isQuery ? size.get() : elements.size(), hidden, isQuery && sizeIsApproximate.get()).toString());
842
                        setupTree(root, showParametersPanel, elements.size());
850
                        setupTree(root, showParametersPanel, elements.size());
843
                    }
851
                    }
844
                    
852
                    
845
                }
853
                }
846
854
847
                private StringBuffer getErrorDesc(int errorsNum, int occurencesNum, int hiddenNum) throws MissingResourceException {
855
                private StringBuffer getErrorDesc(int errorsNum, int occurencesNum, int hiddenNum, boolean occurencesNumApproximate) throws MissingResourceException {
848
                    StringBuffer errorsDesc = new StringBuffer();
856
                    StringBuffer errorsDesc = new StringBuffer();
849
                    errorsDesc.append(" [").append(occurencesNum); // NOI18N
857
                    errorsDesc.append(" ["); // NOI18N
850
                    errorsDesc.append(' ');
858
                    errorsDesc.append(occurencesNumApproximate ?
851
                    errorsDesc.append(occurencesNum == 1 ?
859
                        NbBundle.getMessage(RefactoringPanel.class, "LBL_OccurencesApproximate", occurencesNum) :
852
                        NbBundle.getMessage(RefactoringPanel.class, "LBL_Occurence") :
860
                        NbBundle.getMessage(RefactoringPanel.class, "LBL_Occurences", occurencesNum)
853
                        NbBundle.getMessage(RefactoringPanel.class, "LBL_Occurences")
854
                        );
861
                        );
855
                    if (errorsNum > 0) {
862
                    if (errorsNum > 0) {
856
                        errorsDesc.append(',');
863
                        errorsDesc.append(',');
Lines 1003-1008 Link Here
1003
            tree.setModel(new DefaultTreeModel(root));
1010
            tree.setModel(new DefaultTreeModel(root));
1004
        }
1011
        }
1005
        tree.setRowHeight((int) ((CheckRenderer) tree.getCellRenderer()).getPreferredSize().getHeight());
1012
        tree.setRowHeight((int) ((CheckRenderer) tree.getCellRenderer()).getPreferredSize().getHeight());
1013
1014
        this.tree.addTreeWillExpandListener(new TreeWillExpandListener() {
1015
            @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
1016
                Object last = event.getPath().getLastPathComponent();
1017
1018
                if (last instanceof CheckNode) {
1019
                    ((CheckNode) last).ensureChildrenFilled((DefaultTreeModel) RefactoringPanel.this.tree.getModel());
1020
                }
1021
            }
1022
1023
            @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { }
1024
        });
1006
    }
1025
    }
1007
1026
1008
    private void setupInstantTree(final CheckNode root, final boolean showParametersPanel) {
1027
    private void setupInstantTree(final CheckNode root, final boolean showParametersPanel) {
Lines 1236-1241 Link Here
1236
    
1255
    
1237
    protected void closeNotify() {
1256
    protected void closeNotify() {
1238
        if (fuListener!=null) {
1257
        if (fuListener!=null) {
1258
            stopSearch();
1239
            ui.getRefactoring().removeProgressListener(fuListener);
1259
            ui.getRefactoring().removeProgressListener(fuListener);
1240
        }
1260
        }
1241
        timeStamps.clear();
1261
        timeStamps.clear();
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/impl/ScopeAnnotationProcessor.java (+160 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.impl;
43
44
import java.util.List;
45
import java.util.Set;
46
import javax.annotation.processing.Processor;
47
import javax.annotation.processing.RoundEnvironment;
48
import javax.annotation.processing.SupportedAnnotationTypes;
49
import javax.annotation.processing.SupportedSourceVersion;
50
import javax.lang.model.SourceVersion;
51
import javax.lang.model.element.Element;
52
import javax.lang.model.element.TypeElement;
53
import javax.lang.model.type.TypeMirror;
54
import javax.lang.model.util.Types;
55
import javax.tools.Diagnostic;
56
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
57
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
58
import org.netbeans.modules.refactoring.spi.ui.ScopeReferences;
59
import org.openide.filesystems.annotations.LayerBuilder;
60
import org.openide.filesystems.annotations.LayerGeneratingProcessor;
61
import org.openide.filesystems.annotations.LayerGenerationException;
62
import org.openide.util.lookup.ServiceProvider;
63
64
/**
65
 *
66
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
67
 */
68
@SupportedSourceVersion(SourceVersion.RELEASE_6)
69
@SupportedAnnotationTypes({"org.netbeans.modules.refactoring.spi.ui.ScopeDescription",
70
"org.netbeans.modules.refactoring.spi.ui.ScopeReference",
71
"org.netbeans.modules.refactoring.spi.ui.ScopeReferences"})
72
@ServiceProvider(service = Processor.class)
73
public class ScopeAnnotationProcessor extends LayerGeneratingProcessor {
74
75
    @Override
76
    protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
77
        if (!roundEnv.processingOver()) {
78
            generateTypeList(roundEnv);
79
        }
80
81
        return false;
82
    }
83
84
    private void generateTypeList(RoundEnvironment roundEnv) throws LayerGenerationException {
85
        TypeElement scopeDescription = processingEnv.getElementUtils().getTypeElement("org.netbeans.modules.refactoring.spi.ui.ScopeDescription");
86
        TypeElement scopeReference = processingEnv.getElementUtils().getTypeElement("org.netbeans.modules.refactoring.spi.ui.ScopeReference");
87
        TypeElement scopeReferences = processingEnv.getElementUtils().getTypeElement("org.netbeans.modules.refactoring.spi.ui.ScopeReferences");
88
        TypeMirror customProvider = processingEnv.getElementUtils().getTypeElement("org.netbeans.modules.refactoring.spi.ui.ScopeProvider.CustomScopeProvider").asType();
89
        TypeMirror provider = processingEnv.getElementUtils().getTypeElement("org.netbeans.modules.refactoring.spi.ui.ScopeProvider").asType();
90
        if (scopeDescription == null || scopeReference == null || scopeReferences == null) {
91
            return;
92
        }
93
        Types typeUtils = processingEnv.getTypeUtils();
94
95
        for (Element annotated : roundEnv.getElementsAnnotatedWith(scopeDescription)) {
96
            boolean custom;
97
            if (typeUtils.isSubtype(annotated.asType(), customProvider)) {
98
                custom = true;
99
            } else if (typeUtils.isSubtype(annotated.asType(), provider)) {
100
                custom = false;
101
            } else {
102
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ERR_SUPER_TYPE, annotated);
103
                continue;
104
            }
105
            ScopeDescription ar = annotated.getAnnotation(ScopeDescription.class);
106
            LayerBuilder builder = layer(annotated);
107
            LayerBuilder.File f = builder.file("Scopes/ScopeDescriptions/" + ar.id() + ".instance");
108
            f.bundlevalue("displayName", ar.displayName(), ar, "displayName");
109
            f.stringvalue("id", ar.id());
110
            f.stringvalue("iconBase", ar.iconBase());
111
            f.intvalue("position", ar.position());
112
            f.newvalue("delegate", getFQN((TypeElement) annotated));
113
            
114
            if (custom) {
115
                f.stringvalue("instanceClass", "org.netbeans.modules.refactoring.spi.ui.ScopeProvider");
116
                f.methodvalue("instanceCreate", "org.netbeans.modules.refactoring.spi.impl.Scopes", "createCustom");
117
            } else {
118
                f.stringvalue("instanceClass", "org.netbeans.modules.refactoring.spi.ui.ScopeProvider");
119
                f.methodvalue("instanceCreate", "org.netbeans.modules.refactoring.spi.impl.Scopes", "create");
120
            }
121
            f.write();
122
        }
123
        for (Element annotated : roundEnv.getElementsAnnotatedWith(ScopeReferences.class)) {
124
            final LayerBuilder builder = layer(annotated);
125
            ScopeReferences refs = annotated.getAnnotation(ScopeReferences.class);
126
            if (refs == null) {
127
                continue;
128
            }
129
            for (ScopeReference ar : refs.value()) {
130
                processReference(ar, annotated, builder);
131
            }
132
        }
133
134
        for (Element annotated : roundEnv.getElementsAnnotatedWith(scopeReference)) {
135
            ScopeReference ar = annotated.getAnnotation(ScopeReference.class);
136
            processReference(ar, annotated, layer(annotated));
137
        }
138
    }
139
    private static final String ERR_SUPER_TYPE = "The class must extend org.netbeans.modules.refactoring.api.AbstractAnnotatedRefactoring";
140
    private static final String ERR_ID_NEEDED = "This annotation needs to be used together with ScopeDescription, or you need to specify the id.";
141
142
    private String getFQN(TypeElement clazz) {
143
        return processingEnv.getElementUtils().getBinaryName(clazz).toString();
144
    }
145
146
    private void processReference(ScopeReference ar, Element annotated, LayerBuilder builder) {
147
        String id = ar.id();
148
        if (id.isEmpty()) {
149
            ScopeDescription desc = annotated.getAnnotation(ScopeDescription.class);
150
            if (desc == null) {
151
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ERR_ID_NEEDED, annotated);
152
            } else {
153
                id = desc.id();
154
            }
155
        }
156
        LayerBuilder.File f = builder.file("Scopes/" + ar.path() + "/" + id + ".shadow");
157
        f.stringvalue("originalFile", "Scopes/ScopeDescriptions/" + id + ".instance");
158
        f.write();
159
    }
160
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/impl/Scopes.java (+223 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.impl;
43
44
import java.awt.Image;
45
import java.awt.Toolkit;
46
import java.net.URL;
47
import java.util.Map;
48
import java.util.concurrent.atomic.AtomicBoolean;
49
import javax.swing.Icon;
50
import org.netbeans.modules.refactoring.api.Scope;
51
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
52
import org.openide.util.ImageUtilities;
53
import org.openide.util.Lookup;
54
55
/**
56
 *
57
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
58
 */
59
public class Scopes {
60
61
    public static ScopeProvider create(Map m) {
62
        return new ScopeProviderImpl(m);
63
    }
64
65
    public static ScopeProvider.CustomScopeProvider createCustom(Map m) {
66
        return new CustomScopeProviderImpl(m);
67
    }
68
69
    public static class ScopeProviderImpl extends ScopeProvider implements ScopeInformation {
70
71
        private final String displayName;
72
        private final Icon icon;
73
        private final ScopeProvider delegate;
74
        private final String id;
75
        private final Integer position;
76
77
        public ScopeProviderImpl(Map m) {
78
            displayName = (String) m.get("displayName"); // NOI18N
79
            id = (String) m.get("id"); // NOI18N
80
            position = (Integer) m.get("position"); // NOI18N
81
            icon = resolveIcon(m.get("iconBase")); // NOI18N
82
            Object scopeProvider = m.get("delegate");
83
            if (!(scopeProvider instanceof ScopeProvider)) {
84
                throw new NullPointerException("No 'delegate' in " + m);
85
            }
86
            delegate = (ScopeProvider) scopeProvider;
87
        }
88
        
89
        @Override
90
        public String getId() {
91
            return id;
92
        }
93
94
        @Override
95
        public int getPosition() {
96
            return position;
97
        }
98
99
        @Override
100
        public Icon getIcon() {
101
            Icon delegateIcon = delegate.getIcon();
102
            return delegateIcon == null ? this.icon : delegateIcon;
103
        }
104
105
        @Override
106
        public String getDisplayName() {
107
            return displayName;
108
        }
109
110
        @Override
111
        public String getDetail() {
112
            return delegate.getDetail();
113
        }
114
115
        @Override
116
        public boolean initialize(Lookup context, AtomicBoolean cancel) {
117
            return delegate.initialize(context, cancel);
118
        }
119
120
        @Override
121
        public Scope getScope() {
122
            return delegate.getScope();
123
        }
124
    }
125
126
    public static class CustomScopeProviderImpl extends ScopeProvider.CustomScopeProvider implements ScopeInformation {
127
        private final String displayName;
128
        private final Icon icon;
129
        private final CustomScopeProvider delegate;
130
        private final String id;
131
        private final Integer position;
132
133
        private CustomScopeProviderImpl(Map m) {
134
            displayName = (String) m.get("displayName"); // NOI18N
135
            id = (String) m.get("id"); // NOI18N
136
            position = (Integer) m.get("position"); // NOI18N
137
            icon = resolveIcon(m.get("iconBase")); // NOI18N
138
            Object scopeProvider = m.get("delegate");
139
            if (!(scopeProvider instanceof CustomScopeProvider)) {
140
                throw new NullPointerException("No 'delegate' in " + m);
141
            }
142
            delegate = (CustomScopeProvider) scopeProvider;
143
        }
144
145
        @Override
146
        public String getId() {
147
            return id;
148
        }
149
150
        @Override
151
        public int getPosition() {
152
            return position;
153
        }
154
        
155
        @Override
156
        public Icon getIcon() {
157
            Icon delegateIcon = delegate.getIcon();
158
            return delegateIcon == null ? this.icon : delegateIcon;
159
        }
160
        
161
        @Override
162
        public String getDisplayName() {
163
            return displayName;
164
        }
165
166
        @Override
167
        public String getDetail() {
168
            return delegate.getDetail();
169
        }
170
171
        @Override
172
        public void setScope(Scope value) {
173
            delegate.setScope(value);
174
        }
175
176
        @Override
177
        public boolean showCustomizer() {
178
            return delegate.showCustomizer();
179
        }
180
181
        @Override
182
        public boolean initialize(Lookup context, AtomicBoolean cancel) {
183
            return delegate.initialize(context, cancel);
184
        }
185
186
        @Override
187
        public Scope getScope() {
188
            return delegate.getScope();
189
        }
190
    }
191
192
    private static Icon resolveIcon(Object icon) {
193
        if (icon instanceof Icon) {
194
            return (Icon) icon;
195
        }
196
        if (icon instanceof URL) {
197
            icon = Toolkit.getDefaultToolkit().getImage((URL) icon);
198
        }
199
        if (icon instanceof Image) {
200
            return ImageUtilities.image2Icon((Image) icon);
201
        }
202
        if (icon instanceof String) {
203
            return ImageUtilities.loadImageIcon((String) icon, true);
204
        }
205
        return null;
206
    }
207
208
    public static interface ScopeInformation {
209
        public String getDisplayName();
210
        
211
        public int getPosition();
212
        
213
        public String getId();
214
215
        public String getDetail();
216
217
        public Icon getIcon();
218
219
        public boolean initialize(Lookup context, AtomicBoolean cancel);
220
221
        public Scope getScope();
222
    }
223
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/Bundle.properties (+1 lines)
Line 0 Link Here
1
LBL_Scope=Sco&pe:
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ExpandableTreeElement.java (+67 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import org.openide.util.Cancellable;
45
46
/**
47
 * ExpandableTreeElements are shown in the Find Usages results.
48
 * ExpandableTreeElement allows a TreeElement to have children. It will be
49
 * iterated when the TreeElement is expanded. The iterator is allowed to block,
50
 * it will be called from outside of AWT.
51
 * 
52
 * @author Jan Lahoda
53
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
54
 * @see TreeElement
55
 * @since 1.30
56
 */
57
public interface ExpandableTreeElement extends TreeElement, Iterable<TreeElement>, Cancellable {
58
59
    /**
60
     * Gives an estimate of the amount of children this element has.
61
     * The estimatedChildCount will be used to give the user a rough count
62
     * of found occurrences.
63
     * @return the estimated child count
64
     */
65
    public int estimateChildCount();
66
    
67
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopeDescription.java (+86 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import java.lang.annotation.ElementType;
45
import java.lang.annotation.Retention;
46
import java.lang.annotation.RetentionPolicy;
47
import java.lang.annotation.Target;
48
49
/**
50
 *
51
 * @author Jan Lahoda
52
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
53
 * @since 1.30
54
 */
55
@Target({ElementType.TYPE})
56
@Retention(RetentionPolicy.SOURCE)
57
public @interface ScopeDescription {
58
59
    /**
60
     * The unique ID of the scope description.
61
     *
62
     * @return unique id
63
     */
64
    String id();
65
66
    /**
67
     * Display name. Usually prefixed with '#' to reference value from a
68
     * <code>Bundle.properties</code> file in the same package.
69
     *
70
     * @return display name for the scope
71
     */
72
    String displayName();
73
74
    /**
75
     * Path to image representing the scope's icon.
76
     *
77
     * @return "org/myproject/mypkg/Icon.png"
78
     */
79
    String iconBase() default "";
80
81
    /**
82
     * Position in the location. Negative numbers can be used for scopes that
83
     * should be higher in the list, but not selected by default.
84
     */
85
    int position() default Integer.MAX_VALUE;
86
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopePanel.form (+58 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8" ?>
2
3
<Form version="1.5" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
4
  <AuxValues>
5
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="1"/>
6
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
7
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
8
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
9
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="true"/>
10
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
11
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
12
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
13
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
14
  </AuxValues>
15
16
  <Layout>
17
    <DimensionLayout dim="0">
18
      <Group type="103" groupAlignment="0" attributes="0">
19
          <Group type="102" alignment="0" attributes="0">
20
              <Component id="scopeCombobox" pref="343" max="32767" attributes="0"/>
21
              <EmptySpace max="-2" attributes="0"/>
22
              <Component id="btnCustomScope" min="-2" max="-2" attributes="0"/>
23
          </Group>
24
      </Group>
25
    </DimensionLayout>
26
    <DimensionLayout dim="1">
27
      <Group type="103" groupAlignment="0" attributes="0">
28
          <Group type="103" alignment="0" groupAlignment="3" attributes="0">
29
              <Component id="btnCustomScope" alignment="3" min="-2" max="-2" attributes="0"/>
30
              <Component id="scopeCombobox" alignment="3" min="-2" max="-2" attributes="1"/>
31
          </Group>
32
      </Group>
33
    </DimensionLayout>
34
  </Layout>
35
  <SubComponents>
36
    <Component class="javax.swing.JButton" name="btnCustomScope">
37
      <Properties>
38
        <Property name="action" type="javax.swing.Action" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
39
          <Connection code="new ScopeAction(scopeCombobox)" type="code"/>
40
        </Property>
41
        <Property name="text" type="java.lang.String" value="..." noResource="true"/>
42
      </Properties>
43
    </Component>
44
    <Component class="javax.swing.JComboBox" name="scopeCombobox">
45
      <Properties>
46
        <Property name="renderer" type="javax.swing.ListCellRenderer" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
47
          <Connection code="new ScopeDescriptionRenderer()" type="code"/>
48
        </Property>
49
      </Properties>
50
      <Events>
51
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="scopeComboboxActionPerformed"/>
52
      </Events>
53
      <AuxValues>
54
        <AuxValue name="JavaCodeGenerator_InitCodePost" type="java.lang.String" value="((javax.swing.JTextField) scopeCombobox.getEditor().getEditorComponent()).setColumns(SCOPE_COMBOBOX_COLUMNS);"/>
55
      </AuxValues>
56
    </Component>
57
  </SubComponents>
58
</Form>
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopePanel.java (+359 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import java.awt.Component;
45
import java.awt.event.ActionEvent;
46
import java.util.ArrayList;
47
import java.util.Collection;
48
import java.util.Collections;
49
import java.util.Comparator;
50
import java.util.List;
51
import java.util.concurrent.atomic.AtomicBoolean;
52
import java.util.prefs.Preferences;
53
import javax.swing.AbstractAction;
54
import javax.swing.ComboBoxModel;
55
import javax.swing.DefaultComboBoxModel;
56
import javax.swing.JComboBox;
57
import javax.swing.JLabel;
58
import javax.swing.JList;
59
import javax.swing.ListCellRenderer;
60
import javax.swing.SwingUtilities;
61
import javax.swing.plaf.UIResource;
62
import org.netbeans.api.annotations.common.CheckForNull;
63
import org.netbeans.api.annotations.common.NonNull;
64
import org.netbeans.modules.refactoring.api.Scope;
65
import org.netbeans.modules.refactoring.spi.impl.Scopes;
66
import org.openide.util.Lookup;
67
import org.openide.util.lookup.Lookups;
68
69
/**
70
 * ScopePanel provides a component to use for scope selection. A customize
71
 * button (a JButton with ellipses) will be displayed when any of the registered
72
 * scopes is customizable.
73
 *
74
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
75
 * @since 1.30
76
 */
77
public class ScopePanel extends javax.swing.JPanel {
78
    
79
    private static final String ELLIPSIS = "\u2026"; //NOI18N
80
    private static final int SCOPE_COMBOBOX_COLUMNS = 14;
81
    private final String id;
82
    private final Preferences preferences;
83
    private final String preferencesKey;
84
    
85
    /**
86
     * Creates new form ScopePanel.
87
     *
88
     * @deprecated do not use this constructor. Only available for the Matisse
89
     * GUI-builder.
90
     */
91
    @Deprecated
92
    public ScopePanel() {
93
        this(null, null, null);
94
    }
95
    
96
    /**
97
     * Creates a new ScopePanel. The supplied id will be used to only get the
98
     * Scopes registered for a specific set of Scopes. The preferences and
99
     * preferencesKey will be used to store the user's selection.
100
     *
101
     * @param id the id for which the scopes are registered
102
     * @param preferences a preferences object to store user's selection
103
     * @param preferencesKey a key to use to store user's selection
104
     */
105
    public ScopePanel(String id, Preferences preferences, String preferencesKey) {
106
        this.id = id;
107
        this.preferences = preferences;
108
        this.preferencesKey = preferencesKey;
109
        initComponents();
110
    }
111
    
112
    /**
113
     * Initializes the Combobox and customize button of this ScopePanel. The
114
     * context will be passed to the different ScopeProviders initialize method.
115
     * This method will return false if there are no available scopes and this
116
     * panel should not be available to the user.
117
     *
118
     * @param context the Lookup to pass to the ScopeProviders
119
     * @return true if there is at least one Scope available, false otherwise
120
     */
121
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
122
        final List<Scopes.ScopeInformation> scopes = new ArrayList<Scopes.ScopeInformation>();
123
        Collection<? extends ScopeProvider> scopeProviders = Lookups.forPath("Scopes" + "/" + id).lookupAll(ScopeProvider.class);
124
        final AtomicBoolean customizable = new AtomicBoolean();
125
        for (ScopeProvider provider : scopeProviders) {
126
            if(provider.initialize(context, new AtomicBoolean())) {
127
                scopes.add((Scopes.ScopeInformation)provider);
128
                if(provider instanceof ScopeProvider.CustomScopeProvider) {
129
                    customizable.set(true);
130
                }
131
            }
132
        }
133
134
        Collections.sort(scopes, new Comparator<Scopes.ScopeInformation>() {
135
            @Override public int compare(Scopes.ScopeInformation o1, Scopes.ScopeInformation o2) {
136
                return (o1.getPosition()<o2.getPosition() ? -1 : (o1.getPosition()==o2.getPosition() ? 0 : 1));
137
            }
138
        });
139
        if(!scopes.isEmpty()) {
140
            SwingUtilities.invokeLater(new Runnable() {
141
142
                @Override
143
                public void run() {
144
                    DefaultComboBoxModel model = new DefaultComboBoxModel();
145
                    for (Scopes.ScopeInformation sd : scopes) {
146
                        model.addElement(sd);
147
                    }
148
                    scopeCombobox.setModel(model);
149
                    if(!customizable.get()) {
150
                        ScopePanel.this.btnCustomScope.setVisible(false);
151
                    }
152
                    String preselectId = preferences.get(preferencesKey, null);
153
                    if (preselectId == null) { // Needed for the old preferences of Java's Where Used Panel.
154
                        int defaultItem = (Integer) preferences.getInt(preferencesKey, -1); // NOI18N
155
                        if (defaultItem != (-1)) {
156
                            switch (defaultItem) {
157
                                case 0: preselectId = "all-projects"; break;
158
                                case 1: preselectId = "current-project"; break;
159
                                case 2: preselectId = "current-package"; break;
160
                                case 3: preselectId = "current-file"; break;
161
                                case 4: preselectId = "custom-scope"; break;
162
                            }
163
                        }
164
                    }
165
                    if(preselectId != null) {
166
                        selectScopeById(preselectId);
167
                    } else {
168
                        selectPreferredScope();
169
                    }
170
                }
171
            });
172
        }
173
        return !scopes.isEmpty();
174
    }
175
    
176
    /**
177
     * The currently selected scope in the Combobox. This can be a predefined
178
     * scope, or a customized one.
179
     *
180
     * @return the selected Scope
181
     */
182
    public @CheckForNull Scope getSelectedScope() {
183
        return ((ScopeProvider) scopeCombobox.getSelectedItem()).getScope();
184
    }
185
186
    /**
187
     * This method is called from within the constructor to initialize the form.
188
     * WARNING: Do NOT modify this code. The content of this method is always
189
     * regenerated by the Form Editor.
190
     */
191
    @SuppressWarnings("unchecked")
192
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
193
    private void initComponents() {
194
195
        btnCustomScope = new javax.swing.JButton();
196
        scopeCombobox = new javax.swing.JComboBox();
197
198
        btnCustomScope.setAction(new ScopeAction(scopeCombobox));
199
        org.openide.awt.Mnemonics.setLocalizedText(btnCustomScope, "..."); // NOI18N
200
201
        scopeCombobox.setRenderer(new ScopeDescriptionRenderer());
202
        ((javax.swing.JTextField) scopeCombobox.getEditor().getEditorComponent()).setColumns(SCOPE_COMBOBOX_COLUMNS);
203
        scopeCombobox.addActionListener(new java.awt.event.ActionListener() {
204
            public void actionPerformed(java.awt.event.ActionEvent evt) {
205
                scopeComboboxActionPerformed(evt);
206
            }
207
        });
208
209
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
210
        this.setLayout(layout);
211
        layout.setHorizontalGroup(
212
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
213
            .addGroup(layout.createSequentialGroup()
214
                .addComponent(scopeCombobox, 0, 343, Short.MAX_VALUE)
215
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
216
                .addComponent(btnCustomScope))
217
        );
218
        layout.setVerticalGroup(
219
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
220
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
221
                .addComponent(btnCustomScope)
222
                .addComponent(scopeCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
223
        );
224
    }// </editor-fold>//GEN-END:initComponents
225
226
    private void scopeComboboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scopeComboboxActionPerformed
227
        preferences.putInt(preferencesKey, scopeCombobox.getSelectedIndex());
228
    }//GEN-LAST:event_scopeComboboxActionPerformed
229
230
    // Variables declaration - do not modify//GEN-BEGIN:variables
231
    private javax.swing.JButton btnCustomScope;
232
    private javax.swing.JComboBox scopeCombobox;
233
    // End of variables declaration//GEN-END:variables
234
235
    /**
236
     * Change the selected scope to one with the specified id. If the id does
237
     * not exist, nothing is changed. When the id is from a CustomScopeProvider
238
     * and it returns an empty scope, the preferred scope is selected.
239
     *
240
     * @see ScopeProvider.CustomScopeProvider
241
     *
242
     * @param id the id of the scope to select
243
     */
244
    public void selectScopeById(@NonNull String id) {
245
        ComboBoxModel m = scopeCombobox.getModel();
246
247
        for (int i = 0; i < m.getSize(); i++) {
248
            Scopes.ScopeInformation sd = (Scopes.ScopeInformation) m.getElementAt(i);
249
250
            if (sd.getId().equals(id)) {
251
                if (sd instanceof ScopeProvider.CustomScopeProvider) {
252
                    Scope s = sd.getScope();
253
                    if (s !=null &&
254
                        s.getFiles().isEmpty() &&
255
                        s.getFolders().isEmpty() &&
256
                        s.getSourceRoots().isEmpty()) {
257
                        selectPreferredScope();
258
                        return;
259
                    }
260
                }
261
                scopeCombobox.setSelectedItem(sd);
262
                return ;
263
            }
264
        }
265
    }
266
    
267
    private void selectPreferredScope() {
268
        ComboBoxModel m = scopeCombobox.getModel();
269
270
        for (int i = 0; i < m.getSize(); i++) {
271
            Scopes.ScopeInformation sd = (Scopes.ScopeInformation) m.getElementAt(i);
272
273
            if (sd.getPosition() >= 0) {
274
                scopeCombobox.setSelectedItem(sd);
275
                return;
276
            }
277
        }
278
    }
279
    
280
    private class ScopeAction extends AbstractAction {
281
        private final JComboBox scopeCombobox;
282
283
        private ScopeAction(JComboBox scopeCombobox) {
284
            this.scopeCombobox = scopeCombobox;
285
            this.putValue(NAME, ELLIPSIS);
286
        }
287
288
        @Override
289
        public void actionPerformed(ActionEvent e) {
290
            ComboBoxModel m = this.scopeCombobox.getModel();
291
            ScopeProvider selectedScope = (ScopeProvider) scopeCombobox.getSelectedItem();
292
            Scope scope = selectedScope.getScope();
293
            if (selectedScope instanceof ScopeProvider.CustomScopeProvider) {
294
                showCustomizer((Scopes.CustomScopeProviderImpl)selectedScope, scope);
295
            } else {
296
                for (int i = 0; i < m.getSize(); i++) {
297
                    ScopeProvider sd = (ScopeProvider) m.getElementAt(i);
298
299
                    if (sd instanceof Scopes.CustomScopeProviderImpl) {
300
                        showCustomizer((Scopes.CustomScopeProviderImpl)sd, scope);
301
                        break;
302
                    }
303
                }
304
            }
305
        }
306
307
        private void showCustomizer(Scopes.CustomScopeProviderImpl csd, Scope scope) {
308
            csd.setScope(scope);
309
            if (csd.showCustomizer()) {
310
                selectScopeById(csd.getId());
311
            }
312
        }
313
    }
314
    
315
    private static class ScopeDescriptionRenderer extends JLabel implements ListCellRenderer, UIResource {
316
        public ScopeDescriptionRenderer () {
317
            setOpaque(true);
318
        }
319
        @Override
320
        public Component getListCellRendererComponent(
321
                JList list,
322
                Object value,
323
                int index,
324
                boolean isSelected,
325
                boolean cellHasFocus) {
326
            
327
            // #89393: GTK needs name to render cell renderer "natively"
328
            setName("ComboBox.listRenderer"); // NOI18N
329
            Scopes.ScopeInformation scopeDescription = null;
330
            if(value instanceof Scopes.ScopeInformation) {
331
                scopeDescription = (Scopes.ScopeInformation)value;
332
            }
333
            if ( scopeDescription != null ) {
334
                String detail = scopeDescription.getDetail();
335
                String displayName = scopeDescription.getDisplayName();
336
                setText(detail == null ? displayName : displayName + " (" + detail + ")");
337
                setIcon(scopeDescription.getIcon());
338
            }
339
            
340
            if ( isSelected ) {
341
                setBackground(list.getSelectionBackground());
342
                setForeground(list.getSelectionForeground());
343
            } else {
344
                setBackground(list.getBackground());
345
                setForeground(list.getForeground());
346
            }
347
            
348
            return this;
349
        }
350
        
351
        // #89393: GTK needs name to render cell renderer "natively"
352
        @Override
353
        public String getName() {
354
            String name = super.getName();
355
            return name == null ? "ComboBox.renderer" : name;  // NOI18N
356
        }
357
    }
358
359
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopeProvider.java (+145 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import java.util.concurrent.atomic.AtomicBoolean;
45
import javax.swing.Icon;
46
import org.netbeans.api.annotations.common.CheckForNull;
47
import org.netbeans.api.annotations.common.NonNull;
48
import org.netbeans.api.annotations.common.NullAllowed;
49
import org.netbeans.modules.refactoring.api.Scope;
50
import org.openide.util.Lookup;
51
52
/**
53
 * ScopeProvider is used to add a scope to the {@link ScopePanel}.
54
 *
55
 * @see ScopePanel
56
 * @see ScopeDescription
57
 * @see ScopeReference
58
 *
59
 * @author Jan Lahoda
60
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
61
 *
62
 * @since 1.30
63
 */
64
public abstract class ScopeProvider {
65
66
    /**
67
     * Initialize this scope provider with the supplied context.
68
     *
69
     * @param context a Lookup defining the context
70
     * @param cancel set to true if initialization should be canceled
71
     * @return true if this scope is usable for the supplied context, false
72
     * otherwise
73
     */
74
    public abstract boolean initialize(@NonNull Lookup context, @NonNull AtomicBoolean cancel);
75
76
    /**
77
     * Get this provider's scope. The scope can be null if this provider is not
78
     * yet initialized, or this provider is not usable for the supplied context.
79
     *
80
     * @see ScopeProvider#initialize(org.openide.util.Lookup,
81
     * java.util.concurrent.atomic.AtomicBoolean)
82
     * @return the Scope
83
     */
84
    @CheckForNull
85
    public abstract Scope getScope();
86
87
    /**
88
     * Override this method if the icon should be different depending on the
89
     * context.
90
     *
91
     * @see ScopeProvider#initialize(org.openide.util.Lookup,
92
     * java.util.concurrent.atomic.AtomicBoolean)
93
     * @see ScopeDescription
94
     * @return an icon for the Scope, or null if the default should be used.
95
     */
96
    @CheckForNull
97
    public Icon getIcon() {
98
        return null;
99
    }
100
101
    /**
102
     * Override this method if an explaining string should be displayed behind
103
     * the scope's name. This is used for scopes like "- Current File
104
     * (Filename.java)".
105
     *
106
     * @return an explaining string, or null of nothing should be displayed.
107
     */
108
    @CheckForNull
109
    public String getDetail() {
110
        return null;
111
    }
112
113
    /**
114
     * The CustomScopeProvider extends the normal scope provider to support
115
     * scopes which can be customized by the user.
116
     *
117
     * @see ScopePanel
118
     * @see ScopeDescription
119
     * @see ScopeReference
120
     *
121
     * @author Jan Lahoda
122
     * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
123
     *
124
     * @since 1.30
125
     */
126
    public static abstract class CustomScopeProvider extends ScopeProvider {
127
128
        /**
129
         * Set the scope to be customized. This method will be called right
130
         * before the provider is asked to show the customizer, with the
131
         * currently selected scope.
132
         *
133
         * @param currentScope the Scope currently selected
134
         */
135
        public abstract void setScope(@NullAllowed Scope currentScope);
136
137
        /**
138
         * Show a Dialog to customize the scope.
139
         *
140
         * @return true if the user succesfully specified a scope, false
141
         * otherwise (ie. clicked cancel)
142
         */
143
        public abstract boolean showCustomizer();
144
    }
145
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopeReference.java (+72 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import java.lang.annotation.ElementType;
45
import java.lang.annotation.Retention;
46
import java.lang.annotation.RetentionPolicy;
47
import java.lang.annotation.Target;
48
49
/**
50
 * A reference to a Scope Description to be used by a {@link ScopePanel}
51
 *
52
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
53
 * @since 1.30
54
 */
55
@Target({ElementType.TYPE})
56
@Retention(RetentionPolicy.SOURCE)
57
public @interface ScopeReference {
58
59
    /**
60
     * Into which location one wants to place the reference? Translates to
61
     * {@link FileUtil#getConfigFile(java.lang.String)}.
62
     */
63
    String path();
64
65
    /**
66
     * Identification of the scope this reference shall point to. Usually this
67
     * is specified as {@link ScopeDescription} peer annotation, but in case one
68
     * was to create references to scopes defined by someone else, one can
69
     * specify the id() here.
70
     */
71
    String id() default "";
72
}
(-)a/refactoring.api/src/org/netbeans/modules/refactoring/spi/ui/ScopeReferences.java (+59 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.spi.ui;
43
44
import java.lang.annotation.ElementType;
45
import java.lang.annotation.Retention;
46
import java.lang.annotation.RetentionPolicy;
47
import java.lang.annotation.Target;
48
49
/**
50
 * Allows registration of multiple {@link ScopeReference}s for a single type.
51
 *
52
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
53
 */
54
@Target({ElementType.TYPE})
55
@Retention(RetentionPolicy.SOURCE)
56
public @interface ScopeReferences {
57
58
    ScopeReference[] value();
59
}
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/api/ui/JavaScopeBuilder.java (-1 / +1 lines)
Lines 45-51 Link Here
45
import java.awt.event.ActionListener;
45
import java.awt.event.ActionListener;
46
import java.util.concurrent.atomic.AtomicBoolean;
46
import java.util.concurrent.atomic.AtomicBoolean;
47
import org.netbeans.modules.refactoring.api.Scope;
47
import org.netbeans.modules.refactoring.api.Scope;
48
import org.netbeans.modules.refactoring.java.ui.CustomScopePanel;
48
import org.netbeans.modules.refactoring.java.ui.scope.CustomScopePanel;
49
import org.openide.DialogDescriptor;
49
import org.openide.DialogDescriptor;
50
import org.openide.DialogDisplayer;
50
import org.openide.DialogDisplayer;
51
import org.openide.util.HelpCtx;
51
import org.openide.util.HelpCtx;
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/Bundle.properties (-9 / +1 lines)
Lines 49-60 Link Here
49
LBL_IntroduceParameter=Introduce Parameter
49
LBL_IntroduceParameter=Introduce Parameter
50
50
51
DSC_Rename=Rename <b>{0}</b> to <b>{1}</b>
51
DSC_Rename=Rename <b>{0}</b> to <b>{1}</b>
52
LBL_CustomScope=Custom Scope...
53
DLG_CustomScope=Custom Scope
54
LBL_CurrentFile=Current File ({0})
55
LBL_CurrentPackage=Current Package ({0})
56
LBL_CurrentProject=Current Project ({0})
57
LBL_WaitNode=Please Wait...
58
52
59
LBL_EncapsulateFieldsAction=Encapsula&te Fields...
53
LBL_EncapsulateFieldsAction=Encapsula&te Fields...
60
LBL_EncapsulateFields=Encapsulate Fields
54
LBL_EncapsulateFields=Encapsulate Fields
Lines 418-426 Link Here
418
412
419
LBL_chngsigdecl=Change {0} parameters of {1}
413
LBL_chngsigdecl=Change {0} parameters of {1}
420
414
421
LBL_Scope=Sco&pe\: 
422
LBL_AllProjects=Open Projects
423
424
ExtractSuperclassPanel.nameLabel.AccessibleContext.accessibleDescription=N/A
415
ExtractSuperclassPanel.nameLabel.AccessibleContext.accessibleDescription=N/A
425
416
426
ExtractSuperclassPanel.chooseLabel.AccessibleContext.accessibleDescription=N/A
417
ExtractSuperclassPanel.chooseLabel.AccessibleContext.accessibleDescription=N/A
Lines 496-498 Link Here
496
ReplaceConstructorWithBuilder.jLabel1.text=&Builder Class Name:
487
ReplaceConstructorWithBuilder.jLabel1.text=&Builder Class Name:
497
ReplaceConstructorWithBuilderName=Replace Constructor With Builder
488
ReplaceConstructorWithBuilderName=Replace Constructor With Builder
498
ReplaceConstructorWithBuilderDescription=Replace Constructor {0} with Builder {1}
489
ReplaceConstructorWithBuilderDescription=Replace Constructor {0} with Builder {1}
490
WhereUsedPanel.jLabel1.text=Sco&pe:
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/WhereUsedPanel.form (-74 / +27 lines)
Lines 20-112 Link Here
20
  <Layout>
20
  <Layout>
21
    <DimensionLayout dim="0">
21
    <DimensionLayout dim="0">
22
      <Group type="103" groupAlignment="0" attributes="0">
22
      <Group type="103" groupAlignment="0" attributes="0">
23
          <Component id="scopePanel" max="32767" attributes="0"/>
23
          <Component id="innerPanel" max="32767" attributes="0"/>
24
          <Component id="innerPanel" pref="361" max="32767" attributes="0"/>
24
          <Group type="102" alignment="1" attributes="0">
25
              <EmptySpace max="-2" attributes="0"/>
26
              <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
27
              <EmptySpace max="-2" attributes="0"/>
28
              <Component id="scope" pref="487" max="32767" attributes="0"/>
29
              <EmptySpace max="-2" attributes="0"/>
30
          </Group>
25
      </Group>
31
      </Group>
26
    </DimensionLayout>
32
    </DimensionLayout>
27
    <DimensionLayout dim="1">
33
    <DimensionLayout dim="1">
28
      <Group type="103" groupAlignment="0" attributes="0">
34
      <Group type="103" groupAlignment="0" attributes="0">
29
          <Group type="102" alignment="0" attributes="0">
35
          <Group type="102" alignment="0" attributes="0">
30
              <Component id="innerPanel" pref="45" max="32767" attributes="0"/>
36
              <Component id="innerPanel" pref="169" max="32767" attributes="0"/>
31
              <EmptySpace min="-2" max="-2" attributes="0"/>
37
              <EmptySpace max="-2" attributes="0"/>
32
              <Component id="scopePanel" min="-2" max="-2" attributes="0"/>
38
              <Group type="103" groupAlignment="0" max="-2" attributes="0">
39
                  <Component id="scope" max="32767" attributes="0"/>
40
                  <Component id="jLabel1" max="32767" attributes="0"/>
41
              </Group>
42
              <EmptySpace max="-2" attributes="0"/>
33
          </Group>
43
          </Group>
34
      </Group>
44
      </Group>
35
    </DimensionLayout>
45
    </DimensionLayout>
36
  </Layout>
46
  </Layout>
37
  <SubComponents>
47
  <SubComponents>
38
    <Container class="javax.swing.JPanel" name="scopePanel">
39
40
      <Layout>
41
        <DimensionLayout dim="0">
42
          <Group type="103" groupAlignment="0" attributes="0">
43
              <Group type="102" alignment="0" attributes="0">
44
                  <EmptySpace max="-2" attributes="0"/>
45
                  <Component id="scopeLabel" min="-2" max="-2" attributes="0"/>
46
                  <EmptySpace max="-2" attributes="0"/>
47
                  <Component id="scope" max="32767" attributes="0"/>
48
                  <EmptySpace max="-2" attributes="0"/>
49
                  <Component id="btnCustomScope" min="-2" max="-2" attributes="0"/>
50
                  <EmptySpace max="-2" attributes="0"/>
51
              </Group>
52
          </Group>
53
        </DimensionLayout>
54
        <DimensionLayout dim="1">
55
          <Group type="103" groupAlignment="0" attributes="0">
56
              <Group type="102" alignment="0" attributes="0">
57
                  <EmptySpace max="-2" attributes="0"/>
58
                  <Group type="103" groupAlignment="0" attributes="0">
59
                      <Group type="102" alignment="0" attributes="0">
60
                          <EmptySpace min="-2" pref="6" max="-2" attributes="0"/>
61
                          <Component id="scopeLabel" min="-2" max="-2" attributes="1"/>
62
                      </Group>
63
                      <Group type="103" groupAlignment="3" attributes="0">
64
                          <Component id="btnCustomScope" alignment="3" min="-2" max="-2" attributes="0"/>
65
                          <Component id="scope" alignment="3" min="-2" max="-2" attributes="1"/>
66
                      </Group>
67
                  </Group>
68
                  <EmptySpace min="-2" max="-2" attributes="0"/>
69
              </Group>
70
          </Group>
71
        </DimensionLayout>
72
      </Layout>
73
      <SubComponents>
74
        <Component class="javax.swing.JLabel" name="scopeLabel">
75
          <Properties>
76
            <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
77
              <ComponentRef name="scope"/>
78
            </Property>
79
            <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
80
              <ResourceString bundle="org/netbeans/modules/refactoring/java/ui/Bundle.properties" key="LBL_Scope" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
81
            </Property>
82
          </Properties>
83
          <AuxValues>
84
            <AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
85
          </AuxValues>
86
        </Component>
87
        <Component class="javax.swing.JComboBox" name="scope">
88
          <AccessibilityProperties>
89
            <Property name="AccessibleContext.accessibleDescription" type="java.lang.String" value="N/A"/>
90
          </AccessibilityProperties>
91
          <Events>
92
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="scopeActionPerformed"/>
93
          </Events>
94
          <AuxValues>
95
            <AuxValue name="JavaCodeGenerator_InitCodePost" type="java.lang.String" value="((javax.swing.JTextField) scope.getEditor().getEditorComponent()).setColumns(SCOPE_COMBOBOX_COLUMNS);"/>
96
          </AuxValues>
97
        </Component>
98
        <Component class="javax.swing.JButton" name="btnCustomScope">
99
          <Properties>
100
            <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
101
              <Connection code="ELLIPSIS" type="code"/>
102
            </Property>
103
          </Properties>
104
        </Component>
105
      </SubComponents>
106
    </Container>
107
    <Container class="javax.swing.JPanel" name="innerPanel">
48
    <Container class="javax.swing.JPanel" name="innerPanel">
108
49
109
      <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
50
      <Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
110
    </Container>
51
    </Container>
52
    <Component class="org.netbeans.modules.refactoring.spi.ui.ScopePanel" name="scope">
53
      <AuxValues>
54
        <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new org.netbeans.modules.refactoring.spi.ui.ScopePanel(WhereUsedPanel.class.getCanonicalName().replace(&apos;.&apos;, &apos;-&apos;), NbPreferences.forModule(WhereUsedPanel.class), &quot;whereUsed.scope&quot;)"/>
55
      </AuxValues>
56
    </Component>
57
    <Component class="javax.swing.JLabel" name="jLabel1">
58
      <Properties>
59
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
60
          <ResourceString bundle="org/netbeans/modules/refactoring/java/ui/Bundle.properties" key="WhereUsedPanel.jLabel1.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
61
        </Property>
62
      </Properties>
63
    </Component>
111
  </SubComponents>
64
  </SubComponents>
112
</Form>
65
</Form>
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/WhereUsedPanel.java (-301 / +24 lines)
Lines 43-88 Link Here
43
 */
43
 */
44
package org.netbeans.modules.refactoring.java.ui;
44
package org.netbeans.modules.refactoring.java.ui;
45
45
46
import com.sun.source.tree.ExpressionTree;
47
import com.sun.source.util.TreePath;
48
import java.awt.BorderLayout;
46
import java.awt.BorderLayout;
49
import java.awt.Component;
47
import java.awt.Component;
50
import java.awt.event.ActionEvent;
51
import java.beans.BeanInfo;
52
import java.io.IOException;
48
import java.io.IOException;
53
import java.net.MalformedURLException;
54
import java.net.URL;
55
import java.util.Arrays;
49
import java.util.Arrays;
56
import java.util.LinkedList;
57
import java.util.List;
50
import java.util.List;
58
import java.util.Set;
51
import java.util.concurrent.atomic.AtomicBoolean;
59
import java.util.prefs.BackingStoreException;
60
import java.util.prefs.Preferences;
61
import javax.lang.model.element.Element;
52
import javax.lang.model.element.Element;
62
import javax.lang.model.element.ElementKind;
53
import javax.lang.model.element.ElementKind;
63
import javax.lang.model.element.Modifier;
54
import javax.lang.model.element.Modifier;
64
import javax.swing.*;
55
import javax.swing.*;
65
import javax.swing.event.ChangeListener;
56
import javax.swing.event.ChangeListener;
66
import javax.swing.plaf.UIResource;
67
import org.netbeans.api.fileinfo.NonRecursiveFolder;
68
import org.netbeans.api.java.project.JavaProjectConstants;
69
import org.netbeans.api.java.source.*;
57
import org.netbeans.api.java.source.*;
70
import org.netbeans.api.java.source.JavaSource.Phase;
58
import org.netbeans.api.java.source.JavaSource.Phase;
71
import org.netbeans.api.project.*;
72
import org.netbeans.modules.refactoring.api.Scope;
59
import org.netbeans.modules.refactoring.api.Scope;
73
import org.netbeans.modules.refactoring.java.Pair;
60
import org.netbeans.modules.refactoring.java.Pair;
74
import org.netbeans.modules.refactoring.java.RefactoringModule;
75
import org.netbeans.modules.refactoring.java.api.ui.JavaScopeBuilder;
76
import org.netbeans.modules.refactoring.spi.ui.CustomRefactoringPanel;
61
import org.netbeans.modules.refactoring.spi.ui.CustomRefactoringPanel;
77
import org.openide.filesystems.FileObject;
62
import org.openide.filesystems.FileObject;
78
import org.openide.filesystems.FileStateInvalidException;
79
import org.openide.filesystems.URLMapper;
80
import org.openide.loaders.DataObject;
81
import org.openide.loaders.DataObjectNotFoundException;
82
import org.openide.util.Exceptions;
83
import org.openide.util.ImageUtilities;
84
import org.openide.util.NbBundle;
63
import org.openide.util.NbBundle;
85
import org.openide.util.NbPreferences;
64
import org.openide.util.NbPreferences;
65
import org.openide.util.lookup.Lookups;
86
66
87
67
88
/**
68
/**
Lines 91-104 Link Here
91
 */
71
 */
92
public class WhereUsedPanel extends JPanel implements CustomRefactoringPanel {
72
public class WhereUsedPanel extends JPanel implements CustomRefactoringPanel {
93
    
73
    
94
    private static final String PREF_SCOPE = "FindUsages-Scope";
95
    private static final String PACKAGE = "org/netbeans/spi/java/project/support/ui/package.gif"; // NOI18N
96
    private final transient TreePathHandle element;
74
    private final transient TreePathHandle element;
97
    private final transient ChangeListener parent;
75
    private final transient ChangeListener parent;
98
//    private static final int MAX_NAME = 50;
99
    private static final int SCOPE_COMBOBOX_COLUMNS = 14;
100
    public static final String ELLIPSIS = "\u2026"; //NOI18N
101
    private Scope customScope;
102
    private boolean enableScope;
76
    private boolean enableScope;
103
77
104
    private final WhereUsedInnerPanel panel;
78
    private final WhereUsedInnerPanel panel;
Lines 111-117 Link Here
111
        this.enableScope = true;
85
        this.enableScope = true;
112
        this.panel = panel;
86
        this.panel = panel;
113
        initComponents();
87
        initComponents();
114
        btnCustomScope.setAction(new ScopeAction(scope));
115
    }
88
    }
116
    
89
    
117
    public static WhereUsedPanel create(String name, TreePathHandle e, ElementKind kind, List<Pair<Pair<String, Icon>, TreePathHandle>> classes, ChangeListener parent) {
90
    public static WhereUsedPanel create(String name, TreePathHandle e, ElementKind kind, List<Pair<Pair<String, Icon>, TreePathHandle>> classes, ChangeListener parent) {
Lines 145-182 Link Here
145
    
118
    
146
    public Scope getCustomScope() {
119
    public Scope getCustomScope() {
147
        FileObject file = WhereUsedPanel.this.element.getFileObject();
120
        FileObject file = WhereUsedPanel.this.element.getFileObject();
148
        Scope value = null;
149
        
121
        
150
        if(!enableScope) {
122
        if(!enableScope) {
151
            return Scope.create(null, null, Arrays.asList(file));
123
            return Scope.create(null, null, Arrays.asList(file));
152
        }
124
        }
153
125
154
        switch (scope.getSelectedIndex()) {
126
        return scope.getSelectedScope();
155
            case 1:
156
                value = Scope.create(Arrays.asList(projectSources), null, null);
157
                break;
158
            case 2:
159
                NonRecursiveFolder nonRecursiveFolder = new NonRecursiveFolder() {
160
            @Override
161
                    public FileObject getFolder() {
162
                        return packageFolder;
163
                    }
164
                };
165
                value = Scope.create(null, Arrays.asList(nonRecursiveFolder), null);
166
                break;
167
            case 3:
168
                value = Scope.create(null, null, Arrays.asList(file));
169
                break;
170
            case 4:
171
                value = WhereUsedPanel.this.customScope;
172
                break;
173
        }
174
        return value;
175
    }
127
    }
176
128
177
    private boolean initialized = false;
129
    private boolean initialized = false;
178
    private FileObject packageFolder = null;
179
    private FileObject[] projectSources = null;
180
    
130
    
181
    String getMethodDeclaringClass() {
131
    String getMethodDeclaringClass() {
182
        if(panel instanceof WhereUsedPanelMethod) {
132
        if(panel instanceof WhereUsedPanelMethod) {
Lines 192-198 Link Here
192
            return;
142
            return;
193
        }
143
        }
194
        JavaSource source = JavaSource.forFileObject(element.getFileObject());
144
        JavaSource source = JavaSource.forFileObject(element.getFileObject());
195
        final Project p = FileOwnerQuery.getOwner(element.getFileObject());
196
        CancellableTask<CompilationController> task =new CancellableTask<CompilationController>() {
145
        CancellableTask<CompilationController> task =new CancellableTask<CompilationController>() {
197
            @Override
146
            @Override
198
            public void cancel() {
147
            public void cancel() {
Lines 206-255 Link Here
206
                final Element element = WhereUsedPanel.this.element.resolveElement(info);
155
                final Element element = WhereUsedPanel.this.element.resolveElement(info);
207
                panel.initialize(element, info);
156
                panel.initialize(element, info);
208
157
209
                TreePath path = WhereUsedPanel.this.element.resolve(info);
210
                final ExpressionTree packageName1 = path.getCompilationUnit().getPackageName();
211
                final String packageName = packageName1 == null? "<default package>" : packageName1.toString(); //NOI18N
212
                if(packageName1 == null) {
213
                    packageFolder = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE).findOwnerRoot(WhereUsedPanel.this.element.getFileObject());
214
                } else {
215
                    packageFolder = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE).findResource(packageName.replaceAll("\\.", "/")); //NOI18N
216
                }
217
                
218
                final JLabel customScope;
219
                final JLabel currentFile;
220
                final JLabel currentPackage;
221
                final JLabel currentProject;
222
                final JLabel allProjects;
223
                if (p != null) {
224
                    ProjectInformation pi = ProjectUtils.getInformation(FileOwnerQuery.getOwner(WhereUsedPanel.this.element.getFileObject()));
225
                    
226
                    SourceGroup[] sources = ProjectUtils.getSources(pi.getProject()).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
227
                    projectSources = new FileObject[sources.length];
228
                    for (int i = 0; i < sources.length; i++) {
229
                        projectSources[i] = sources[i].getRootFolder();
230
                    }
231
                    
232
                    DataObject currentFileDo = null;
233
                    try {
234
                        currentFileDo = DataObject.find(WhereUsedPanel.this.element.getFileObject());
235
                    } catch (DataObjectNotFoundException ex) {
236
                    } // Not important, only for Icon.
237
                    customScope = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CustomScope"), pi.getIcon(), SwingConstants.LEFT); //NOI18N
238
                    currentFile = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentFile", WhereUsedPanel.this.element.getFileObject().getNameExt()), currentFileDo != null ? new ImageIcon(currentFileDo.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16)) : pi.getIcon(), SwingConstants.LEFT); //NOI18N
239
                    currentPackage = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentPackage", packageName), ImageUtilities.loadImageIcon(PACKAGE, false), SwingConstants.LEFT); //NOI18N
240
                    currentProject = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_CurrentProject", pi.getDisplayName()), pi.getIcon(), SwingConstants.LEFT); //NOI18N
241
                    allProjects = new JLabel(NbBundle.getMessage(WhereUsedPanel.class, "LBL_AllProjects"), pi.getIcon(), SwingConstants.LEFT); //NOI18N
242
                } else {
243
                    customScope = null;
244
                    currentFile = null;
245
                    currentPackage = null;
246
                    currentProject = null;
247
                    allProjects = null;
248
                }
249
250
                if((element.getKind().equals(ElementKind.LOCAL_VARIABLE) || element.getKind().equals(ElementKind.PARAMETER))
158
                if((element.getKind().equals(ElementKind.LOCAL_VARIABLE) || element.getKind().equals(ElementKind.PARAMETER))
251
                        || element.getModifiers().contains(Modifier.PRIVATE)) {
159
                        || element.getModifiers().contains(Modifier.PRIVATE)) {
252
                    enableScope = false;
160
                    enableScope = false;
161
                } else {
162
                    enableScope = scope.initialize(Lookups.fixed(WhereUsedPanel.this.element.getFileObject(), WhereUsedPanel.this.element.resolve(info)), new AtomicBoolean());
253
                }
163
                }
254
164
255
                SwingUtilities.invokeLater(new Runnable() {
165
                SwingUtilities.invokeLater(new Runnable() {
Lines 258-280 Link Here
258
                        innerPanel.removeAll();
168
                        innerPanel.removeAll();
259
                        innerPanel.add(panel, BorderLayout.CENTER);
169
                        innerPanel.add(panel, BorderLayout.CENTER);
260
                        panel.setVisible(true);
170
                        panel.setVisible(true);
261
171
                        scope.setVisible(enableScope);
262
                        if(enableScope && currentProject!=null) {
263
                            scope.setModel(new DefaultComboBoxModel(new Object[]{allProjects, currentProject, currentPackage, currentFile, customScope }));
264
                            int defaultItem = (Integer) RefactoringModule.getOption("whereUsed.scope", 0); // NOI18N
265
                            WhereUsedPanel.this.customScope = readScope();
266
                            if(defaultItem == 4 && WhereUsedPanel.this.customScope !=null &&
267
                                    WhereUsedPanel.this.customScope.getFiles().isEmpty() &&
268
                                    WhereUsedPanel.this.customScope.getFolders().isEmpty() &&
269
                                    WhereUsedPanel.this.customScope.getSourceRoots().isEmpty()) {
270
                                scope.setSelectedIndex(0);
271
                            } else {
272
                                scope.setSelectedIndex(defaultItem);
273
                            }
274
                            scope.setRenderer(new JLabelRenderer());
275
                        } else {
276
                            scopePanel.setVisible(false);
277
                        }
278
                    }
172
                    }
279
                });
173
                });
280
            }};
174
            }};
Lines 285-426 Link Here
285
            }
179
            }
286
            initialized = true;
180
            initialized = true;
287
    }
181
    }
288
    private static class JLabelRenderer extends JLabel implements ListCellRenderer, UIResource {
289
        public JLabelRenderer () {
290
            setOpaque(true);
291
        }
292
        @Override
293
        public Component getListCellRendererComponent(
294
                JList list,
295
                Object value,
296
                int index,
297
                boolean isSelected,
298
                boolean cellHasFocus) {
299
            
300
            // #89393: GTK needs name to render cell renderer "natively"
301
            setName("ComboBox.listRenderer"); // NOI18N
302
            
303
            if ( value != null ) {
304
                setText(((JLabel)value).getText());
305
                setIcon(((JLabel)value).getIcon());
306
            }
307
            
308
            if ( isSelected ) {
309
                setBackground(list.getSelectionBackground());
310
                setForeground(list.getSelectionForeground());
311
            } else {
312
                setBackground(list.getBackground());
313
                setForeground(list.getForeground());
314
            }
315
            
316
            return this;
317
        }
318
        
319
        // #89393: GTK needs name to render cell renderer "natively"
320
        @Override
321
        public String getName() {
322
            String name = super.getName();
323
            return name == null ? "ComboBox.renderer" : name;  // NOI18N
324
        }
325
    }
326
182
327
    static abstract class WhereUsedInnerPanel extends JPanel {
183
    static abstract class WhereUsedInnerPanel extends JPanel {
328
        abstract boolean isSearchInComments();
184
        abstract boolean isSearchInComments();
329
        abstract void initialize(Element element, CompilationController info);
185
        abstract void initialize(Element element, CompilationController info);
330
    }
186
    }
331
332
    private class ScopeAction extends AbstractAction {
333
        private final JComboBox scope;
334
335
        private ScopeAction(JComboBox scope) {
336
            this.scope = scope;
337
            this.putValue(NAME, ELLIPSIS);
338
        }
339
340
        @Override
341
        public void actionPerformed(ActionEvent e) {
342
            Scope customScope = getCustomScope();
343
            
344
            customScope = JavaScopeBuilder.open(NbBundle.getMessage(WhereUsedPanel.class, "DLG_CustomScope"), customScope); //NOI18N
345
            if (customScope != null) {
346
                WhereUsedPanel.this.customScope = customScope;
347
                scope.setSelectedIndex(4);
348
                storeScope(customScope);
349
            }
350
        }
351
    }
352
    
353
    private void storeScope(Scope customScope) {
354
        try {
355
            storeFileList(customScope.getSourceRoots(), "sourceRoot" ); //NOI18N
356
            storeFileList(customScope.getFolders(), "folder" ); //NOI18N
357
            storeFileList(customScope.getFiles(), "file" ); //NOI18N
358
        } catch (BackingStoreException ex) {
359
            Exceptions.printStackTrace(ex);
360
        }
361
    }
362
    
363
    private Scope readScope() {
364
        try {
365
            if (NbPreferences.forModule(JavaScopeBuilder.class).nodeExists(PREF_SCOPE)) { //NOI18N
366
                return Scope.create(
367
                        loadFileList("sourceRoot", FileObject.class), //NOI18N
368
                        loadFileList("folder", NonRecursiveFolder.class), //NOI18N
369
                        loadFileList("file", FileObject.class)); //NOI18N
370
            }
371
        } catch (BackingStoreException ex) {
372
            Exceptions.printStackTrace(ex);
373
        }
374
        return null;
375
    }
376
    
377
    private <T> List<T> loadFileList(String basekey, Class<T> type) throws BackingStoreException {
378
        Preferences pref = NbPreferences.forModule(JavaScopeBuilder.class).node(PREF_SCOPE).node(basekey);
379
        List<T> toRet = new LinkedList<T>();
380
        for (String key : pref.keys()) {
381
            final String url = pref.get(key, null);
382
            if (url != null && !url.isEmpty()) {
383
                try {
384
                    final FileObject f = URLMapper.findFileObject(new URL(url));
385
                    if (f != null && f.isValid()) {
386
                        if (type.isAssignableFrom(FileObject.class)) {
387
                            toRet.add((T) f);
388
                        } else {
389
                            toRet.add((T) new NonRecursiveFolder() {
390
391
                                @Override
392
                                public FileObject getFolder() {
393
                                    return f;
394
                                }
395
                            });
396
                        }
397
                    }
398
                } catch (MalformedURLException ex) {
399
                    Exceptions.printStackTrace(ex);
400
                }
401
            }
402
        }
403
        return toRet;
404
    }
405
    
406
    private void storeFileList(Set files, String basekey) throws BackingStoreException {
407
        Preferences pref = NbPreferences.forModule(WhereUsedPanel.class).node(PREF_SCOPE).node(basekey);
408
        assert files != null;
409
        pref.clear();
410
        int count = 0;
411
        for (Object next : files) {
412
            try {
413
                if (next instanceof FileObject) {
414
                    pref.put(basekey + count++, ((FileObject) next).getURL().toExternalForm());
415
                } else {
416
                    pref.put(basekey + count++, ((NonRecursiveFolder) next).getFolder().getURL().toExternalForm());
417
                }
418
            } catch (FileStateInvalidException ex) {
419
                Exceptions.printStackTrace(ex);
420
            }
421
        }
422
        pref.flush();
423
    }
424
    
187
    
425
//    static String getHeader(Element call, CompilationInfo info) {
188
//    static String getHeader(Element call, CompilationInfo info) {
426
//        String result = ElementHeaders.getHeader(call, info, ElementHeaders.NAME + ElementHeaders.PARAMETERS);
189
//        String result = ElementHeaders.getHeader(call, info, ElementHeaders.NAME + ElementHeaders.PARAMETERS);
Lines 452-533 Link Here
452
    private void initComponents() {
215
    private void initComponents() {
453
216
454
        buttonGroup = new javax.swing.ButtonGroup();
217
        buttonGroup = new javax.swing.ButtonGroup();
455
        scopePanel = new javax.swing.JPanel();
456
        scopeLabel = new javax.swing.JLabel();
457
        scope = new javax.swing.JComboBox();
458
        btnCustomScope = new javax.swing.JButton();
459
        innerPanel = new javax.swing.JPanel();
218
        innerPanel = new javax.swing.JPanel();
460
219
        scope = new org.netbeans.modules.refactoring.spi.ui.ScopePanel(WhereUsedPanel.class.getCanonicalName().replace('.', '-'), NbPreferences.forModule(WhereUsedPanel.class), "whereUsed.scope");
461
        scopeLabel.setLabelFor(scope);
220
        jLabel1 = new javax.swing.JLabel();
462
        org.openide.awt.Mnemonics.setLocalizedText(scopeLabel, org.openide.util.NbBundle.getMessage(WhereUsedPanel.class, "LBL_Scope")); // NOI18N
463
464
        ((javax.swing.JTextField) scope.getEditor().getEditorComponent()).setColumns(SCOPE_COMBOBOX_COLUMNS);
465
        scope.addActionListener(new java.awt.event.ActionListener() {
466
            public void actionPerformed(java.awt.event.ActionEvent evt) {
467
                scopeActionPerformed(evt);
468
            }
469
        });
470
471
        btnCustomScope.setText(ELLIPSIS);
472
473
        javax.swing.GroupLayout scopePanelLayout = new javax.swing.GroupLayout(scopePanel);
474
        scopePanel.setLayout(scopePanelLayout);
475
        scopePanelLayout.setHorizontalGroup(
476
            scopePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
477
            .addGroup(scopePanelLayout.createSequentialGroup()
478
                .addContainerGap()
479
                .addComponent(scopeLabel)
480
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
481
                .addComponent(scope, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
482
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
483
                .addComponent(btnCustomScope)
484
                .addContainerGap())
485
        );
486
        scopePanelLayout.setVerticalGroup(
487
            scopePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
488
            .addGroup(scopePanelLayout.createSequentialGroup()
489
                .addContainerGap()
490
                .addGroup(scopePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
491
                    .addGroup(scopePanelLayout.createSequentialGroup()
492
                        .addGap(6, 6, 6)
493
                        .addComponent(scopeLabel))
494
                    .addGroup(scopePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
495
                        .addComponent(btnCustomScope)
496
                        .addComponent(scope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
497
                .addContainerGap())
498
        );
499
500
        scope.getAccessibleContext().setAccessibleDescription("N/A");
501
221
502
        innerPanel.setLayout(new java.awt.BorderLayout());
222
        innerPanel.setLayout(new java.awt.BorderLayout());
503
223
224
        jLabel1.setText(org.openide.util.NbBundle.getMessage(WhereUsedPanel.class, "WhereUsedPanel.jLabel1.text")); // NOI18N
225
504
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
226
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
505
        this.setLayout(layout);
227
        this.setLayout(layout);
506
        layout.setHorizontalGroup(
228
        layout.setHorizontalGroup(
507
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
229
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
508
            .addComponent(scopePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
230
            .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
509
            .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
231
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
232
                .addContainerGap()
233
                .addComponent(jLabel1)
234
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
235
                .addComponent(scope, javax.swing.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE)
236
                .addContainerGap())
510
        );
237
        );
511
        layout.setVerticalGroup(
238
        layout.setVerticalGroup(
512
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
239
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
513
            .addGroup(layout.createSequentialGroup()
240
            .addGroup(layout.createSequentialGroup()
514
                .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
241
                .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
515
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
242
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
516
                .addComponent(scopePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
243
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
244
                    .addComponent(scope, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
245
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
246
                .addContainerGap())
517
        );
247
        );
518
    }// </editor-fold>//GEN-END:initComponents
248
    }// </editor-fold>//GEN-END:initComponents
519
249
520
private void scopeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scopeActionPerformed
521
    RefactoringModule.setOption("whereUsed.scope", scope.getSelectedIndex()); // NOI18N
522
}//GEN-LAST:event_scopeActionPerformed
523
524
    // Variables declaration - do not modify//GEN-BEGIN:variables
250
    // Variables declaration - do not modify//GEN-BEGIN:variables
525
    private javax.swing.JButton btnCustomScope;
526
    private javax.swing.ButtonGroup buttonGroup;
251
    private javax.swing.ButtonGroup buttonGroup;
527
    private javax.swing.JPanel innerPanel;
252
    private javax.swing.JPanel innerPanel;
528
    private javax.swing.JComboBox scope;
253
    private javax.swing.JLabel jLabel1;
529
    private javax.swing.JLabel scopeLabel;
254
    private org.netbeans.modules.refactoring.spi.ui.ScopePanel scope;
530
    private javax.swing.JPanel scopePanel;
531
    // End of variables declaration//GEN-END:variables
255
    // End of variables declaration//GEN-END:variables
532
256
533
    public boolean isMethodFromBaseClass() {
257
    public boolean isMethodFromBaseClass() {
Lines 587-590 Link Here
587
        return this;
311
        return this;
588
    }
312
    }
589
}
313
}
590
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/Bundle.properties (+43 lines)
Line 0 Link Here
1
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
#
3
# Copyright 2012 Oracle and/or its affiliates. All rights reserved.
4
#
5
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
# Other names may be trademarks of their respective owners.
7
#
8
# The contents of this file are subject to the terms of either the GNU
9
# General Public License Version 2 only ("GPL") or the Common
10
# Development and Distribution License("CDDL") (collectively, the
11
# "License"). You may not use this file except in compliance with the
12
# License. You can obtain a copy of the License at
13
# http://www.netbeans.org/cddl-gplv2.html
14
# or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
15
# specific language governing permissions and limitations under the
16
# License.  When distributing the software, include this License Header
17
# Notice in each file and include the License file at
18
# nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
19
# particular file as subject to the "Classpath" exception as provided
20
# by Oracle in the GPL Version 2 section of the License file that
21
# accompanied this code. If applicable, add the following below the
22
# License Header, with the fields enclosed by brackets [] replaced by
23
# your own identifying information:
24
# "Portions Copyrighted [year] [name of copyright owner]"
25
#
26
# If you wish your version of this file to be governed by only the CDDL
27
# or only the GPL Version 2, indicate your decision by adding
28
# "[Contributor] elects to include this software in this distribution
29
# under the [CDDL or GPL Version 2] license." If you do not indicate a
30
# single choice of license, a recipient has the option to distribute
31
# your version of this file under either the CDDL, the GPL Version 2 or
32
# to extend the choice of license to its licensees as provided above.
33
# However, if you add GPL Version 2 code and therefore, elected the GPL
34
# Version 2 license, then the option applies only if the new code is
35
# made subject to such option by the copyright holder.
36
#
37
# Contributor(s):
38
#
39
# Portions Copyrighted 2012 Sun Microsystems, Inc.
40
41
ScopePanel.scopeLabel.text=Sco&pe: 
42
43
LBL_WaitNode=Please Wait...
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/CurrentFileScopeProvider.java (+105 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.java.ui.scope;
43
44
import java.beans.BeanInfo;
45
import java.util.Arrays;
46
import java.util.concurrent.atomic.AtomicBoolean;
47
import javax.swing.Icon;
48
import javax.swing.ImageIcon;
49
import org.netbeans.modules.refactoring.api.Scope;
50
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
51
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
52
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
53
import org.openide.filesystems.FileObject;
54
import org.openide.loaders.DataObject;
55
import org.openide.loaders.DataObjectNotFoundException;
56
import org.openide.util.Lookup;
57
import org.openide.util.NbBundle.Messages;
58
59
/**
60
 *
61
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
62
 */
63
@ScopeDescription(displayName = "#LBL_CurrentFile", id = "current-file", position = 400, iconBase = "org/netbeans/modules/refactoring/java/resources/newFile.png")
64
@ScopeReference(path="org-netbeans-modules-refactoring-java-ui-WhereUsedPanel")
65
@Messages(value = {"# {0} - Filename", "LBL_CurrentFile=Current File"})
66
public final class CurrentFileScopeProvider extends ScopeProvider {
67
68
    private Scope scope;
69
    private ImageIcon icon;
70
    private String detail;
71
72
    @Override
73
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
74
        FileObject file = context.lookup(FileObject.class);
75
        if (file == null || file.isFolder()) {
76
            return false;
77
        }
78
79
        DataObject currentFileDo = null;
80
        try {
81
            currentFileDo = DataObject.find(file);
82
        } catch (DataObjectNotFoundException ex) {
83
        } // Not important, only for Icon.
84
        icon = currentFileDo != null ? new ImageIcon(currentFileDo.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16)) : null;
85
        detail = file.getNameExt();
86
        scope = Scope.create(null, null, Arrays.asList(file));
87
88
        return true;
89
    }
90
91
    @Override
92
    public Scope getScope() {
93
        return scope;
94
    }
95
96
    @Override
97
    public Icon getIcon() {
98
        return icon != null ? icon : super.getIcon();
99
    }
100
101
    @Override
102
    public String getDetail() {
103
        return detail;
104
    }
105
}
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/CurrentJavaProjectScopeProvider.java (+127 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.java.ui.scope;
43
44
import java.util.Arrays;
45
import java.util.Map;
46
import java.util.concurrent.atomic.AtomicBoolean;
47
import javax.swing.Icon;
48
import org.netbeans.api.java.classpath.ClassPath;
49
import org.netbeans.api.java.project.JavaProjectConstants;
50
import org.netbeans.api.project.FileOwnerQuery;
51
import org.netbeans.api.project.Project;
52
import org.netbeans.api.project.ProjectInformation;
53
import org.netbeans.api.project.ProjectUtils;
54
import org.netbeans.api.project.SourceGroup;
55
import org.netbeans.modules.refactoring.api.Scope;
56
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
57
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
58
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
59
import org.openide.filesystems.FileObject;
60
import org.openide.loaders.DataFolder;
61
import org.openide.util.Lookup;
62
import org.openide.util.NbBundle.Messages;
63
64
/**
65
 *
66
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
67
 */
68
@ScopeDescription(id = "current-project", displayName = "#LBL_CurrentProject", position = 200)
69
@ScopeReference(path = "org-netbeans-modules-refactoring-java-ui-WhereUsedPanel")
70
@Messages({"LBL_CurrentProject=Current Project"})
71
public final class CurrentJavaProjectScopeProvider extends ScopeProvider {
72
73
    private String detail;
74
    private Scope scope;
75
    private Icon icon;
76
77
    @Override
78
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
79
        FileObject file = context.lookup(FileObject.class);
80
        Project selected = null;
81
        if (file != null) {
82
            selected = FileOwnerQuery.getOwner(file);
83
        }
84
        if (selected == null) {
85
            selected = context.lookup(Project.class);
86
            if (selected == null) {
87
                SourceGroup sg = context.lookup(SourceGroup.class);
88
                if (sg != null) {
89
                    selected = FileOwnerQuery.getOwner(sg.getRootFolder());
90
                }
91
            }
92
            if (selected == null) {
93
                DataFolder df = context.lookup(DataFolder.class);
94
                if (df != null) {
95
                    selected = FileOwnerQuery.getOwner(df.getPrimaryFile());
96
                }
97
            }
98
        }
99
        if (selected == null) {
100
            return false;
101
        }
102
103
        ProjectInformation pi = ProjectUtils.getInformation(selected);
104
105
        Map<Project, Map<FileObject, ClassPath>> projects2RegisteredContent = OpenProjectsScopeProvider.projects2RegisteredContent(cancel);
106
        scope = OpenProjectsScopeProvider.addProjectToScope(pi.getProject(), Scope.create(null, null, null), cancel, projects2RegisteredContent);
107
108
        detail = pi.getDisplayName();
109
        icon = pi.getIcon();
110
        return true;
111
    }
112
113
    @Override
114
    public String getDetail() {
115
        return detail;
116
    }
117
118
    @Override
119
    public Icon getIcon() {
120
        return icon;
121
    }
122
123
    @Override
124
    public Scope getScope() {
125
        return scope;
126
    }
127
}
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/CurrentPackageScopeProvider.java (+121 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.java.ui.scope;
43
44
import com.sun.source.tree.ExpressionTree;
45
import com.sun.source.util.TreePath;
46
import java.util.Arrays;
47
import java.util.concurrent.atomic.AtomicBoolean;
48
import javax.swing.Icon;
49
import org.netbeans.api.fileinfo.NonRecursiveFolder;
50
import org.netbeans.api.java.classpath.ClassPath;
51
import org.netbeans.modules.refactoring.api.Scope;
52
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
53
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
54
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
55
import org.openide.filesystems.FileObject;
56
import org.openide.util.Lookup;
57
import org.openide.util.NbBundle.Messages;
58
59
/**
60
 *
61
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
62
 */
63
@Messages({"LBL_CurrentPackage=Current Package"})
64
@ScopeDescription(id = "current-package", displayName = "#LBL_CurrentPackage", position = 300, iconBase = "org/netbeans/spi/java/project/support/ui/package.gif")
65
@ScopeReference(path="org-netbeans-modules-refactoring-java-ui-WhereUsedPanel")
66
public final class CurrentPackageScopeProvider extends ScopeProvider {
67
68
    private String detail;
69
    private Scope scope;
70
71
    @Override
72
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
73
        FileObject file = context.lookup(FileObject.class);
74
        if (file == null) {
75
            return false;
76
        }
77
        final FileObject packageFolder;
78
        final String packageName;
79
        ClassPath sourceCP = ClassPath.getClassPath(file, ClassPath.SOURCE);
80
        if (sourceCP != null) {
81
            TreePath path = context.lookup(TreePath.class);
82
            if (path != null) {
83
                final ExpressionTree packageName1 = path.getCompilationUnit().getPackageName();
84
                packageName = packageName1 == null ? "<default package>" : packageName1.toString(); //NOI18N
85
                if (packageName1 == null) {
86
                    packageFolder = sourceCP.findOwnerRoot(file);
87
                } else {
88
                    packageFolder = sourceCP.findResource(packageName.replaceAll("\\.", "/")); //NOI18N
89
                }
90
            } else {
91
                packageFolder = file.isFolder()? file : file.getParent();
92
                packageName = sourceCP.getResourceName(packageFolder, '.', false);
93
            }
94
        } else {
95
            packageFolder = null;
96
            packageName = null;
97
        }
98
99
        if (packageFolder != null) {
100
            detail = packageName;
101
            scope = Scope.create(null, Arrays.<NonRecursiveFolder>asList(new NonRecursiveFolder() {
102
                @Override
103
                public FileObject getFolder() {
104
                    return packageFolder;
105
                }
106
            }), null);
107
            return true;
108
        }
109
        return false;
110
    }
111
112
    @Override
113
    public Scope getScope() {
114
        return scope;
115
    }
116
117
    @Override
118
    public String getDetail() {
119
        return detail;
120
    }
121
}
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/CustomScopePanel.java (-1 / +2 lines)
Lines 45-51 Link Here
45
 *
45
 *
46
 * Created on Jun 13, 2011, 9:51:30 AM
46
 * Created on Jun 13, 2011, 9:51:30 AM
47
 */
47
 */
48
package org.netbeans.modules.refactoring.java.ui;
48
package org.netbeans.modules.refactoring.java.ui.scope;
49
49
50
import java.awt.*;
50
import java.awt.*;
51
import java.awt.image.BufferedImage;
51
import java.awt.image.BufferedImage;
Lines 92-97 Link Here
92
 *
92
 *
93
 * @author Ralph Ruijs
93
 * @author Ralph Ruijs
94
 */
94
 */
95
@NbBundle.Messages({"DLG_CustomScope=Custom Scope"})
95
public class CustomScopePanel extends javax.swing.JPanel implements ExplorerManager.Provider {
96
public class CustomScopePanel extends javax.swing.JPanel implements ExplorerManager.Provider {
96
97
97
    private static final Image PACKAGEBADGE = ImageUtilities.loadImage("org/netbeans/spi/java/project/support/ui/packageBadge.gif"); // NOI18N
98
    private static final Image PACKAGEBADGE = ImageUtilities.loadImage("org/netbeans/spi/java/project/support/ui/packageBadge.gif"); // NOI18N
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/CustomScopeProvider.java (+174 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.java.ui.scope;
43
44
import java.net.MalformedURLException;
45
import java.net.URL;
46
import java.util.LinkedList;
47
import java.util.List;
48
import java.util.Set;
49
import java.util.concurrent.atomic.AtomicBoolean;
50
import java.util.prefs.BackingStoreException;
51
import java.util.prefs.Preferences;
52
import javax.swing.Icon;
53
import org.netbeans.api.fileinfo.NonRecursiveFolder;
54
import org.netbeans.modules.refactoring.api.Scope;
55
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
56
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
57
import org.netbeans.modules.refactoring.java.api.ui.JavaScopeBuilder;
58
import org.openide.filesystems.FileObject;
59
import org.openide.filesystems.URLMapper;
60
import org.openide.util.Exceptions;
61
import org.openide.util.Lookup;
62
import org.openide.util.NbPreferences;
63
import static org.netbeans.modules.refactoring.java.ui.scope.Bundle.*;
64
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
65
import org.openide.util.NbBundle.Messages;
66
67
/**
68
 *
69
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
70
 */
71
@Messages("LBL_CustomScope=Custom Scope...")
72
@ScopeDescription(id = "custom-scope", displayName = "#LBL_CustomScope", position = 900, iconBase = "org/netbeans/modules/refactoring/java/resources/filter.png")
73
@ScopeReference(path="org-netbeans-modules-refactoring-java-ui-WhereUsedPanel")
74
public final class CustomScopeProvider extends ScopeProvider.CustomScopeProvider {
75
76
    private static final String PREF_SCOPE = "FindUsages-Scope";
77
    private Scope customScope;
78
79
    @Override
80
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
81
        return true;
82
    }
83
84
    @Override
85
    public void setScope(Scope value) {
86
        customScope = value != null ? Scope.create(value.getSourceRoots(), value.getFolders(), value.getFiles()) : null;
87
    }
88
89
    @Override
90
    @Messages("TTL_CustomScope=Custom Scope")
91
    public boolean showCustomizer() {
92
        Scope nue = JavaScopeBuilder.open(TTL_CustomScope(), customScope); //NOI18N
93
        if (nue != null) {
94
            storeScope(customScope = nue);
95
        }
96
97
        return nue != null;
98
    }
99
100
    @Override
101
    public Scope getScope() {
102
        if (customScope == null) {
103
            customScope = readScope();
104
        }
105
        return customScope;
106
    }
107
108
    private void storeScope(Scope customScope) {
109
        try {
110
            storeFileList(customScope.getSourceRoots(), "sourceRoot"); //NOI18N
111
            storeFileList(customScope.getFolders(), "folder"); //NOI18N
112
            storeFileList(customScope.getFiles(), "file"); //NOI18N
113
        } catch (BackingStoreException ex) {
114
            Exceptions.printStackTrace(ex);
115
        }
116
    }
117
118
    private Scope readScope() {
119
        try {
120
            if (NbPreferences.forModule(JavaScopeBuilder.class).nodeExists(PREF_SCOPE)) { //NOI18N
121
                return Scope.create(
122
                        loadFileList("sourceRoot", FileObject.class), //NOI18N
123
                        loadFileList("folder", NonRecursiveFolder.class), //NOI18N
124
                        loadFileList("file", FileObject.class)); //NOI18N
125
            }
126
        } catch (BackingStoreException ex) {
127
            Exceptions.printStackTrace(ex);
128
        }
129
        return null;
130
    }
131
132
    private <T> List<T> loadFileList(String basekey, Class<T> type) throws BackingStoreException {
133
        Preferences pref = NbPreferences.forModule(JavaScopeBuilder.class).node(PREF_SCOPE).node(basekey);
134
        List<T> toRet = new LinkedList<T>();
135
        for (String key : pref.keys()) {
136
            final String url = pref.get(key, null);
137
            if (url != null && !url.isEmpty()) {
138
                try {
139
                    final FileObject f = URLMapper.findFileObject(new URL(url));
140
                    if (f != null && f.isValid()) {
141
                        if (type.isAssignableFrom(FileObject.class)) {
142
                            toRet.add((T) f);
143
                        } else {
144
                            toRet.add((T) new NonRecursiveFolder() {
145
                                @Override
146
                                public FileObject getFolder() {
147
                                    return f;
148
                                }
149
                            });
150
                        }
151
                    }
152
                } catch (MalformedURLException ex) {
153
                    Exceptions.printStackTrace(ex);
154
                }
155
            }
156
        }
157
        return toRet;
158
    }
159
160
    private void storeFileList(Set files, String basekey) throws BackingStoreException {
161
        Preferences pref = NbPreferences.forModule(CustomScopeProvider.class).node(PREF_SCOPE).node(basekey);
162
        assert files != null;
163
        pref.clear();
164
        int count = 0;
165
        for (Object next : files) {
166
            if (next instanceof FileObject) {
167
                pref.put(basekey + count++, ((FileObject) next).toURL().toExternalForm());
168
            } else {
169
                pref.put(basekey + count++, ((NonRecursiveFolder) next).getFolder().toURL().toExternalForm());
170
            }
171
        }
172
        pref.flush();
173
    }
174
}
(-)a/refactoring.java/src/org/netbeans/modules/refactoring/java/ui/scope/OpenProjectsScopeProvider.java (+180 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.refactoring.java.ui.scope;
43
44
import java.util.Collection;
45
import java.util.Collections;
46
import java.util.HashMap;
47
import java.util.HashSet;
48
import java.util.IdentityHashMap;
49
import java.util.Map;
50
import java.util.Set;
51
import java.util.concurrent.atomic.AtomicBoolean;
52
import org.netbeans.api.annotations.common.NonNull;
53
import org.netbeans.api.annotations.common.NullAllowed;
54
import org.netbeans.api.fileinfo.NonRecursiveFolder;
55
import org.netbeans.api.java.classpath.ClassPath;
56
import org.netbeans.api.java.classpath.GlobalPathRegistry;
57
import org.netbeans.api.project.FileOwnerQuery;
58
import org.netbeans.api.project.Project;
59
import org.netbeans.api.project.ui.OpenProjects;
60
import org.netbeans.modules.parsing.spi.indexing.PathRecognizer;
61
import org.netbeans.modules.refactoring.api.Scope;
62
import org.netbeans.modules.refactoring.spi.ui.ScopeDescription;
63
import org.netbeans.modules.refactoring.spi.ui.ScopeProvider;
64
import org.netbeans.modules.refactoring.spi.ui.ScopeReference;
65
import org.openide.filesystems.FileObject;
66
import org.openide.util.Lookup;
67
import org.openide.util.NbBundle;
68
69
/**
70
 *
71
 * @author Ralph Benjamin Ruijs <ralphbenjamin@netbeans.org>
72
 */
73
@NbBundle.Messages("LBL_AllProjects=Open Projects")
74
@ScopeDescription(id = "all-projects", displayName = "#LBL_AllProjects", position = 100, iconBase = "org/netbeans/modules/refactoring/java/resources/all_projects.png")
75
@ScopeReference(path = "org-netbeans-modules-refactoring-java-ui-WhereUsedPanel")
76
public class OpenProjectsScopeProvider extends ScopeProvider {
77
78
    private Scope scope;
79
80
    @Override
81
    public boolean initialize(Lookup context, AtomicBoolean cancel) {
82
        Map<Project, Map<FileObject, ClassPath>> projects2RegisteredContent = projects2RegisteredContent(cancel);
83
84
        scope = Scope.create(null, null, null);
85
86
        if (cancel.get()) {
87
            return false;
88
        }
89
90
        for (Project p : OpenProjects.getDefault().getOpenProjects()) {
91
            scope = addProjectToScope(p, scope, cancel, projects2RegisteredContent);
92
        }
93
94
        return true;
95
    }
96
97
    @Override
98
    public Scope getScope() {
99
        return scope;
100
    }
101
102
    static Map<Project, Map<FileObject, ClassPath>> projects2RegisteredContent(AtomicBoolean cancel) {
103
        Set<String> sourceIds = new HashSet<String>();
104
105
        for (PathRecognizer pr : Lookup.getDefault().lookupAll(PathRecognizer.class)) {
106
            Set<String> ids = pr.getSourcePathIds();
107
108
            if (ids == null) {
109
                continue;
110
            }
111
112
            sourceIds.addAll(ids);
113
        }
114
115
        Map<Project, Map<FileObject, ClassPath>> sourceRoots = new IdentityHashMap<Project, Map<FileObject, ClassPath>>();
116
117
        for (String id : sourceIds) {
118
            for (ClassPath sCP : GlobalPathRegistry.getDefault().getPaths(id)) {
119
                for (FileObject root : sCP.getRoots()) {
120
                    if (cancel.get()) {
121
                        return null;
122
                    }
123
                    Project owner = FileOwnerQuery.getOwner(root);
124
125
                    if (owner != null) {
126
                        Map<FileObject, ClassPath> projectSources = sourceRoots.get(owner);
127
128
                        if (projectSources == null) {
129
                            sourceRoots.put(owner, projectSources = new HashMap<FileObject, ClassPath>());
130
                        }
131
132
                        projectSources.put(root, sCP);
133
                    }
134
                }
135
            }
136
        }
137
138
        return sourceRoots;
139
    }
140
141
    static Scope addProjectToScope(Project p, Scope target, AtomicBoolean cancel, Map<Project, Map<FileObject, ClassPath>> projects2RegisteredContent) {
142
        Scope projectScope = p.getLookup().lookup(Scope.class);
143
144
        if (projectScope != null) {
145
            return augment(target, projectScope.getSourceRoots(), projectScope.getFolders(), projectScope.getFiles());
146
        }
147
148
        Map<FileObject, ClassPath> roots = projects2RegisteredContent.get(p);
149
150
        if (roots != null) {
151
            for (Map.Entry<FileObject, ClassPath> e : roots.entrySet()) {
152
                if (cancel.get()) {
153
                    return null;
154
                }
155
                target = augment(target, Collections.singletonList(e.getKey()), null, null);
156
            }
157
        }
158
159
        return target;
160
    }
161
162
    private static @NonNull
163
    Scope augment(@NonNull Scope source, @NullAllowed Collection<FileObject> sourceRoots,
164
            @NullAllowed Collection<NonRecursiveFolder> folders,
165
            @NullAllowed Collection<FileObject> files) {
166
        Collection<FileObject> sourceRootsSet = new HashSet<FileObject>(source.getSourceRoots());
167
        if (sourceRoots != null) {
168
            sourceRootsSet.addAll(sourceRoots);
169
        }
170
        Collection<FileObject> filesSet = new HashSet<FileObject>(source.getFiles());
171
        if (files != null) {
172
            filesSet.addAll(files);
173
        }
174
        Collection<NonRecursiveFolder> foldersSet = new HashSet<NonRecursiveFolder>(source.getFolders());
175
        if (folders != null) {
176
            foldersSet.addAll(folders);
177
        }
178
        return Scope.create(sourceRootsSet, foldersSet, filesSet);
179
    }
180
}

Return to bug 217347