Java Code Examples for org.netbeans.api.editor.mimelookup.MimeLookup#getLookup()

The following examples show how to use org.netbeans.api.editor.mimelookup.MimeLookup#getLookup() . 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: EditorSettingsStorageTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAllColors() {
    MimePath mimePath = MimePath.parse("text/x-type-A");
    Lookup lookup = MimeLookup.getLookup(mimePath);
    
    FontColorSettings fcs = lookup.lookup(FontColorSettings.class);
    assertNotNull("Can't find FontColorSettings", fcs);
    
    AttributeSet attribs = fcs.getTokenFontColors("test-all");
    assertNotNull("Can't find test-all coloring", attribs);
    assertEquals("Wrong background color", 
        new Color(0x0A0B0C), attribs.getAttribute(StyleConstants.Background));
    assertEquals("Wrong foreground color", 
        new Color(0x0D0E0F), attribs.getAttribute(StyleConstants.Foreground));
    assertEquals("Wrong underline color", 
        new Color(0x010203), attribs.getAttribute(StyleConstants.Underline));
    assertEquals("Wrong strikeThrough color", 
        new Color(0x040506), attribs.getAttribute(StyleConstants.StrikeThrough));
    assertEquals("Wrong waveUnderline color", 
        new Color(0x070809), attribs.getAttribute(EditorStyleConstants.WaveUnderlineColor));
}
 
Example 2
Source File: DocumentModelProviderFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public DocumentModelProvider getDocumentModelProvider(String mimeType) {
    DocumentModelProvider provider = null; // result
    if(mimeType != null) {
        provider = mime2provider.get(mimeType);
        if (provider == null) { // not cached yet
            Lookup mimeLookup = MimeLookup.getLookup(MimePath.get(mimeType));
            Collection<? extends DocumentModelProvider> providers = 
                    mimeLookup.lookup(new Lookup.Template<DocumentModelProvider>(DocumentModelProvider.class)).allInstances();
            if(providers.size() > 1)
                ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Only one DocumentModelProvider can be registered for one mimetype!");
            
            if(providers.size() == 0)
                ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new IllegalStateException("There isn't any DocumentModelProvider registered for " + mimeType + " mimetype!"));
            
            provider = providers.size() > 0 ? (DocumentModelProvider)providers.iterator().next() : null;
            mime2provider.put(mimeType, provider);
            
        } else return provider;
    } else
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new NullPointerException("mimeType cannot be null!"));
    
    return provider;
}
 
Example 3
Source File: RefactoringUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String getHtml(String text) {
    StringBuilder buf = new StringBuilder();
    // TODO - check whether we need Js highlighting or rhtml highlighting
    TokenHierarchy tokenH = TokenHierarchy.create(text, PHPTokenId.language());
    Lookup lookup = MimeLookup.getLookup(MimePath.get(FileUtils.PHP_MIME_TYPE));
    FontColorSettings settings = lookup.lookup(FontColorSettings.class);
    @SuppressWarnings("unchecked")
    TokenSequence<? extends TokenId> tok = tokenH.tokenSequence();
    while (tok.moveNext()) {
        Token<? extends TokenId> token = tok.token();
        String category = token.id().name();
        AttributeSet set = settings.getTokenFontColors(category);
        if (set == null) {
            category = token.id().primaryCategory();
            if (category == null) {
                category = "whitespace"; //NOI18N

            }
            set = settings.getTokenFontColors(category);
        }
        String tokenText = htmlize(token.text().toString());
        buf.append(color(tokenText, set));
    }
    return buf.toString();
}
 
Example 4
Source File: MimeLookupPerformanceTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testTemplateLookuping() throws IOException{
    MimePath mp = MimePath.parse("text/x-java/text/html/text/xml");
    Lookup lookup = MimeLookup.getLookup(mp);
    Result result = lookup.lookup(new Template(PopupActions.class));
    Collection col = result.allInstances();
    checkPopupItemPresence(lookup, RenameAction.class, true);
    gc();
    int size = assertSize("", Arrays.asList( new Object[] {lookup} ), 10000000,  getFilter());
    for (int i=0; i<30; i++){
        result = lookup.lookup(new Template(PopupActions.class));
        col = result.allInstances();
        checkPopupItemPresence(lookup, RenameAction.class, true);
    }
    gc();
    assertSize("", size, lookup);
}
 
Example 5
Source File: MimePathLookupTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private <T> void checkRemovingMimeDataProvider(String instanceFile, Class<T> markerClass) throws Exception {
    TestUtilities.createFile(getWorkDir(), instanceFile);
    TestUtilities.sleepForWhile();

    MimePath path = MimePath.get("text/x-java");
    Lookup lookup = MimeLookup.getLookup(path);
    
    Collection markers = lookup.lookupAll(markerClass);
    assertEquals("No markers found", 1, markers.size());

    TestUtilities.deleteFile(getWorkDir(), instanceFile);
    TestUtilities.sleepForWhile();
    
    markers = lookup.lookupAll(markerClass);
    assertEquals("There should be no markers", 0, markers.size());
}
 
Example 6
Source File: SettingsProviderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLookupsGCedAfterFcs() {
    MimePath mimePath = MimePath.parse("text/x-type-A");
    FontColorSettingsImpl fcsi = FontColorSettingsImpl.get(mimePath);
    Lookup lookup = MimeLookup.getLookup(mimePath);
    FontColorSettings fcs = lookup.lookup(FontColorSettings.class);

    WeakReference<FontColorSettingsImpl> fcsiRef = new WeakReference<FontColorSettingsImpl>(fcsi);
    WeakReference<MimePath> mimePathRef = new WeakReference<MimePath>(mimePath);
    WeakReference<Lookup> lookupRef = new WeakReference<Lookup>(lookup);
    WeakReference<FontColorSettings> fcsRef = new WeakReference<FontColorSettings>(fcs);

    fcsi = null;
    mimePath = null;
    lookup = null;
    fcs = null;
    
    // release text/x-type-A from MimePath's LRU
    for(int i = 0; i < 10; i++) {
        MimePath.parse("text/x-type-" + ('Z' + i));
    }
    
    assertGC("FCSI hasn't been GCed", fcsiRef);
    assertGC("MimePath hasn't been GCed", mimePathRef);
    assertGC("Lookup hasn't been GCed", lookupRef);
    assertGC("FCS hasn't been GCed", fcsRef);
}
 
Example 7
Source File: MimeLookupInheritanceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Testing MIME level popup items lookup, inheritance and sorting */
public void testMimeLevelPopups(){
    MimePath mp = MimePath.parse("text/x-java/text/html"); //NOI18N
    Lookup lookup = MimeLookup.getLookup(mp);
    Class layerObjects[] = {CutAction.class, CopyAction.class, NewAction.class, PasteAction.class};
    testPopupItems(lookup, layerObjects);
}
 
Example 8
Source File: StyledDocumentWriter.java    From editorconfig-netbeans with MIT License 5 votes vote down vote up
public static EditorKit getEditorKit(DataObject dataObject) {
  FileObject fileObject = dataObject.getPrimaryFile();
  String mimePath = fileObject.getMIMEType();
  Lookup lookup = MimeLookup.getLookup(MimePath.parse(mimePath));
  EditorKit kit = lookup.lookup(EditorKit.class);

  return kit;
}
 
Example 9
Source File: SyntaxHighlighting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param innerLanguage
 * @param mimePath note it may start with mimeTypeForOptions
 */
public FCSInfo(String mimePath, Language<T> innerLanguage) {
    this.innerLanguage = innerLanguage;
    this.mimePath = mimePath;
    this.listeners = new ListenerList<ChangeListener>();
    Lookup lookup = MimeLookup.getLookup("text/textmate");
    result = lookup.lookupResult(FontColorSettings.class);
    // Do not listen on font color settings changes in tests
    // since "random" lookup events translate into highlight change events
    // that are monitored by tests and so the tests may then fail
    if (TEST_FALLBACK_COLORING == null) {
        result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
    }
    updateFCS();
}
 
Example 10
Source File: MimeLookupTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 
 * Looking up the class that has NOT registered subfolder via Class2LayerFolder.
 * It should be found appropriate mime-type specific folder
 */
public void testNotRegisteredClassLookup() throws IOException {
    MimePath mp = MimePath.get(MimePath.get("text/xml"), "text/html"); //NOI18N
    Lookup lookup = MimeLookup.getLookup(mp);
    checkLookupObject(lookup, StringBuffer.class, true);
    TestUtilities.deleteFile(getWorkDir(),
            "Editors/text/xml/text/html/java-lang-StringBuffer.instance");
    checkLookupObject(lookup, StringBuffer.class, false);
}
 
Example 11
Source File: Terminal.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Map<?, ?> getRenderingHints() {
       Map<?, ?> renderingHints = null;
       // init hints if any
       Lookup lookup = MimeLookup.getLookup("text/plain"); // NOI18N
       if (lookup != null) {
           FontColorSettings fcs = lookup.lookup(FontColorSettings.class);
           if (fcs != null) {
               AttributeSet attributes = fcs.getFontColors(FontColorNames.DEFAULT_COLORING);
               if (attributes != null) {
                   renderingHints = (Map<?, ?>) attributes.getAttribute(EditorStyleConstants.RenderingHints);
               }
           }
       }
return renderingHints;
   }
 
Example 12
Source File: SyntaxHighlighting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param innerLanguage
 * @param mimePath note it may start with mimeTypeForOptions
 */
public FCSInfo(String mimePath, Language<T> innerLanguage) {
    this.innerLanguage = innerLanguage;
    this.mimePath = mimePath;
    this.listeners = new ListenerList<ChangeListener>();
    Lookup lookup = MimeLookup.getLookup(MimePath.parse(mimePath));
    result = lookup.lookupResult(FontColorSettings.class);
    // Do not listen on font color settings changes in tests
    // since "random" lookup events translate into highlight change events
    // that are monitored by tests and so the tests may then fail
    if (TEST_FALLBACK_COLORING == null) {
        result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
    }
    updateFCS();
}
 
Example 13
Source File: MimePathLookupTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    // System.out.println("T1 running");
    MimePath path = MimePath.get("text/x-java");
    Lookup lookup = MimeLookup.getLookup(path);
    lookup.lookup(Task1.class);
    // System.out.println("T1 done");
    done = true;
}
 
Example 14
Source File: KeybindingStorageTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testKeybindingsForSpecialTestMimeType() throws Exception {
    final String origMimeType = "text/x-orig";
    final String specialTestMimeType = "test123456_" + origMimeType;
    
    Lookup lookup = MimeLookup.getLookup(MimePath.parse(specialTestMimeType));
    
    // Check the API class
    Collection<? extends KeyBindingSettings> c = lookup.lookupAll(KeyBindingSettings.class);
    assertEquals("Wrong number of kbs", 1, c.size());
    
    KeyBindingSettings kbs = c.iterator().next();
    assertNotNull("KBS should not be null", kbs);
    assertTrue("Wrong kbs impl", kbs instanceof KeyBindingSettingsImpl.Immutable);
}
 
Example 15
Source File: WhitespaceHighlighting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
WhitespaceHighlighting(JTextComponent c) {
    // Upon doc change all layers become recreated by infrastructure (no need to listen for doc change)
    this.doc = c.getDocument();
    this.docText = DocumentUtilities.getText(doc);
    doc.addDocumentListener(this);
    String mimeType = (String) doc.getProperty("mimeType"); //NOI18N
    if (mimeType == null) {
        mimeType = "";
    }
    Lookup lookup = MimeLookup.getLookup(mimeType);
    result = lookup.lookupResult(FontColorSettings.class);
    result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
    resultChanged(null); // Update attrs
}
 
Example 16
Source File: SourceCache.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Collection<SchedulerTask> createTasks () {
    List<SchedulerTask> tasks1 = null;
    Set<SchedulerTask> pendingTasks1 = null;
    if (tasks == null) {
        tasks1 = new ArrayList<SchedulerTask> ();
        pendingTasks1 = new HashSet<SchedulerTask> ();
        Lookup lookup = MimeLookup.getLookup (mimeType);
        Collection<? extends TaskFactory> factories = lookup.lookupAll (TaskFactory.class);
        Snapshot fakeSnapshot = null;
        for (TaskFactory factory : factories) {
            // #185586 - this is here in order not to create snapshots (a copy of file/doc text)
            // if there is no task that would really need it (eg. in C/C++ projects there is no parser
            // registered and no tasks will ever run on these files, even though there may be tasks
            // registered for all mime types
            Collection<? extends SchedulerTask> newTasks = factory.create(getParser() != null ? 
                getSnapshot() :
                fakeSnapshot == null ?
                    fakeSnapshot = SourceAccessor.getINSTANCE().createSnapshot(
                        "", //NOI18N
                        new int [] { 0 },
                        source,
                        MimePath.get (mimeType),
                        new int[][] {new int[] {0, 0}},
                        new int[][] {new int[] {0, 0}}) :
                    fakeSnapshot
            );
            if (newTasks != null) {
                tasks1.addAll (newTasks);
                pendingTasks1.addAll (newTasks);
            }
        }
        Collections.sort(tasks1, PRIORITY_ORDER);
    }
    synchronized (TaskProcessor.INTERNAL_LOCK) {
        if ((tasks == null) && (tasks1 != null)) {
            tasks = tasks1;
            pendingTasks = pendingTasks1;
        }
        if (tasks != null) {
            // this should be normal return in most cases
            return tasks;
        }
    }
    // recurse and hope
    return createTasks();
}
 
Example 17
Source File: CompletionTestCase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void completionQuery(PrintWriter  out,
        PrintWriter  log,
        JEditorPane  editor,
        boolean      unsorted,
        int queryType
        ) {
    BaseDocument doc = Utilities.getDocument(editor);
    SyntaxSupport support = doc.getSyntaxSupport();
    
    CompletionImpl completion = CompletionImpl.get();
    String mimeType = (String) doc.getProperty("mimeType");
    Lookup lookup = MimeLookup.getLookup(MimePath.get(mimeType));
    Collection<? extends CompletionProvider> col = lookup.lookupAll(CompletionProvider.class);
    JavaCompletionProvider  jcp = null;
    for (Iterator<? extends CompletionProvider> it = col.iterator(); it.hasNext();) {
        CompletionProvider completionProvider = it.next();
        if(completionProvider instanceof JavaCompletionProvider) jcp = (JavaCompletionProvider) completionProvider;
    }
    if(jcp==null) log.println("JavaCompletionProvider not found");
    CompletionTask task = jcp.createTask(queryType, editor);
    CompletionResultSetImpl result =  completion.createTestResultSet(task,queryType);
    task.query(result.getResultSet());
    EditorTestCase.waitMaxMilisForValue(5000, new ResultReadyResolver(result), Boolean.TRUE);
    if(!result.isFinished()) log.println("Result is not finished");
    List<? extends  CompletionItem> list = result.getItems();
    CompletionItem[] array = list.toArray(new CompletionItem[]{});
    if(!unsorted) {
        Arrays.sort(array, new Comparator<CompletionItem>(){
            public int compare(CompletionItem arg0, CompletionItem arg1) {
                Integer p1 = arg0.getSortPriority();
                Integer p2 = arg1.getSortPriority();
                if(p1.intValue()!=p2.intValue()) return p1.compareTo(p2);                                        
                String a0 = getStringFromCharSequence(arg0.getSortText());
                String a1 = getStringFromCharSequence(arg1.getSortText());                    
                return a0.compareTo(a1);
            }
        });
    }
    for (int i = 0; i < array.length; i++) {
        CompletionItem completionItem = array[i];
         out.println(getStringFromCharSequence(completionItem.getSortText()));                                    
    }
    /*Completion completion = ExtUtilities.getCompletion(editor);
    if (completion != null) {
        CompletionQuery completionQuery = completion.getQuery();
        if (completionQuery != null) {
            CompletionQuery.Result query = completionQuery.query(editor, editor.getCaret().getDot(), support);
     
            if (query != null) {
                List list = query.getData();
     
                if (list != null) {
     
                    String[] texts = new String[list.size()];
                    for (int cntr = 0; cntr < list.size(); cntr++) {
                        texts[cntr] = list.get(cntr).toString();
                    };
                    if (sort)
                        Arrays.sort(texts);
     
                    for (int cntr = 0; cntr < texts.length; cntr++) {
                        out.println(texts[cntr].toString());
                    };
                } else {
                    log.println("CompletionTest: query.getData() == null");
                    throw new IllegalStateException("CompletionTest: query.getData() == null");
                }
            } else {
                log.println("CompletionTest: completionQuery.query(pane, end, support) == null");
                throw new IllegalStateException("CompletionTest: completionQuery.query(pane, end, support) == null");
            }
        } else {
            log.println("CompletionTest: completion.getQuery() == null");
            throw new IllegalStateException("CompletionTest: completion.getQuery() == null");
        }
    } else {
        log.println("CompletionTest: ExtUtilities.getCompletion(pane) == null");
        throw new IllegalStateException("CompletionTest: ExtUtilities.getCompletion(pane) == null");
    }*/
}
 
Example 18
Source File: MimeLookupPopupItemsChangeTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Testing Base level popup items lookup and sorting */
@RandomlyFails // NB-Core-Build #4599: resultChangedCount is:2 instead of 1
public void testDynamicChangeInPopupFolders() throws Exception {
    final int resultChangedCount[] = new int[1];
    resultChangedCount[0] = 0;

    MimePath mp = MimePath.parse("text/x-java/text/xml/text/html");
    Lookup lookup = getLookup(mp);
    Lookup.Result result = lookup.lookup(new Template(PopupActions.class));
    result.allInstances(); // remove this line if issue #60010 is fixed
    LookupListener listener = new LookupListener(){
        public void resultChanged(LookupEvent ev){
            resultChangedCount[0]++;
        }
    };
    result.addLookupListener(listener);
    PopupActions actions = (PopupActions) lookup.lookup(PopupActions.class);
    assertTrue("PopupActions should be found", actions != null);
    List popupActions = actions.getPopupActions();
    int size = popupActions.size();
    assertTrue("Number of PopupActions found:"+size+" and should be:"+fsstruct.length, size == fsstruct.length);

    //delete RenameAction
    TestUtilities.deleteFile(getWorkDir(),
            "Editors/text/html/Popup/org-openide-actions-RenameAction.instance");
    checkPopupItemPresence(lookup, RenameAction.class, false);

    // check firing the change
    assertTrue(("resultChangedCount is:"+resultChangedCount[0]+" instead of 1"),resultChangedCount[0] == 1);
    resultChangedCount[0] = 0;
    
    //delete base CutAction
    TestUtilities.deleteFile(getWorkDir(),
            "Editors/Popup/org-openide-actions-CutAction.instance");

    checkPopupItemPresence(lookup, CutAction.class, false);

    // check firing the change
    assertTrue(("resultChangedCount is:"+resultChangedCount[0]+" instead of 1"),resultChangedCount[0] == 1);
    resultChangedCount[0] = 0;
    
    //simulate module installation, new action will be added
    TestUtilities.createFile(getWorkDir(), 
            "Editors/Popup/org-openide-actions-FindAction.instance"); //NOI18N      

    checkPopupItemPresence(lookup, FindAction.class, true);

    // check firing the change
    assertTrue(("resultChangedCount is:"+resultChangedCount[0]+" instead of 1"),resultChangedCount[0] == 1);
    resultChangedCount[0] = 0;
    
    //simulate module installation, new action will be added
    TestUtilities.createFile(getWorkDir(), 
            "Editors/text/x-java/text/xml/text/html/Popup/org-openide-actions-ReplaceAction.instance"); //NOI18N      

    checkPopupItemPresence(lookup, ReplaceAction.class, true);
    
    //ReplaceAction was created in the uppermost folder
    // let's try it is missing in the lower lookup
    mp = MimePath.get(MimePath.get("text/x-java"), "text/xml");
    lookup = getLookup(mp);
    checkPopupItemPresence(lookup, ReplaceAction.class, false);        
    checkPopupItemPresence(lookup, FindAction.class, true);
    
    // lookup for ReplaceAction in the folder that doesn't exist
    lookup = MimeLookup.getLookup("text/html"); //NOI18N
    checkPopupItemPresence(lookup, ReplaceAction.class, false); 
    // create folder with ReplaceAction
    TestUtilities.createFile(getWorkDir(), 
            "Editors/text/html/Popup/org-openide-actions-ReplaceAction.instance"); //NOI18N      

    checkPopupItemPresence(lookup, ReplaceAction.class, true);
    
}
 
Example 19
Source File: EditorActionUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Preferences getGlobalPreferences() {
    Lookup globalMimeLookup = MimeLookup.getLookup(MimePath.EMPTY);
    return (globalMimeLookup != null) ? globalMimeLookup.lookup(Preferences.class) : null;
}
 
Example 20
Source File: PaletteSwitch.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/** 
 * Finds appropriate PaletteController for given mime type.
 *
 * @param mimeType Mime type to check for associated palette content.
 * 
 * @return PaletteController that is associated with the given mime type and that should
 * be displayed in the Common Palette when an editor window with the given mime type is activated.
 * @since 1.10
 */
PaletteController getPaletteFromMimeType( String mimeType ) {
    MimePath path = MimePath.get( mimeType );
    Lookup lkp = MimeLookup.getLookup( path );
    return lkp.lookup( PaletteController.class );
}