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 106629
Collapse All | Expand All

(-)source/apichanges.xml (+13 lines)
Lines 83-88 Link Here
83
83
84
    <changes>
84
    <changes>
85
        
85
        
86
        <change id="jsp-dialogs">
87
            <api name="general"/>
88
            <summary>Support for JSPs and dialogs</summary>
89
            <version major="0" minor="16"/>
90
            <date day="15" month="6" year="2007"/>
91
            <author login="jlahoda"/>
92
            <compatibility addition="yes" binary="compatible" deletion="no" deprecation="no" modification="no" semantic="compatible" source="compatible"/>
93
            <description>
94
                Adding ability to use Java infrastructure for non-Java file (eg. JSP files) and inside dialogs.
95
            </description>
96
            <issue number="999999"/>
97
        </change>
98
	
86
        <change id="ClassIndex-interruption">
99
        <change id="ClassIndex-interruption">
87
            <api name="general"/>
100
            <api name="general"/>
88
            <summary>ClassIndex methods are cancellable</summary>
101
            <summary>ClassIndex methods are cancellable</summary>
(-)source/nbproject/project.xml (+1 lines)
Lines 336-340 Link Here
336
                <package>org.netbeans.spi.java.loaders</package>
336
                <package>org.netbeans.spi.java.loaders</package>
337
            </public-packages>
337
            </public-packages>
338
        </data>
338
        </data>
339
        <junit-version xmlns="http://www.netbeans.org/ns/junit/1" value="junit3"/>
339
    </configuration>
340
    </configuration>
340
</project>
341
</project>
(-)source/preprocessorbridge/manifest.mf (-1 / +1 lines)
Lines 1-5 Link Here
1
Manifest-Version: 1.0
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.netbeans.modules.java.preprocessorbridge
2
OpenIDE-Module: org.netbeans.modules.java.preprocessorbridge
3
OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/java/preprocessorbridge/Bundle.properties
3
OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/java/preprocessorbridge/Bundle.properties
4
OpenIDE-Module-Specification-Version: 1.0
4
OpenIDE-Module-Specification-Version: 1.1
5
5
(-)source/preprocessorbridge/nbproject/project.xml (-1 / +11 lines)
Lines 4-13 Link Here
4
    <configuration>
4
    <configuration>
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
6
            <code-name-base>org.netbeans.modules.java.preprocessorbridge</code-name-base>
6
            <code-name-base>org.netbeans.modules.java.preprocessorbridge</code-name-base>
7
            <module-dependencies/>
7
            <module-dependencies>
8
                <dependency>
9
                    <code-name-base>org.openide.filesystems</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <specification-version>7.0</specification-version>
14
                    </run-dependency>
15
                </dependency>
16
            </module-dependencies>
8
            <friend-packages>
17
            <friend-packages>
9
                <friend>org.netbeans.modules.java.source</friend>
18
                <friend>org.netbeans.modules.java.source</friend>
10
                <friend>org.netbeans.modules.mobility.project</friend>
19
                <friend>org.netbeans.modules.mobility.project</friend>
20
                <friend>org.netbeans.modules.web.core.syntax</friend>
11
                <package>org.netbeans.modules.java.preprocessorbridge.spi</package>
21
                <package>org.netbeans.modules.java.preprocessorbridge.spi</package>
12
            </friend-packages>
22
            </friend-packages>
13
        </data>
23
        </data>
(-)source/preprocessorbridge/src/org/netbeans/modules/java/preprocessorbridge/spi/JavaSourceProvider.java (+62 lines)
Added Link Here
1
/*
2
 * The contents of this file are subject to the terms of the Common Development
3
 * and Distribution License (the License). You may not use this file except in
4
 * compliance with the License.
5
 *
6
 * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7
 * or http://www.netbeans.org/cddl.txt.
8
 *
9
 * When distributing Covered Code, include this CDDL Header Notice in each file
10
 * and include the License file at http://www.netbeans.org/cddl.txt.
11
 * If applicable, add the following below the CDDL Header, with the fields
12
 * enclosed by brackets [] replaced by your own identifying information:
13
 * "Portions Copyrighted [year] [name of copyright owner]"
14
 *
15
 * The Original Software is NetBeans. The Initial Developer of the Original
16
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17
 * Microsystems, Inc. All Rights Reserved.
18
 */
19
package org.netbeans.modules.java.preprocessorbridge.spi;
20
21
import org.openide.filesystems.FileObject;
22
23
/**Allows creation of JavaSource instances for non-Java files.
24
 * Is expected to produce "virtual" Java source, which is then parsed
25
 * by the Java parser and used by selected Java features.
26
 *
27
 * @author Jan Lahoda, Dusan Balek
28
 */
29
public interface JavaSourceProvider {
30
    
31
    /**Create {@link PositionTranslatingJavaFileFilterImplementation} for given file.
32
     * 
33
     * @param fo file for which the implementation should be created
34
     * @return PositionTranslatingJavaFileFilterImplementation or null if which provider
35
     *         cannot create one for this file
36
     */
37
    public PositionTranslatingJavaFileFilterImplementation forFileObject(FileObject fo);
38
    
39
    /**"Virtual" Java source provider
40
     * 
41
     * Currently, only {@link JavaFileFilterImplementation#filterCharSequence},
42
     * {@link JavaFileFilterImplementation#getOriginalPosition}, 
43
     * {@link JavaFileFilterImplementation#getJavaSourcePosition} are called.
44
     */
45
    public static interface PositionTranslatingJavaFileFilterImplementation extends JavaFileFilterImplementation {
46
        /**Compute position in the document for given position in the virtual
47
         * Java source.
48
         *
49
         * @param javaSourcePosition position in the virtual Java Source
50
         * @return position in the document
51
         */
52
        public int getOriginalPosition(int javaSourcePosition);
53
        
54
        /**Compute position in the virtual Java source for given position
55
         * in the document.
56
         * 
57
         * @param originalPosition position in the document
58
         * @return position in the virtual Java source
59
         */
60
        public int getJavaSourcePosition(int originalPosition);
61
    }
62
}
(-)source/src/org/netbeans/api/java/source/CompilationController.java (-2 / +7 lines)
Lines 30-37 Link Here
30
import javax.swing.text.Document;
30
import javax.swing.text.Document;
31
import javax.tools.Diagnostic;
31
import javax.tools.Diagnostic;
32
import org.netbeans.api.lexer.TokenHierarchy;
32
import org.netbeans.api.lexer.TokenHierarchy;
33
import static org.netbeans.api.java.source.JavaSource.Phase.*;
34
import org.openide.filesystems.FileObject;
33
import org.openide.filesystems.FileObject;
34
import static org.netbeans.api.java.source.JavaSource.Phase.*;
35
35
36
/** Class for explicit invocation of compilation phases on a java source.
36
/** Class for explicit invocation of compilation phases on a java source.
37
 *  The implementation delegates to the {@link CompilationInfo} to get the data,
37
 *  The implementation delegates to the {@link CompilationInfo} to get the data,
Lines 175-184 Link Here
175
    public FileObject getFileObject() {
175
    public FileObject getFileObject() {
176
        return this.delegate.getFileObject();
176
        return this.delegate.getFileObject();
177
    }
177
    }
178
178
    
179
    @Override
179
    @Override
180
    public Document getDocument() throws IOException {
180
    public Document getDocument() throws IOException {
181
        return this.delegate.getDocument();
181
        return this.delegate.getDocument();
182
    }
183
    
184
    @Override
185
    public PositionConverter getPositionConverter() {
186
        return this.delegate.getPositionConverter();
182
    }
187
    }
183
    
188
    
184
    @Override
189
    @Override
(-)source/src/org/netbeans/api/java/source/CompilationInfo.java (-13 / +22 lines)
Lines 41-54 Link Here
41
import org.netbeans.api.lexer.TokenHierarchy;
41
import org.netbeans.api.lexer.TokenHierarchy;
42
import org.netbeans.modules.java.source.parsing.FileObjects;
42
import org.netbeans.modules.java.source.parsing.FileObjects;
43
import org.netbeans.modules.java.source.parsing.SourceFileObject;
43
import org.netbeans.modules.java.source.parsing.SourceFileObject;
44
import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation;
45
import org.openide.ErrorManager;
44
import org.openide.ErrorManager;
46
import org.openide.cookies.EditorCookie;
45
import org.openide.cookies.EditorCookie;
47
import org.openide.filesystems.FileObject;
46
import org.openide.filesystems.FileObject;
48
import org.openide.filesystems.FileUtil;
47
import org.openide.filesystems.FileUtil;
49
import org.openide.loaders.DataObject;
48
import org.openide.loaders.DataObject;
50
49
51
52
/** Asorted information about the JavaSource.
50
/** Asorted information about the JavaSource.
53
 *
51
 *
54
 * @author Petr Hrebejk, Tomas Zezula
52
 * @author Petr Hrebejk, Tomas Zezula
Lines 60-66 Link Here
60
    private List<Diagnostic> errors;
58
    private List<Diagnostic> errors;
61
    
59
    
62
    private JavacTaskImpl javacTask;
60
    private JavacTaskImpl javacTask;
63
    private FileObject fo;
61
    private PositionConverter binding;
64
    final JavaFileObject jfo;    
62
    final JavaFileObject jfo;    
65
    final JavaSource javaSource;        
63
    final JavaSource javaSource;        
66
    boolean needsRestart;
64
    boolean needsRestart;
Lines 76-86 Link Here
76
        this.errors = null;
74
        this.errors = null;
77
    }
75
    }
78
    
76
    
79
    CompilationInfo ( final JavaSource javaSource, final FileObject fo, final JavaFileFilterImplementation filter, final JavacTaskImpl javacTask) throws IOException {
77
    CompilationInfo (  final JavaSource javaSource,final PositionConverter binding, final JavacTaskImpl javacTask) throws IOException {
80
        assert javaSource != null;        
78
        assert javaSource != null;        
81
        this.javaSource = javaSource;
79
        this.javaSource = javaSource;
82
        this.fo = fo;
80
        this.binding = binding;
83
        this.jfo = fo != null ? javaSource.jfoProvider.createJavaFileObject(fo, filter) : null;
81
        this.jfo = this.binding != null ? javaSource.jfoProvider.createJavaFileObject(binding.getFileObject(), this.binding.getFilter()) : null;
84
        this.javacTask = javacTask;        
82
        this.javacTask = javacTask;        
85
        this.errors = new ArrayList<Diagnostic>();
83
        this.errors = new ArrayList<Diagnostic>();
86
    }
84
    }
Lines 172-178 Link Here
172
            Elements elements = getElements();
170
            Elements elements = getElements();
173
            assert elements != null;
171
            assert elements != null;
174
            assert this.javaSource.rootFo != null;
172
            assert this.javaSource.rootFo != null;
175
            String name = FileObjects.convertFolder2Package(FileObjects.stripExtension(FileUtil.getRelativePath(javaSource.rootFo, fo)));
173
            String name = FileObjects.convertFolder2Package(FileObjects.stripExtension(FileUtil.getRelativePath(javaSource.rootFo, getFileObject())));
176
            TypeElement e = ((JavacElements)elements).getTypeElementByBinaryName(name);
174
            TypeElement e = ((JavacElements)elements).getTypeElementByBinaryName(name);
177
            if (e != null) {                
175
            if (e != null) {                
178
                if (!isLocal(e)) {
176
                if (!isLocal(e)) {
Lines 237-253 Link Here
237
	return javaSource.getClasspathInfo();
235
	return javaSource.getClasspathInfo();
238
    }
236
    }
239
    
237
    
240
    public FileObject getFileObject() {        
238
    public FileObject getFileObject() {
241
        return fo;
239
        return this.binding != null ? this.binding.getFileObject() : null;
240
    }
241
    
242
    /**Return {@link PositionConverter} binding virtual Java source and the real source.
243
     * Please note that this method is needed only for clients that need to work
244
     * in non-Java files (eg. JSP files) or in dialogs, like code completion.
245
     * Most clients do not need to use {@link PositionConverter}.
246
     * 
247
     * @return PositionConverter binding the virtual Java source and the real source.
248
     */
249
    public PositionConverter getPositionConverter() {
250
        return binding;
242
    }
251
    }
243
    
252
    
244
    public Document getDocument() throws IOException {
253
    public Document getDocument() throws IOException {
245
        if (this.fo == null) {
254
        if (this.binding == null || this.binding.getFileObject() == null) {
246
            return null;
255
            return null;
247
        }
256
        }
248
        DataObject od = DataObject.find(fo);            
257
        DataObject od = DataObject.find(this.binding.getFileObject());            
249
        EditorCookie ec = (EditorCookie) od.getCookie(EditorCookie.class);        
258
        EditorCookie ec = od.getCookie(EditorCookie.class);
250
        if (ec != null) {                
259
        if (ec != null) {
251
            return  ec.getDocument();
260
            return  ec.getDocument();
252
        } else {
261
        } else {
253
            return null;
262
            return null;
(-)source/src/org/netbeans/api/java/source/JavaSource.java (-61 / +94 lines)
Lines 92-101 Link Here
92
import javax.tools.JavaFileObject;
92
import javax.tools.JavaFileObject;
93
import javax.tools.ToolProvider;
93
import javax.tools.ToolProvider;
94
import org.netbeans.api.java.classpath.ClassPath;
94
import org.netbeans.api.java.classpath.ClassPath;
95
import org.netbeans.api.java.lexer.JavaTokenId;
95
import org.netbeans.api.java.platform.JavaPlatformManager;
96
import org.netbeans.api.java.platform.JavaPlatformManager;
96
import org.netbeans.api.java.queries.SourceLevelQuery;
97
import org.netbeans.api.java.queries.SourceLevelQuery;
97
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
98
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
98
import org.netbeans.api.java.source.ModificationResult.Difference;
99
import org.netbeans.api.java.source.ModificationResult.Difference;
100
import org.netbeans.api.lexer.Language;
101
import org.netbeans.api.timers.TimesCollector;
99
import org.netbeans.editor.Registry;
102
import org.netbeans.editor.Registry;
100
import org.netbeans.modules.java.source.JavaFileFilterQuery;
103
import org.netbeans.modules.java.source.JavaFileFilterQuery;
101
import org.netbeans.modules.java.source.builder.ASTService;
104
import org.netbeans.modules.java.source.builder.ASTService;
Lines 106-111 Link Here
106
import org.netbeans.modules.java.source.engine.RootTree;
109
import org.netbeans.modules.java.source.engine.RootTree;
107
import org.netbeans.modules.java.source.parsing.FileObjects;
110
import org.netbeans.modules.java.source.parsing.FileObjects;
108
import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation;
111
import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation;
112
import org.netbeans.modules.java.preprocessorbridge.spi.JavaSourceProvider;
109
import org.netbeans.modules.java.source.TreeLoader;
113
import org.netbeans.modules.java.source.TreeLoader;
110
import org.netbeans.modules.java.source.builder.DefaultEnvironment;
114
import org.netbeans.modules.java.source.builder.DefaultEnvironment;
111
import org.netbeans.modules.java.source.tasklist.CompilerSettings;
115
import org.netbeans.modules.java.source.tasklist.CompilerSettings;
Lines 130-135 Link Here
130
import org.openide.loaders.DataObjectNotFoundException;
134
import org.openide.loaders.DataObjectNotFoundException;
131
import org.openide.modules.SpecificationVersion;
135
import org.openide.modules.SpecificationVersion;
132
import org.openide.util.Exceptions;
136
import org.openide.util.Exceptions;
137
import org.openide.util.Lookup;
133
import org.openide.util.NbBundle;
138
import org.openide.util.NbBundle;
134
import org.openide.util.RequestProcessor;
139
import org.openide.util.RequestProcessor;
135
import org.openide.util.WeakListeners;
140
import org.openide.util.WeakListeners;
Lines 280-285 Link Here
280
    //Preprocessor support
285
    //Preprocessor support
281
    private FilterListener filterListener;
286
    private FilterListener filterListener;
282
    
287
    
288
    private PositionConverter binding;
289
    
283
    private static final Logger LOGGER = Logger.getLogger(JavaSource.class.getName());
290
    private static final Logger LOGGER = Logger.getLogger(JavaSource.class.getName());
284
        
291
        
285
    static {
292
    static {
Lines 299-312 Link Here
299
        if (files == null || cpInfo == null) {
306
        if (files == null || cpInfo == null) {
300
            throw new IllegalArgumentException ();
307
            throw new IllegalArgumentException ();
301
        }
308
        }
302
        try {
309
        return create(cpInfo, null, files);
303
            return new JavaSource(cpInfo, files);
304
        } catch (DataObjectNotFoundException donf) {
305
            LOGGER.warning("Ignoring non existent file: " + FileUtil.getFileDisplayName(donf.getFileObject()));     //NOI18N
306
        } catch (IOException ex) {            
307
            Exceptions.printStackTrace(ex);
308
        }        
309
        return null;
310
    }
310
    }
311
    
311
    
312
    
312
    
Lines 322-328 Link Here
322
        if (files == null || cpInfo == null) {
322
        if (files == null || cpInfo == null) {
323
            throw new IllegalArgumentException ();
323
            throw new IllegalArgumentException ();
324
        }
324
        }
325
        return create(cpInfo, Arrays.asList(files));
325
        return create(cpInfo, null, Arrays.asList(files));
326
    }
327
    
328
    private static JavaSource create(final ClasspathInfo cpInfo, final PositionConverter binding, final Collection<? extends FileObject> files) throws IllegalArgumentException {
329
        try {
330
            return new JavaSource(cpInfo, binding, files);
331
        } catch (DataObjectNotFoundException donf) {
332
            Logger.getLogger("global").warning("Ignoring non existent file: " + FileUtil.getFileDisplayName(donf.getFileObject()));     //NOI18N
333
        } catch (IOException ex) {            
334
            Exceptions.printStackTrace(ex);
335
        }        
336
        return null;
326
    }
337
    }
327
    
338
    
328
    private static Map<FileObject, Reference<JavaSource>> file2JavaSource = new WeakHashMap<FileObject, Reference<JavaSource>>();
339
    private static Map<FileObject, Reference<JavaSource>> file2JavaSource = new WeakHashMap<FileObject, Reference<JavaSource>>();
Lines 341-383 Link Here
341
        if (!fileObject.isValid()) {
352
        if (!fileObject.isValid()) {
342
            return null;
353
            return null;
343
        }
354
        }
344
        if ("text/x-java".equals(FileUtil.getMIMEType(fileObject)) || "java".equals(fileObject.getExt())) {  //NOI18N
355
345
           Reference<JavaSource> ref = file2JavaSource.get(fileObject);
356
        Reference<JavaSource> ref = file2JavaSource.get(fileObject);
346
            JavaSource js = ref != null ? ref.get() : null;
357
        JavaSource js = ref != null ? ref.get() : null;
347
            if (js == null) {
358
        if (js == null) {
348
                file2JavaSource.put(fileObject, new WeakReference<JavaSource>(js = create(ClasspathInfo.create(fileObject), fileObject)));
359
            if ("application/x-class-file".equals(FileUtil.getMIMEType(fileObject)) || "class".equals(fileObject.getExt())) {   //NOI18N
349
            }
360
                ClassPath bootPath = ClassPath.getClassPath(fileObject, ClassPath.BOOT);
350
            return js;
361
                ClassPath compilePath = ClassPath.getClassPath(fileObject, ClassPath.COMPILE);
351
        }
362
                if (compilePath == null) {
352
        if ("application/x-class-file".equals(FileUtil.getMIMEType(fileObject)) || "class".equals(fileObject.getExt())) {   //NOI18N
363
                    compilePath = ClassPathSupport.createClassPath(new URL[0]);
353
            ClassPath bootPath = ClassPath.getClassPath(fileObject, ClassPath.BOOT);
364
                }
354
            ClassPath compilePath = ClassPath.getClassPath(fileObject, ClassPath.COMPILE);
365
                ClassPath srcPath = ClassPath.getClassPath(fileObject, ClassPath.SOURCE);
355
            if (compilePath == null) {
366
                if (srcPath == null) {
356
                compilePath = ClassPathSupport.createClassPath(new URL[0]);
367
                    srcPath = ClassPathSupport.createClassPath(new URL[0]);
357
            }
368
                }
358
            ClassPath srcPath = ClassPath.getClassPath(fileObject, ClassPath.SOURCE);
369
                ClassPath execPath = ClassPath.getClassPath(fileObject, ClassPath.EXECUTE);
359
            if (srcPath == null) {
370
                if (execPath != null) {
360
                srcPath = ClassPathSupport.createClassPath(new URL[0]);
371
                    bootPath = ClassPathSupport.createProxyClassPath(execPath, bootPath);
361
            }
372
                }
362
            ClassPath execPath = ClassPath.getClassPath(fileObject, ClassPath.EXECUTE);
373
                final ClasspathInfo info = ClasspathInfo.create(bootPath, compilePath, srcPath);
363
            if (execPath != null) {
374
                FileObject root = ClassPathSupport.createProxyClassPath(bootPath,compilePath,srcPath).findOwnerRoot(fileObject);
364
                bootPath = ClassPathSupport.createProxyClassPath(execPath, bootPath);
375
                try {
376
                    js = new JavaSource (info,fileObject,root);
377
                } catch (IOException ioe) {
378
                    Exceptions.printStackTrace(ioe);
379
                }
380
            } else {
381
            PositionConverter binding = null;
382
            if (!"text/x-java".equals(FileUtil.getMIMEType(fileObject)) && !"java".equals(fileObject.getExt())) {  //NOI18N
383
                for (JavaSourceProvider provider : Lookup.getDefault().lookupAll(JavaSourceProvider.class)) {
384
                    JavaFileFilterImplementation filter = provider.forFileObject(fileObject);
385
                    if (filter != null) {
386
                        binding = new PositionConverter(fileObject, filter);
387
                        break;
388
                    }
389
                }
390
                if (binding == null)
391
                    return null;
365
            }
392
            }
366
            final ClasspathInfo info = ClasspathInfo.create(bootPath, compilePath, srcPath);
393
            js = create(ClasspathInfo.create(fileObject), binding, Collections.singletonList(fileObject));
367
            FileObject root = ClassPathSupport.createProxyClassPath(bootPath,compilePath,srcPath).findOwnerRoot(fileObject);
368
            try {
369
                return new JavaSource (info,fileObject,root);
370
            } catch (IOException ioe) {
371
                Exceptions.printStackTrace(ioe);
372
            }
394
            }
395
            file2JavaSource.put(fileObject, new WeakReference<JavaSource>(js));
373
        }
396
        }
374
        return null;        
397
        return js;
375
    }
398
    }
376
    
399
    
377
    /**
400
    /**
378
     * Returns a {@link JavaSource} instance associated to {@link org.openide.filesystems.FileObject}
401
     * Returns a {@link JavaSource} instance associated to the given {@link javax.swing.Document},
379
     * the {@link Document} was created from, it returns null if the {@link Document} is not
402
     * it returns null if the {@link Document} is not
380
     * associanted with data type providing the {@link JavaSource}.
403
     * associated with data type providing the {@link JavaSource}.
381
     * @param doc {@link Document} for which the {@link JavaSource} should be found/created.
404
     * @param doc {@link Document} for which the {@link JavaSource} should be found/created.
382
     * @return {@link JavaSource} or null
405
     * @return {@link JavaSource} or null
383
     * @throws {@link IllegalArgumentException} if doc is null
406
     * @throws {@link IllegalArgumentException} if doc is null
Lines 386-393 Link Here
386
        if (doc == null) {
409
        if (doc == null) {
387
            throw new IllegalArgumentException ("doc == null");  //NOI18N
410
            throw new IllegalArgumentException ("doc == null");  //NOI18N
388
        }
411
        }
389
        Reference<?> ref = (Reference<?>) doc.getProperty(JavaSource.class);
412
        JavaSource js = (JavaSource)doc.getProperty(JavaSource.class);
390
        JavaSource js = ref != null ? (JavaSource) ref.get() : null;
391
        if (js == null) {
413
        if (js == null) {
392
            DataObject dObj = (DataObject)doc.getProperty(Document.StreamDescriptionProperty);
414
            DataObject dObj = (DataObject)doc.getProperty(Document.StreamDescriptionProperty);
393
            if (dObj != null)
415
            if (dObj != null)
Lines 401-410 Link Here
401
     * @param files to create JavaSource for
423
     * @param files to create JavaSource for
402
     * @param cpInfo classpath info
424
     * @param cpInfo classpath info
403
     */
425
     */
404
    private JavaSource (ClasspathInfo cpInfo, Collection<? extends FileObject> files) throws IOException {
426
    private JavaSource (ClasspathInfo cpInfo, PositionConverter binding, Collection<? extends FileObject> files) throws IOException {
405
        this.reparseDelay = REPARSE_DELAY;
427
        this.reparseDelay = REPARSE_DELAY;
406
        this.files = Collections.unmodifiableList(new ArrayList<FileObject>(files));   //Create a defensive copy, prevent modification
428
        this.files = Collections.unmodifiableList(new ArrayList<FileObject>(files));   //Create a defensive copy, prevent modification
407
        this.fileChangeListener = new FileChangeListenerImpl ();
429
        this.fileChangeListener = new FileChangeListenerImpl ();
430
        this.binding = binding;
408
        boolean multipleSources = this.files.size() > 1, filterAssigned = false;
431
        boolean multipleSources = this.files.size() > 1, filterAssigned = false;
409
        for (Iterator<? extends FileObject> it = this.files.iterator(); it.hasNext();) {
432
        for (Iterator<? extends FileObject> it = this.files.iterator(); it.hasNext();) {
410
            FileObject file = it.next();
433
            FileObject file = it.next();
Lines 418-424 Link Here
418
                }
441
                }
419
                if (!filterAssigned) {
442
                if (!filterAssigned) {
420
                    filterAssigned = true;
443
                    filterAssigned = true;
421
                    JavaFileFilterImplementation filter = JavaFileFilterQuery.getFilter(file);
444
                    if (this.binding == null) {
445
                        this.binding = new PositionConverter(file, JavaFileFilterQuery.getFilter(file));
446
                    }
447
                    JavaFileFilterImplementation filter = this.binding.getFilter();
422
                    if (filter != null) {
448
                    if (filter != null) {
423
                        this.filterListener = new FilterListener (filter);
449
                        this.filterListener = new FilterListener (filter);
424
                    }
450
                    }
Lines 433-439 Link Here
433
                }
459
                }
434
            }
460
            }
435
        }
461
        }
436
        this.classpathInfo = cpInfo;        
462
        this.classpathInfo = cpInfo;
437
        if (this.files.size() == 1) {
463
        if (this.files.size() == 1) {
438
            this.rootFo = classpathInfo.getClassPath(PathKind.SOURCE).findOwnerRoot(this.files.iterator().next());
464
            this.rootFo = classpathInfo.getClassPath(PathKind.SOURCE).findOwnerRoot(this.files.iterator().next());
439
        }
465
        }
Lines 486-492 Link Here
486
        assert !holdsDocumentWriteLock(files) : "JavaSource.runCompileControlTask called under Document write lock.";    //NOI18N
512
        assert !holdsDocumentWriteLock(files) : "JavaSource.runCompileControlTask called under Document write lock.";    //NOI18N
487
        
513
        
488
        boolean a = false;
514
        boolean a = false;
489
        assert a = true;        
515
        assert a = true;
490
        if (a && javax.swing.SwingUtilities.isEventDispatchThread()) {
516
        if (a && javax.swing.SwingUtilities.isEventDispatchThread()) {
491
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[2];
517
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[2];
492
            if (warnedAboutRunInEQ.add(stackTraceElement)) {
518
            if (warnedAboutRunInEQ.add(stackTraceElement)) {
Lines 512-518 Link Here
512
                        }                        
538
                        }                        
513
                    }
539
                    }
514
                    if (currentInfo == null) {
540
                    if (currentInfo == null) {
515
                        currentInfo = createCurrentInfo(this,this.files.isEmpty() ? null : this.files.iterator().next(), filterListener, null);                
541
                        currentInfo = createCurrentInfo(this, binding, null);
516
                        if (shared) {
542
                        if (shared) {
517
                            synchronized (this) {                        
543
                            synchronized (this) {                        
518
                                if (this.currentInfo == null || (this.flags & INVALID) != 0) {
544
                                if (this.currentInfo == null || (this.flags & INVALID) != 0) {
Lines 581-587 Link Here
581
                        else {
607
                        else {
582
                            restarted = true;
608
                            restarted = true;
583
                        }
609
                        }
584
                        CompilationInfo ci = createCurrentInfo(this,activeFile,filterListener,jt);
610
                        CompilationInfo ci = createCurrentInfo(this, new PositionConverter(activeFile, null), jt);
585
                        task.run(new CompilationController(ci));
611
                        task.run(new CompilationController(ci));
586
                        if (!ci.needsRestart) {
612
                        if (!ci.needsRestart) {
587
                            jt = ci.getJavacTask();
613
                            jt = ci.getJavacTask();
Lines 732-738 Link Here
732
                        }
758
                        }
733
                    }
759
                    }
734
                    if (currentInfo == null) {
760
                    if (currentInfo == null) {
735
                        currentInfo = createCurrentInfo(this,this.files.isEmpty() ? null : this.files.iterator().next(), filterListener, null);
761
                        currentInfo = createCurrentInfo(this, binding, null);
736
                        synchronized (this) {
762
                        synchronized (this) {
737
                            if (this.currentInfo == null || (this.flags & INVALID) != 0) {
763
                            if (this.currentInfo == null || (this.flags & INVALID) != 0) {
738
                                this.currentInfo = currentInfo;
764
                                this.currentInfo = currentInfo;
Lines 791-797 Link Here
791
                        else {
817
                        else {
792
                            restarted = true;
818
                            restarted = true;
793
                        }
819
                        }
794
                        CompilationInfo ci = createCurrentInfo(this,activeFile, filterListener, jt);
820
                        CompilationInfo ci = createCurrentInfo(this, new PositionConverter(activeFile, null), jt);
795
                        WorkingCopy copy = new WorkingCopy(ci);
821
                        WorkingCopy copy = new WorkingCopy(ci);
796
                        task.run(copy);
822
                        task.run(copy);
797
                        if (!ci.needsRestart) {
823
                        if (!ci.needsRestart) {
Lines 864-870 Link Here
864
            currentInfo = this.currentInfo;
890
            currentInfo = this.currentInfo;
865
        }
891
        }
866
        if (currentInfo == null) {
892
        if (currentInfo == null) {
867
            currentInfo = createCurrentInfo (this, this.files.isEmpty() ? null : this.files.iterator().next(), filterListener, null);
893
            currentInfo = createCurrentInfo (this, binding, null);
868
        }
894
        }
869
        synchronized (this) {
895
        synchronized (this) {
870
            if (this.currentInfo == null) {
896
            if (this.currentInfo == null) {
Lines 1407-1413 Link Here
1407
                                    try {
1433
                                    try {
1408
                                        //createCurrentInfo has to be out of synchronized block, it aquires an editor lock                                    
1434
                                        //createCurrentInfo has to be out of synchronized block, it aquires an editor lock                                    
1409
                                        if (jsInvalid) {
1435
                                        if (jsInvalid) {
1410
                                            ci = createCurrentInfo (js,js.files.isEmpty() ? null : js.files.iterator().next(), js.filterListener, null);
1436
                                            ci = createCurrentInfo (js, js.binding, null);
1411
                                            synchronized (js) {
1437
                                            synchronized (js) {
1412
                                                if ((js.flags & INVALID) != 0) {
1438
                                                if ((js.flags & INVALID) != 0) {
1413
                                                    js.currentInfo = ci;
1439
                                                    js.currentInfo = ci;
Lines 1715-1725 Link Here
1715
    
1741
    
1716
    private final class FilterListener implements ChangeListener {        
1742
    private final class FilterListener implements ChangeListener {        
1717
        
1743
        
1718
        private final JavaFileFilterImplementation filter;
1719
        
1720
        public FilterListener (final JavaFileFilterImplementation filter) {
1744
        public FilterListener (final JavaFileFilterImplementation filter) {
1721
            this.filter = filter;
1745
            filter.addChangeListener(WeakListeners.change(this, filter));
1722
            this.filter.addChangeListener(WeakListeners.change(this, this.filter));
1723
        }
1746
        }
1724
        
1747
        
1725
        public void stateChanged(ChangeEvent event) {
1748
        public void stateChanged(ChangeEvent event) {
Lines 1727-1736 Link Here
1727
        }
1750
        }
1728
    }
1751
    }
1729
        
1752
        
1730
    private static CompilationInfo createCurrentInfo (final JavaSource js, final FileObject fo, final FilterListener filterListener, final JavacTaskImpl javac) throws IOException {        
1753
    private static CompilationInfo createCurrentInfo (final JavaSource js, final PositionConverter binding, final JavacTaskImpl javac) throws IOException {        
1731
        CompilationInfo info = new CompilationInfo (js, fo, filterListener == null ? null : filterListener.filter, javac);
1754
        CompilationInfo info = new CompilationInfo (js, binding, javac);
1732
        Logger.getLogger("TIMER").log(Level.FINE, "CompilationInfo",
1755
        if (binding != null) {
1733
            new Object[] {fo, info});
1756
            Logger.getLogger("TIMER").log(Level.FINE, "CompilationInfo",
1757
                    new Object[] {binding.getFileObject(), info});
1758
        }
1734
        return info;
1759
        return info;
1735
    }
1760
    }
1736
1761
Lines 1814-1819 Link Here
1814
        public boolean isDispatchThread () {
1839
        public boolean isDispatchThread () {
1815
            return factory.isDispatchThread(Thread.currentThread());
1840
            return factory.isDispatchThread(Thread.currentThread());
1816
        }
1841
        }
1842
1843
        public JavaSource create(ClasspathInfo cpInfo, PositionConverter binding, Collection<? extends FileObject> files) throws IllegalArgumentException {
1844
            return JavaSource.create(cpInfo, binding, files);
1845
        }
1846
1847
        public PositionConverter create(FileObject fo, int offset, int length, JTextComponent component) {
1848
            return new PositionConverter(fo, offset, length, component);
1849
        }
1817
    }
1850
    }
1818
    
1851
    
1819
    
1852
    
Lines 2179-2185 Link Here
2179
        String dumpDir = System.getProperty("netbeans.user") + "/var/log/"; //NOI18N
2212
        String dumpDir = System.getProperty("netbeans.user") + "/var/log/"; //NOI18N
2180
        String src = info.getText();
2213
        String src = info.getText();
2181
        FileObject file = info.getFileObject();
2214
        FileObject file = info.getFileObject();
2182
        String fileName = FileUtil.getFileDisplayName(info.getFileObject());
2215
        String fileName = FileUtil.getFileDisplayName(file);
2183
        String origName = file.getName();
2216
        String origName = file.getName();
2184
        File f = new File(dumpDir + origName + ".dump"); // NOI18N
2217
        File f = new File(dumpDir + origName + ".dump"); // NOI18N
2185
        boolean dumpSucceeded = false;
2218
        boolean dumpSucceeded = false;
(-)source/src/org/netbeans/api/java/source/PositionConverter.java (+154 lines)
Added Link Here
1
/*
2
 * The contents of this file are subject to the terms of the Common Development
3
 * and Distribution License (the License). You may not use this file except in
4
 * compliance with the License.
5
 *
6
 * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7
 * or http://www.netbeans.org/cddl.txt.
8
 *
9
 * When distributing Covered Code, include this CDDL Header Notice in each file
10
 * and include the License file at http://www.netbeans.org/cddl.txt.
11
 * If applicable, add the following below the CDDL Header, with the fields
12
 * enclosed by brackets [] replaced by your own identifying information:
13
 * "Portions Copyrighted [year] [name of copyright owner]"
14
 *
15
 * The Original Software is NetBeans. The Initial Developer of the Original
16
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17
 * Microsystems, Inc. All Rights Reserved.
18
 */
19
20
package org.netbeans.api.java.source;
21
22
import java.io.Reader;
23
import java.io.Writer;
24
import java.util.concurrent.CopyOnWriteArrayList;
25
import javax.swing.event.ChangeListener;
26
import javax.swing.event.DocumentEvent;
27
import javax.swing.event.DocumentListener;
28
import javax.swing.text.JTextComponent;
29
import org.netbeans.modules.java.preprocessorbridge.spi.JavaFileFilterImplementation;
30
import org.netbeans.modules.java.preprocessorbridge.spi.JavaSourceProvider;
31
import org.openide.filesystems.FileObject;
32
33
/**Binding between virtual Java source and the real source.
34
 * Please note that this class is needed only for clients that need to work
35
 * in non-Java files (eg. JSP files) or in dialogs, like code completion.
36
 * Most clients do not need to use this class.
37
 * 
38
 * @author Dusan Balek
39
 */
40
public final class PositionConverter {
41
    
42
    private FileObject fo;
43
    private JavaFileFilterImplementation filter;
44
    private int offset;
45
    private int length;
46
    private JTextComponent component;
47
    
48
    PositionConverter (final FileObject fo, final JavaFileFilterImplementation filter) {
49
        this.fo = fo;
50
        this.filter = filter;
51
    }
52
    
53
    PositionConverter (final FileObject fo, int offset, int length, final JTextComponent component) {
54
        this.fo = fo;
55
        this.offset = offset;
56
        this.length = length;
57
        this.component = component;
58
        this.filter = new Filter();
59
    }
60
    // API of the class --------------------------------------------------------
61
62
    /**Compute position in the document for given position in the virtual
63
     * Java source.
64
     * 
65
     * @param javaSourcePosition position in the virtual Java Source
66
     * @return position in the document
67
     */
68
    public int getOriginalPosition(int javaSourcePosition) {
69
        if (filter instanceof JavaSourceProvider.PositionTranslatingJavaFileFilterImplementation) {
70
            return ((JavaSourceProvider.PositionTranslatingJavaFileFilterImplementation)filter).getOriginalPosition(javaSourcePosition);
71
        }
72
        return javaSourcePosition;
73
    }
74
    
75
    /**Compute position in the virtual Java source for given position
76
     * in the document.
77
     *
78
     * @param originalPosition position in the document
79
     * @return position in the virtual Java source
80
     */
81
    public int getJavaSourcePosition(int originalPosition) {
82
        if (filter instanceof JavaSourceProvider.PositionTranslatingJavaFileFilterImplementation) {
83
            return ((JavaSourceProvider.PositionTranslatingJavaFileFilterImplementation)filter).getJavaSourcePosition(originalPosition);
84
        }
85
        return originalPosition;
86
    }
87
88
    // Package private methods -------------------------------------------------
89
90
    JavaFileFilterImplementation getFilter() {
91
        return filter;
92
    }
93
    
94
    FileObject getFileObject() {
95
        return fo;
96
    }
97
    
98
    // Nested classes ----------------------------------------------------------
99
100
    private class Filter implements JavaSourceProvider.PositionTranslatingJavaFileFilterImplementation, DocumentListener {
101
        
102
        CopyOnWriteArrayList<ChangeListener> listeners = new CopyOnWriteArrayList<ChangeListener>();
103
        
104
        public Filter() {
105
            component.getDocument().addDocumentListener(this);
106
        }
107
108
        public Reader filterReader(Reader r) {
109
            throw new UnsupportedOperationException("Not supported yet.");
110
        }
111
112
        public CharSequence filterCharSequence(CharSequence charSequence) {
113
            return charSequence.subSequence(0, offset) + 
114
                    component.getText() + 
115
                    charSequence.subSequence(offset + length, charSequence.length());
116
        }
117
118
        public Writer filterWriter(Writer w) {
119
            throw new UnsupportedOperationException("Not supported yet.");
120
        }
121
122
        public void addChangeListener(ChangeListener listener) {
123
            listeners.addIfAbsent(listener);
124
        }
125
        
126
        public void removeChangeListener(ChangeListener listener) {
127
            listeners.remove(listener);
128
        }
129
    
130
        public int getOriginalPosition(int javaSourcePosition) {
131
            if (javaSourcePosition < offset)
132
                return -1;
133
            int diff = javaSourcePosition - offset;
134
            return diff <= component.getText().length() ? diff : -1;
135
        }
136
137
        public int getJavaSourcePosition(int originalPosition) {
138
            return offset + originalPosition;
139
        }
140
    
141
        public void insertUpdate(DocumentEvent event) {
142
            this.changedUpdate(event);
143
        }
144
145
        public void removeUpdate(DocumentEvent event) {
146
            this.changedUpdate(event);
147
        }
148
149
        public void changedUpdate(DocumentEvent event) {
150
            for (ChangeListener changeListener : listeners)
151
                changeListener.stateChanged(null);
152
        }
153
    }
154
}
(-)source/src/org/netbeans/api/java/source/SourceUtils.java (+24 lines)
Lines 27-32 Link Here
27
import java.util.*;
27
import java.util.*;
28
28
29
import javax.lang.model.element.*;
29
import javax.lang.model.element.*;
30
import javax.lang.model.type.*;
30
import javax.lang.model.element.VariableElement;
31
import javax.lang.model.element.VariableElement;
31
import javax.lang.model.type.ArrayType;
32
import javax.lang.model.type.ArrayType;
32
import javax.lang.model.type.DeclaredType;
33
import javax.lang.model.type.DeclaredType;
Lines 59-66 Link Here
59
import java.net.URLEncoder;
60
import java.net.URLEncoder;
60
import javax.swing.text.BadLocationException;
61
import javax.swing.text.BadLocationException;
61
import javax.swing.text.Document;
62
import javax.swing.text.Document;
63
import java.util.logging.Level;
64
import java.util.logging.Logger;
62
65
63
import org.netbeans.api.java.classpath.ClassPath;
66
import org.netbeans.api.java.classpath.ClassPath;
67
import org.netbeans.api.java.lexer.JavaTokenId;
64
import org.netbeans.api.java.classpath.GlobalPathRegistry;
68
import org.netbeans.api.java.classpath.GlobalPathRegistry;
65
import org.netbeans.api.java.queries.JavadocForBinaryQuery;
69
import org.netbeans.api.java.queries.JavadocForBinaryQuery;
66
import org.netbeans.api.java.queries.SourceForBinaryQuery;
70
import org.netbeans.api.java.queries.SourceForBinaryQuery;
Lines 68-73 Link Here
68
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
72
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
69
import org.netbeans.api.java.source.JavaSource.Phase;
73
import org.netbeans.api.java.source.JavaSource.Phase;
70
import org.netbeans.api.java.source.WorkingCopy;
74
import org.netbeans.api.java.source.WorkingCopy;
75
import org.netbeans.api.lexer.TokenHierarchy;
76
import org.netbeans.api.lexer.TokenId;
77
import org.netbeans.api.lexer.TokenSequence;
71
import org.netbeans.modules.java.JavaDataLoader;
78
import org.netbeans.modules.java.JavaDataLoader;
72
import org.netbeans.modules.java.source.parsing.FileObjects;
79
import org.netbeans.modules.java.source.parsing.FileObjects;
73
import org.netbeans.modules.java.source.pretty.VeryPretty;
80
import org.netbeans.modules.java.source.pretty.VeryPretty;
Lines 79-86 Link Here
79
86
80
import org.openide.filesystems.FileObject;
87
import org.openide.filesystems.FileObject;
81
import org.openide.filesystems.FileStateInvalidException;
88
import org.openide.filesystems.FileStateInvalidException;
89
import org.openide.filesystems.FileUtil;
82
import org.openide.filesystems.URLMapper;
90
import org.openide.filesystems.URLMapper;
83
import org.openide.util.Exceptions;
91
import org.openide.util.Exceptions;
92
import org.openide.util.Parameters;
84
import org.openide.util.RequestProcessor;
93
import org.openide.util.RequestProcessor;
85
94
86
/**
95
/**
Lines 124-129 Link Here
124
        return ((MethodSymbol)method).implementation((TypeSymbol)origin, com.sun.tools.javac.code.Types.instance(c), true);
133
        return ((MethodSymbol)method).implementation((TypeSymbol)origin, com.sun.tools.javac.code.Types.instance(c), true);
125
    }
134
    }
126
135
136
    public static TokenSequence<JavaTokenId> getJavaTokenSequence(final TokenHierarchy hierarchy, final int offset) {
137
        if (hierarchy != null) {
138
            TokenSequence<? extends TokenId> ts = hierarchy.tokenSequence();
139
            while(ts != null && (ts.moveNext() || offset == 0)) {
140
                ts.move(offset);
141
                if (!ts.moveNext())
142
                    return null;
143
                if (ts.language() == JavaTokenId.language())
144
                    return (TokenSequence<JavaTokenId>)ts;
145
                ts = ts.embedded();
146
            }
147
        }
148
        return null;
149
    }
150
    
127
    public static boolean checkTypesAssignable(CompilationInfo info, TypeMirror from, TypeMirror to) {
151
    public static boolean checkTypesAssignable(CompilationInfo info, TypeMirror from, TypeMirror to) {
128
        Context c = ((JavacTaskImpl) info.getJavacTask()).getContext();
152
        Context c = ((JavacTaskImpl) info.getJavacTask()).getContext();
129
        if (from.getKind() == TypeKind.DECLARED) {
153
        if (from.getKind() == TypeKind.DECLARED) {
(-)source/src/org/netbeans/api/java/source/support/CaretAwareJavaSourceTaskFactory.java (-3 / +20 lines)
Lines 19-24 Link Here
19
package org.netbeans.api.java.source.support;
19
package org.netbeans.api.java.source.support;
20
20
21
import java.util.ArrayList;
21
import java.util.ArrayList;
22
import java.util.Arrays;
22
import java.util.HashMap;
23
import java.util.HashMap;
23
import java.util.List;
24
import java.util.List;
24
import java.util.Map;
25
import java.util.Map;
Lines 31-36 Link Here
31
import org.netbeans.api.java.source.JavaSource.Phase;
32
import org.netbeans.api.java.source.JavaSource.Phase;
32
import org.netbeans.api.java.source.JavaSource.Priority;
33
import org.netbeans.api.java.source.JavaSource.Priority;
33
import org.netbeans.api.java.source.JavaSourceTaskFactory;
34
import org.netbeans.api.java.source.JavaSourceTaskFactory;
35
import org.netbeans.api.java.source.SourceUtils;
34
import org.openide.filesystems.FileObject;
36
import org.openide.filesystems.FileObject;
35
import org.openide.util.RequestProcessor;
37
import org.openide.util.RequestProcessor;
36
38
Lines 39-44 Link Here
39
 * opened and visible JTextComponents and reschedules the tasks as necessary.
41
 * opened and visible JTextComponents and reschedules the tasks as necessary.
40
 *
42
 *
41
 * The tasks may access current caret position using {@link #getLastPosition} method.
43
 * The tasks may access current caret position using {@link #getLastPosition} method.
44
 * 
45
 * The files returned from the {@link #getFileObjects} method will be filtered using
46
 * {@link org.netbeans.api.java.source.SourceUtils#filterSupportedMIMETypes}.
42
 *
47
 *
43
 * @author Jan Lahoda
48
 * @author Jan Lahoda
44
 */
49
 */
Lines 48-53 Link Here
48
    private static final RequestProcessor WORKER = new RequestProcessor("CaretAwareJavaSourceTaskFactory worker");
53
    private static final RequestProcessor WORKER = new RequestProcessor("CaretAwareJavaSourceTaskFactory worker");
49
    
54
    
50
    private int timeout;
55
    private int timeout;
56
    private String[] supportedMimeTypes;
51
    
57
    
52
    /**Construct the CaretAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
58
    /**Construct the CaretAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
53
     *
59
     *
Lines 55-75 Link Here
55
     * @param priority priority to use for tasks created by {@link #createTask}
61
     * @param priority priority to use for tasks created by {@link #createTask}
56
     */
62
     */
57
    public CaretAwareJavaSourceTaskFactory(Phase phase, Priority priority) {
63
    public CaretAwareJavaSourceTaskFactory(Phase phase, Priority priority) {
64
        this(phase, priority, (String[]) null);
65
    }
66
    
67
    /**Construct the CaretAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
68
     *
69
     * @param phase phase to use for tasks created by {@link #createTask}
70
     * @param priority priority to use for tasks created by {@link #createTask}
71
     * @param supportedMimeTypes a list of mime types on which the tasks created by this factory should be run
72
     */
73
    public CaretAwareJavaSourceTaskFactory(Phase phase, Priority priority, String... supportedMimeTypes) {
58
        super(phase, priority);
74
        super(phase, priority);
59
        //XXX: weak, or something like this:
75
        //XXX: weak, or something like this:
60
        OpenedEditors.getDefault().addChangeListener(new ChangeListenerImpl());
76
        OpenedEditors.getDefault().addChangeListener(new ChangeListenerImpl());
61
        this.timeout = DEFAULT_RESCHEDULE_TIMEOUT;
77
        this.timeout = DEFAULT_RESCHEDULE_TIMEOUT;
78
        this.supportedMimeTypes = supportedMimeTypes != null ? supportedMimeTypes.clone() : null;
62
    }
79
    }
63
    
80
    
64
    /**@inheritDoc*/
81
    /**@inheritDoc*/
65
    public List<FileObject> getFileObjects() {
82
    public List<FileObject> getFileObjects() {
66
        List<FileObject> files = new ArrayList<FileObject>(OpenedEditors.getDefault().getVisibleEditorsFiles());
83
        List<FileObject> files = OpenedEditors.filterSupportedMIMETypes(OpenedEditors.getDefault().getVisibleEditorsFiles(), supportedMimeTypes);
67
84
68
        return files;
85
        return files;
69
    }
86
    }
70
87
71
    private Map<JTextComponent, ComponentListener> component2Listener = new HashMap();
88
    private Map<JTextComponent, ComponentListener> component2Listener = new HashMap<JTextComponent, ComponentListener>();
72
    private static Map<FileObject, Integer> file2LastPosition = new WeakHashMap();
89
    private static Map<FileObject, Integer> file2LastPosition = new WeakHashMap<FileObject, Integer>();
73
    
90
    
74
    /**Returns current caret position in current {@link JTextComponent} for a given file.
91
    /**Returns current caret position in current {@link JTextComponent} for a given file.
75
     *
92
     *
(-)source/src/org/netbeans/api/java/source/support/EditorAwareJavaSourceTaskFactory.java (-5 / +18 lines)
Lines 18-56 Link Here
18
 */
18
 */
19
package org.netbeans.api.java.source.support;
19
package org.netbeans.api.java.source.support;
20
20
21
import java.util.ArrayList;
22
import java.util.List;
21
import java.util.List;
23
import javax.swing.event.ChangeEvent;
22
import javax.swing.event.ChangeEvent;
24
import javax.swing.event.ChangeListener;
23
import javax.swing.event.ChangeListener;
25
import javax.swing.text.Document;
26
import javax.swing.text.JTextComponent;
27
import org.netbeans.api.java.source.JavaSource.Phase;
24
import org.netbeans.api.java.source.JavaSource.Phase;
28
import org.netbeans.api.java.source.JavaSource.Priority;
25
import org.netbeans.api.java.source.JavaSource.Priority;
29
import org.netbeans.api.java.source.JavaSourceTaskFactory;
26
import org.netbeans.api.java.source.JavaSourceTaskFactory;
27
import org.netbeans.api.java.source.SourceUtils;
30
import org.openide.filesystems.FileObject;
28
import org.openide.filesystems.FileObject;
31
import org.openide.loaders.DataObject;
32
29
33
/**A {@link JavaSourceTaskFactorySupport} that registers tasks to all files that are
30
/**A {@link JavaSourceTaskFactorySupport} that registers tasks to all files that are
34
 * opened in the editor and are visible.
31
 * opened in the editor and are visible.
35
 *
32
 *
33
 * The files returned from the {@link #getFileObjects} method will be filtered using
34
 * {@link org.netbeans.api.java.source.SourceUtils#filterSupportedMIMETypes}.
35
 *
36
 * @author Jan Lahoda
36
 * @author Jan Lahoda
37
 */
37
 */
38
public abstract class EditorAwareJavaSourceTaskFactory extends JavaSourceTaskFactory {
38
public abstract class EditorAwareJavaSourceTaskFactory extends JavaSourceTaskFactory {
39
    
39
    
40
    private String[] supportedMimeTypes;
41
    
40
    /**Construct the EditorAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
42
    /**Construct the EditorAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
41
     *
43
     *
42
     * @param phase phase to use for tasks created by {@link #createTask}
44
     * @param phase phase to use for tasks created by {@link #createTask}
43
     * @param priority priority to use for tasks created by {@link #createTask}
45
     * @param priority priority to use for tasks created by {@link #createTask}
44
     */
46
     */
45
    protected EditorAwareJavaSourceTaskFactory(Phase phase, Priority priority) {
47
    protected EditorAwareJavaSourceTaskFactory(Phase phase, Priority priority) {
48
        this(phase, priority, (String[]) null);
49
    }
50
    
51
    /**Construct the EditorAwareJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
52
     *
53
     * @param phase phase to use for tasks created by {@link #createTask}
54
     * @param priority priority to use for tasks created by {@link #createTask}
55
     * @param supportedMimeTypes a list of mime types on which the tasks created by this factory should be run
56
     */
57
    protected EditorAwareJavaSourceTaskFactory(Phase phase, Priority priority, String... supportedMimeTypes) {
46
        super(phase, priority);
58
        super(phase, priority);
47
        //XXX: weak, or something like this:
59
        //XXX: weak, or something like this:
48
        OpenedEditors.getDefault().addChangeListener(new ChangeListenerImpl());
60
        OpenedEditors.getDefault().addChangeListener(new ChangeListenerImpl());
61
        this.supportedMimeTypes = supportedMimeTypes != null ? supportedMimeTypes.clone() : null;
49
    }
62
    }
50
    
63
    
51
    /**@inheritDoc*/
64
    /**@inheritDoc*/
52
    public List<FileObject> getFileObjects() {
65
    public List<FileObject> getFileObjects() {
53
        List<FileObject> files = new ArrayList<FileObject>(OpenedEditors.getDefault().getVisibleEditorsFiles());
66
        List<FileObject> files = OpenedEditors.filterSupportedMIMETypes(OpenedEditors.getDefault().getVisibleEditorsFiles(), supportedMimeTypes);
54
67
55
        return files;
68
        return files;
56
    }
69
    }
(-)source/src/org/netbeans/api/java/source/support/LookupBasedJavaSourceTaskFactory.java (-2 / +19 lines)
Lines 21-32 Link Here
21
import java.util.ArrayList;
21
import java.util.ArrayList;
22
import java.util.Collections;
22
import java.util.Collections;
23
import java.util.HashSet;
23
import java.util.HashSet;
24
import java.util.LinkedList;
24
import java.util.List;
25
import java.util.List;
25
import java.util.Set;
26
import java.util.Set;
26
import javax.swing.event.ChangeEvent;
27
import javax.swing.event.ChangeEvent;
27
import org.netbeans.api.java.source.JavaSource.Phase;
28
import org.netbeans.api.java.source.JavaSource.Phase;
28
import org.netbeans.api.java.source.JavaSource.Priority;
29
import org.netbeans.api.java.source.JavaSource.Priority;
29
import org.netbeans.api.java.source.JavaSourceTaskFactory;
30
import org.netbeans.api.java.source.JavaSourceTaskFactory;
31
import org.netbeans.api.java.source.SourceUtils;
30
import org.openide.filesystems.FileObject;
32
import org.openide.filesystems.FileObject;
31
import org.openide.loaders.DataObject;
33
import org.openide.loaders.DataObject;
32
import org.openide.nodes.Node;
34
import org.openide.nodes.Node;
Lines 42-47 Link Here
42
 * in the lookup. If {@link Node}(s) are found, its/their lookup is searched for
44
 * in the lookup. If {@link Node}(s) are found, its/their lookup is searched for
43
 * {@link FileObject} and {@link DataObject}.
45
 * {@link FileObject} and {@link DataObject}.
44
 *
46
 *
47
 * The files returned from the {@link #getFileObjects} method will be filtered using
48
 * {@link org.netbeans.api.java.source.SourceUtils#filterSupportedMIMETypes}.
49
 *
45
 * @author Jan Lahoda
50
 * @author Jan Lahoda
46
 */
51
 */
47
public abstract class LookupBasedJavaSourceTaskFactory extends JavaSourceTaskFactory {
52
public abstract class LookupBasedJavaSourceTaskFactory extends JavaSourceTaskFactory {
Lines 52-57 Link Here
52
    
57
    
53
    private List<FileObject> currentFiles;
58
    private List<FileObject> currentFiles;
54
    private LookupListener listener;
59
    private LookupListener listener;
60
    
61
    private String[] supportedMimeTypes;
55
62
56
    /**Construct the LookupBasedJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
63
    /**Construct the LookupBasedJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
57
     *
64
     *
Lines 59-67 Link Here
59
     * @param priority priority to use for tasks created by {@link #createTask}
66
     * @param priority priority to use for tasks created by {@link #createTask}
60
     */
67
     */
61
    public LookupBasedJavaSourceTaskFactory(Phase phase, Priority priority) {
68
    public LookupBasedJavaSourceTaskFactory(Phase phase, Priority priority) {
69
        this(phase, priority, (String[]) null);
70
    }
71
    
72
    /**Construct the LookupBasedJavaSourceTaskFactory with given {@link Phase} and {@link Priority}.
73
     *
74
     * @param phase phase to use for tasks created by {@link #createTask}
75
     * @param priority priority to use for tasks created by {@link #createTask}
76
     */
77
    public LookupBasedJavaSourceTaskFactory(Phase phase, Priority priority, String... supportedMimeTypes) {
62
        super(phase, priority);
78
        super(phase, priority);
63
        currentFiles = Collections.emptyList();
79
        currentFiles = Collections.emptyList();
64
        listener = new LookupListenerImpl();
80
        listener = new LookupListenerImpl();
81
        this.supportedMimeTypes = supportedMimeTypes != null ? supportedMimeTypes.clone() : null;
65
    }
82
    }
66
83
67
    /**Sets a new {@link Lookup} to search.
84
    /**Sets a new {@link Lookup} to search.
Lines 91-97 Link Here
91
    }
108
    }
92
109
93
    private synchronized void updateCurrentFiles() {
110
    private synchronized void updateCurrentFiles() {
94
        Set<FileObject> newCurrentFiles = new HashSet();
111
        Set<FileObject> newCurrentFiles = new HashSet<FileObject>();
95
112
96
        newCurrentFiles.addAll(fileObjectResult.allInstances());
113
        newCurrentFiles.addAll(fileObjectResult.allInstances());
97
114
Lines 107-113 Link Here
107
            }
124
            }
108
        }
125
        }
109
126
110
        currentFiles = new ArrayList<FileObject>(newCurrentFiles);
127
        currentFiles = OpenedEditors.filterSupportedMIMETypes(new LinkedList<FileObject>(newCurrentFiles), supportedMimeTypes);
111
        
128
        
112
        lookupContentChanged();
129
        lookupContentChanged();
113
    }
130
    }
(-)source/src/org/netbeans/api/java/source/support/OpenedEditors.java (-1 / +108 lines)
Lines 21-39 Link Here
21
import java.beans.PropertyChangeEvent;
21
import java.beans.PropertyChangeEvent;
22
import java.beans.PropertyChangeListener;
22
import java.beans.PropertyChangeListener;
23
import java.util.ArrayList;
23
import java.util.ArrayList;
24
import java.util.Arrays;
24
import java.util.Collection;
25
import java.util.Collection;
25
import java.util.Collections;
26
import java.util.Collections;
26
import java.util.HashMap;
27
import java.util.HashMap;
28
import java.util.LinkedList;
27
import java.util.List;
29
import java.util.List;
28
import java.util.Map;
30
import java.util.Map;
31
import java.util.logging.Level;
32
import java.util.logging.Logger;
29
import javax.swing.JEditorPane;
33
import javax.swing.JEditorPane;
30
import javax.swing.event.ChangeEvent;
34
import javax.swing.event.ChangeEvent;
31
import javax.swing.event.ChangeListener;
35
import javax.swing.event.ChangeListener;
32
import javax.swing.text.Document;
36
import javax.swing.text.Document;
33
import javax.swing.text.JTextComponent;
37
import javax.swing.text.JTextComponent;
38
import org.netbeans.api.java.source.JavaSource;
34
import org.netbeans.editor.Registry;
39
import org.netbeans.editor.Registry;
35
import org.openide.filesystems.FileObject;
40
import org.openide.filesystems.FileObject;
41
import org.openide.filesystems.FileUtil;
36
import org.openide.loaders.DataObject;
42
import org.openide.loaders.DataObject;
43
import org.openide.util.Parameters;
37
44
38
/**
45
/**
39
 *
46
 *
Lines 98-104 Link Here
98
105
99
        JTextComponent editor = Registry.getMostActiveComponent();
106
        JTextComponent editor = Registry.getMostActiveComponent();
100
107
101
        if (editor instanceof JEditorPane && "text/x-java".equals(((JEditorPane) editor).getContentType())) {
108
        FileObject fo = editor != null ? getFileObject(editor) : null;
109
        if (editor instanceof JEditorPane && fo != null && JavaSource.forFileObject(fo) != null) {
102
            visibleEditors.add(editor);
110
            visibleEditors.add(editor);
103
        }
111
        }
104
112
Lines 131-134 Link Here
131
        return null;
139
        return null;
132
    }
140
    }
133
141
142
    /**Checks if the given file is supported. See {@link #filterSupportedMIMETypes}
143
     * for more details.
144
     *
145
     * @param file to check
146
     * @param type the type to check for the {@link SupportedMimeTypes} annotation
147
     * @return true if and only if the given file is supported (see {@link #filterSupportedMIMETypes})
148
     * @throws NullPointerException if <code>file == null</code> or <code>type == null</code>
149
     */
150
    public static boolean isSupported(FileObject file, String... mimeTypes) throws NullPointerException {
151
        Parameters.notNull("files", file);
152
        
153
        return !filterSupportedMIMETypes(Collections.singletonList(file), mimeTypes).isEmpty();
154
    }
155
    
156
    /**Filter unsupported files from the <code>files</code> parameter. A supported file
157
     * <code>f</code> is defined as follows:
158
     * <ul>
159
     *     <li><code>JavaSource.forFileObject(f) != null</code></li>
160
     *     <li>If the <code>type</code> is annotated with the {@link SupportedMimeTypes} annotation,
161
     *         the file is supported if <code>type.getAnnotation(SupportedMimeTypes.class).value()</code>
162
     *         contains <code>FileUtil.getMIMEType(f)</code>.
163
     *     </li>
164
     *     <li>If the <code>type</code> is not annotated with the {@link SupportedMimeTypes} annotation,
165
     *         the file is supported if <code>FileUtil.getMIMEType(f) == "text/x-java"</code>.
166
     * </ul>
167
     *
168
     * @param files the list of files to filter
169
     * @param type the type to check for the {@link SupportedMimeTypes} annotation
170
     * @return list of files that are supported (see above).
171
     * @throws NullPointerException if <code>files == null</code> or <code>type == null</code>
172
     */
173
    public static List<FileObject> filterSupportedMIMETypes(Collection<FileObject> files, String... mimeTypes) throws NullPointerException {
174
        Parameters.notNull("files", files);
175
        
176
        boolean            allowJavaExtension = false;
177
        
178
        if (mimeTypes == null) {
179
            mimeTypes = new String[] {"text/x-java"};
180
            allowJavaExtension = true;
181
        }
182
        
183
        List<String>       mimeTypesList = Arrays.asList(mimeTypes);
184
        boolean            allowAll  = mimeTypesList.contains("*");
185
        List<FileObject>   result    = new LinkedList<FileObject>();
186
        
187
        Logger.getLogger(OpenedEditors.class.getName()).log(Level.FINER, "mimeTypesList={0}", mimeTypesList);
188
        
189
        for (FileObject f : files) {
190
            Logger.getLogger(OpenedEditors.class.getName()).log(Level.FINER, "analyzing={0}", f);
191
            
192
            if (JavaSource.forFileObject(f) == null)
193
                continue;
194
            
195
            if (allowAll) {
196
                result.add(f);
197
                continue;
198
            }
199
            
200
            if (allowJavaExtension && "java".equals(f.getExt())) {
201
                result.add(f);
202
                continue;
203
            }
204
            
205
            String fileMimeType = FileUtil.getMIMEType(f);
206
            
207
            Logger.getLogger(OpenedEditors.class.getName()).log(Level.FINER, "fileMimeType={0}", fileMimeType);
208
            
209
            if (mimeTypesList.contains(fileMimeType)) {
210
                result.add(f);
211
                continue;
212
            }
213
            
214
            String shorterMimeType = fileMimeType;
215
            
216
            while (true) {
217
                int slash = shorterMimeType.indexOf('/');
218
                
219
                if (slash == (-1))
220
                    break;
221
                
222
                int plus  = shorterMimeType.indexOf('+', slash);
223
                
224
                if (plus == (-1))
225
                    break;
226
                
227
                shorterMimeType = shorterMimeType.substring(0, slash + 1) + shorterMimeType.substring(plus + 1);
228
                
229
                if (mimeTypesList.contains(shorterMimeType)) {
230
                    result.add(f);
231
                    break;
232
                }
233
            }
234
        }
235
        
236
        Logger.getLogger(OpenedEditors.class.getName()).log(Level.FINE, "filter({0}, {1})={2}", new Object[] {files, mimeTypesList, result});
237
        
238
        return result;
239
    }
240
    
134
}
241
}
(-)source/src/org/netbeans/modules/java/source/JavaSourceAccessor.java (+7 lines)
Lines 21-35 Link Here
21
21
22
import com.sun.tools.javac.api.JavacTaskImpl;
22
import com.sun.tools.javac.api.JavacTaskImpl;
23
import java.io.IOException;
23
import java.io.IOException;
24
import java.util.Collection;
25
import javax.swing.text.JTextComponent;
24
import javax.tools.DiagnosticListener;
26
import javax.tools.DiagnosticListener;
25
import javax.tools.JavaFileObject;
27
import javax.tools.JavaFileObject;
26
import org.netbeans.api.java.source.CancellableTask;
28
import org.netbeans.api.java.source.CancellableTask;
27
import org.netbeans.api.java.source.ClasspathInfo;
29
import org.netbeans.api.java.source.ClasspathInfo;
28
import org.netbeans.api.java.source.CompilationInfo;
30
import org.netbeans.api.java.source.CompilationInfo;
29
import org.netbeans.api.java.source.JavaSource;
31
import org.netbeans.api.java.source.JavaSource;
32
import org.netbeans.api.java.source.PositionConverter;
30
import org.netbeans.api.java.source.WorkingCopy;
33
import org.netbeans.api.java.source.WorkingCopy;
31
import org.netbeans.modules.java.source.builder.DefaultEnvironment;
34
import org.netbeans.modules.java.source.builder.DefaultEnvironment;
32
import org.openide.ErrorManager;
35
import org.openide.ErrorManager;
36
import org.openide.filesystems.FileObject;
33
37
34
/**
38
/**
35
 *
39
 *
Lines 85-90 Link Here
85
    
89
    
86
    public abstract void revalidate(JavaSource js); 
90
    public abstract void revalidate(JavaSource js); 
87
    
91
    
92
    public abstract JavaSource create(final ClasspathInfo cpInfo, final PositionConverter binding, final Collection<? extends FileObject> files) throws IllegalArgumentException;
93
    
94
    public abstract PositionConverter create(final FileObject fo, int offset, int length, final JTextComponent component);
88
    
95
    
89
    /**
96
    /**
90
     * Returns true when the caller is a {@link JavaSource} worker thread
97
     * Returns true when the caller is a {@link JavaSource} worker thread
(-)source/src/org/netbeans/modules/java/source/parsing/SourceFileObject.java (-2 / +6 lines)
Lines 366-374 Link Here
366
            doc.render(new Runnable() {
366
            doc.render(new Runnable() {
367
                public void run () {
367
                public void run () {
368
                  try {
368
                  try {
369
			int len = doc.getLength();
369
			CharSequence text = doc.getText(0, doc.getLength());
370
                        if (filter != null) {
371
                            text = filter.filterCharSequence(text);
372
                        }
373
                        int len = text.length();
370
			result[0] = new char[len+1];
374
			result[0] = new char[len+1];
371
			doc.getText(0,len).getChars(0,len,result[0],0);
375
			text.toString().getChars(0,len,result[0],0);
372
                        length[0] = len;
376
                        length[0] = len;
373
                    } catch (BadLocationException e) {
377
                    } catch (BadLocationException e) {
374
                        ErrorManager.getDefault().notify(e);
378
                        ErrorManager.getDefault().notify(e);
(-)source/test/unit/src/org/netbeans/api/java/source/JavaSourceTest.java (-2 / +2 lines)
Lines 1119-1125 Link Here
1119
        
1119
        
1120
        js.runUserActionTask(new CancellableTask<CompilationController>() {
1120
        js.runUserActionTask(new CancellableTask<CompilationController>() {
1121
            public void run(CompilationController cc) throws IOException {
1121
            public void run(CompilationController cc) throws IOException {
1122
                files.add(cc.getFileObject());
1122
                files.add(cc.getPositionConverter().getFileObject());
1123
                cc.toPhase(Phase.RESOLVED);
1123
                cc.toPhase(Phase.RESOLVED);
1124
            }
1124
            }
1125
            public void cancel() {}
1125
            public void cancel() {}
Lines 1131-1137 Link Here
1131
        
1131
        
1132
        js.runModificationTask(new CancellableTask<WorkingCopy>() {
1132
        js.runModificationTask(new CancellableTask<WorkingCopy>() {
1133
            public void run(WorkingCopy cc) throws IOException {
1133
            public void run(WorkingCopy cc) throws IOException {
1134
                files.add(cc.getFileObject());
1134
                files.add(cc.getPositionConverter().getFileObject());
1135
                cc.toPhase(Phase.RESOLVED);
1135
                cc.toPhase(Phase.RESOLVED);
1136
            }
1136
            }
1137
            public void cancel() {}
1137
            public void cancel() {}
(-)source/test/unit/src/org/netbeans/api/java/source/SourceUtilsTest.java (+101 lines)
Lines 21-26 Link Here
21
21
22
import java.io.File;
22
import java.io.File;
23
import java.io.IOException;
23
import java.io.IOException;
24
import java.io.Reader;
25
import java.io.Writer;
24
import java.net.URL;
26
import java.net.URL;
25
import java.util.Arrays;
27
import java.util.Arrays;
26
import java.util.HashMap;
28
import java.util.HashMap;
Lines 39-45 Link Here
39
import org.netbeans.api.java.queries.SourceForBinaryQuery.Result;
41
import org.netbeans.api.java.queries.SourceForBinaryQuery.Result;
40
import org.netbeans.api.java.source.ClasspathInfo;
42
import org.netbeans.api.java.source.ClasspathInfo;
41
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
43
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
44
import org.netbeans.api.java.source.JavaSource.Phase;
45
import org.netbeans.junit.MockServices;
42
import org.netbeans.junit.NbTestCase;
46
import org.netbeans.junit.NbTestCase;
47
import org.netbeans.modules.java.preprocessorbridge.spi.JavaSourceProvider;
43
import org.netbeans.modules.java.source.ElementHandleAccessor;
48
import org.netbeans.modules.java.source.ElementHandleAccessor;
44
import org.netbeans.modules.java.source.TestUtil;
49
import org.netbeans.modules.java.source.TestUtil;
45
import org.netbeans.modules.java.source.usages.ClasspathInfoAccessor;
50
import org.netbeans.modules.java.source.usages.ClasspathInfoAccessor;
Lines 48-53 Link Here
48
import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation;
53
import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation;
49
import org.openide.filesystems.FileObject;
54
import org.openide.filesystems.FileObject;
50
import org.openide.filesystems.FileUtil;
55
import org.openide.filesystems.FileUtil;
56
import org.openide.filesystems.MIMEResolver;
57
import org.openide.util.Lookup;
51
58
52
/**
59
/**
53
 *
60
 *
Lines 422-425 Link Here
422
        }
429
        }
423
    }
430
    }
424
    
431
    
432
//    //tests for SourceUtils.filterSupportedMIMETypes:
433
//
434
//    @SuppressWarnings("deprecation")
435
//    public void testFilter() throws Exception {
436
//        SourceUtilsTestUtil.setLookup(new Object[] {new JavaSourceProviderImpl(), new ResolverImpl()}, SourceUtilsTest.class.getClassLoader());
437
//        boolean registered = false;
438
//        
439
//        for (JavaSourceProvider p : Lookup.getDefault().lookupAll(JavaSourceProvider.class)) {
440
//            if (p instanceof JavaSourceProvider) {
441
//                registered = true;
442
//                break;
443
//            }
444
//        }
445
//        
446
//        assertTrue(registered);
447
//        
448
//        FileObject work = FileUtil.toFileObject(getWorkDir());
449
//        
450
//        FileObject file1 = FileUtil.createData(work, "test.ext1");
451
//        FileObject file2 = FileUtil.createData(work, "test.ext2");
452
//        FileObject file3 = FileUtil.createData(work, "test.ext3");
453
//        FileObject file4 = FileUtil.createData(work, "test.ext4");
454
//        FileObject file5 = FileUtil.createData(work, "test.txt");
455
//        FileObject file6 = FileUtil.createData(work, "test.ant");
456
//
457
//        assertEquals("text/x-java", FileUtil.getMIMEType(file1));
458
//        assertEquals("text/jsp", FileUtil.getMIMEType(file2));
459
//        assertEquals("text/plain", FileUtil.getMIMEType(file3));
460
//        assertEquals("text/test+x-java", FileUtil.getMIMEType(file4));
461
//        assertEquals("text/test+x-ant+xml", FileUtil.getMIMEType(file6));
462
//        
463
//        List<FileObject> files = Arrays.asList(file1, file2, file3, file4, file5, file6);
464
//        
465
//        assertEquals(Arrays.asList(file1, file2, file3, file4, file6), SourceUtils.filterSupportedMIMETypes(files, F1.class));
466
//        assertEquals(Arrays.asList(file1, file4), SourceUtils.filterSupportedMIMETypes(files, F2.class));
467
//        assertEquals(Arrays.asList(file4), SourceUtils.filterSupportedMIMETypes(files, F3.class));
468
//        assertEquals(Arrays.asList(file1, file4), SourceUtils.filterSupportedMIMETypes(files, F4.class));
469
//        assertEquals(Arrays.asList(file1, file2, file4), SourceUtils.filterSupportedMIMETypes(files, F5.class));
470
//    }
471
//    
472
//    public static class JavaSourceProviderImpl implements JavaSourceProvider {
473
//        public PositionTranslatingJavaFileFilterImplementation forFileObject(FileObject fo) {
474
//            if ("txt".equals(fo.getExt()))
475
//                return null;
476
//            
477
//            return new PositionTranslatingJavaFileFilterImplementation() {
478
//                public int getOriginalPosition(int javaSourcePosition) {
479
//                    return javaSourcePosition;
480
//                }
481
//                public int getJavaSourcePosition(int originalPosition) {
482
//                    return originalPosition;
483
//                }
484
//                public Reader filterReader(Reader r) {
485
//                    return r;
486
//                }
487
//                public CharSequence filterCharSequence(CharSequence charSequence) {
488
//                    return charSequence;
489
//                }
490
//                public Writer filterWriter(Writer w) {
491
//                    return w;
492
//                }
493
//                public void addChangeListener(ChangeListener listener) {}
494
//                public void removeChangeListener(ChangeListener listener) {}
495
//            };
496
//        }
497
//    }
498
//    
499
//    public static class ResolverImpl extends MIMEResolver {
500
//        public String findMIMEType(FileObject fo) {
501
//            String ext = fo.getExt();
502
//            
503
//            if ("ext1".contains(ext)) return "text/x-java";
504
//            if ("ext2".contains(ext)) return "text/jsp";
505
//            if ("ext3".contains(ext)) return "text/plain";
506
//            if ("ext4".contains(ext)) return "text/test+x-java";
507
//            if ("ant".contains(ext)) return "text/test+x-ant+xml";
508
//            
509
//            return null;
510
//        }
511
//    }
512
//    
513
//    @SupportedMimeTypes("*")
514
//    private static class F1 {}
515
//    
516
//    @SupportedMimeTypes("text/x-java")
517
//    private static class F2 {}
518
//    
519
//    @SupportedMimeTypes("text/test+x-java")
520
//    private static class F3 {}
521
//    
522
//    private static class F4 {}
523
//    
524
//    @SupportedMimeTypes({"text/x-java", "text/jsp"})
525
//    private static class F5 {}
425
}
526
}
(-)sourceui/nbproject/project.xml (-12 / +30 lines)
Lines 6-11 Link Here
6
            <code-name-base>org.netbeans.modules.java.sourceui</code-name-base>
6
            <code-name-base>org.netbeans.modules.java.sourceui</code-name-base>
7
            <module-dependencies>
7
            <module-dependencies>
8
                <dependency>
8
                <dependency>
9
                    <code-name-base>org.netbeans.api.java</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <release-version>1</release-version>
14
                        <specification-version>1.13</specification-version>
15
                    </run-dependency>
16
                </dependency>
17
                <dependency>
9
                    <code-name-base>org.netbeans.libs.javacapi</code-name-base>
18
                    <code-name-base>org.netbeans.libs.javacapi</code-name-base>
10
                    <build-prerequisite/>
19
                    <build-prerequisite/>
11
                    <compile-dependency/>
20
                    <compile-dependency/>
Lines 14-19 Link Here
14
                    </run-dependency>
23
                    </run-dependency>
15
                </dependency>
24
                </dependency>
16
                <dependency>
25
                <dependency>
26
                    <code-name-base>org.netbeans.modules.java.lexer</code-name-base>
27
                    <build-prerequisite/>
28
                    <compile-dependency/>
29
                    <run-dependency>
30
                        <release-version>1</release-version>
31
                        <specification-version>1.2</specification-version>
32
                    </run-dependency>
33
                </dependency>
34
                <dependency>
17
                    <code-name-base>org.netbeans.modules.java.source</code-name-base>
35
                    <code-name-base>org.netbeans.modules.java.source</code-name-base>
18
                    <build-prerequisite/>
36
                    <build-prerequisite/>
19
                    <compile-dependency/>
37
                    <compile-dependency/>
Lines 22-37 Link Here
22
                    </run-dependency>
40
                    </run-dependency>
23
                </dependency>
41
                </dependency>
24
                <dependency>
42
                <dependency>
25
                    <code-name-base>org.netbeans.modules.projectapi</code-name-base>
43
                    <code-name-base>org.netbeans.modules.jumpto</code-name-base>
26
                    <build-prerequisite/>
44
                    <build-prerequisite/>
27
                    <compile-dependency/>
45
                    <compile-dependency/>
28
                    <run-dependency>
46
                    <run-dependency>
29
                        <release-version>1</release-version>
47
                        <release-version>1</release-version>
30
                        <specification-version>1.13</specification-version>
48
                        <specification-version>1.2</specification-version>
31
                    </run-dependency>
49
                    </run-dependency>
32
                </dependency>
50
                </dependency>
33
                <dependency>
51
                <dependency>
34
                    <code-name-base>org.netbeans.api.java</code-name-base>
52
                    <code-name-base>org.netbeans.modules.lexer</code-name-base>
53
                    <build-prerequisite/>
54
                    <compile-dependency/>
55
                    <run-dependency>
56
                        <release-version>2</release-version>
57
                        <specification-version>1.20</specification-version>
58
                    </run-dependency>
59
                </dependency>
60
                <dependency>
61
                    <code-name-base>org.netbeans.modules.projectapi</code-name-base>
35
                    <build-prerequisite/>
62
                    <build-prerequisite/>
36
                    <compile-dependency/>
63
                    <compile-dependency/>
37
                    <run-dependency>
64
                    <run-dependency>
Lines 77-91 Link Here
77
                    <compile-dependency/>
104
                    <compile-dependency/>
78
                    <run-dependency>
105
                    <run-dependency>
79
                        <specification-version>7.9</specification-version>
106
                        <specification-version>7.9</specification-version>
80
                    </run-dependency>
81
                </dependency>
82
                <dependency>
83
                    <code-name-base>org.netbeans.modules.jumpto</code-name-base>
84
                    <build-prerequisite/>
85
                    <compile-dependency/>
86
                    <run-dependency>
87
                        <release-version>1</release-version>
88
                        <specification-version>1.2</specification-version>
89
                    </run-dependency>
107
                    </run-dependency>
90
                </dependency>
108
                </dependency>
91
            </module-dependencies>
109
            </module-dependencies>
(-)sourceui/src/org/netbeans/api/java/source/ui/DialogBinding.java (+76 lines)
Added Link Here
1
/*
2
 * The contents of this file are subject to the terms of the Common Development
3
 * and Distribution License (the License). You may not use this file except in
4
 * compliance with the License.
5
 * 
6
 * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7
 * or http://www.netbeans.org/cddl.txt.
8
 * 
9
 * When distributing Covered Code, include this CDDL Header Notice in each file
10
 * and include the License file at http://www.netbeans.org/cddl.txt.
11
 * If applicable, add the following below the CDDL Header, with the fields
12
 * enclosed by brackets [] replaced by your own identifying information:
13
 * "Portions Copyrighted [year] [name of copyright owner]"
14
 * 
15
 * Portions Copyrighted 2007 Sun Microsystems, Inc.
16
 */
17
package org.netbeans.api.java.source.ui;
18
19
import java.util.Collections;
20
import javax.swing.text.Document;
21
import javax.swing.text.JTextComponent;
22
import org.netbeans.api.java.lexer.JavaTokenId;
23
import org.netbeans.api.java.source.ClasspathInfo;
24
import org.netbeans.api.java.source.JavaSource;
25
import org.netbeans.api.java.source.PositionConverter;
26
import org.netbeans.api.lexer.Language;
27
import org.netbeans.modules.java.source.JavaSourceAccessor;
28
import org.openide.filesystems.FileObject;
29
import org.openide.filesystems.FileUtil;
30
31
/**
32
 *
33
 * @author Dusan Balek, Jan Lahoda
34
 */
35
public final class DialogBinding {
36
37
    private DialogBinding() {}
38
    
39
    /**
40
     * Bind given component and given file together.
41
     * @param fileObject to bind
42
     * @param offset position at which content of the component will be virtually placed
43
     * @param length how many characters replace from the original file
44
     * @param component component to bind
45
     * @return {@link JavaSource} or null
46
     * @throws {@link IllegalArgumentException} if fileObject is null
47
     */
48
    public static JavaSource bindComponentToFile(FileObject fileObject, int offset, int length, JTextComponent component) throws IllegalArgumentException {
49
        if (fileObject == null) {
50
            throw new IllegalArgumentException ("fileObject == null");  //NOI18N
51
        }
52
        if (!fileObject.isValid()) {
53
            return null;
54
        }
55
        if (!"text/x-java".equals(FileUtil.getMIMEType(fileObject)) && !"java".equals(fileObject.getExt())) {  //NOI18N
56
            //TODO: JavaSource cannot be created for all kinds of files, but text/x-java is too restrictive:
57
            return null;
58
        }
59
        Document doc = component.getDocument();
60
        
61
        if (doc.getProperty(JavaSource.class) != null) {
62
            throw new IllegalArgumentException("A JavaSource is already attached to the given component.");
63
        }
64
        
65
        JavaSource js = JavaSourceAccessor.INSTANCE.create(ClasspathInfo.create(fileObject), JavaSourceAccessor.INSTANCE.create(fileObject, offset, length, component), Collections.singletonList(fileObject));
66
        
67
        doc.putProperty(JavaSource.class, js);
68
        
69
        if (doc.getProperty(Language.class) == null) {
70
            doc.putProperty(Language.class, JavaTokenId.language());
71
        }
72
        
73
        return js;
74
    }
75
76
}

Return to bug 106629