Java源码示例:org.netbeans.spi.editor.hints.HintsController

示例1
public void run(CompilationInfo info) {
    cancel.set(false);

    FileObject file = info.getFileObject();
    int[] selection = SelectionAwareJavaSourceTaskFactory.getLastSelection(file);

    if (selection == null) {
        //nothing to do....
        HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), Collections.<ErrorDescription>emptyList());
    } else {
        HintsController.setErrors(info.getFileObject(), IntroduceHint.class.getName(), computeError(info, selection[0], selection[1], null, new EnumMap<IntroduceKind, String>(IntroduceKind.class), cancel));

        Document doc = info.getSnapshot().getSource().getDocument(false);

        if (doc != null) {
            PositionRefresherHelperImpl.setVersion(doc, selection[0], selection[1]);
        }
    }
}
 
示例2
static final void refreshHints(ResultIterator controller) {
    List<ErrorDescription>[] allHints = new ArrayList[3];
    collectHints(controller, allHints, controller.getSnapshot());
    FileObject f = controller.getSnapshot().getSource().getFileObject();
    if (f != null) {
        if (allHints[0] != null) {
            HintsController.setErrors(f, HintsTask.class.getName(), allHints[0]);
        }
        if (allHints[1] != null) {
            HintsController.setErrors(f, SuggestionsTask.class.getName(), allHints[1]);
        }
        if (allHints[2] != null) {
            HintsController.setErrors(f, GsfHintsFactory.LAYER_NAME, allHints[2]);
        }
    } else {
        LOG.warning("Source " + controller.getSnapshot().getSource() + " returns null from getFileObject()"); // NOI18N
    }
}
 
示例3
@Override
public void publishDiagnostics(PublishDiagnosticsParams pdp) {
    try {
        FileObject file = URLMapper.findFileObject(new URI(pdp.getUri()).toURL());
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        Document doc = ec != null ? ec.getDocument() : null;
        if (doc == null)
            return ; //ignore...
        List<ErrorDescription> diags = pdp.getDiagnostics().stream().map(d -> {
            LazyFixList fixList = allowCodeActions ? new DiagnosticFixList(pdp.getUri(), d) : ErrorDescriptionFactory.lazyListForFixes(Collections.emptyList());
            return ErrorDescriptionFactory.createErrorDescription(severityMap.get(d.getSeverity()), d.getMessage(), fixList, file, Utils.getOffset(doc, d.getRange().getStart()), Utils.getOffset(doc, d.getRange().getEnd()));
        }).collect(Collectors.toList());
        HintsController.setErrors(doc, LanguageClientImpl.class.getName(), diags);
    } catch (URISyntaxException | MalformedURLException ex) {
        LOG.log(Level.FINE, null, ex);
    }
}
 
示例4
@Override
public void run(CfgPropsParser.CfgPropsParserResult cfgResult, SchedulerEvent se) {
    canceled = false;
    final Preferences prefs = NbPreferences.forModule(PrefConstants.class);
    final int sevLevel = prefs.getInt(getHighlightPrefName(), getHighlightDefaultValue());
    List<ErrorDescription> errors = new ArrayList<>();
    final BaseDocument document = (BaseDocument) cfgResult.getSnapshot().getSource().getDocument(false);
    if (document != null) {
        // skip error calculation if preference set to "None"
        if (sevLevel > 0) {
            Severity severity = decodeSeverity(sevLevel);
            document.readLock();
            internalRun(cfgResult, se, document, errors, severity);
            document.readUnlock();
        }
        HintsController.setErrors(document, getErrorLayerName(), errors);
    }
}
 
示例5
@Override
public void run(ECParserResult result, SchedulerEvent event) {
  List<SyntaxError> syntaxErrors = result.getErrors();
  Document document = result.getSnapshot().getSource().getDocument(false);
  List<ErrorDescription> errors = new ArrayList<>();
  for (SyntaxError syntaxError : syntaxErrors) {
    String message = syntaxError.getMessage();
    int line = syntaxError.getLine();
    if (line <= 0) {
      continue;
    }
    ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription(
            Severity.ERROR,
            message,
            document,
            line);
    errors.add(errorDescription);
  }
  HintsController.setErrors(document, EDITORCONFIG, errors); // NOI18N
}
 
示例6
@Override
public void run(final Result result, SchedulerEvent event) {
    final DeclarativeHintsParser.Result res = ParserImpl.getResult(result);
    final List<ErrorDescription> errors;

    if (res != null) {
        errors = computeErrors(res, result.getSnapshot().getText(), result.getSnapshot().getSource().getFileObject());
    } else {
        errors = Collections.emptyList();
    }

    HintsController.setErrors(result.getSnapshot().getSource().getFileObject(),
                              HintsTask.class.getName(),
                              errors);
}
 
示例7
public static void setAnnotations(Snapshot snap, List<ErrorDescription> descs) {
    if (snap.getMimePath().size() == 1) {
        Document doc = snap.getSource().getDocument(false);
        if (doc == null) {
            // the document may have disappeared before errors were computed.
            return;
        }
        HintsController.setErrors(doc, "java-hints", descs);
        return;
    }
    
    synchronized (hints) {
        hints.put(snap, descs);
    }
}
 
示例8
@Override
public void run(Parser.Result result, SchedulerEvent event) {
    cancelled = false;
    final Snapshot mySnapshot = result.getSnapshot();
    if (mySnapshot.getMimePath().size() > 1) {
        // I do not want the inner mimetype
        return;
    }
    if (mySnapshot.getMimeType().equals("text/x-java")) {
        // ignore toplevel java
        return;
    }
    try {
        synchronized (hints) {
            for (Snapshot snap : hints.keySet()) {
                if (snap.getSource().equals(mySnapshot.getSource())) {
                    collectResult(snap);
                }
            }
        }
        if (cancelled) {
            return;
        }
        if (allHints != null) {
            HintsController.setErrors(result.getSnapshot().getSource().getDocument(false), "java-hints", allHints);
        }
    } finally {
        synchronized (hints) {
            hints.clear();
            allHints = null;
        }
    }
}
 
示例9
@Override
public void run( CompilationInfo compilationInfo ) throws Exception {
    FileObject fileObject = compilationInfo.getFileObject();
    
    if( !isApplicable(fileObject)){
        return;
    }
    
    AsyncHintsTask task = new AsyncHintsTask(compilationInfo);
    runTask.set(task);
    task.run();
    runTask.compareAndSet(task, null);
    HintsController.setErrors(fileObject, "REST Async Converter",         // NOI18N 
            task.getDescriptions()); 
}
 
示例10
@Override
public void run( CompilationInfo info ) throws Exception {
    RestScanTask scanTask = new RestScanTask(factory, fileObject, info );
    task.set(scanTask);
    scanTask.run();
    task.compareAndSet(scanTask, null);
    HintsController.setErrors(fileObject, "REST Configuration",         // NOI18N 
            scanTask.getHints()); 
}
 
示例11
@Override
public void run(CompilationInfo compilationInfo) throws Exception {
    FileObject fileObject = compilationInfo.getFileObject();

    if (!isApplicable(fileObject)) {
        return;
    }

    WebSocketTask task = new WebSocketTask(compilationInfo);
    runTask.set(task);
    task.run();
    runTask.compareAndSet(task, null);
    HintsController.setErrors(fileObject, "WebSocket Methods Scanner", // NOI18N
            task.getDescriptions());
}
 
示例12
public void run(final CompilationInfo info) throws Exception{
    synchronized(singleInstanceLock){
        if (runningInstance != null){
            runningInstance.cancel();
        }
        runningInstance = this;
        // the 'cancelled' flag must be reset as the instance of WebServicesHintsProvider is reused
        cancelled = false;
        problemsFound.clear();
        for (Tree tree : info.getCompilationUnit().getTypeDecls()){
            if (isCancelled()){
                break;
            }
            
            if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())){
                TreePath path = info.getTrees().getPath(info.getCompilationUnit(), tree);
                TypeElement javaClass = (TypeElement) info.getTrees().getElement(path);
                if (javaClass != null) {
                    initServiceMetadata(javaClass);
                    createProblemContext(info, javaClass);

                    RulesEngine rulesEngine = new WebServicesRulesEngine();
                    javaClass.accept(rulesEngine, context);
                    problemsFound.addAll(rulesEngine.getProblemsFound());

                    synchronized(cancellationLock){
                        context = null;
                    }
                }
            }
        }
        
        //TODO: should we really reset the errors if the task is cancelled?
        HintsController.setErrors(file, "WebService Verification", problemsFound); //NOI18N
        runningInstance = null;
    }
}
 
示例13
@Override
public void run( CompilationInfo compInfo ) throws Exception {
    if ( !WebBeansActionHelper.isEnabled() ){
        return;
    }
    AbstractAnalysisTask task = createTask();
    myTask.set( task );
    task.run( compInfo );
    myTask.compareAndSet( task, null);
    HintsController.setErrors(myFileObject, getLayerName(), task.getProblems()); 
}
 
示例14
@Override
public void run(FxmlParserResult result, SchedulerEvent event) {
    Collection<ErrorMark> marks = result.getProblems();
    
    document = result.getSnapshot().getSource().getDocument(false);
    if (document == null) {
        // no op
        return;
    }
    List<ErrorDescription> descs = new ArrayList<ErrorDescription>();
    for (ErrorMark m : marks) {
        try {
            descs.add(ErrorDescriptionFactory.createErrorDescription(
                    m.isError() ? Severity.ERROR : Severity.WARNING,
                    m.getMessage(),
                    document, 
                    NbDocument.createPosition(document, 
                        m.getOffset(), Position.Bias.Forward),
                    NbDocument.createPosition(document, 
                        m.getOffset() + m.getLen(), Position.Bias.Forward))
                );
        } catch (BadLocationException ex) {
            // ignore
        }
    }
    HintsController.setErrors(document, "fxml-parsing", descs);
}
 
示例15
@Override
public final void refreshHints(RuleContext context) {
    List<ErrorDescription>[] result = new List[3];
    getHints(this, context, result, context.parserResult.getSnapshot());
    FileObject f = context.parserResult.getSnapshot().getSource().getFileObject();
    if (result[0] != null) {
        HintsController.setErrors(f, HintsTask.class.getName(), result[0]);
    }
    if (result[1] != null) {
        HintsController.setErrors(f, SuggestionsTask.class.getName(), result[1]);
    }
    if (result[2] != null) {
        HintsController.setErrors(f, GsfHintsFactory.LAYER_NAME, result[2]);
    }
}
 
示例16
private void showSurroundWithHint() {
    try {
        final Caret caret = component.getCaret();
        if (caret != null) {
            final Position pos = doc.createPosition(caret.getDot());
            RP.post(new Runnable() {
                public void run() {
                    final List<Fix> fixes = SurroundWithFix.getFixes(component);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            if (!fixes.isEmpty()) {
                                errorDescription = ErrorDescriptionFactory.createErrorDescription(
                                        Severity.HINT, SURROUND_WITH, surrounsWithFixes = fixes, doc, pos, pos);

                                HintsController.setErrors(doc, SURROUND_WITH, Collections.singleton(errorDescription));
                            } else {
                                hideSurroundWithHint();
                            }
                        }
                    });
                }
            });
        }
    } catch (BadLocationException ble) {
        Logger.getLogger("global").log(Level.WARNING, ble.getMessage(), ble);
    }
}
 
示例17
private void hideSurroundWithHint() {
    if (surrounsWithFixes != null)
        surrounsWithFixes = null;
    if (errorDescription != null) {
        errorDescription = null;
        HintsController.setErrors(doc, SURROUND_WITH, Collections.<ErrorDescription>emptySet());
    }
}
 
示例18
public void run(CompilationInfo info) {
    cancel.set(false);

    if (org.netbeans.modules.java.hints.spiimpl.Utilities.disableErrors(info.getFileObject()).contains(Severity.VERIFIER)) {
        return;
    }

    Document doc = info.getSnapshot().getSource().getDocument(false);
    FileObject f = info.getSnapshot().getSource().getFileObject();
    if (f != null) {
        // hints use TreePathHandles to persist info for fixes, whcih in turn assume CloneableEditorSupport is
        // available on the document's DataObject. Since the document is opened, it would have to be opened through
        // the editor/open cookie, so there should not be a performance penalty in asking for them:
        PositionRefProvider prp;
        try {
            prp = PositionRefProvider.get(f);
            if (prp == null) {
                return;
            }
            prp.createPosition(0, Position.Bias.Forward);
        } catch (IOException | IllegalArgumentException ex) {
            // the position provider is not working properly; bail out. Hints would fail
            // unexpectedly on creating TPHs, trying to open or save files etc.
            return;
        }
    }
    long version = doc != null ? DocumentUtilities.getDocumentVersion(doc) : 0;
    long startTime = System.currentTimeMillis();

    int caret = CaretAwareJavaSourceTaskFactory.getLastPosition(info.getFileObject());
    HintsSettings settings = HintsSettings.getSettingsFor(info.getFileObject());
    HintsInvoker inv = caretAware ? new HintsInvoker(settings, caret, cancel) : new HintsInvoker(settings, cancel);
    List<ErrorDescription> result = inv.computeHints(info);

    if (result == null || cancel.get()) {
        return;
    }

    HintsController.setErrors(info.getFileObject(), caretAware ? KEY_SUGGESTIONS : KEY_HINTS, result);

    if (caretAware) {
        SuggestionsPositionRefresherHelper.setVersion(doc, caret);
    } else {
        HintPositionRefresherHelper.setVersion(doc);
    }

    long endTime = System.currentTimeMillis();
    
    TIMER.log(Level.FINE, "Jackpot 3.0 Hints Task" + (caretAware ? " - Caret Aware" : ""), new Object[] {info.getFileObject(), endTime - startTime});

    Logger l = caretAware ? TIMER_CARET : TIMER_EDITOR;

    for (Entry<String, Long> e : inv.getTimeLog().entrySet()) {
        l.log(Level.FINE, e.getKey(), new Object[] {info.getFileObject(), e.getValue()});
    }
}
 
示例19
private void checkHints() {
    if (model == null) {
        return;
    }
    HintsController.setErrors(document, LAYER_POM, findHints(model, project, -1, -1, -1));
}
 
示例20
@Override
public UpToDateStatus getUpToDate() {
    if (model == null) {
        return UpToDateStatus.UP_TO_DATE_OK;
    }
    FileObject fo = NbEditorUtilities.getFileObject(document);
    boolean ok = false;
    try {
        if (fo.isValid()) {
            DataObject dobj = DataObject.find(fo);
            EditorCookie ed = dobj.getLookup().lookup(EditorCookie.class);
            if (ed != null) {
                JEditorPane[] panes = ed.getOpenedPanes();
                if (panes != null && panes.length > 0) {
                    //#214527
                    JEditorPane pane = panes[0];
                    if (panes.length > 1) {
                        for (JEditorPane p : panes) {
                            if (p.isFocusOwner()) {
                                pane = p;
                                break;
                            }
                        }
                    }
                    //TODO this code is called very often apparently.
                    //we should only run the checks if something changed..
                    //something means file + selection start + selection end.
                    final int selectionStart = pane.getSelectionStart();
                    final int selectionEnd = pane.getSelectionEnd();
                    final int caretPosition = pane.getCaretPosition();
                    RP.post(new Runnable() {
                        @Override
                        public void run() {
                            refreshLinkAnnotations(document, model, selectionStart, selectionEnd);
                        }
                    });
                    if (selectionStart != selectionEnd) { //maybe we want to remove the condition?
                        RP.post(new Runnable() {
                            @Override public void run() {
                                //this condition is important in order not to break any running hints
                                //the model sync+refresh renders any existing POMComponents people
                                // might be holding useless
                                if (!model.isIntransaction()) {
                                    HintsController.setErrors(document, LAYER_POM_SELECTION, findHints(model, project, selectionStart, selectionEnd, caretPosition));
                                } else {
                                    HintsController.setErrors(document, LAYER_POM_SELECTION, Collections.<ErrorDescription>emptyList());
                                }
                                
                            }
                        });
                        ok = true;
                        return UpToDateStatus.UP_TO_DATE_PROCESSING;
                    }
                }
            }
        }
    } catch (DataObjectNotFoundException ex) {
        //#166011 just a minor issue, just log, but don't show to user directly
        LOG.log(Level.INFO, "Touched somehow invalidated FileObject", ex);
    } finally {
        if (!ok) {
            HintsController.setErrors(document, LAYER_POM_SELECTION, Collections.<ErrorDescription>emptyList());
        }
    }
    return UpToDateStatus.UP_TO_DATE_OK; // XXX should use UP_TO_DATE_PROCESSING if checkHints task is currently running
}
 
示例21
private void cancelAll() {
    HintsController.setErrors(doc, LayerHints.class.getName(), Collections.<ErrorDescription>emptyList());
    processed = true;
    firePropertyChange(PROP_UP_TO_DATE, null, null);
}
 
示例22
@Override
public void warningOpened(ErrorDescription warning) {
    HintsController.setErrors(warning.getFile(), "phpStanWarning", Collections.singleton(warning)); // NOI18N
}
 
示例23
@Override
public void warningOpened(ErrorDescription warning) {
    HintsController.setErrors(warning.getFile(), "phpMessDetectorWarning", Collections.singleton(warning)); // NOI18N
}
 
示例24
@Override
public void warningOpened(ErrorDescription warning) {
    HintsController.setErrors(warning.getFile(), "phpCodeSnifferWarning", Collections.singleton(warning)); // NOI18N
}
 
示例25
public @Override void run(ParserResult result, SchedulerEvent event) {

        final FileObject fileObject = result.getSnapshot().getSource().getFileObject();
        if (fileObject == null || cancel.isCancelled()) {
            return;
        }

        if (!(event instanceof CursorMovedSchedulerEvent) || cancel.isCancelled()) {
            return;
        }

        SpiSupportAccessor.getInstance().setCancelSupport(cancel);
        try {
            // Do we have a selection? If so, don't do suggestions
            CursorMovedSchedulerEvent evt = (CursorMovedSchedulerEvent) event;
            final int[] range = new int [] {
                Math.min(evt.getMarkOffset(), evt.getCaretOffset()),
                Math.max(evt.getMarkOffset(), evt.getCaretOffset())
            };
            if (range == null || range.length != 2 || range[0] == -1 || range[1] == -1 || range[0] == range[1]) {
                HintsController.setErrors(fileObject, SelectionHintsTask.class.getName(), Collections.<ErrorDescription>emptyList());
                return;
            }

            try {
                ParserManager.parse(Collections.singleton(result.getSnapshot().getSource()), new UserTask() {
                    public @Override void run(ResultIterator resultIterator) throws Exception {
                        Parser.Result r = resultIterator.getParserResult(range[0]);
                        if(!(r instanceof ParserResult)) {
                            return ;
                        }
                        Language language = LanguageRegistry.getInstance().getLanguageByMimeType(r.getSnapshot().getMimeType());
                        if (language == null || cancel.isCancelled()) {
                            return;
                        }

                        HintsProvider provider = language.getHintsProvider();
                        if (provider == null || cancel.isCancelled()) {
                            return;
                        }

                        GsfHintsManager manager = language.getHintsManager();
                        if (manager == null || cancel.isCancelled()) {
                            return;
                        }

                        List<ErrorDescription> description = new ArrayList<ErrorDescription>();
                        List<Hint> hints = new ArrayList<Hint>();

                        RuleContext ruleContext = manager.createRuleContext((ParserResult) r, language, -1, range[0], range[1]);
                        if (ruleContext != null) {
                            try {
                                synchronized (this) {
                                    pendingProvider = provider;
                                    if (cancel.isCancelled()) {
                                        return;
                                    }
                                }
                                provider.computeSelectionHints(manager, ruleContext, hints, range[0], range[1]);
                            } finally {
                                pendingProvider = null;
                            }

                            for (int i = 0; i < hints.size(); i++) {
                                Hint hint= hints.get(i);

                                if (cancel.isCancelled()) {
                                    return;
                                }

                                ErrorDescription desc = manager.createDescription(hint, ruleContext, false, i == hints.size()-1);
                                description.add(desc);
                            }
                        }

                        if (cancel.isCancelled()) {
                            return;
                        }

                        HintsController.setErrors(fileObject, SelectionHintsTask.class.getName(), description);
                    }
                });
            } catch (ParseException e) {
                LOG.log(Level.WARNING, null, e);
            }
        } finally {
            SpiSupportAccessor.getInstance().removeCancelSupport(cancel);
        }
    }
 
示例26
private void refreshErrors(final ResultIterator resultIterator) throws ParseException {
    List<ErrorDescription> descs = new ArrayList<ErrorDescription>();
    Document doc = getDocument();
    processErrorsRecursive(resultIterator, doc, descs, resultIterator.getSnapshot());
    HintsController.setErrors(doc, GsfHintsFactory.LAYER_NAME, descs);
}