public void testFindTestSources() throws Exception {
   NbModuleProject p = generateStandaloneModule("p");
   FileObject test = p.getTestSourceDirectory("unit");
   FileObject oneTest = FileUtil.createData(test, "p/OneTest.java");
   FileObject r = FileUtil.createData(test, "p/r.png");
   FileObject otherTest = FileUtil.createData(test, "p/OtherTest.java");
   FileObject pkg = test.getFileObject("p");
   FileObject thirdTest = FileUtil.createData(test, "p2/ThirdTest.java");
   ModuleActions a = new ModuleActions(p);
   assertEquals("null", String.valueOf(a.findTestSources(Lookup.EMPTY, false)));
   assertEquals(
       "unit:p/OneTest.java",
       String.valueOf(a.findTestSources(Lookups.singleton(oneTest), false)));
   assertEquals(
       "unit:p/OneTest.java,p/OtherTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(oneTest, otherTest), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(pkg), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(r), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.fixed(oneTest, r), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookup.EMPTY, true)));
   assertEquals(
       "unit:p/OneTest.java", String.valueOf(a.findTestSources(Lookups.singleton(oneTest), true)));
   assertEquals(
       "unit:p/OneTest.java,p/OtherTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(oneTest, otherTest), true)));
   assertEquals("unit:p/**", String.valueOf(a.findTestSources(Lookups.singleton(pkg), true)));
   assertEquals(
       "unit:p/**,p2/ThirdTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(pkg, thirdTest), true)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(r), true)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.fixed(oneTest, r), true)));
 }
Example #2
0
 public static Lookup createAdditionalLookup(final Lookup lookup) {
   final Project project = lookup.lookup(Project.class);
   final ProjectType projectType = lookup(project);
   if (projectType != null) {
     return Lookups.fixed(new Object[] {new ProjectOpenedHookImp(projectType, project)});
   } else {
     return Lookups.fixed(new Object[0]);
   }
 }
 @Override
 public Lookup getLookup() {
   if (this.lookup == null) {
     this.lookup = Lookups.fixed(this, new Info(), new RIACropModelDatasetLV(this));
   }
   return this.lookup;
 }
Example #4
0
  @Override
  @SuppressWarnings("unchecked")
  public TopComponent getTopComponent() {
    // Loading the multiview windows:
    FileObject multiviewsFolder = FileUtil.getConfigFile("skitmultiviews");
    FileObject[] kids = multiviewsFolder.getChildren();
    MultiViewDescription[] descriptionArray = new MultiViewDescription[kids.length];
    ArrayList<MultiViewDescription> listOfDescs = new ArrayList<MultiViewDescription>();

    for (FileObject kid : FileUtil.getOrder(Arrays.asList(kids), true)) {
      MultiViewDescription attribute = (MultiViewDescription) kid.getAttribute("multiview");

      if (attribute instanceof ContextAwareInstance) {
        Lookup lu = Lookups.fixed(this);
        attribute =
            ((ContextAwareInstance<MultiViewDescription>) attribute).createContextAwareInstance(lu);
      }

      listOfDescs.add(attribute);
    }

    for (int i = 0; i < listOfDescs.size(); i++) {
      descriptionArray[i] = listOfDescs.get(i);
    }

    CloneableTopComponent ctc =
        MultiViewFactory.createCloneableMultiView(descriptionArray, descriptionArray[0]);

    return ctc;
  }
 public synchronized void propertyChange(PropertyChangeEvent event) {
   if (propertyChanging) {
     // Avoid an infinite loop whereby changing the lookup contents
     // causes the activated nodes to change, which calls us again.
     return;
   }
   propertyChanging = true;
   try {
     Node[] newNodes = (Node[]) event.getNewValue();
     if (newNodes == null || newNodes.length == 0) {
       setLookups(
           new Lookup[] {
             new ProxyLookup(lookups),
             new NoNodeLookup(delegate.getLookup()),
             Lookups.singleton(delegate)
           });
     } else {
       Lookup[] newNodeLookups = new Lookup[newNodes.length];
       for (int i = 0; i < newNodes.length; i++) {
         newNodeLookups[i] = new NoNodeLookup(newNodes[i].getLookup());
       }
       setLookups(
           new Lookup[] {
             new ProxyLookup(lookups),
             new ProxyLookup(newNodeLookups),
             Lookups.fixed((Object[]) newNodes)
           });
     }
   } finally {
     propertyChanging = false;
   }
 }
  DefaultPraxisProject(FileObject directory, FileObject projectFile, ProjectState state)
      throws IOException {
    this.directory = directory;
    this.projectFile = projectFile;
    this.state = state;
    properties = parseProjectFile(projectFile);
    propsListener = new PropertiesListener();
    properties.addPropertyChangeListener(propsListener);

    Lookup base =
        Lookups.fixed(
            new Object[] {
              this,
              properties,
              new Info(),
              new ActionImpl(),
              state,
              new PraxisCustomizerProvider(this),
              new PraxisLogicalViewProvider(this),
              new BaseTemplates(),
              UILookupMergerSupport.createPrivilegedTemplatesMerger()
            });

    this.lookup = LookupProviderSupport.createCompositeLookup(base, LOOKUP_PATH);
    helperListener = new HelperListener();
    ProjectHelper.getDefault()
        .addPropertyChangeListener(
            WeakListeners.propertyChange(helperListener, ProjectHelper.getDefault()));
  }
 @Override
 public void run() {
   try {
     progressHandle.start();
     progressHandle.progress("Creating dataset");
     List<INamedElementProvider<? extends IChromatogram2D, ? extends IScan2D>> providers =
         new ArrayList<>();
     if (!(chromatogram.getChromatogram() instanceof IChromatogram2D)) {
       throw new IllegalArgumentException("Action only of 2D chromatograms!");
     }
     providers.add(
         new Chromatogram2DElementProvider(
             chromatogram.getDisplayName(), (IChromatogram2D) chromatogram.getChromatogram()));
     final Chromatogram2DDataset ds =
         new Chromatogram2DDataset(providers, Lookups.fixed(chromatogram, project));
     onEdt(
         new Runnable() {
           @Override
           public void run() {
             final Chromatogram2DViewTopComponent jtc =
                 new Chromatogram2DViewTopComponent(dobj, ds);
             jtc.open();
             jtc.requestActive();
           }
         });
   } finally {
     progressHandle.finish();
   }
 }
  public void showCustomizer(String preselectedCategory, String preselectedSubCategory) {

    Dialog dialog = project2Dialog.get(project);
    if (dialog != null) {
      dialog.setVisible(true);
      return;
    } else {
      SharedRubyProjectProperties uiProperties =
          createUiProperties(project, updateHelper, evaluator, refHelper, genFileHelper);
      Lookup context =
          Lookups.fixed(
              new Object[] {
                project,
                uiProperties,
                new SubCategoryProvider(preselectedCategory, preselectedSubCategory)
              });

      OptionListener listener = new OptionListener(project, uiProperties);
      dialog =
          ProjectCustomizer.createCustomizerDialog(
              getCustomizerFolderPath(), context, preselectedCategory, listener, null);
      dialog.addWindowListener(listener);
      dialog.setTitle(
          MessageFormat.format(
              NbBundle.getMessage(
                  BaseRubyCustomizerProvider.class, "LBL_Customizer_Title"), // NOI18N
              new Object[] {ProjectUtils.getInformation(project).getDisplayName()}));

      project2Dialog.put(project, dialog);
      dialog.setVisible(true);
    }
  }
  @Override
  public Lookup createAdditionalLookup(Lookup lkp) {
    final Project j2seProject = lkp.lookup(Project.class);

    return Lookups.fixed(
        new KotlinPrivilegedTemplates(),
        new J2SEExtendedClassPathProvider(j2seProject),
        new J2SEProjectOpenedHook(j2seProject));
  }
  @ServiceProvider(service = MimeDataProvider.class)
  public static final class JavacParserProvider implements MimeDataProvider {

    private Lookup javaLookup =
        Lookups.fixed(new JavacParserFactory(), new JavaCustomIndexer.Factory());

    @Override
    public Lookup getLookup(MimePath mimePath) {
      if (mimePath.getPath().endsWith(JavacParser.MIME_TYPE)) {
        return javaLookup;
      }

      return Lookup.EMPTY;
    }
  }
  private Lookup getDefaultLookup() {
    // The Lookup is not created in the constructor, so that we do not need
    // to share "this" in the constructor.
    Lookup result = defaultLookupRef.get();
    if (result == null) {
      GradleAuxiliaryConfiguration auxConfig = new GradleAuxiliaryConfiguration(this);

      Lookup newLookup =
          Lookups.fixed(
              new Object[] {
                this,
                state, // allow outside code to mark the project as needing saving
                NbGradleSingleProjectConfigProvider.create(this),
                new GradleProjectInformation(this),
                new GradleProjectLogicalViewProvider(this),
                new GradleActionProvider(this),
                new GradleSharabilityQuery(this),
                new GradleSourceEncodingQuery(this),
                new GradleCustomizer(this),
                new OpenHook(),
                auxConfig,
                new GradleAuxiliaryProperties(auxConfig),
                new GradleTemplateAttrProvider(this),
                new DefaultGradleCommandExecutor(this),
                ProjectPropertiesApi.buildPlatform(getProperties().getPlatform()),
                ProjectPropertiesApi.scriptPlatform(getProperties().getScriptPlatform()),
                ProjectPropertiesApi.sourceEncoding(getProperties().getSourceEncoding()),
                ProjectPropertiesApi.sourceLevel(getProperties().getSourceLevel()),
                new ProjectInfoManager(),

                // FileOwnerQueryImplementation cannot be added to the project's
                // lookup, since NetBeans will ignore it. It must be added
                // using the ServiceProviders annotation. Our implementation is
                // GradleFileOwnerQuery and is added using the annotation.
              });

      if (defaultLookupRef.compareAndSet(null, newLookup)) {
        for (ProjectInitListener listener : newLookup.lookupAll(ProjectInitListener.class)) {
          listener.onInitProject();
        }

        loadProject(true, true);
      }
      result = defaultLookupRef.get();
    }
    return result;
  }
 @Override
 public void showCustomizer() {
   Dialog dialog =
       ProjectCustomizer.createCustomizerDialog(
           // Path to layer folder:
           CUSTOMIZER_FOLDER_PATH,
           // Lookup, which must contain, at least, the Project:
           Lookups.fixed(project),
           // Preselected category:
           "",
           // OK button listener:
           new OKOptionListener(),
           // HelpCtx for Help button of dialog:
           null);
   dialog.setTitle(ProjectUtils.getInformation(project).getDisplayName());
   dialog.setVisible(true);
 }
  private void setExtensions(List<GradleProjectExtension> extensions) {
    List<GradleProjectExtension> newExtensions =
        Collections.unmodifiableList(new ArrayList<GradleProjectExtension>(extensions));
    List<Lookup> allLookups = new ArrayList<Lookup>(newExtensions.size() + 1);
    List<ProjectExtensionRef> newExtensionRefs =
        new ArrayList<ProjectExtensionRef>(newExtensions.size());

    allLookups.add(getDefaultLookup());
    for (final GradleProjectExtension extension : newExtensions) {
      allLookups.add(extension.getExtensionLookup());
      newExtensionRefs.add(new ProjectExtensionRef(extension));
    }

    this.extensionsOnLookup = Lookups.fixed(newExtensions.toArray());
    this.extensionRefs = Collections.unmodifiableList(newExtensionRefs);
    getMainLookup().replaceLookups(allLookups);
  }
    private Map<String, Lookup> createLookups(FetchedProjectModels projectModels) {
      GenericProjectProperties genericProperties =
          projectModels.getProjectDef().getMainProject().getGenericProperties();

      Map<String, Lookup> result = CollectionUtils.newHashMap(extensions.size());
      for (NbGradleExtensionRef extension : extensions) {
        String extensionName = extension.getName();

        List<Object> models = new ArrayList<>();
        addProjectInfoResults(projectModels, extension, models);
        addAllNullSafe(models, modelFetcher.getToolingModelsForExtension(extension, projectModels));
        models.add(genericProperties);

        result.put(extensionName, Lookups.fixed(models.toArray()));
      }

      return result;
    }
 private void initialize() {
   // create and associate lookup
   ProxyLookup lookup =
       new ProxyLookup(
           new Lookup[] {
             Lookups.fixed(
                 new Object[] {
                   // Need ActionMap in lookup so editor actions work.
                   getActionMap(),
                   // Need the data object registered in the lookup so that the
                   // projectui code will close our open editor windows when the
                   // project is closed.
                   mDataObject
                 }),
             mDataObject.getNodeDelegate().getLookup(),
           });
   associateLookup(lookup);
 }
  @Override
  protected Node createNodeForKey(final Message key) {
    Node node =
        new AbstractNode(
            Children.LEAF,
            Lookups.fixed(
                key,
                new OpenCookie() {

                  @Override
                  public void open() {
                    MsgDetailsTopComponent win = MsgDetailsTopComponent.findInstance();
                    win.open();
                  }
                })) {

          @Override
          public SystemAction[] getActions() {
            SystemAction[] saa = new SystemAction[2];
            saa[0] = SystemAction.get(OpenAction.class);
            saa[1] = SystemAction.get(DeleteAction.class);
            return saa;
          }

          @Override
          public boolean canDestroy() {
            return true;
          }

          @Override
          public void destroy() throws IOException {
            MessageBoardClient client = new MessageBoardClient();
            client.deleteMessage(key);
            ExplorerTopComponent.refresh();
          }
        };
    node.setDisplayName(key.getMessage());
    node.setShortDescription(key.getCreated().toString());
    return node;
  }
 public OtherResourcesNode(TaskElement taskElement, OtherResourceSet resourceSet) {
   super(new ResourcesChildern(taskElement, resourceSet), Lookups.fixed(taskElement, resourceSet));
   this.resourceSet = resourceSet;
   setDisplayName(resourceSet.getName());
 }
 /**
  * @param node
  * @param keys
  * @throws IntrospectionException
  */
 public DirObjectNode(Node node, DirectoryObject object) {
   super(
       Children.LEAF,
       new ProxyLookup(new Lookup[] {Lookups.fixed(new Object[] {object}), node.getLookup()}));
 }
 /**
  * Creates a new instance of ExtractInterfaceRefactoring
  *
  * @param sourceType Type the members of which should be extracted into an interface.
  */
 public ExtractInterfaceRefactoring(TreePathHandle sourceType) {
   super(Lookups.fixed(sourceType));
 }
Example #20
0
 private static Lookup buildLookup(VisualClassPathItem vcpi, JbiProject project) {
   return Lookups.fixed(
       new Object[] {
         vcpi, project,
       });
 }
Example #21
0
 public Lookup getLookup() {
   return Lookups.fixed(this);
 }
    @Override
    public void run() {
      try {
        progressHandle.start(chromatograms.size());
        int workunit = 0;
        boolean is1D = true;
        for (IChromatogramDescriptor descr : chromatograms) {
          //            System.out.println("descr: "+(descr instanceof IChromatogram1D));
          if (!(descr.getChromatogram() instanceof IChromatogram1D)) {
            is1D = false;
          }
        }
        if (is1D) {
          Logger.getLogger(getClass().getName()).info("Creating 1D data providers and dataset.");
          List<INamedElementProvider<? extends IChromatogram1D, ? extends IScan>> providers =
              new ArrayList<>(chromatograms.size());
          InstanceContent ic = new InstanceContent();
          for (IChromatogramDescriptor descr : chromatograms) {
            progressHandle.progress("Creating data set for " + descr.getDisplayName(), workunit++);
            providers.add(
                new Chromatogram1DElementProvider(
                    descr.getDisplayName(), (IChromatogram1D) descr.getChromatogram()));
            ic.add(descr);
          }

          final Chromatogram1DDataset ds =
              new Chromatogram1DDataset(
                  providers,
                  Lookups.fixed(
                      new AbstractLookup(ic),
                      Utilities.actionsGlobalContext().lookup(IChromAUIProject.class)));
          onEdt(
              new Runnable() {
                @Override
                public void run() {
                  Chromatogram1DViewTopComponent topComponent =
                      new Chromatogram1DViewTopComponent();
                  topComponent.open();
                  topComponent.initialize(
                      Utilities.actionsGlobalContext().lookup(IChromAUIProject.class),
                      chromatograms,
                      ds);
                  topComponent.requestActive();
                  //                            topComponent.load();
                }
              });
        } else {
          Logger.getLogger(getClass().getName()).info("Creating 2D data providers and dataset.");
          List<INamedElementProvider<? extends IChromatogram1D, ? extends IScan>> providers =
              new ArrayList<>(chromatograms.size());
          InstanceContent ic = new InstanceContent();
          for (IChromatogramDescriptor descr : chromatograms) {
            progressHandle.progress("Creating data set for " + descr.getDisplayName(), workunit++);
            providers.add(
                new Chromatogram1DElementProvider(
                    descr.getDisplayName(), (IChromatogram2D) descr.getChromatogram()));
            ic.add(descr);
          }

          final Chromatogram1DDataset ds =
              new Chromatogram1DDataset(
                  providers,
                  Lookups.fixed(
                      new AbstractLookup(ic),
                      Utilities.actionsGlobalContext().lookup(IChromAUIProject.class)));
          onEdt(
              new Runnable() {
                @Override
                public void run() {
                  Chromatogram1DViewTopComponent topComponent =
                      new Chromatogram1DViewTopComponent();
                  topComponent.open();
                  topComponent.initialize(
                      Utilities.actionsGlobalContext().lookup(IChromAUIProject.class),
                      chromatograms,
                      ds);
                  //                            topComponent.load();
                }
              });
        }
      } finally {
        progressHandle.finish();
      }
    }
 public ExceptionNode(@Nonnull Exception ex) {
   super(Children.LEAF, Lookups.fixed(ex, internalCounter++));
 }
/* package */ final class NbEditorToolBar extends ToolbarWithOverflow {

  // -J-Dorg.netbeans.modules.editor.NbEditorToolBar.level=FINE
  private static final Logger LOG = Logger.getLogger(NbEditorToolBar.class.getName());

  /** Flag for testing the sorting support by debugging messages. */
  private static final boolean debugSort =
      Boolean.getBoolean("netbeans.debug.editor.toolbar.sort"); // NOI18N

  private static final Insets BUTTON_INSETS = new Insets(2, 1, 0, 1);

  // An empty lookup. Can't use Lookup.EMPTY as this can be returned by clients.
  private static final Lookup NO_ACTION_CONTEXT = Lookups.fixed();

  private FileChangeListener moduleRegListener;

  /**
   * Shared mouse listener used for setting the border painting property of the toolbar buttons and
   * for invoking the popup menu.
   */
  private static final MouseListener sharedMouseListener =
      new org.openide.awt.MouseUtils.PopupMouseAdapter() {
        public @Override void mouseEntered(MouseEvent evt) {
          Object src = evt.getSource();

          if (src instanceof AbstractButton) {
            AbstractButton button = (AbstractButton) evt.getSource();
            if (button.isEnabled()) {
              button.setContentAreaFilled(true);
              button.setBorderPainted(true);
            }
          }
        }

        public @Override void mouseExited(MouseEvent evt) {
          Object src = evt.getSource();
          if (src instanceof AbstractButton) {
            AbstractButton button = (AbstractButton) evt.getSource();
            removeButtonContentAreaAndBorder(button);
          }
        }

        protected void showPopup(MouseEvent evt) {}
      };

  /** Text component for which the toolbar gets constructed. */
  private Reference componentRef;

  private boolean presentersAdded;

  private boolean addListener = true;

  private static final String NOOP_ACTION_KEY = "noop-action-key"; // NOI18N
  private static final Action NOOP_ACTION = new NoOpAction();

  private final Lookup.Result<KeyBindingSettings> lookupResult;
  private final LookupListener keybindingsTracker =
      new LookupListener() {
        public void resultChanged(LookupEvent ev) {
          refreshToolbarButtons();
        }
      };

  private final Preferences preferences;
  private final PreferenceChangeListener prefsTracker =
      new PreferenceChangeListener() {
        public void preferenceChange(PreferenceChangeEvent evt) {
          String settingName = evt == null ? null : evt.getKey();
          if (settingName == null || SimpleValueNames.TOOLBAR_VISIBLE_PROP.equals(settingName)) {
            refreshToolbarButtons();
          }
        }
      };

  public NbEditorToolBar(JTextComponent component) {
    this.componentRef = new WeakReference(component);

    setFloatable(false);
    // mkleint - instead of here, assign the border in CloneableEditor and MultiView module.
    //        // special border installed by core or no border if not available
    //        Border b = (Border)UIManager.get("Nb.Editor.Toolbar.border"); //NOI18N
    //        setBorder(b);
    addMouseListener(sharedMouseListener);

    installModulesInstallationListener();
    installNoOpActionMappings();

    lookupResult =
        MimeLookup.getLookup(DocumentUtilities.getMimeType(component))
            .lookupResult(KeyBindingSettings.class);
    lookupResult.addLookupListener(
        WeakListeners.create(LookupListener.class, keybindingsTracker, lookupResult));

    String mimeType = DocumentUtilities.getMimeType(component);
    preferences =
        MimeLookup.getLookup(mimeType == null ? MimePath.EMPTY : MimePath.parse(mimeType))
            .lookup(Preferences.class);
    preferences.addPreferenceChangeListener(
        WeakListeners.create(PreferenceChangeListener.class, prefsTracker, preferences));

    refreshToolbarButtons();
    setBorderPainted(true);
  }

  @Override
  public void addNotify() {
    super.addNotify();
    // In GTK L&F the border of the toolbar looks raised. It does not help to set null border
    // nor setting EmptyBorder helps. Curent solution is to set one-pixel LineBorder
    // which overwrites the "raising line".
    setBorder(new LineBorder(getBackground(), 1));
  }

  // issue #69642
  private void installNoOpActionMappings() {
    InputMap im = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    // cut
    KeyStroke[] keys =
        findEditorKeys(
            DefaultEditorKit.cutAction,
            KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));
    for (int i = 0; i < keys.length; i++) {
      im.put(keys[i], NOOP_ACTION_KEY);
    }
    // copy
    keys =
        findEditorKeys(
            DefaultEditorKit.copyAction,
            KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
    for (int i = 0; i < keys.length; i++) {
      im.put(keys[i], NOOP_ACTION_KEY);
    }
    // delete
    keys =
        findEditorKeys(
            DefaultEditorKit.deleteNextCharAction,
            KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); // NOI18N
    for (int i = 0; i < keys.length; i++) {
      im.put(keys[i], NOOP_ACTION_KEY);
    }
    // paste
    keys =
        findEditorKeys(
            DefaultEditorKit.pasteAction,
            KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));
    for (int i = 0; i < keys.length; i++) {
      im.put(keys[i], NOOP_ACTION_KEY);
    }

    getActionMap().put(NOOP_ACTION_KEY, NOOP_ACTION);
  }

  /**
   * See issue #57773 for details. Toolbar should be updated with possible changes after module
   * install/uninstall
   */
  private void installModulesInstallationListener() {
    moduleRegListener =
        new FileChangeAdapter() {
          public @Override void fileChanged(FileEvent fe) {
            // some module installed/uninstalled. Refresh toolbar content
            Runnable r =
                new Runnable() {
                  public void run() {
                    if (isToolbarVisible()) {
                      checkPresentersRemoved();
                      checkPresentersAdded();
                    }
                  }
                };
            Utilities.runInEventDispatchThread(r);
          }
        };

    FileObject moduleRegistry = FileUtil.getConfigFile("Modules"); // NOI18N

    if (moduleRegistry != null) {
      moduleRegistry.addFileChangeListener(
          FileUtil.weakFileChangeListener(moduleRegListener, moduleRegistry));
    }
  }

  public @Override String getUIClassID() {
    // For GTK and Aqua look and feels, we provide a custom toolbar UI -
    // but we cannot override this globally or it will cause problems for
    // the form editor & other things
    if (UIManager.get("Nb.Toolbar.ui") != null) { // NOI18N
      return "Nb.Toolbar.ui"; // NOI18N
    } else {
      return super.getUIClassID();
    }
  }

  public @Override String getName() {
    // Required for Aqua L&F toolbar UI
    return "editorToolbar"; // NOI18N
  }

  public @Override void setUI(ToolBarUI ui) {
    addListener = false;
    super.setUI(ui);
    addListener = true;
  }

  public @Override synchronized void addMouseListener(MouseListener l) {
    if (addListener) {
      super.addMouseListener(l);
    }
  }

  public @Override synchronized void addMouseMotionListener(MouseMotionListener l) {
    if (addListener) {
      super.addMouseMotionListener(l);
    }
  }

  private boolean isToolbarVisible() {
    return preferences.getBoolean(
        SimpleValueNames.TOOLBAR_VISIBLE_PROP, EditorPreferencesDefaults.defaultToolbarVisible);
  }

  private void refreshToolbarButtons() {
    final JTextComponent c = getComponent();
    final boolean visible = isToolbarVisible();

    Runnable r =
        new Runnable() {
          public void run() {
            if (visible) {
              checkPresentersAdded();
              if (c != null) { // #62487
                installNoOpActionMappings();
                Map<String, MultiKeyBinding> keybsMap = getKeyBindingMap();

                Component comps[] = getComponents();
                for (int i = 0; i < comps.length; i++) {
                  Component comp = comps[i];
                  if (comp instanceof JButton) {
                    JButton button = (JButton) comp;
                    Action action = button.getAction();
                    if (action == null) {
                      continue;
                    }
                    String actionName = (String) action.getValue(Action.NAME);
                    if (actionName == null) {
                      continue;
                    }

                    String tooltipText = button.getToolTipText();
                    if (tooltipText != null) {
                      int index = tooltipText.indexOf("("); // NOI18N
                      if (index > 0) {
                        tooltipText = tooltipText.substring(0, index - 1);
                      }
                    }

                    MultiKeyBinding mkb = keybsMap.get(actionName);
                    if (mkb != null) {
                      button.setToolTipText(tooltipText + " (" + getMnemonic(mkb) + ")"); // NOI18N
                    } else {
                      button.setToolTipText(tooltipText);
                    }
                  }
                }
              }
            } else {
              checkPresentersRemoved();
            }
            setVisible(visible);
          }
        };

    Utilities.runInEventDispatchThread(r);
  }

  private void checkPresentersAdded() {
    if (!presentersAdded) {
      presentersAdded = true;
      addPresenters();
    }
  }

  private void checkPresentersRemoved() {
    presentersAdded = false;
    removeAll();
  }

  /**
   * Utility method for getting the mnemonic of the multi key binding.
   *
   * @param binding multi key binding
   * @return mnemonic for the binding.
   */
  private static String getMnemonic(MultiKeyBinding binding) {
    StringBuilder sb = new StringBuilder();
    for (KeyStroke keyStroke : binding.getKeyStrokeList()) {
      if (sb.length() > 0) {
        sb.append(' '); // NOI18N
      }
      sb.append(getKeyMnemonic(keyStroke));
    }
    return sb.toString();
  }

  /**
   * Get the mnemonic for a keystroke.
   *
   * @param key a keystroke
   * @return mnemonic of tghe keystroke.
   */
  private static String getKeyMnemonic(KeyStroke key) {
    String sk = org.openide.util.Utilities.keyToString(key);
    StringBuffer sb = new StringBuffer();
    int mods = key.getModifiers();
    if ((mods & KeyEvent.CTRL_MASK) != 0) {
      sb.append("Ctrl+"); // NOI18N
    }
    if ((mods & KeyEvent.ALT_MASK) != 0) {
      sb.append("Alt+"); // NOI18N
    }
    if ((mods & KeyEvent.SHIFT_MASK) != 0) {
      sb.append("Shift+"); // NOI18N
    }
    if ((mods & KeyEvent.META_MASK) != 0) {
      sb.append("Meta+"); // NOI18N
    }

    int i = sk.indexOf('-'); // NOI18N
    if (i != -1) {
      sk = sk.substring(i + 1);
    }
    sb.append(sk);

    return sb.toString();
  }

  private Map<String, MultiKeyBinding> getKeyBindingMap() {
    Map<String, MultiKeyBinding> map = new HashMap<String, MultiKeyBinding>();
    List<? extends MultiKeyBinding> list = getKeyBindingList();

    for (MultiKeyBinding mkb : list) {
      map.put(mkb.getActionName(), mkb);
    }

    return map;
  }

  private List<? extends MultiKeyBinding> getKeyBindingList() {
    Collection<? extends KeyBindingSettings> c = lookupResult.allInstances();
    if (!c.isEmpty()) {
      KeyBindingSettings kbs = c.iterator().next();
      return kbs.getKeyBindings();
    } else {
      return Collections.<MultiKeyBinding>emptyList();
    }
  }

  public static void initKeyBindingList(String mimeType) {
    Collection<? extends KeyBindingSettings> c =
        MimeLookup.getLookup(mimeType).lookupAll(KeyBindingSettings.class);
    if (!c.isEmpty()) {
      // just do something with the collection
      c.iterator().next();
    }
  }

  private JTextComponent getComponent() {
    return (JTextComponent) componentRef.get();
  }

  /**
   * Add the presenters (usually buttons) for the contents of the toolbar contained in the base and
   * mime folders.
   *
   * @param baseFolder folder that corresponds to "text/base"
   * @param mimeFolder target mime type folder.
   * @param toolbar toolbar being constructed.
   */
  private void addPresenters() {
    JTextComponent c = getComponent();
    String mimeType = c == null ? null : NbEditorUtilities.getMimeType(c);

    if (mimeType == null) {
      return; // Probably no component or it's not loaded properly
    }

    List<? extends MultiKeyBinding> keybindings = null;
    Lookup actionContext = null;
    List items = ToolbarActionsProvider.getToolbarItems(mimeType);

    // COMPAT: The ToolbarsActionsProvider treats 'text/base' in a special way. It
    // will list only items registered for this particular mime type, but won't
    // inherit anything else. The 'text/base' is normally empty, but could be
    // used by some legacy code.
    List oldTextBaseItems = ToolbarActionsProvider.getToolbarItems("text/base"); // NOI18N
    if (oldTextBaseItems.size() > 0) {
      items = new ArrayList(items);
      items.add(new JSeparator());
      items.addAll(oldTextBaseItems);
    }

    for (Object item : items) {
      LOG.log(Level.FINE, "Adding item {0}", item); // NOI18N

      if (item == null || item instanceof JSeparator) {
        addSeparator();
        continue;
      }

      if (item instanceof String) {
        EditorKit kit = c.getUI().getEditorKit(c);
        if (kit instanceof BaseKit) {
          Action a = ((BaseKit) kit).getActionByName((String) item);
          if (a != null) {
            if (LOG.isLoggable(Level.FINE)) {
              LOG.log(
                  Level.FINE,
                  "Item {0} converted to an editor action {1}",
                  new Object[] {item, s2s(a)}); // NOI18N
            }
            item = a;
          } else {
            // unknown action
            continue;
          }
        }
      }

      if (item instanceof ContextAwareAction) {
        if (actionContext == null) {
          Lookup context = createActionContext(c);
          actionContext = context == null ? NO_ACTION_CONTEXT : context;
        }

        if (actionContext != NO_ACTION_CONTEXT) {
          Action caa = ((ContextAwareAction) item).createContextAwareInstance(actionContext);

          // use the context aware instance only if it implements Presenter.Toolbar
          // or is a Component else fall back to the original object
          if (caa instanceof Presenter.Toolbar || caa instanceof Component) {
            if (LOG.isLoggable(Level.FINE)) {
              LOG.log(
                  Level.FINE,
                  "Item {0} converted to a context-aware Action {1}",
                  new Object[] {s2s(item), s2s(caa)}); // NOI18N
            }
            item = caa;
          }
        }
      }

      if (item instanceof Presenter.Toolbar) {
        Component presenter = ((Presenter.Toolbar) item).getToolbarPresenter();
        if (presenter != null) {
          if (LOG.isLoggable(Level.FINE)) {
            LOG.log(
                Level.FINE,
                "Item {0} converted to a Presenter.Toolbar {1}",
                new Object[] {s2s(item), s2s(presenter)}); // NOI18N
          }
          item = presenter;
        }
      }

      if (item instanceof Component) {
        add((Component) item);
        if (LOG.isLoggable(Level.FINE)) {
          LOG.log(Level.FINE, "Adding component {0}", s2s(item)); // NOI18N
        }
      } else if (item instanceof Action) {
        // Wrap action to execute on the proper text component
        // because the default fallback in TextAction.getTextComponent()
        // might not work properly if the focus was switched
        // to e.g. a JTextField and then toolbar was clicked.
        Action a = new WrapperAction(componentRef, (Action) item);

        // Try to find an icon if not present
        updateIcon(a);

        // Add the action and let the JToolbar to creat a presenter for it
        item = add(a);
        if (LOG.isLoggable(Level.FINE)) {
          LOG.log(
              Level.FINE, "Adding action {0} as {1}", new Object[] {s2s(a), s2s(item)}); // NOI18N
        }
      } else {
        // Some sort of crappy item -> ignore
        if (LOG.isLoggable(Level.FINE)) {
          LOG.log(Level.FINE, "Ignoring item {0}", s2s(item)); // NOI18N
        }
        continue;
      }

      if (item instanceof AbstractButton) {
        AbstractButton button = (AbstractButton) item;
        processButton(button);

        if (keybindings == null) {
          List<? extends MultiKeyBinding> l = getKeyBindingList();
          keybindings = l == null ? Collections.<MultiKeyBinding>emptyList() : l;
        }
        updateTooltip(button, keybindings);
        if (LOG.isLoggable(Level.FINE)) {
          LOG.log(Level.FINE, "Special treatment for button {0}", s2s(item)); // NOI18N
        }
      }
    }
  }

  // XXX: this is actually wierd, because it changes the action's properties
  // perhaps we should just update the presenter, but should not touch the
  // action itself
  private static void updateIcon(Action a) {
    Object icon = a.getValue(Action.SMALL_ICON);
    if (icon == null) {
      String resourceId = (String) a.getValue(BaseAction.ICON_RESOURCE_PROPERTY);
      if (resourceId != null) {
        Image img = ImageUtilities.loadImage(resourceId);
        if (img != null) {
          a.putValue(Action.SMALL_ICON, new ImageIcon(img));
        }
      }
    }
  }

  private static void updateTooltip(AbstractButton b, List<? extends MultiKeyBinding> keybindings) {
    Action a = b.getAction();
    String actionName = a == null ? null : (String) a.getValue(Action.NAME);

    if (actionName == null) {
      // perhaps no action at all
      return;
    }

    for (MultiKeyBinding mkb : keybindings) {
      if (actionName.equals(mkb.getActionName())) {
        b.setToolTipText(b.getToolTipText() + " (" + getMnemonic(mkb) + ")"); // NOI18N
        break; // multiple shortcuts ?
      }
    }
  }

  /** Not private because of the tests. */
  static Lookup createActionContext(JTextComponent c) {
    Lookup nodeLookup = null;
    DataObject dobj = (c != null) ? NbEditorUtilities.getDataObject(c.getDocument()) : null;
    if (dobj != null && dobj.isValid()) {
      nodeLookup = dobj.getNodeDelegate().getLookup();
    }

    Lookup ancestorLookup = null;
    for (java.awt.Component comp = c; comp != null; comp = comp.getParent()) {
      if (comp instanceof Lookup.Provider) {
        Lookup lookup = ((Lookup.Provider) comp).getLookup();
        if (lookup != null) {
          ancestorLookup = lookup;
          break;
        }
      }
    }

    Lookup componentLookup = Lookups.singleton(c);
    if (nodeLookup == null && ancestorLookup == null) {
      return componentLookup;
    } else if (nodeLookup == null) {
      return new ProxyLookup(new Lookup[] {ancestorLookup, componentLookup});
    } else if (ancestorLookup == null) {
      return new ProxyLookup(new Lookup[] {nodeLookup, componentLookup});
    }
    assert nodeLookup != null && ancestorLookup != null;

    Node node = (Node) nodeLookup.lookup(Node.class);
    boolean ancestorLookupContainsNode =
        ancestorLookup.lookup(new Lookup.Template(Node.class)).allInstances().contains(node);

    if (ancestorLookupContainsNode) {
      return new ProxyLookup(new Lookup[] {ancestorLookup, componentLookup});
    } else {
      return new ProxyLookup(new Lookup[] {nodeLookup, ancestorLookup, componentLookup});
    }
  }

  private void processButton(AbstractButton button) {
    removeButtonContentAreaAndBorder(button);
    button.setMargin(BUTTON_INSETS);
    if (button instanceof AbstractButton) {
      button.addMouseListener(sharedMouseListener);
    }
    // fix of issue #69642. Focus shouldn't stay in toolbar
    button.setFocusable(false);
  }

  private static void removeButtonContentAreaAndBorder(AbstractButton button) {
    boolean canRemove = true;
    if (button instanceof JToggleButton) {
      canRemove = !button.isSelected();
    }
    if (canRemove) {
      button.setContentAreaFilled(false);
      button.setBorderPainted(false);
    }
  }

  /** Attempt to find the editor keystroke for the given action. */
  private KeyStroke[] findEditorKeys(String editorActionName, KeyStroke defaultKey) {
    KeyStroke[] ret = new KeyStroke[] {defaultKey};
    JTextComponent comp = getComponent();
    if (editorActionName != null && comp != null) {
      TextUI textUI = comp.getUI();
      Keymap km = comp.getKeymap();
      if (textUI != null && km != null) {
        EditorKit kit = textUI.getEditorKit(comp);
        if (kit instanceof BaseKit) {
          Action a = ((BaseKit) kit).getActionByName(editorActionName);
          if (a != null) {
            KeyStroke[] keys = km.getKeyStrokesForAction(a);
            if (keys != null && keys.length > 0) {
              ret = keys;
            } else {
              // try kit's keymap
              Keymap km2 = ((BaseKit) kit).getKeymap();
              KeyStroke[] keys2 = km2.getKeyStrokesForAction(a);
              if (keys2 != null && keys2.length > 0) {
                ret = keys2;
              }
            }
          }
        }
      }
    }
    return ret;
  }

  private static String s2s(Object o) {
    return o == null
        ? "null"
        : o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); // NOI18N
  }

  /** No operation action - do nothing when invoked issue #69642 */
  private static final class NoOpAction extends AbstractAction {
    public NoOpAction() {}

    public void actionPerformed(ActionEvent e) {}
  } // End of NoOpAction class

  private static final class WrapperAction implements Action {

    private final Reference componentRef;

    private final Action delegate;

    WrapperAction(Reference componentRef, Action delegate) {
      this.componentRef = componentRef;
      assert (delegate != null);
      this.delegate = delegate;
    }

    public Object getValue(String key) {
      return delegate.getValue(key);
    }

    public void putValue(String key, Object value) {
      delegate.putValue(key, value);
    }

    public void setEnabled(boolean b) {
      delegate.setEnabled(b);
    }

    public boolean isEnabled() {
      return delegate.isEnabled();
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
      delegate.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
      delegate.removePropertyChangeListener(listener);
    }

    public void actionPerformed(ActionEvent e) {
      JTextComponent c = (JTextComponent) componentRef.get();
      if (c != null) { // Override action event to text component
        e = new ActionEvent(c, e.getID(), e.getActionCommand());
      }
      delegate.actionPerformed(e);
    }
  } // End of WrapperAction class
}
Example #25
0
 /** Creates a new instance of PMDResult */
 public PMDResult(Report report /*, PMDSession session*/) {
   this.report = report;
   //        this.session = session;
   lookup = Lookups.fixed(new Object[] {this});
 }