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

The following examples show how to use org.openide.cookies.EditorCookie#open() . 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: CssBracketCompleterTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void setupEditor() throws IOException {
    // this doesn't work since the JTextPane doesn't like our Kits since they aren't StyleEditorKits.
    //            Document doc = createDocument();
    //            JTextPane pane = new JTextPane((StyledDocument)doc);
    //            EditorKit kit = CloneableEditorSupport.getEditorKit("text/css");
    //            pane.setEditorKit(kit);

    File tmpFile = new File(getWorkDir(), "bracketCompleterTest.css");
    tmpFile.createNewFile();
    FileObject fo = FileUtil.createData(tmpFile);
    DataObject dobj = DataObject.find(fo);
    EditorCookie ec = dobj.getCookie(EditorCookie.class);
    this.doc = ec.openDocument();
    ec.open();
    this.pane = ec.getOpenedPanes()[0];

    this.defaultKeyTypedAction = (BaseAction) pane.getActionMap().get(NbEditorKit.defaultKeyTypedAction);
    this.backspaceAction = (BaseAction) pane.getActionMap().get(NbEditorKit.deletePrevCharAction);
    this.deleteAction = (BaseAction) pane.getActionMap().get(NbEditorKit.deleteNextCharAction);
}
 
Example 2
Source File: AnnotationProviderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@RandomlyFails
public void testContextLookupIsConsistentAfterMove() throws Exception {              
    ConsistencyCheckProvider.setCalled(0);
    // Prepare the data object (to initialize the lookup)
    FileObject fo = fs.getRoot().createData("test2", "txt");
    DataObject data = DataObject.find(fo);
    EditorCookie ec = data.getCookie(EditorCookie.class);

    // now move it (the lookup should update itself)
    FileObject fld = fs.getRoot().createFolder("folder1");
    DataFolder df = DataFolder.findFolder(fld);
    data.move(df);

    // now open the editor (invoke AnnotationProviders)
    // and check the lookup
    ec.open();
    assertEquals("Consistent lookup content", data.getPrimaryFile(),ConsistencyCheckProvider.getInLkp());
}
 
Example 3
Source File: GoToPopup.java    From cakephp3-netbeans with Apache License 2.0 6 votes vote down vote up
private void openSelected() {
    GoToItem item = jList1.getSelectedValue();
    if (item == null) {
        return;
    }
    FileObject fileObject = item.getFileObject();
    int offset = item.getOffset();
    if (fileObject != null && offset >= 0) {
        if (offset == 0) {
            try {
                DataObject dataObject = DataObject.find(fileObject);
                EditorCookie ec = dataObject.getLookup().lookup(EditorCookie.class);
                ec.open();
            } catch (DataObjectNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            UiUtils.open(fileObject, offset);
        }
    } else {
        Toolkit.getDefaultToolkit().beep();
    }

    PopupUtil.hidePopup();
}
 
Example 4
Source File: ViewWSDLAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performAction(Node[] nodes) {
    for (Node node :  nodes) {
        WsdlSaas saas = getWsdlSaas(node);
        String location = saas.getWsdlData().getWsdlFile();
        FileObject wsdlFileObject = saas.getLocalWsdlFile();

        if (wsdlFileObject == null) {
            String errorMessage = NbBundle.getMessage(ViewWSDLAction.class, "WSDL_FILE_NOT_FOUND", location); // NOI18N
            NotifyDescriptor d = new NotifyDescriptor.Message(errorMessage);
            DialogDisplayer.getDefault().notify(d);
            continue;
        }

        //TODO: open in read-only mode
        try {
            DataObject wsdlDataObject = DataObject.find(wsdlFileObject);
            EditorCookie editorCookie = wsdlDataObject.getLookup().lookup(EditorCookie.class);
            editorCookie.open();
        } catch (Exception e) {
            Exceptions.printStackTrace(e);
        }
    }
}
 
Example 5
Source File: TomcatInstanceNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Open server.xml file in editor.
 */
public void editServerXml() {
    FileObject fileObject = getTomcatConf();
    if (fileObject != null) {
        DataObject dataObject = null;
        try {
            dataObject = DataObject.find(fileObject);
        } catch(DataObjectNotFoundException ex) {
            Logger.getLogger(TomcatInstanceNode.class.getName()).log(Level.INFO, null, ex);
        }
        if (dataObject != null) {
            EditorCookie editorCookie = (EditorCookie)dataObject.getCookie(EditorCookie.class);
            if (editorCookie != null) {
                editorCookie.open();
            } else {
                Logger.getLogger(TomcatInstanceNode.class.getName()).log(Level.INFO, "Cannot find EditorCookie."); // NOI18N
            }
        }
    }
}
 
Example 6
Source File: MarkOccurrencesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private JavaSource openFile(String name) throws DataObjectNotFoundException, IOException, InterruptedException, InvocationTargetException {
    String dataDir = getDataDir().getAbsoluteFile().getPath();
    File sample = new File(dataDir+"/projects/java_editor_test/src/markOccurrences",name);
    assertTrue("file "+sample.getAbsolutePath()+" does not exist",sample.exists());
    
    fileObject = FileUtil.toFileObject(sample);
    dataObject = DataObject.find(fileObject);
    JavaSource js = JavaSource.forFileObject(fileObject);                
    final EditorCookie ec = dataObject.getCookie(EditorCookie.class);
    ec.openDocument();
    ec.open();
            
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            JEditorPane[] panes = ec.getOpenedPanes();
            editorPane = panes[0];
            
        }
    });
    return js;
    
}
 
Example 7
Source File: ResourceHyperlinkProcessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean openFile(FileObject file) {
    if (file == null) {
        return false;
    }
    DataObject dObj;
    try {
        dObj = DataObject.find(file);
    } catch (DataObjectNotFoundException ex) {
        return false;
    }
    EditorCookie editorCookie = dObj.getCookie(EditorCookie.class);
    if (editorCookie == null) {
        return false;
    }
    editorCookie.open();
    return true;
}
 
Example 8
Source File: BookmarkUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void openEditor(EditorCookie ec, int lineIndex) {
    Line.Set lineSet = ec.getLineSet();
    if (lineSet != null) {
        try {
            Line line = lineSet.getCurrent(lineIndex);
            if (line != null) {
                line.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
            }
        } catch (IndexOutOfBoundsException ex) {
            // attempt at least to open the editor
            ec.open();
            // expected, bookmark contains an invalid line
            StatusDisplayer.getDefault().setStatusText(
                    NbBundle.getMessage(BookmarkUtils.class, "MSG_InvalidLineNumnber", lineIndex));
        }
        JEditorPane[] panes = ec.getOpenedPanes();
        if (panes.length > 0) {
            panes[0].requestFocusInWindow();
        }
    }
}
 
Example 9
Source File: AnnotationProviderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@RandomlyFails
public void testContextLookupFiresDuringMove() throws Exception {              
    // Prepare the data object (to initialize the lookup)
    FileObject fo = fs.getRoot().createData("test3", "txt");
    DataObject data = DataObject.find(fo);
    EditorCookie ec = data.getCookie(EditorCookie.class);

    // open the editor and check the lookup before move
    ec.open();
    assertEquals("Lookup content consistent before move", data.getPrimaryFile(),ConsistencyCheckProvider.getInLkp());

    forceGC ();
    
    // now move the file
    ConsistencyCheckProvider.setCalled(0);
    FileObject fld = fs.getRoot().createFolder("folder1");
    DataFolder df = DataFolder.findFolder(fld);
    data.move(df);

    forceGC ();
    
    // check the result
    assertEquals("Lookup fires one change during move", 1, ConsistencyCheckProvider.changes);
    assertEquals("Lookup content consistent after move", data.getPrimaryFile(),ConsistencyCheckProvider.getInLkp());
}
 
Example 10
Source File: EntityRelations.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private EditorOperator openFile(String fileName) throws Exception {
    secondFile = new File(getDataDir(), fileName);
    DataObject dataObj = DataObject.find(FileUtil.toFileObject(secondFile));
    EditorCookie ed = dataObj.getCookie(EditorCookie.class);
    ed.open();
    return new EditorOperator(secondFile.getName()); // wait for opening
}
 
Example 11
Source File: JavaRefactoringActionsProviderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test190101() throws Exception {
    writeFilesAndWaitForScan(src,
                             new File("t/A.java", "package t;\n" +
                                                  "//public class A {\n" +
                                                  "    public static void foo() {}\n" +
                                                  "}"));
    FileObject testFile = src.getFileObject("t/A.java");
    DataObject testFileDO = DataObject.find(testFile);
    EditorCookie ec = testFileDO.getLookup().lookup(EditorCookie.class);
    ec.open();
    ec.getOpenedPanes()[0].setCaretPosition(30);
    final AtomicInteger called = new AtomicInteger();
    ContextAnalyzer.SHOW = new ContextAnalyzer.ShowUI() {
        @Override
        public void show(RefactoringUI ui, TopComponent activetc) {
            assertNull(ui);
            called.incrementAndGet();
        }
    };
    int expectedCount = 0;
    new JavaRefactoringActionsProvider().doChangeParameters(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doEncapsulateFields(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doExtractInterface(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doExtractSuperclass(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doInnerToOuter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doPullUp(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doPushDown(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    new JavaRefactoringActionsProvider().doUseSuperType(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
}
 
Example 12
Source File: CommentActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private EditorOperator openFile(String fileName) throws DataObjectNotFoundException {
    FileObject project = FileUtil.toFileObject(new File(getDataDir(), PROJECT_DIR_NAME));
    FileObject file = project.getFileObject("web").getFileObject(fileName);
    DataObject dataObj = DataObject.find(file);
    EditorCookie ed = dataObj.getCookie(EditorCookie.class);
    ed.open();
    return new EditorOperator(fileName);
}
 
Example 13
Source File: GitCommitPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void beforeFilesChanged () {
    if (controller != null) {
        SaveCookie[] saveCookies = getSaveCookies();
        if (saveCookies.length > 0 && SaveBeforeClosingDiffConfirmation.allSaved(saveCookies)) {
            EditorCookie[] editorCookies = getEditorCookies();
            for (EditorCookie cookie : editorCookies) {
                cookie.open();
            }
        }
    }
}
 
Example 14
Source File: I18nAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 
 * Actually performs the action. Implements superclass abstract method.
 * @param activatedNodes Currently activated nodes.
 */
protected void performAction(final Node[] activatedNodes) {
    if (activatedNodes.length != 1) {
        return;
    }

    final Node node = activatedNodes[0];
    DataObject dataObject = node.getCookie(DataObject.class);
    if (dataObject == null) {
        return;
    }

    if (FileOwnerQuery.getOwner(dataObject.getPrimaryFile()) == null) {
        return;
    }

    EditorCookie editorCookie = node.getCookie(EditorCookie.class);
    if (editorCookie == null) {
        editorCookie = dataObject.getCookie(EditorCookie.class);
        if (editorCookie == null) {
            return;
        }
    }

    editorCookie.open(); 
    I18nManager.getDefault().internationalize(dataObject);
}
 
Example 15
Source File: MiscEditorUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void openFileObject(FileObject fileObject) {
    if (fileObject == null) {
        return;
    }
    
    try {
        DataObject dataObject = DataObject.find(fileObject);
        EditorCookie cookie = dataObject.getCookie(EditorCookie.class);
        cookie.open();
    } catch (DataObjectNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: CssBracketCompleterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDoNotAutocompleteQuteInHtmlAttribute() throws DataObjectNotFoundException, IOException, BadLocationException {
    FileObject fo = getTestFile("testfiles/test.html");
    assertEquals("text/html", fo.getMIMEType());

    DataObject dobj = DataObject.find(fo);
    EditorCookie ec = dobj.getCookie(EditorCookie.class);
    Document document = ec.openDocument();
    ec.open();
    JEditorPane jep = ec.getOpenedPanes()[0];
    BaseAction type = (BaseAction) jep.getActionMap().get(NbEditorKit.defaultKeyTypedAction);
    //find the pipe
    String text = document.getText(0, document.getLength());

    int pipeIdx = text.indexOf('|');
    assertTrue(pipeIdx != -1);

    //delete the pipe
    document.remove(pipeIdx, 1);

    jep.setCaretPosition(pipeIdx);
    
    //type "
    ActionEvent ae = new ActionEvent(doc, 0, "\"");
    type.actionPerformed(ae, jep);

    //check the document content
    String beforeCaret = document.getText(pipeIdx, 2);
    assertEquals("\" ", beforeCaret);

}
 
Example 17
Source File: RefactorActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private EditorOperator openFile(String fileName) throws DataObjectNotFoundException {
    FileObject project = FileUtil.toFileObject(new File(getDataDir(), PROJECT_DIR_NAME));
    FileObject file = project.getFileObject("web").getFileObject(fileName);
    DataObject dataObj = DataObject.find(file);
    EditorCookie ed = dataObj.getCookie(EditorCookie.class);
    ed.open();
    return new EditorOperator(file.getNameExt());
}
 
Example 18
Source File: ErrorLineConvertor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void outputLineAction(OutputEvent ev) {
    FileObject sourceFile = GlobalPathRegistry.getDefault().findResource(
            path);
    if (sourceFile == null) {
        sourceFile = FileUtil.toFileObject(FileUtil.normalizeFile(
                new File(path)));
    }
    DataObject dataObject = null;
    if (sourceFile != null) {
        try {
            dataObject = DataObject.find(sourceFile);
        } catch(DataObjectNotFoundException ex) {
            Logger.getLogger(ErrorLineConvertor.class.getName()).log(
                    Level.INFO, null, ex);
        }
    }
    if (dataObject != null) {
        EditorCookie editorCookie = (EditorCookie)dataObject.getCookie(
                EditorCookie.class);
        if (editorCookie == null) {
            return;
        }
        editorCookie.open();
        Line errorLine = null;
        try {
            errorLine = editorCookie.getLineSet().getCurrent(line - 1);
        } catch (IndexOutOfBoundsException iobe) {
            return;
        }
        errorLine.show(ShowOpenType.OPEN, ShowVisibilityType.NONE);
    }
}
 
Example 19
Source File: IntroduceParameterActionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("ValueOfIncrementOrDecrementUsed")
public void testIPvar() throws Exception {
    String file;
    writeFilesAndWaitForScan(src,
            new RefactoringTestBase.File("t/A.java", file = "package t;\n"
                    + "\n"
                    + "public class A {\n"
                    + "\n"
                    + "  public void m1(){\n"
                    + "    m2(1);\n"
                    + "  }\n"
                    + "\n"
                    + "  public void m2(int i){\n"
                    + "    if (i > 5) {\n"
                    + "      System.out.println(\"abcd\");\n"
                    + "    }\n"
                    + "  }\n"
                    + "}\n"
                    + "class B {\n"
                    + "}\n"));
    FileObject testFile = src.getFileObject("t/A.java");
    DataObject testFileDO = DataObject.find(testFile);
    EditorCookie ec = testFileDO.getLookup().lookup(EditorCookie.class);
    ec.open();
    final AtomicInteger called = new AtomicInteger();
    int expectedCount = 0;
    
    final TreePathHandle[] handle = {null};
    ContextAnalyzer.SHOW = new ContextAnalyzer.ShowUI() {
        @Override public void show(RefactoringUI ui, TopComponent activetc) {
            assertTrue(ui instanceof IntroduceParameterUI);
            handle[0] = ui.getRefactoring().getRefactoringSource().lookup(TreePathHandle.class);
            called.incrementAndGet();
        }
    };
    
    // a. Parameter i is selected and caret is at position (i| > 5)
    ec.getOpenedPanes()[0].setCaretPosition(99);
    ec.getOpenedPanes()[0].moveCaretPosition(100);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.IDENTIFIER, handle[0].getKind());

    // b. Parameter i is selected and caret is at position (|i > 5)
    ec.getOpenedPanes()[0].setCaretPosition(100);
    ec.getOpenedPanes()[0].moveCaretPosition(99);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.IDENTIFIER, handle[0].getKind());
    
    // c. Nothing is selected and caret is at position (|i > 5)
    ec.getOpenedPanes()[0].setCaretPosition(99);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.IDENTIFIER, handle[0].getKind());
    
    // d. Nothing is selected and caret is at position (i| > 5)
    ec.getOpenedPanes()[0].setCaretPosition(100);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.IDENTIFIER, handle[0].getKind());
    
    // e. Nothing is selected and caret is at position (i > |5)
    ec.getOpenedPanes()[0].setCaretPosition(103);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.INT_LITERAL, handle[0].getKind());
    
    // f. Nothing is selected and caret is at position (i > 5|)
    ec.getOpenedPanes()[0].setCaretPosition(104);
    new JavaRefactoringActionsProvider().doIntroduceParameter(Lookups.fixed(ec));
    assertEquals(++expectedCount, called.get());
    assertEquals(Tree.Kind.INT_LITERAL, handle[0].getKind());
}
 
Example 20
Source File: FileUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Open the file and optionally set cursor to the line. If the file does not exist,
 * nothing is done.
 * <p>
 * <i>Note:</i> This action is always run in AWT thread.
 * @param file file to be opened
 * @param line line of a file to set cursor to, {@code -1} if no specific line is needed
 * @see #openFile(File)
 * @since 2.54
 */
public static void openFile(@NonNull File file, int line) {
    Parameters.notNull("file", file); // NOI18N

    FileObject fileObject = FileUtil.toFileObject(FileUtil.normalizeFile(file));
    if (fileObject == null) {
        LOGGER.log(Level.INFO, "FileObject not found for {0}", file);
        return;
    }

    DataObject dataObject;
    try {
        dataObject = DataObject.find(fileObject);
    } catch (DataObjectNotFoundException ex) {
        LOGGER.log(Level.INFO, "DataObject not found for {0}", file);
        return;
    }

    if (line == -1) {
        // simply open file
        EditorCookie ec = dataObject.getLookup().lookup(EditorCookie.class);
        ec.open();
        return;
    }

    // open at specific line
    LineCookie lineCookie = dataObject.getLookup().lookup(LineCookie.class);
    if (lineCookie == null) {
        LOGGER.log(Level.INFO, "LineCookie not found for {0}", file);
        return;
    }
    Line.Set lineSet = lineCookie.getLineSet();
    try {
        final Line currentLine = lineSet.getOriginal(line - 1);
        Mutex.EVENT.readAccess(new Runnable() {
            @Override
            public void run() {
                currentLine.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
            }
        });
    } catch (IndexOutOfBoundsException exc) {
        LOGGER.log(Level.FINE, null, exc);
    }
}