下面列出了怎么用org.openide.util.ContextAwareAction的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
};
}
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;
}
});
}
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);
}
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());
}
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;
}
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);
}
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);
}
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);
}
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();
}
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);
}
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);
}
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();
}
@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();
}
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);
}
/** 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);
}
}
});
}
});
}
private Action getAction(AnnotationDesc anno, Action action) {
if (action instanceof ContextAwareAction && anno instanceof Lookup.Provider) {
Lookup lookup = ((Lookup.Provider) anno).getLookup();
action = ((ContextAwareAction) action).createContextAwareInstance(lookup);
}
return action;
}
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()]);
}
private void selectInProjectsView(final DataFolder destinationFolder) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ContextAwareAction action = FileUtil.getConfigObject("Actions/Window/SelectDocumentNode/org-netbeans-modules-project-ui-SelectInProjects.instance", ContextAwareAction.class); //NOI18N
if(action != null) {
Action contextAction = action.createContextAwareInstance(Lookups.fixed(destinationFolder));
contextAction.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
}
}
});
}
/**
* Run an action as if it were in the context menu of a project.
*/
private void runContextMenuAction(Action a, Project p) {
if (a instanceof ContextAwareAction) {
Lookup l = Lookups.singleton(p);
a = ((ContextAwareAction) a).createContextAwareInstance(l);
}
a.actionPerformed(null);
}
public @Override Action createContextAwareInstance(Lookup ctx) {
Project p = ctx.lookup(Project.class);
if (p == null) {
return this;
}
if (!CoverageManager.INSTANCE.isEnabled(p)) {
// or could show it anyway in case provider is present
return this;
}
return ((ContextAwareAction) CoverageActionFactory.createCollectorAction(null, null)).createContextAwareInstance(ctx);
}
/** Tests whether the cut, copy (callback) actions are enabled/disabled
* in the right time, see # */
public void testCutCopyActionsEnabling() throws Exception {
assertTrue ("Can run only in AWT thread", java.awt.EventQueue.isDispatchThread());
TestNode enabledNode = new TestNode(true, true, true);
TestNode disabledNode = new TestNode(false, false, false);
manager.setRootContext(new TestRoot(
new Node[] {enabledNode, disabledNode}));
Action copy = ((ContextAwareAction)SystemAction.get(CopyAction.class)).createContextAwareInstance(context);
Action cut = ((ContextAwareAction)SystemAction.get(CutAction.class)).createContextAwareInstance(context);
assertTrue("Copy action has to be disabled", !copy.isEnabled());
assertTrue("Cut action has to be disabled", !cut.isEnabled());
manager.setSelectedNodes(new Node[] {enabledNode});
manager.waitActionsFinished();
assertTrue("Copy action has to be enabled", copy.isEnabled());
assertTrue("Cut action has to be enabled", cut.isEnabled());
copy.actionPerformed (new java.awt.event.ActionEvent (this, 0, "waitFinished"));
assertEquals ("clipboardCopy invoked", 1, enabledNode.countCopy);
cut.actionPerformed (new java.awt.event.ActionEvent (this, 0, "waitFinished"));
assertEquals ("clipboardCut invoked", 1, enabledNode.countCut);
manager.setSelectedNodes(new Node[] {disabledNode});
manager.waitActionsFinished();
assertTrue("Copy action has to be disabled", !copy.isEnabled());
assertTrue("Cut action has to be disabled", !cut.isEnabled());
}
@RandomlyFails // NB-Core-Build #8351 (from ExplorerActionsCompatTest): Now it gets enabled
public void testDeleteAction () throws Exception {
TestNode enabledNode = new TestNode(true, true, true);
TestNode enabledNode2 = new TestNode(true, true, true);
TestNode disabledNode = new TestNode(false, false, false);
manager.setRootContext(new TestRoot(
new Node[] {enabledNode, enabledNode2, disabledNode}));
Action delete = ((ContextAwareAction)SystemAction.get(org.openide.actions.DeleteAction.class)).createContextAwareInstance(context);
assertTrue ("By default delete is disabled", !delete.isEnabled());
manager.setSelectedNodes(new Node[] { enabledNode });
manager.waitActionsFinished();
assertTrue ("Now it gets enabled", delete.isEnabled ());
manager.setSelectedNodes (new Node[] { disabledNode });
manager.waitActionsFinished();
assertTrue ("Is disabled", !delete.isEnabled ());
manager.setSelectedNodes(new Node[] { manager.getRootContext() });
manager.waitActionsFinished();
assertTrue ("Delete is enabled on root", delete.isEnabled ());
manager.setSelectedNodes(new Node[] { manager.getRootContext(), enabledNode });
manager.waitActionsFinished();
assertTrue ("But is disabled on now, as one selected node is child of another", !delete.isEnabled ());
manager.setSelectedNodes (new Node[] { enabledNode, enabledNode2 });
manager.waitActionsFinished();
assertTrue ("It gets enabled", delete.isEnabled ());
delete.actionPerformed(new java.awt.event.ActionEvent (this, 0, "waitFinished"));
assertEquals ("Destoy was called", 1, enabledNode.countDelete);
assertEquals ("Destoy was called", 1, enabledNode2.countDelete);
}
public void testKeyMustBeProvided() {
String key = null;
Action defaultDelegate = null;
Lookup context = Lookup.EMPTY;
ContextAwareAction expResult = null;
try {
ContextAwareAction result = GeneralAction.callback(key, defaultDelegate, context, false, false);
fail("Shall fail as key is null");
} catch (NullPointerException ex) {
// ok
}
}
public void testSaveAsActionDisabledForNonEditorWindows() throws Exception {
ContextAwareAction action = SaveAsAction.create();
viewWithoutSaveAs.requestActive();
assertTrue( TopComponent.getRegistry().getActivated() == viewWithoutSaveAs );
assertFalse( "action is disabled when SaveAsCapable is not present in active TC lookup", action.isEnabled() );
}
public void testSaveAsActionDisabledForViewsWithSaveAsCapable() throws Exception {
ContextAwareAction action = SaveAsAction.create();
viewWithSaveAs.requestActive();
assertTrue( TopComponent.getRegistry().getActivated() == viewWithSaveAs );
assertFalse( "action is disabled other window than editor is activated", action.isEnabled() );
}
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() );
}
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
}
/** 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;
}
/** 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();
}
}
}
}
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);
}