Mystified by right-click editor popup psielement selection

Answered

So, sorry for being ignorant despite reading forum/doc/code but what is the CORRECT method to identify the psielement you right-click on for an action popup? I use this:

PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(e.getDataContext());

and I've used the "get offset mechanism" as well:

int offset;
Point mousePosition = editor.getContentComponent().getMousePosition();
if ( mousePosition!=null ) {
LogicalPosition pos = editor.xyToLogicalPosition(mousePosition);
offset = editor.logicalPositionToOffset(pos);
}
else {
offset = editor.getCaretModel().getOffset();
}
PsiElement el = file.findElementAt(offset);

The values for the above for repeated update() calls seem to vary within a SINGLE right click. It starts out where the cursor is (not where I right click) the first call to update(). Then, update() is called again with a new event as I move the mouse down to select the menu item to ultimately point at the target element.

The 

Point mousePosition = editor.getContentComponent().getMousePosition();

doesn't seem to be right as it changes as I move the mouse to activate the action.

Can someone please state exactly how update()/actionPerformed() are supposed to get the targeted psielement under where you right click? This should be easy I know but I can't find a method that works reliably. 

thanks!

Terence

4 comments
Comment actions Permalink

More data. This works all the time in actionPerformed() as apparently the mouse event has moved the caret but it does NOT work in update() but I need to disable the menu item if I right click on something other than a special psielement. help anyone?

int offset = editor.getCaretModel().getOffset();

omg. so update() is called 2x before i select my popup action and then again before actionPerformed() as I select the item. Makes sense. BUT, this 3rd time, the mouse position can no longer be used as it's moved to where the popup menu item is. How are we supposed to distinguish these cases? Ahhhhh!

0
Comment actions Permalink

Actually, update() isn't called more than 2x. The other menu items were triggering some of my "get selected element" helper routines. Just wanted to clear up that point. It still remains that I cannot know which target psielement is selected from update(). only actionPerformed can reliably get that using my methods above.

0
Comment actions Permalink

Since IDEA-137062 has been fixed (in 2016.1), CommonDataKeys.PSI_ELEMENT.getData(e.getDataContext()) should return correct value for actions invoked from context menu. Doesn't it work as expected for you?

0
Comment actions Permalink

Thanks. My hack appears to work in older and latest versions now.

0

Please sign in to leave a comment.