SWT, Maintain default tab ordering when adding Key Listner - java

I've been creating a custom TabFolder extension that adds a key listener to allow quick tab switching using an ALT + # hotkey.
By adding the KeyAdapter to my TabFolder, the event handler works properly only when you have a tab header selected (in which case the ALT + ARROW_LEFT/ARROW_RIGHT also work.). I need this hot key to be active when any Widget with-in the TabFolder is active; however, it shouldn't be active if the selection is in a different tab folder or widget outside of a tab folder.
In an attempt to solve this, I wrote a simple recursive function to apply the key listener to all of the children of the tab folder:
public void applyQuickSwitchKeyBindings() {
removeKeyListener(ka);
addKeyListener(ka);
for(Control c: getChildren())
applyQuickSwitchKeyBindingsToChildren(c);
}
private void applyQuickSwitchKeyBindingsToChildren(Control c) {
if(c==null) return;
if(c instanceof Composite) {
Control[] controls = ((Composite)c).getChildren();
for(Control c2: controls)
applyQuickSwitchKeyBindingsToChildren(c2);
if(controls.length < 1) {
c.removeKeyListener(ka);
c.addKeyListener(ka);
}
}
}
Then i call the applyQuickSwitchKeyBindings() after I add the controls to each TabItem in the tab group.
The good news was that the quick switch hot key (ALT + #) worked great!
The bad news was that the original TAB ordering based on z-index is now gone. When you hit the SWT.TAB key you lose focus on your current text box and don't gain focus on anything else...
Questions:
1.) Can each control only have one KeyListener?
2.) Why is the original TAB traversal not working anymore?
Thanks in advance!

to 1) I'm pretty sure that more than one KeyListener is allowed.
to 2) I'm not sure, that depends on what you're doing in your KeyAdapter. Maybe you can post that too?
I just the tab order is broken somehow, you can reset ( or change ) it with a call to setTabList( Control[] ).
setTablList( new Control[] {
control1,
control2,
control3,
....
} );

So after more time learning and developing with SWT i've discovered my problem. When you add a listener it is applied to the widget/control you call the addXXXListener function on. So if that control is not active the listeners will not be fired.
The solution seems to be SWT's global Filter mechanism which allows you to add global application(Display) scope listeners.
Display.getCurrent().addFilter(SWT.keyPress, new KeyPressListener());
Pardon the incorrectness of this line, but if you google it you'll see what i mean.
I have also read to use this sparingly.

Related

Eclipse RCP application key bindings conflicts with typing in textbox

I've assign W,A,S,D as hotkeys for zooming/scrolling through the key bindings extension point, and those are global hotkeys. This causes an issue that I can't type WASD in textbox. How should I fix this? I was thinking to disable the hotkey or do something in the textbox OnFocus event handler.
If you really think that W A S D are good key bindings and if you still think they make for good global key bindings (both I doubt), you can use key binding contexts to make the binding only available when outside editing controls.
Once you have defined an org.eclipse.ui.contexts extension, assign this context to the respective key bindings thought the contextId attribute.
Now these key bindings are only available if the specified context is active. The IContextService can be used to activate and deactivate the context.
Use a display filter to deactivate the context when entering an editing control like Text, Spinner, StyledText, etc. and to activate it when leaving such a control.
For example:
Listener filter = new Listener() {
IContextActivation activation;
#Override
public void handleEvent( Event event ) {
if( isEditingWidget( event.widget ) ) {
if( event.type = SWT.FocusIn ) {
contextService.deactivateContext( activation );
} else {
activation = contextService.activateContext( "context id" );
}
}
}
};
display.addFilter( SWT.FocusIn, filter );
display.addFilter( SWT.FocusOut, filter );
You have to change your Hotkeys. WASD are already mapped as single single pressed and as pressed in combination with shift. Use the normal arrow keys. It is not worth modifying every textbox just so you can use an unwisely chosen set of hotkeys

How enable or disable correctly an Action

i have a little problem when i try to disable an Action of my Netbeans platform project. When the app starts, some Actions must be disabled, and i do that with this method:
CallableSystemAction.get(BuildProjectAction.class).setEnabled(FLAG);
It works, because the BuildProjectAction is disabled, but the corresponding items of the MenuBar and the Toolbar remains enabled until i click on one of it.
Only later that i have clicked on it, the comportament start to work correctly.
First question: Why?
If i want disable an Action, it's obvious that i want disable also the relative Icon in the Menu and in the Toolbar, so it must be automatic when i call Action.setEnabled(false).
It doesn't have sense that the Icons are not refreshed if i don't click on they.
Same problem if i try to use .getToolbarPresenter().setEnabled(false); and .getMenuPresenter().setEnabled(false);
For start the application with the icons disabled, I have tried to set the lazy attribute to FALSE and declare the image programmatically with the method setIcon(new ImageIcon(image)); that sets the same image for Menu and Toolbar.
And it works; there is only another problem: Menu and Toolbar have icons of different size (16x16 and 24x24).
It doesn't have sense that the if i set the icon with the #ActionRegistration(iconBase = "image.png") the correct icon is automatically selected, but if i use the method .setIcon(), it doesn't.
I have read some articles about Action, CookieAction, Lookup, but the only thing that i want is disable the graphic elements in the same moment when i disable the Action.
Second question: How i can do that?
This is an example of my Action.
#ActionID(
category = "Run",
id = "BuildProjectAction")
#ActionRegistration(
lazy = true,
iconBase = "images/icons/compile.png",
displayName = "#CTL_BuildProjectAction")
#ActionReferences({
#ActionReference(
path = "Menu/Run",
position = 3),
#ActionReference(path = "Toolbars/Run",
position = 3),
#ActionReference(
path = "Shortcuts",
name = "D-B")
})
#Messages("CTL_BuildProjectAction=Build Project")
public final class BuildProjectAction extends CallableSystemAction {
#Override
public void actionPerformed(ActionEvent e) {...}
#Override
public void performAction() {}
#Override
public String getName() {
return Bundle.CTL_BuildProjectAction();
}
#Override
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
Thanks
The easiest way to create an action that is disabled at startup is to use the platform’s New Action Wizard to create your action, and to create one that depends on a "context" -- this is, on finding a specific object in the global lookup. If no object is available in the lookup, as at startup, then the action will be disabled.
The menu and toolbar graphic elements are bundled together with your action via the annotations. This means that enabled/disabled state of your context-aware action will automatically affect the icons in the menu and toolbar as well.
This article by Geertjan Wielenga has a walkthrough on creating a context-aware action:
http://netbeans.dzone.com/how-to-make-context-sensitive-actions
When you want to enable your action, you will add the object on which the action depends into the global lookup, which will cause the action (and its graphic elements) to be enabled.
This entry in the platform’s Developer FAQ has some examples of how to add an object to the global context:
http://wiki.netbeans.org/DevFaqAddGlobalContext
If you need to create an action that depends on a more complex set of conditions there is some discussion, as well as a code sample illustrating how to do this, in this platform developer list thread:
http://forums.netbeans.org/ptopic55295.html
The grayed-out versions of the icons that are shown when your action is disabled are created automatically by the platform. You only have to provide the "normal" non-grayed-out images.
As for the icons of different sizes, it’s a matter of filename convention. If your annotation declares the icon with #ActionRegistration(iconBase = "image.png”), then you will provide a 16x16 image called “image.png” and a 24x24 version called “image24.png”. The platform will find and use the appropriate size in the menu and toolbar.

How to force a Value change on a Vaadin RichTextArea component

I have developed a custom component consist of a layout and two labels within it. This layout is draggable. The code is similar to this :
DragAndDropWrapper boxWrap= new DragAndDropWrapper(layout);
mainLayout.addComponent(boxWrap);
After that I have a RichTextArea that allows the layout to be dropped in it. With this code.
RichTextArea richText= new RichTextArea;
DragAndDropWrapper dndWrapper = new DragAndDropWrapper(richText);
dndWrapper.setDropHandler(new DropHandler() {
public void drop(DragAndDropEvent event) {
//Do whatever you want when something is dropped
}
//Criterio de aceptacion
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
});
The code works fine. But when I drop the layout within the RichTextArea y want to get the Text written in this area and add some text but the method richText.getValue() is not updated unless I change the focus to another component or tab out. I guess there is not being communication with the server side so the value is not updated. Is there any way to force a a focus change when mousedown on the layout? I tried with JavaScript but i dont know how to add a onmousedown="function()" attribute to the layout component. I also tried extending RichTextArea and implementing the MouseListener or something or a TextChangeListener, but nothing works.
Any clue? Thank you.
PS: The component cannot be different from a RichTextArea.
Have you set richText.setImmediate(true); ?

Eclipse 4 RCP Editor using SourceViewer Undo and Redo operations are not working

I'm creating an editor using 'SourceViewer'. Given below is the code snippet from my '#PostConstruct' method.
// viewer is my SourceViewer instance
viewer = new SourceViewer(parent,verticalRuler, styles);
IUndoManager undoManager = new TextViewerUndoManager(25);
undoManager.connect(viewer);
viewer.setUndoManager(undoManager);
Even though a default 'TextViewerUndoManager' associated with 'SourceViewer'. Ctrl+Z and Ctrl+Y is not working.
Another alternative that I tried is to override the 'IUndoManager getUndoManager(ISourceViewer sourceViewer)' of 'SourceViewerConfiguration' subclass and return a 'TextViewerUndoManager'. This approach also doesn't give the desired result.
Kindly let me know what I'm missing in the above approaches.
It is normally the SourceViewerConfiguration that provides the Undo manager, the SourceViewer expects this and will set up the manager from that. The defaults already set up TextViewerUndoManager.
In an e4 application you do not get any default key bindings, commands or handlers so you will have to set up all these to make use of the undo manager.
In your application model declare Commands for undo and redo.
Declare key bindings for Ctrl+Z and Ctrl+Y specifying your commands. You might want to put the key bindings in a Binding Table that is specific to text editors.
Declare Handlers for the undo and redo commands, the code for undo might look like:
public class UndoHandler
{
#Inject
private Adapter _adapter;
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_PART) final MPart part)
{
final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);
opTarget.doOperation(ITextOperationTarget.UNDO);
}
#CanExecute
public boolean canExecute(#Named(IServiceConstants.ACTIVE_PART) final MPart part)
{
final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);
if (opTarget == null)
return false;
return opTarget.canDoOperation(ITextOperationTarget.UNDO);
}
}
Redo would be similar but using ITextOperationTarget.REDO.
The order of doing/registering things is important. Be sure to connect the undo manager AFTER setting the document to the SourceViewer instance because on connect() the document will be retrieved from the viewer by the undo manager and if it doesn't find a document it will not register anything and undoable() will always return false.

Hide certain actions from Swing's undo manager

I am trying to write a JTextPane which supports some sort of coloring: as the user is typing the text, I am running some code that colors the text according to a certain algorithm. This works well.
The problem is that the coloring operations is registered with the undo manager (a DefaultDocumentEvent with EventType.CHANGE). So when the user clicks undo the coloring disappears. Only at the second undo request the text itself is rolled back.
(Note that the coloring algorithm is somewhat slow so I cannot color the text as it is being inserted).
If I try to prevent the CHANGE events from reaching the undo manager I get an exception after several undo requests: this is because the document contents are not conforming to what the undoable-edit object expects.
Any ideas?
You could intercept the CHANGE edits and wrap each one in another UndoableEdit whose isSignificant() method returns false, before adding it to the UndoManager. Then each Undo command will undo the most recent INSERT or REMOVE edit, plus every CHANGE edit that occurred since then.
Ultimately, I think you'll find that the styling mechanism provided by JTextPane/StyledDocument/etc. is too limited for this kind of thing. It's slow, it uses too much memory, and it's based on the same Element tree that's used to keep track of the lexical structure of the document. It's okay (I guess) for applications in which the styles are applied by the user, like word processors, but not for a syntax highlighter that has to update the styles constantly as the user types.
There are several examples out there of syntax-highlighting editors based on custom implementations of the Swing JTextComponent, View and Document classes. Some, like JEdit, re-implement practically the whole javax.swing.text package, but I don't think you need to go that far.
How are you trying to prevent the CHANGE events from reaching the undo manager?
Can you not send the UndoManager a lastEdit().die() call immediately after the CHANGE is queued?
I can only assume how you are doing the text colouring. If you are doing it in the StyledDocuments change character attribute method you can get the undo listener and temporarily deregister it from the document for that operation and then once the colour change has finshed then you can reregister the listener.
Should be fine for what you are trying to do there.
hope that helps
I have just been through this problem. Here is my solution:
private class UndoManagerFix extends UndoManager {
private static final long serialVersionUID = 5335352180435980549L;
#Override
public synchronized void undo() throws CannotUndoException {
do {
UndoableEdit edit = editToBeUndone();
if (edit instanceof AbstractDocument.DefaultDocumentEvent) {
AbstractDocument.DefaultDocumentEvent event = (AbstractDocument.DefaultDocumentEvent) edit;
if (event.getType() == EventType.CHANGE) {
super.undo();
continue;
}
}
break;
} while (true);
super.undo();
}
#Override
public synchronized void redo() throws CannotRedoException {
super.redo();
int caretPosition = getCaretPosition();
do {
UndoableEdit edit = editToBeRedone();
if (edit instanceof AbstractDocument.DefaultDocumentEvent) {
AbstractDocument.DefaultDocumentEvent event = (AbstractDocument.DefaultDocumentEvent) edit;
if (event.getType() == EventType.CHANGE) {
super.redo();
continue;
}
}
break;
} while (true);
setCaretPosition(caretPosition);
}
}
It is an inner class in my custom JTextPane, so I can fix the caret position on redo.

Categories