Java Code Examples for org.openide.cookies.EditorCookie#getDocument()

The following examples show how to use org.openide.cookies.EditorCookie#getDocument() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line number of the caret in the most recent editor.
 * This returns the current line number in the current editor if there's one,
 * or a line number of the caret in the editor, that was most recently active.
 * @return the line number or <code>-1</code> when there was no recent active editor.
 */
public int getMostRecentLineNumber() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return -1;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return -1;
    StyledDocument d = e.getDocument ();
    if (d == null) return -1;
    Caret caret = ep.getCaret ();
    if (caret == null) return -1;
    int ln = NbDocument.findLineNumber (
        d,
        caret.getDot ()
    );
    return ln + 1;
}
 
Example 2
Source File: LanguageClientImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 3
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line of the caret in the most recent editor.
 * This returns the current line in the current editor if there's one,
 * or a line of the caret in the editor, that was most recently active.
 * @return the line or <code>null</code> when there was no recent active editor.
 */
public Line getMostRecentLine() {
    EditorCookie e = getMostRecentEditorCookie ();
    if (e == null) return null;
    JEditorPane ep = getMostRecentEditor ();
    if (ep == null) return null;
    StyledDocument d = e.getDocument ();
    if (d == null) return null;
    Caret caret = ep.getCaret ();
    if (caret == null) return null;
    int lineNumber = NbDocument.findLineNumber(d, caret.getDot());
    Line.Set lineSet = e.getLineSet();
    try {
        return lineSet.getCurrent(lineNumber);
    } catch (IndexOutOfBoundsException ex) {
        return null;
    }
}
 
Example 4
Source File: J2eeUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isRestJavaFile(DataObject d) {
    try {
        if (!JavaUtil.isJava(d)) {
            return false;
        }
        EditorCookie ec = d.getCookie(EditorCookie.class);
        if (ec == null) {
            return false;
        }
        javax.swing.text.Document doc = ec.getDocument();
        if (doc != null) {
            String docText = doc.getText(0, doc.getLength());

            return (docText.indexOf(Util.APATH) != -1) ||
                    (docText.indexOf(Util.AGET) != -1) ||
                    (docText.indexOf(Util.APOST) != -1) ||
                    (docText.indexOf(Util.APUT) != -1) ||
                    (docText.indexOf(Util.ADELETE) != -1);
        }
    } catch (BadLocationException ex) {
    }
    return false;
}
 
Example 5
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Get the line number of the caret in the current editor.
 * @return the line number or <code>-1</code> when there is no current editor.
 */
public int getCurrentLineNumber() {
    EditorCookie e = getCurrentEditorCookie ();
    if (e == null) return -1;
    JEditorPane ep = getCurrentEditor ();
    if (ep == null) return -1;
    StyledDocument d = e.getDocument ();
    if (d == null) return -1;
    Caret caret = ep.getCaret ();
    if (caret == null) return -1;
    int ln = NbDocument.findLineNumber (
        d,
        caret.getDot ()
    );
    return ln + 1;
}
 
Example 6
Source File: BatchUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static @CheckForNull Document getDocument(@NonNull FileObject file) {
    try {
        DataObject od = DataObject.find(file);
        EditorCookie ec = od.getLookup().lookup(EditorCookie.class);

        if (ec == null) return null;

        return ec.getDocument();
    } catch (DataObjectNotFoundException ex) {
        LOG.log(Level.FINE, null, ex);
        return null;
    }
}
 
Example 7
Source File: GsfUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Load the document for the given fileObject.
 * @param fileObject the file whose document we want to obtain
 * @param openIfNecessary If true, block if necessary to open the document. If false, will only return the
 *    document if it is already open.
 * @param skipLarge If true, check the file size, and if the file is really large (defined by
 *    openide.loaders), then skip it (otherwise we could end up with a large file warning).
 * @return
 */
public static BaseDocument getDocument(FileObject fileObject, boolean openIfNecessary, boolean skipLarge) {
    if (skipLarge) {
        // Make sure we're not dealing with a huge file!
        // Causes issues like 132306
        // openide.loaders/src/org/openide/text/DataEditorSupport.java
        // has an Env#inputStream method which posts a warning to the user
        // if the file is greater than 1Mb...
        //SG_ObjectIsTooBig=The file {1} seems to be too large ({2,choice,0#{2}b|1024#{3} Kb|1100000#{4} Mb|1100000000#{5} Gb}) to safely open. \n\
        //  Opening the file could cause OutOfMemoryError, which would make the IDE unusable. Do you really want to open it?

        // Apparently there is a way to handle this
        // (see issue http://www.netbeans.org/issues/show_bug.cgi?id=148702 )
        // but for many cases, the user probably doesn't want really large files as indicated
        // by the skipLarge parameter).
        if (fileObject.getSize () > 1024 * 1024) {
            return null;
        }
    }

    try {
        EditorCookie ec = fileObject.isValid() ? DataLoadersBridge.getDefault().getCookie(fileObject, EditorCookie.class) : null;
        if (ec != null) {
            if (openIfNecessary) {
                try {
                    return (BaseDocument) ec.openDocument();
                } catch (UserQuestionException uqe) {
                    uqe.confirmed();
                    return (BaseDocument) ec.openDocument();
                }
            } else {
                return (BaseDocument) ec.getDocument();
            }
        }
    } catch (IOException ex) {
        LOG.log(Level.WARNING, null, ex);
    }

    return null;
}
 
Example 8
Source File: PreviewManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isOriginalDocumentLoaded() {
     try {
         FileObject fo = element.getParentFile();
         DataObject dObj = DataObject.find(fo);
         EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
         if (ec != null) {
             StyledDocument doc = ec.getDocument();
             return doc!=null;
         }
     } catch (DataObjectNotFoundException ex) {
         //ignore;
     }
     return false;
     
}
 
Example 9
Source File: AnnotationHolder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static synchronized AnnotationHolder getInstance(FileObject file) {
    if (file == null)
        return null;

    try {
        DataObject od = DataObject.find(file);
        AnnotationHolder result = file2Holder.get(od);

        if (result == null) {
            EditorCookie editorCookie = od.getCookie(EditorCookie.class);

            if (editorCookie == null) {
                LOG.log(Level.WARNING,
                        "No EditorCookie.Observable for file: {0}", FileUtil.getFileDisplayName(file)); //NOI18N
            } else {
                Document doc = editorCookie.getDocument();

                if (doc instanceof BaseDocument) {
                    file2Holder.put(od, result = new AnnotationHolder(file, od, (BaseDocument) doc));
                }
            }
        }

        return result;
    } catch (IOException e) {
        LOG.log(Level.FINE, null, e);
        return null;
    }
}
 
Example 10
Source File: I18nSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Constructor. Note: It gets document from data object's editor cookie. If the document
 * is not available it tries to load it. Therefore this construction could take some time.
 * @exception IOException when the document is could not be loaded
 */
public I18nSupport(DataObject sourceDataObject) {
    this.sourceDataObject = sourceDataObject;
    
    EditorCookie editorCookie = sourceDataObject.getCookie(EditorCookie.class);
    
    if (editorCookie == null) {
        throw new IllegalArgumentException("I18N: Illegal data object type"+ sourceDataObject); // NOI18N
    }
    
    this.document = editorCookie.getDocument();
    
    this.resourceHolder = createResourceHolder();
}
 
Example 11
Source File: EventSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Document readDocument(FileObject fileObject, boolean forceOpen) {
    EditorCookie ec = null;
    
    try {
        DataObject dataObject = DataObject.find (fileObject);
        ec = dataObject.getLookup ().lookup (EditorCookie.class);
    } catch (DataObjectNotFoundException ex) {
        //DataobjectNotFoundException may happen in case of deleting opened file
        //handled by returning null
    }

    if (ec == null) return null;
    Document doc = ec.getDocument ();
    if (doc == null && forceOpen) {
        try {
            try {
                doc = ec.openDocument ();
            } catch (UserQuestionException uqe) {
                uqe.confirmed ();
                doc = ec.openDocument ();
            }
        } catch (IOException ioe) {
            LOGGER.log (Level.WARNING, null, ioe);
        }
    }
    return doc;
}
 
Example 12
Source File: TokensBrowserTopComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AbstractDocument getCurrentDocument () {
    Node[] ns = TopComponent.getRegistry ().getActivatedNodes ();
    if (ns.length != 1) return null;
    EditorCookie editorCookie = ns [0].getLookup ().
        lookup (EditorCookie.class);
    if (editorCookie == null) return null;
    if (editorCookie.getOpenedPanes () == null) return null;
    if (editorCookie.getOpenedPanes ().length < 1) return null;
    JEditorPane pane = editorCookie.getOpenedPanes () [0];
    
    if (caretListener == null)
        caretListener = new CListener ();
    if (lastPane != null && lastPane != pane) {
        lastPane.removeCaretListener (caretListener);
        lastPane = null;
    }
    if (lastPane == null) {
        pane.addCaretListener (caretListener);
        lastPane = pane;
    }

    AbstractDocument doc = (AbstractDocument) editorCookie.getDocument ();
    if (documentListener == null)
        documentListener = new CDocumentListener ();
    if (lastDocument != null && lastDocument != doc) {
        lastDocument.removeDocumentListener (documentListener);
        lastDocument = null;
    }
    if (lastDocument == null) {
        doc.addDocumentListener (documentListener);
        lastDocument = doc;
    }
    return doc;
}
 
Example 13
Source File: DataObjectAdapters.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Reader getCharacterStream() {

            EditorCookie editor = dataObject.getCookie(EditorCookie.class);

            if (editor != null) {
                Document doc = editor.getDocument();
                if (doc != null) {
                    return  new DocumentInputSource(doc).getCharacterStream();
                }
            }             
            
            return null;
        }
 
Example 14
Source File: CallHierarchyTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void resolveRoot(final Lookup lookup, final boolean searchFromBase, final boolean isCallerGraph, final Task<Call> rootCallback) {
        JavaSource js = null;
        RootResolver resolver = null;
        EditorCookie ec = lookup.lookup(EditorCookie.class);
        if (ec != null/*RefactoringActionsProvider.isFromEditor(ec)*/) {
            JEditorPane openedPane = NbDocument.findRecentEditorPane(ec);
            Document doc = ec.getDocument();
            js = JavaSource.forDocument(doc);
            resolver = new RootResolver(openedPane.getCaretPosition(), isCallerGraph, searchFromBase);
        }
//        else {
            // XXX resolve Node.class
//        }
        postResolveRoot(js, resolver, rootCallback);
    }
 
Example 15
Source File: GsfUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean doOpen(FileObject fo, int offset, String search) {
    try {
        DataObject od = DataObject.find(fo);
        EditorCookie ec = od.getCookie(EditorCookie.class);
        LineCookie lc = od.getCookie(LineCookie.class);

        // If the caller hasn't specified an offset, and the document is
        // already open, don't jump to a particular line!
        if (ec != null && offset == -1 && ec.getDocument() != null && search == null) {
            ec.open();
            return true;
        }

        // Simple text search if no known offset (e.g. broken/unparseable source)
        if ((search != null) && (offset == -1)) {
            StyledDocument doc = NbDocument.getDocument(od);

            try {
                String text = doc.getText(0, doc.getLength());
                int caretDelta = search.indexOf('^');
                if (caretDelta != -1) {
                    search = search.substring(0, caretDelta) + search.substring(caretDelta+1);
                } else {
                    caretDelta = 0;
                }
                offset = text.indexOf(search);
                if (offset != -1) {
                    offset += caretDelta;
                }
            } catch (BadLocationException ble) {
                LOG.log(Level.WARNING, null, ble);
            }
        }
        
        return NbDocument.openDocument(od, offset, Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
    } catch (IOException e) {
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
    }

    return false;
}
 
Example 16
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test142212() throws Exception {
    EqualsHashCodeGenerator.randomNumber = 1;
    
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "class X {\n" +
                         "  private byte b;\n" +
                         "  private int[] x;\n" +
                         "  private String[] y;\n" +
                         "  private String s;\n" +
                         "  private Object o;\n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.generateEqualsAndHashCode(copy, clazz, vars, vars, -1);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t).commit();

    DataObject dObj = DataObject.find(java);
    EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
    Document doc = ec != null ? ec.getDocument() : null;
    
    String result = doc != null ? doc.getText(0, doc.getLength()) : TestUtilities.copyFileToString(FileUtil.toFile(java));
    String golden = "\nimport java.util.Arrays;\n" +
                    "class X {\n" +
                    "  private byte b;\n" +
                    "  private int[] x;\n" +
                    "  private String[] y;\n" +
                    "  private String s;\n" +
                    "  private Object o;\n" +
                    "    @Override\n" +
                    "    public int hashCode() {\n" +
                    "        int hash = 1;\n" +
                    "        hash = 1 * hash + this.b;\n" +
                    "        hash = 1 * hash + Arrays.hashCode(this.x);\n" +
                    "        hash = 1 * hash + Arrays.deepHashCode(this.y);\n" +
                    "        hash = 1 * hash + (this.s != null ? this.s.hashCode() : 0);\n" +
                    "        hash = 1 * hash + (this.o != null ? this.o.hashCode() : 0);\n" +
                    "        return hash;\n" +
                    "    }\n" +
                    "    @Override\n" +
                    "    public boolean equals(Object obj) {\n" +
                    "        if (this == obj) {\n" +
                    "            return true;\n" +
                    "        }\n" +
                    "        if (obj == null) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (getClass() != obj.getClass()) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        final X other = (X) obj;\n" +
                    "        if (this.b != other.b) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if ((this.s == null) ? (other.s != null) : !this.s.equals(other.s)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.equals(this.x, other.x)) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (!Arrays.deepEquals(this.y, other.y)) {\n" +
                    "            return false;\n" +
                    "        }" +
                    "        if (this.o != other.o && (this.o == null || !this.o.equals(other.o))) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        return true;\n" +
                    "    }\n" +
                    "}\n";

    result = result.replaceAll("[ \t\n]+", " ");
    golden = golden.replaceAll("[ \t\n]+", " ");
    
    assertEquals(golden, result);
}
 
Example 17
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test171265() throws Exception {
    EqualsHashCodeGenerator.randomNumber = 1;

    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "class X {\n" +
                         "  private String s;\n" +
                         "  private EE e;\n";

    String what2 =
        "}\n" +
        "enum EE { A, B;}";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.generateEqualsAndHashCode(copy, clazz, Collections.<VariableElement>emptyList(), vars, -1);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t).commit();
    
    DataObject dObj = DataObject.find(java);
    EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
    Document doc = ec != null ? ec.getDocument() : null;
    
    String result = doc != null ? doc.getText(0, doc.getLength()) : TestUtilities.copyFileToString(FileUtil.toFile(java));

    String golden = "" +
                    "class X {\n" +
                    "  private String s;\n" +
                    "  private EE e;\n" +
                    "    @Override\n" +
                    "    public int hashCode() {\n" +
                    "        int hash = 1;\n" +
                    "        hash = 1 * hash + (this.s != null ? this.s.hashCode() : 0);\n" +
                    "        hash = 1 * hash + (this.e != null ? this.e.hashCode() : 0);\n" +
                    "        return hash;\n" +
                    "    }\n" +
                    "    @Override\n" +
                    "    public boolean equals(Object obj) {\n" +
                    "        if (this == obj) {\n" +
                    "            return true;\n" +
                    "        }\n" +
                    "        if (obj == null) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        if (getClass() != obj.getClass()) {\n" +
                    "            return false;\n" +
                    "        }\n" +
                    "        final X other = (X) obj;\n" +
                    "        return true;\n" +
                    "    }\n" +
                    "}\n" +
                    "enum EE { A, B;}";

    result = result.replaceAll("[ \t\n]+", " ");
    golden = golden.replaceAll("[ \t\n]+", " ");

    assertEquals(golden, result);

}
 
Example 18
Source File: DatasourceSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Perform datasources graph changes defined by the jbossWeb modifier. Update editor
 * content and save changes, if appropriate.
 *
 * @param modifier
 */
private JBossDatasource modifyDSResource(DSResourceModifier modifier) 
throws ConfigurationException, DatasourceAlreadyExistsException {

    JBossDatasource ds = null;
    
    try {
        ensureResourceDirExists();
        ensureDatasourcesFileExists();
        
        DataObject datasourcesDO = DataObject.find(datasourcesFO);

        EditorCookie editor = (EditorCookie)datasourcesDO.getCookie(EditorCookie.class);
        StyledDocument doc = editor.getDocument();
        if (doc == null)
            doc = editor.openDocument();

        Datasources newDatasources = null;
        try {  // get the up-to-date model
            // try to create a graph from the editor content
            byte[] docString = doc.getText(0, doc.getLength()).getBytes();
            newDatasources = Datasources.createGraph(new ByteArrayInputStream(docString));
        } catch (RuntimeException e) {
            Datasources oldDatasources = getDatasourcesGraph(true);
            if (oldDatasources == null) {
                // neither the old graph is parseable, there is not much we can do here
                // TODO: should we notify the user?
                throw new ConfigurationException(
                        NbBundle.getMessage(DatasourceSupport.class, "MSG_datasourcesXmlCannotParse", DS_RESOURCE_NAME)); // NOI18N
            }
            // current editor content is not parseable, ask whether to override or not
            NotifyDescriptor notDesc = new NotifyDescriptor.Confirmation(
                    NbBundle.getMessage(DatasourceSupport.class, "MSG_datasourcesXmlNotValid", DS_RESOURCE_NAME),       // NOI18N
                    NotifyDescriptor.OK_CANCEL_OPTION);
            Object result = DialogDisplayer.getDefault().notify(notDesc);
            if (result == NotifyDescriptor.CANCEL_OPTION) {
                // keep the old content
                return null;
            }
            // use the old graph
            newDatasources = oldDatasources;
        }

        // perform changes
        ds = modifier.modify(newDatasources);

        // save if appropriate
        boolean modified = datasourcesDO.isModified();
        ResourceConfigurationHelper.replaceDocument(doc, newDatasources);
        if (!modified) {
            SaveCookie cookie = (SaveCookie)datasourcesDO.getCookie(SaveCookie.class);
            cookie.save();
        }

        datasources = newDatasources;

    } catch(DataObjectNotFoundException donfe) {
        Exceptions.printStackTrace(donfe);
    } catch (BadLocationException ble) {
        // this should not occur, just log it if it happens
        Exceptions.printStackTrace(ble);
    } catch (IOException ioe) {
        String msg = NbBundle.getMessage(DatasourceSupport.class, "MSG_CannotUpdateFile", datasourcesFile.getAbsolutePath());
        throw new ConfigurationException(msg, ioe);
    }
    
    return ds;
}
 
Example 19
Source File: DefaultDataObjectHasOpenTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doRegularCheck(final EditorCookie c) throws Exception {
    assertEquals(
            "Next questions results in the same cookie",
            c,
            obj.getCookie(EditorCookie.class)
            );
    assertEquals(
            "Next questions results in the same cookie",
            c,
            obj.getLookup().lookup(EditorCookie.class)
            );
    assertEquals(
            "Print cookie is provided",
            c,
            obj.getCookie(PrintCookie.class)
            );
    assertEquals(
            "CloseCookie as well",
            c,
            obj.getCookie(CloseCookie.class)
            );

    OpenCookie open = obj.getCookie(OpenCookie.class);
    open.open();


    Document d = null;
    for (int i = 0; i < 10; i++) {
        d = c.getDocument();
        if (d != null) {
            break;
        }
        Thread.sleep(1000);
    }
    assertNotNull(d);

    d.insertString(0, "Kuk", null);

    assertNotNull(
            "Now there is a save cookie",
            obj.getCookie(SaveCookie.class)
            );
}
 
Example 20
Source File: EditorContextDispatcher.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Get a list of MIME types of languages found on a line.
 * @param line The line to search for the MIME types.
 * @return A set of MIME types.
 * @since 2.50
 */
public Set<String> getMIMETypesOnLine(Line line) {
    EditorCookie editorCookie = line.getLookup().lookup(EditorCookie.class);
    if (editorCookie == null) {
        DataObject dobj = line.getLookup().lookup(DataObject.class);
        if (dobj != null) {
            editorCookie = dobj.getLookup().lookup(EditorCookie.class);
        }
        if (editorCookie == null) {
            return Collections.emptySet();
        }
    }
    StyledDocument document = editorCookie.getDocument();
    if (document == null) {
        return Collections.emptySet();
    }
    Set<String> mimeTypes = null;
    ((AbstractDocument) document).readLock();
    try {
        TokenHierarchy<Document> th = TokenHierarchy.get((Document) document);
        int ln = line.getLineNumber();
        int offset = NbDocument.findLineOffset(document, ln);
        int maxOffset = document.getLength() - 1;
        int maxLine = NbDocument.findLineNumber(document, maxOffset);
        int offset2;
        if (ln + 1 > maxLine) {
            offset2 = maxOffset;
        } else {
            offset2 = NbDocument.findLineOffset(document, ln+1) - 1;
        }
        // The line has offsets <offset, offset2>
        Set<LanguagePath> languagePaths = th.languagePaths();
        for (LanguagePath lp : languagePaths) {
            List<TokenSequence<?>> tsl = th.tokenSequenceList(lp, offset, offset2);
            for (TokenSequence ts : tsl) {
                if (ts.moveNext()) {
                    //int to = ts.offset();
                    //if (!(offset <= to && to < offset2)) {
                    //    continue;
                    //}
                    String mimeType = ts.language().mimeType();
                    if (mimeType != null) {
                        if (mimeTypes == null) {
                            mimeTypes = Collections.singleton(mimeType);
                        } else {
                            if (mimeTypes.size() == 1) {
                                mimeTypes = new HashSet<String>(mimeTypes);
                            }
                            mimeTypes.add(mimeType);
                        }
                    }
                }
            }
        }
    } finally {
        ((AbstractDocument) document).readUnlock();
    }
    return (mimeTypes != null) ? mimeTypes : Collections.<String>emptySet();
    
}