org.openide.util.ContextAwareAction Java Examples

The following examples show how to use org.openide.util.ContextAwareAction. 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: ContextManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testListenerGCed () throws Exception {
    InstanceContent ic = new InstanceContent();
    lkp = new AbstractLookup(ic);
    Lookup.Result<Integer> lookupResult = lkp.lookupResult(Integer.class);

    Action action = ((ContextAwareAction) Actions.forID("cat", "survive")).createContextAwareInstance(lkp);
    Action fallbackAction = ((GeneralAction.DelegateAction) action).fallback;
    WeakReference<Action> fallbackActionRef = new WeakReference<Action>(fallbackAction);
    WeakReference<Action> clone = new WeakReference<Action>(action);
    cm = ContextManager.findManager(lkp, true);
    WeakReference lsetRef = new WeakReference<Object>(cm.findLSet(Integer.class));

    action = null;

    assertGC("Action should be GCed", clone);

    fallbackAction = null;

    assertGC("Fallback action should be GCed", fallbackActionRef);
    assertGC("Action LSet Should be GCed", lsetRef);
    lookupResult.allInstances();
}
 
Example #2
Source File: ContextActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testBasicUsageWithEnablerFromLayer() throws Exception {
    FileObject folder;
    folder = FileUtil.getConfigFile("actions/support/test");
    assertNotNull("testing layer is loaded: ", folder);

    FileObject fo = folder.getFileObject("testContextEnabler.instance");
    
    Object obj = fo.getAttribute("instanceCreate");
    if (!(obj instanceof ContextAwareAction)) {
        fail("Shall create an action: " + obj);
    }
    ContextAwareAction caa = (ContextAwareAction)obj;
    Action action = caa.createContextAwareInstance(lookupProxy);
    
    
    doBasicUsageWithEnabler(action);
}
 
Example #3
Source File: ActionProviderImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@ActionID(id = "org.netbeans.modules.maven.customPopup", category = "Project")
@ActionRegistration(displayName = "#LBL_Custom_Run", lazy=false)
@ActionReferences({
    @ActionReference(position = 1400, path = "Projects/org-netbeans-modules-maven/Actions"),
    @ActionReference(position = 250, path = "Loaders/text/x-maven-pom+xml/Actions"),
    @ActionReference(position = 1296, path = "Loaders/text/x-java/Actions"),
    @ActionReference(position = 1821, path = "Editors/text/x-java/Popup")
})
@Messages({"LBL_Custom_Run=Run Maven", "LBL_Custom_Run_File=Run Maven"})
public static ContextAwareAction customPopupActions() {
    return new ConditionallyShownAction() {
        
        protected @Override Action forProject(Project p, FileObject fo) {
            ActionProviderImpl ap = p.getLookup().lookup(ActionProviderImpl.class);
            return ap != null ? ap.new CustomPopupActions(triggeredOnFile, triggeredOnPom, fo) : null;
        }
    };
}
 
Example #4
Source File: ContextManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@RandomlyFails
public void testListenerGCedAfterActionGCed () throws Exception {
    InstanceContent ic = new InstanceContent();
    lkp = new AbstractLookup(ic);
    Lookup.Result<Integer> lookupResult = lkp.lookupResult(Integer.class);

    Action action = ((ContextAwareAction) Actions.forID("cat", "survive")).createContextAwareInstance(lkp);
    Action fallbackAction = ((GeneralAction.DelegateAction) action).fallback;
    WeakReference<Action> fallbackActionRef = new WeakReference<Action>(fallbackAction);
    WeakReference<Action> clone = new WeakReference<Action>(action);
    cm = ContextManager.findManager(lkp, true);
    WeakReference lsetRef = new WeakReference<Object>(cm.findLSet(Integer.class));

    // both delegate and delegating actions are GCed before WeakListenerSupport is triggered in ActiveRefQueue:
    // fallbackAction.removePropertyChangeListener(delegating.weakL);
    fallbackAction = null;
    action = null;
    assertGC("Action should be GCed", clone);

    assertGC("Fallback action should be GCed", fallbackActionRef);
    assertGC("Action LSet Should be GCed", lsetRef);
    lookupResult.allInstances();
}
 
Example #5
Source File: SuiteOperations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void close(final Project prj) {
    Mutex.EVENT.readAccess(new Mutex.Action<Object>() {
        public Object run() {
            LifecycleManager.getDefault().saveAll();
            
            Action closeAction = CommonProjectActions.closeProjectAction();
            closeAction = closeAction instanceof ContextAwareAction ? ((ContextAwareAction) closeAction).createContextAwareInstance(Lookups.fixed(new Object[] {prj})) : null;
            
            if (closeAction != null && closeAction.isEnabled()) {
                closeAction.actionPerformed(new ActionEvent(prj, -1, "")); // NOI18N
            } else {
                //fallback:
                OpenProjects.getDefault().close(new Project[] {prj});
            }
            
            return null;
        }
    });
}
 
Example #6
Source File: CallbackActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCopyLikeProblem() throws Exception {
    FileObject fo = folder.getFileObject("testCopyLike.instance");

    Object obj = fo.getAttribute("instanceCreate");
    if (!(obj instanceof Action)) {
        fail("Shall create an action: " + obj);
    }

    InstanceContent ic = new InstanceContent();
    AbstractLookup l = new AbstractLookup(ic);
    ActionMap map = new ActionMap();
    map.put("copy-to-clipboard", new MyAction());
    ic.add(map);

    CntListener list = new CntListener();
    Action clone = ((ContextAwareAction)obj).createContextAwareInstance(l);
    clone.addPropertyChangeListener(list);
    assertTrue("Enabled", clone.isEnabled());

    ic.remove(map);
    assertFalse("Disabled", clone.isEnabled());
    list.assertCnt("one change", 1);
}
 
Example #7
Source File: GlobalManagerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testActionsUpdatedWhenActionMapChanges() throws Exception {
    ContextAwareAction a = Actions.callback("ahoj", null, true, "Ahoj!", "no/icon.png", true);
    final InstanceContent ic = new InstanceContent();
    Lookup lkp = new AbstractLookup(ic);

    ActionMap a1 = new ActionMap();
    ActionMap a2 = new ActionMap();
    a2.put("ahoj", new Enabled());

    ic.add(a1);
    Action clone = a.createContextAwareInstance(lkp);
    class L implements PropertyChangeListener {
        int cnt;
        public void propertyChange(PropertyChangeEvent evt) {
            cnt++;
        }
    }
    L listener = new L();
    clone.addPropertyChangeListener(listener);
    assertFalse("Not enabled", isEnabled(clone));

    ic.set(Collections.singleton(a2), null);

    assertTrue("Enabled now", isEnabled(clone));
    assertEquals("one change", 1, listener.cnt);
}
 
Example #8
Source File: TopComponentTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCanTCGarbageCollectWhenActionInMap() {
    TopComponent tc = new TopComponent();
    class CAA extends AbstractAction implements
            ContextAwareAction {
        public void actionPerformed(ActionEvent arg0) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public Action createContextAwareInstance(Lookup actionContext) {
            return this;
        }

    }
    ContextAwareAction del = new CAA();
    ContextAwareAction context = Actions.context(Integer.class, true, true, del, null, "DisplayName", null, true);
    Action a = context.createContextAwareInstance(tc.getLookup());
    tc.getActionMap().put("key", a);

    WeakReference<Object> ref = new WeakReference<Object>(tc);
    tc = null;
    a = null;
    del = null;
    context = null;
    assertGC("Can the component GC?", ref);
}
 
Example #9
Source File: ModuleOperationsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testOperationActions() throws Exception { // #72397
    final NbModuleProject project = generateStandaloneModule("module");
    cgpi.setProject(project);
    DialogDisplayerImpl dd = (DialogDisplayerImpl) Lookup.getDefault().lookup(DialogDisplayer.class);
    FileObject lock = FileUtil.createData(project.getProjectDirectory(), "build/testuserdir/lock");
    RandomAccessFile raf = new RandomAccessFile(FileUtil.toFile(lock), "rw");
    FileLock lck = raf.getChannel().lock();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            ((ContextAwareAction) CommonProjectActions.deleteProjectAction()).createContextAwareInstance(Lookups.singleton(project)).actionPerformed(null);
        }
    });
    assertNotNull("warning message emitted", dd.getLastNotifyDescriptor());
    assertEquals("warning message emitted", dd.getLastNotifyDescriptor().getMessage(),
            Bundle.ERR_ModuleIsBeingRun());
    dd.reset();
    lck.release();
    raf.close();
    lock.delete();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            CommonProjectActions.deleteProjectAction().actionPerformed(null);
        }
    });
    assertNull("no warning message", dd.getLastNotifyDescriptor());
}
 
Example #10
Source File: EJBActionGroup.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public JPopupMenu getPopupMenu() {
    if (getItemCount() == 0) {
        Action[] grouped = grouped();
        for (int i = 0; i < grouped.length; i++) {
            Action action = grouped[i];
            if (action == null && getItemCount() != 0) {
                addSeparator();
            } else {
                if (action instanceof ContextAwareAction) {
                    action = ((ContextAwareAction)action).createContextAwareInstance(lookup);
                }
                if (action instanceof Presenter.Popup) {
                    add(((Presenter.Popup)action).getPopupPresenter());
                }
            }
        }
    }
    return super.getPopupMenu();
}
 
Example #11
Source File: ContextAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Object delegate0(Lookup.Provider everything, List<?> data, boolean getAction) {
    Object d = instDelegate != null ? instDelegate.get() : null;
    if (d != null) {
        if (getAction && (d instanceof Performer)) {
            return ((Performer)d).delegate0(everything, data, getAction);
        }
        return d;
    }
    d = createDelegate(everything, data);
    if (d != null) {
        if (getAction && (d instanceof Performer)) {
            final Object fd = d;
            instDelegate = new WeakReference<Object>(d) { private Object hardRef = fd; };
            return ((Performer)d).delegate0(everything, data, getAction);
        }
        if (d instanceof ContextAwareAction) {
            d = ((ContextAwareAction)d).createContextAwareInstance(everything.getLookup());
        }
        instDelegate = new WeakReference<>(d);
    } else {
        instDelegate = NONE;
    }
    return d;
}
 
Example #12
Source File: GeneralActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testIconIsCorrect() throws Exception {
    if (true) return; // disabled right now
    
    myListenerCounter = 0;
    myIconResourceCounter = 0;
    Action a = readAction();
    
    assertTrue("Always enabled", a.isEnabled());
    a.setEnabled(false);
    assertTrue("Still Always enabled", a.isEnabled());
    
    
    assertEquals("No icon in menu", Boolean.TRUE, a.getValue("noIconInMenu"));
    
    if (a instanceof ContextAwareAction) {
        fail("Should not be context sensitive, otherwise it would have to implement equal correctly: " + a);
    }
    
    a.actionPerformed(null);
}
 
Example #13
Source File: ActionProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testContextAction() throws Exception {
    Action a = Actions.forID("Tools", "on.int");
    assertTrue("It is context aware action", a instanceof ContextAwareAction);

    InstanceContent ic = new InstanceContent();
    AbstractLookup lkp = new AbstractLookup(ic);
    Action clone = ((ContextAwareAction) a).createContextAwareInstance(lkp);
    NumberLike ten = new NumberLike(10);
    ic.add(ten);

    assertEquals("Number lover!", clone.getValue(Action.NAME));
    clone.actionPerformed(new ActionEvent(this, 300, ""));
    assertEquals("Global Action not called", 10, Context.cnt);

    ic.remove(ten);
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("Global Action stays same", 10, Context.cnt);
}
 
Example #14
Source File: ActionProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMultiContextAction() throws Exception {
    ContextAwareAction a = (ContextAwareAction) Actions.forID("Tools", "on.numbers");

    InstanceContent ic = new InstanceContent();
    AbstractLookup lkp = new AbstractLookup(ic);
    Action clone = a.createContextAwareInstance(lkp);
    NumberLike ten = new NumberLike(10);
    NumberLike three = new NumberLike(3);
    ic.add(ten);
    ic.add(three);

    assertEquals("Number lover!", clone.getValue(Action.NAME));
    clone.actionPerformed(new ActionEvent(this, 300, ""));
    assertEquals("Global Action not called", 13, MultiContext.cnt);

    ic.remove(ten);
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("Adds 3", 16, MultiContext.cnt);

    ic.remove(three);
    assertFalse("It is disabled", clone.isEnabled());
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("No change", 16, MultiContext.cnt);
}
 
Example #15
Source File: GeneralAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static ContextAwareAction context(Map map, boolean instanceReady) {
    Class<?> dataType = readClass(map.get("type")); // NOI18N
    ContextAwareAction ca = _context(map, dataType, Utilities.actionsGlobalContext(), instanceReady);
    // autodetect on/off actions
    if (ca.getValue(Action.SELECTED_KEY) != null) {
        return new StateDelegateAction(map, ca);
    } else {
        return new DelegateAction(map, ca);
    }
}
 
Example #16
Source File: FodDataObjectXMLFactoryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Action assertAction(String msg, boolean enabled, Action[] arr, Lookup context) {
    for (int i = 0; i < arr.length; i++) {
        Action action = arr[i];
        if (action instanceof OpenAdvancedAction) {
            Action clone = ((ContextAwareAction)action).createContextAwareInstance(context);
            assertEquals("Correctly enabled. " + msg, enabled, clone.isEnabled());
            return clone;
        }
    }
    fail("No open advanced action found!");
    return null;
}
 
Example #17
Source File: GuiUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void callAction(Action a, Node node, ActionEvent actionEvent) {
    if (a instanceof ContextAwareAction) {
        a = ((ContextAwareAction)a).createContextAwareInstance(node.getLookup());
    }
    if (a == null) {
        return;
    }
    a.actionPerformed(actionEvent);
}
 
Example #18
Source File: ActionProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCallbackOnFieldAction() throws Exception {
    Callback.cnt = 0;
    
    FileObject fo = FileUtil.getConfigFile(
        "Actions/Edit/my-field-action.instance"
    );
    assertNotNull("File found", fo);
    Object icon = fo.getAttribute("iconBase");
    assertEquals("Icon found", "org/openide/awt/TestIcon.png", icon);
    Object obj = fo.getAttribute("instanceCreate");
    assertNotNull("Attribute present", obj);
    assertTrue("It is context aware action", obj instanceof ContextAwareAction);
    ContextAwareAction a = (ContextAwareAction)obj;

    class MyAction extends AbstractAction {
        int cnt;
        @Override
        public void actionPerformed(ActionEvent e) {
            cnt += e.getID();
        }
    }
    MyAction my = new MyAction();
    ActionMap m = new ActionMap();
    m.put(ACTION_MAP_KEY, my);

    InstanceContent ic = new InstanceContent();
    AbstractLookup lkp = new AbstractLookup(ic);
    Action clone = a.createContextAwareInstance(lkp);
    ic.add(m);

    assertEquals("I am context", clone.getValue(Action.NAME));
    clone.actionPerformed(new ActionEvent(this, 300, ""));
    assertEquals("Local Action called", 300, my.cnt);
    assertEquals("Global Action not called", 0, Callback.cnt);

    ic.remove(m);
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("Local Action stays", 300, my.cnt);
    assertEquals("Global Action not called, there is no fallback", 0, Callback.cnt);
}
 
Example #19
Source File: ProjectUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Invokes the preferred action on given object and tries to select it in
 * corresponding view, e.g. in logical view if possible otherwise
 * in physical project's view.
 * Note: execution this methods can invokes new threads to assure the action
 * is called in EQ.
 *
 * @param newDo new data object
 */   
public static void openAndSelectNewObject (final DataObject newDo) {
    // call the preferred action on main class
    Mutex.EVENT.writeAccess (new Runnable () {
        @Override
        public void run () {
            final Node node = newDo.getNodeDelegate ();
            Action a = node.getPreferredAction();
            if (a instanceof ContextAwareAction) {
                a = ((ContextAwareAction) a).createContextAwareInstance(node.getLookup ());
            }
            if (a != null) {
                a.actionPerformed(new ActionEvent(node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N
            }

            // next action -> expand && select main class in package view
            final ProjectTab ptLogical = ProjectTab.findDefault(ProjectTab.ID_LOGICAL);
            final ProjectTab ptPhysical = ProjectTab.findDefault(ProjectTab.ID_PHYSICAL);
            ProjectTab.RP.post(new Runnable() {
                public @Override void run() {
                    ProjectTab tab = ptLogical;
                    Node n = tab.findNode(newDo.getPrimaryFile());
                    if (n == null) {
                        tab = ptPhysical;
                        n = tab.findNode(newDo.getPrimaryFile());
                    }
                    if (n != null) {
                        tab.selectNode(n);
                    }
                }
            });
        }
    });
}
 
Example #20
Source File: ContextManagerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAllResultListenersRemoved () throws Exception {
    InstanceContent ic = new InstanceContent();
    lkp = new AbstractLookup(ic);
    Lookup.Result<Integer> lookupResult = lkp.lookupResult(Integer.class);

    Action action = ((ContextAwareAction) Actions.forID("cat", "survive")).createContextAwareInstance(lkp);
    Action fallbackAction = ((GeneralAction.DelegateAction) action).fallback;
    WeakReference<Action> fallbackActionRef = new WeakReference<Action>(fallbackAction);
    WeakReference<Action> clone = new WeakReference<Action>(action);
    cm = ContextManager.findManager(lkp, true);
    WeakReference<ContextManager.LSet> lsetRef = new WeakReference<ContextManager.LSet>(cm.findLSet(Integer.class));
    WeakReference<Lookup.Result> lookupResultRef = new WeakReference<Lookup.Result>(lsetRef.get().result);

    action = null;

    assertGC("Action should be GCed", clone);

    fallbackAction = null;

    assertGC("Fallback action should be GCed", fallbackActionRef);
    assertGC("Action LSet Should be GCed", lsetRef);
    if (lookupResultRef.get() == lookupResult) {
        // LSet holds ref to the actual real lookup result, nothing to test
    } else {
        // LSet holds ref to a wrapper class NeverEmptyResult, which should have been GCed
        assertGC("NeverEmptyResult should be GCed", lookupResultRef);
    }
}
 
Example #21
Source File: ActionProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSurviveFocusChangeBehavior() throws Exception {
    class MyAction extends AbstractAction {
        public int cntEnabled;
        public int cntPerformed;
        
        @Override
        public boolean isEnabled() {
            cntEnabled++;
            return true;
        }
        
        @Override
        public void actionPerformed(ActionEvent ev) {
            cntPerformed++;
        }
    }
    MyAction myAction = new MyAction();
    
    ActionMap disable = new ActionMap();
    ActionMap enable = new ActionMap();
    
    InstanceContent ic = new InstanceContent();
    AbstractLookup al = new AbstractLookup(ic);
    
    ContextAwareAction temp = (ContextAwareAction) Actions.forID("Windows", "my.survival.action");
    Action a = temp.createContextAwareInstance(al);
    
    enable.put(SURVIVE_KEY, myAction);
    
    ic.add(enable);
    assertTrue("MyAction is enabled", a.isEnabled());
    ic.set(Collections.singletonList(disable), null);
    assertTrue("Remains enabled on other component", a.isEnabled());
    ic.remove(disable);
}
 
Example #22
Source File: GeneralAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ContextAwareAction callback(
    String key, Action defaultDelegate, Lookup context, boolean surviveFocusChange, boolean async
) {
    if (key == null) {
        throw new NullPointerException();
    }
    return new DelegateAction(null, key, context, defaultDelegate, surviveFocusChange, async);
}
 
Example #23
Source File: ContextMenuWarmUpTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Warms up tools action popup menu item. */
private static void warmUpToolsPopupMenuItem() {
    SystemAction toolsAction = SystemAction.get(ToolsAction.class);
    if(toolsAction instanceof ContextAwareAction) {
        // Here is important to create proper lookup
        // to warm up Tools sub actions.
        Lookup lookup = new org.openide.util.lookup.ProxyLookup(
            new Lookup[] {
                // This part of lookup causes warm up of Node (cookie) actions.
                new AbstractNode(Children.LEAF).getLookup(),
                // This part of lookup causes warm up of Callback actions.
                new TopComponent().getLookup()
            }
        );
        
        Action action = ((ContextAwareAction)toolsAction)
                            .createContextAwareInstance(lookup);
        if(action instanceof Presenter.Popup) {
            JMenuItem toolsMenuItem = ((Presenter.Popup)action)
                                            .getPopupPresenter();
            if(toolsMenuItem instanceof Runnable) {
                // This actually makes the warm up.
                // See ToolsAction.Popup impl.
                ((Runnable)toolsMenuItem).run();
            }
        }
    }
}
 
Example #24
Source File: CallbackSystemActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testPropertyChangeListenersDetachedAtFinalizeIssue58100() throws Exception {
    
    class MyAction extends AbstractAction {
        public void actionPerformed(ActionEvent ev) {
        }
    }
    MyAction action = new MyAction();
    ActionMap map = new ActionMap();
    
    map.put("key", action);
    Lookup context = Lookups.singleton(map);
    ContextAwareAction systemaction = CallbackActionTest.callback("key", null, Utilities.actionsGlobalContext(), false);
    Action delegateaction = systemaction.createContextAwareInstance(context);
    
    assertEquals("Action is expected to have no listener", 0, action.getPropertyChangeListeners().length);
    
    Reference<Object> actionref = new WeakReference<Object>(systemaction);
    systemaction = null;
    delegateaction = null;
    assertGC("CallbackSystemAction is supposed to be GCed", actionref);
    
    assertEquals(
        "Action is expected to have no PropertyChangeListener attached:\n" + 
            Arrays.asList(action.getPropertyChangeListeners())
        , 0, 
        action.getPropertyChangeListeners().length
    );
}
 
Example #25
Source File: ToolsAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Tells if there is any action that is willing to provide
 * Presenter.Popup
 */
private boolean isPopupEnabled(Action toolsAction) {
    boolean en = false;
    Action[] copy = actions;

    // Get action conext.
    Lookup lookup;

    if (toolsAction instanceof Lookup.Provider) {
        lookup = ((Lookup.Provider) toolsAction).getLookup();
    } else {
        lookup = null;
    }

    for (int i = 0; i < copy.length; i++) {
        if (copy[i] == null) {
            continue;
        }
        // Get context aware action instance if needed.
        Action act;

        // Retrieve context aware action instance if possible.
        if ((lookup != null) && copy[i] instanceof ContextAwareAction) {
            act = ((ContextAwareAction) copy[i]).createContextAwareInstance(lookup);
            if (act == null) {
                throw new IllegalStateException("createContextAwareInstance for " + copy[i] + " returned null!");
            }
        } else {
            act = copy[i];
        }

        if (act.isEnabled()) {
            en = true;

            break;
        }
    }

    return en;
}
 
Example #26
Source File: DelegatingVCS.java    From netbeans with Apache License 2.0 5 votes vote down vote up
Action[] getInitActions(VCSContext ctx) {
    String category = (String) map.get("actionsCategory");              // NOI18N
    List<? extends Action> l = Utilities.actionsForPath("Versioning/" + category + "/Actions/Unversioned"); // NOI18N
    List<Action> ret = new ArrayList<Action>(l.size());
    for (Action action : l) {
        if(action instanceof ContextAwareAction) {
            ret.add(((ContextAwareAction)action).createContextAwareInstance(Lookups.singleton(ctx)));
        } else {
            ret.add(action);
        }
    }
    return ret.toArray(new Action[ret.size()]);
}
 
Example #27
Source File: HgProjectUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void renameProject(Project p, Object caller) {
    if( p == null) return;
    
    ContextAwareAction action = (ContextAwareAction) CommonProjectActions.renameProjectAction();
    Lookup ctx = Lookups.singleton(p);
    Action ctxAction = action.createContextAwareInstance(ctx);
    ctxAction.actionPerformed(new ActionEvent(caller, 0, "")); // NOI18N
}
 
Example #28
Source File: CallbackSystemActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testGlobalChanges() throws Exception {
    class MyAction extends AbstractAction {
        public int cntEnabled;
        public int cntPerformed;
        
        public MyAction() {
            setEnabled(true);
        }
        
        @Override
        public boolean isEnabled() {
            cntEnabled++;
            return super.isEnabled();
        }
        
        public void actionPerformed(ActionEvent ev) {
            cntPerformed++;
        }
    }
    MyAction myAction = new MyAction();
    
    ActionMap tc = new ActionMap();
    tc.put(DefaultEditorKit.copyAction, myAction);

    InstanceContent ic = new InstanceContent();
    AbstractLookup al = new AbstractLookup(ic);
    ContextAwareAction a = CallbackActionTest.callback(DefaultEditorKit.copyAction, null, al, false);
    
    ic.add(tc);
    assertTrue("MyAction is enabled", a.isEnabled());
    assertEquals("isEnabled called once", 1, myAction.cntEnabled);
    
    myAction.setEnabled(false);
    assertEquals("An enabled is not called on property change", 1, myAction.cntEnabled);
    assertFalse("MyAction is disabled", a.isEnabled());
    assertEquals("An enabled is currentlly called again", 2, myAction.cntEnabled);
}
 
Example #29
Source File: ContextActionInjectTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMultiContextActionLookup() throws Exception {
    FileObject fo = FileUtil.getConfigFile(
        "actions/support/test/testInjectContextLookup.instance"
    );
    assertNotNull("File found", fo);
    Object obj = fo.getAttribute("instanceCreate");
    assertNotNull("Attribute present", obj);
    assertTrue("It is context aware action", obj instanceof ContextAwareAction);
    ContextAwareAction a = (ContextAwareAction)obj;

    InstanceContent ic = new InstanceContent();
    AbstractLookup lkp = new AbstractLookup(ic);
    Action clone = a.createContextAwareInstance(lkp);
    ic.add(10);
    ic.add(3L);

    assertEquals("Number lover!", clone.getValue(Action.NAME));
    clone.actionPerformed(new ActionEvent(this, 300, ""));
    assertEquals("Global Action not called", 13, LookupContext.cnt);

    ic.remove(10);
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("Adds 3", 16, LookupContext.cnt);

    ic.remove(3L);
    assertFalse("It is disabled", clone.isEnabled());
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("No change", 16, LookupContext.cnt);
}
 
Example #30
Source File: SaveAsActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSaveAsActionDisabledForEditorsWithoutSaveAsCapable() throws Exception {
    ContextAwareAction action = SaveAsAction.create();
    
    editorWithoutSaveAs.requestActive();
    assertTrue( TopComponent.getRegistry().getActivated() == editorWithoutSaveAs );
    assertFalse( "action is disabled for editor windows without SaveAsCapable in their Lookup", action.isEnabled() );
}