Any workarounds to lack of PreSelection events in SWT/JFace? - java

In my application I want the user to save any changes before he leaves a tab (implemented as CTabFolder).
I tried to handle SelectionEvent, but it fires after the tab has been changed (so why does it even have a doit field? Does it fire before change for some other controls?)
Looking on Bugzilla, I've found https://bugs.eclipse.org/bugs/show_bug.cgi?id=193453 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=193064, neither of which is fixed.
Since this requirement is probably common, does anybody have a workaround?

I have a workaround that works with org.eclipse.ui.part.MultiPageEditorPart which is backed by a CTabFolder. I'll adapt it for a straight CTabFolder implementation.
First off use the selection listener:
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pageChange(tabFolder.indexOf((CTabItem) e.item));
}
});
Then I implement pageChange() like this:
protected void pageChange(int newPageIndex) {
boolean changingPages = this.changingPages;
this.changingPages = true;
int oldPageIndex = tabFolder.getSelectionIndex();
if (isDirty() && !changingPages) {
tabFolder.setSelection(oldPageIndex);
if (canChangePages()) {
tabFolder.setSelection(newPageIndex);
}
}
this.changingPages = false;
}
In canChangePages() I pop up a do you want to save dialog and give the user an opportunity to select yes, no, or cancel. Yes saves the info and returns true. No reverts the info to the last saved state and returns true. Cancel simply returns false. You may simply want to try saving and return false only if the save fails.
It may look weird that I switch back to the old page before calling canChangePages(). This call executes quickly so it gives the illusion the tab never switched. No matter how long canChangePages() takes the user will not see a tab change unless it is approved by that method.

Related

Vaadin unbuffered grids won't close

I am having a weird problem on my Vaadin app. I have a screen with two separate unbuffered grids.
The user is able to edit the data in those two grids and then click a "Save" button to save the changes made.
My problem is that I want to close the editors when the user clicks on "Save".
I tried the following code:
private void closeEditors() {
if (tab1.getEditor().isOpen()) {
tab1.getEditor().closeEditor();
}
if (tab2.getEditor().isOpen()) {
tab2.getEditor().closeEditor();
}
}
I don't understand why this code doesn't work, editors stay opened. I also tried calling the cancel method but in vain.
I am using Vaadin 14.
I am posting this here with not much hope of finding an answer, this problem seems really precise.
But with any luck, maybe someone has experienced a similar issue ?
Maybe there is another glitchier way of forcing my editors to close ?
Any suggestion would be of great help, thanks in advance for anything you could think of !
EDIT: a little more code
This is the grids:
private Grid<Map<String, String>> tab1;
private Grid<Map<String, List<String>>> tab2;
This is the save function
public void saveData() {
saveDataFromTab1();
saveDataFromTab2();
try {
ServicesProxyImpl.getInstance().updateInBD(someObject);
saveButton.setEnabled(false);
cancelButton.setEnabled(false);
closeEditors();
Dialog dialog = VaadinComponentUtils.generateDialog(Constantes.MSG_SAVE_OK);
dialog.open();
} catch (JAXBException e) {
e.printStackTrace();
Dialog dialog = VaadinComponentUtils.generateDialog(Constantes.MSG_SAVE_KO);
dialog.open();
}
}
And this is the save button:
public Button getSaveButton() {
Button saveButton= VaadinComponentUtils.generateButton("Save",
VaadinIcon.CHECK_CIRCLE_O, null, true);
saveButton.setEnabled(false);
saveButton.addClickListener(event -> saveData());
return saveButton;
}
EDIT 2:
I have noticed something, when I click on an element of one of my two grids, I want the editor to open for that specific element and I want to close the editor on the other grid (the one not concerned by the modification). This works ! My grids behave like I want. It seems I am only losing control over my editors after I have actually modified one of the cells and clicked on my save button.
The isOpen function returns false on both grids after I call my closeEditors function, so it seems the grid thinks its editor is closed but it is still opened on my UI.
EDIT 3: I have found a workaround
Well, I have solved my problem by adding a close event listener on both my grids and calling resetGrids when the close event is fired. This function simply removes the grids from the UI, fetches the data to be displayed and then adds the grid one again, both editors being closed. I guess it solves my problem but I would have wanted to understand what was going on...
private void closeEditors() {
tableauHoraires.getEditor().addCloseListener(e -> resetGrids());
tableauRamassagePorteAPorte.getEditor().addCloseListener(e -> resetGrids());
if (tableauRamassagePorteAPorte.getEditor().isOpen()) {
tableauRamassagePorteAPorte.getEditor().closeEditor();
}
if (tableauHoraires.getEditor().isOpen()) {
tableauHoraires.getEditor().closeEditor();
tableauHoraires.getEditor().refresh();
}
}
Make sure that the objects in your grid have proper equals and hashcode methods and that the field(s) being edited do not influence them.
I use the PK from the database.

Record status: Booleans, Text Changed Listeners, and logic

I am working on a problem where a record in my application has three different states (represented by Booleans): isNew, exists, and isDirty. isNew denotes whether or not a record is a new record. exists denotes whether or not that particular record exists in the database. isDirty denotes whether or not any of the values in the record have changed.
The idea is to check these states, and prompt a warning that the record hasn't been saved if they try to go back.
I am using a TextChangedListener to monitor the fields.
When a user first opens the page, it will display the most recent record, set isNew to false and exists to true. On creating a new record, isNew is set to true (and exists become false). Once new values are entered, isDirty then becomes true. Saving the record sets isNew to false and exists to true.
Now when a user attempts to exit without saving, the warning should appear.
The logic for the warning should be something like:
An unchanged new record should not prompt warning.
An unchanged existing record should not prompt warning.
A changed new and a changed existing record should prompt.
The problem I'm having is how to set the states (booleans) inside the TextChanged listener.
Right now the TextChanged listener fires on page load as well as when any of the fields are changed, including on the creation of a new record. Which means that isDirty is essentially always true. Which then makes it useless for using as a check on exit.
I tried using
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (isNew || exists) {
isDirty = false;
}
}
And that works to not set isDirty = true when it loads, but any subsequent field changes also return the same result. Which still makes it useless.
is using TextChangedListener the correct way to go? Or is there some other means I can check if the text has changed without calling TextChangedListener on load? Perhaps a way to NOT call the listener when the page loads or creates a new record?
I ended up using
public void afterTextChanged(Editable s) { if (s.toString().equals("") && isNew) { isDirty = false; } else { isDirty = true; }}
Works great!

Apply and OK Button in Eclipse PreferencePage

What is the standard and recommended way the apply and ok button in eclipse preference page should work.
I checked and found that performOK() method is called when we click apply or ok button. It means if I have some computations or let say thread starting on in performOK() and the user first click on apply and then ok button it will be executed twice and if the user clicks on apply and cancel the changes will be applied anyways?
Is there a way to not execute the code twice if the user clicks on apply and then ok ?
#Override
protected void performApply() {
this.performOk();
}
#Override
public boolean performOk() {
PreferencesUtil.savePreferences();
return super.performOk();
}
Thanks
It is up to you to remember that Apply has been run by overriding performApply and setting a flag. You can then test the flag in performOk and skip doing the same thing.
Be sure to clear the flag if the user changes something after pressing Apply.
So something like:
private boolean saveDone = false;
public boolean performOk() {
if (!saveDone) {
saveDone = true;
store.setValue(Constants.ENABLE_DEFAULT_COLOR, this.defaultColoringCheckBox.getSelection());
PreferencesUtil.addToPreferenceStore(viewer.getTable());
PreferencesUtil.savePreferences();
}
return super.performOk();
}
Set saveDone = false if anything is changed in the page.
I think it would make sense to extract the functionality to be executed while the user wishes to apply the changes in a separate method. This method is called from apply AND ok.
I would not call "performOK" from within "performApply". In performOk the additional closing of the preferences Dialog is then performed by the super method, I suppose.

In GWT, how to reset the URL when the user hits "Cancel" in the navigation confirmation dialog?

In my GWT application, I want to ask a user confirmation when he navigates out of the current application, i.e. by entering a URL or closing the browser. This is typically done by registering a ClosingHandler and setting the desired dialog message in the onWindowClosing method. This seems to work well.
However, if the user tries to navigate say to http://www.gmail.com (by typing it in the URL bar) and hits Cancel to indicate he doesn't want to navigate, then my app keeps running but the browser's URL bar keeps indicating http://www.gmail.com. This causes a number of problems later in my application and will give the wrong result if the user bookmarks the page.
Is there a way to automatically reset the URL when the user presses Cancel?
Or, alternatively, is there a way to detect the user pressed the Cancel button? If so, is there a way to set the URL without triggering a ValueChangeEvent? (I could add some logic to prevent this, but I'd rather use a built-in mechanism if it exists.)
Not sure if this works but did you try: History.newItem(History.getToken(), false); to reset the URL? It does set the history token without triggering a new history item.
I managed to do this. It looks like GWT DeferredCommand are executed after the confirmation window has been closed. This, combined with Hilbrand's answer above, give me exactly what I want. Here is exactly what I do:
public final void onWindowClosing(Window.ClosingEvent event) {
event.setMessage(onLeaveQuestion);
DeferredCommand.addCommand( new Command() {
public void execute() {
Window.Location.replace(currentLocation);
}
});
}
Where currentLocation is obtained by calling Window.Location.getHref() every time the history token changes.
I solved this by creating a custom PlaceController and replacing the token in the url. Not an ideal solution but it works!
if (warning == null || Window.confirm(warning)) {
where = newPlace;
eventBus.fireEvent(new PlaceChangeEvent(newPlace));
currentToken = History.getToken();
} else {
// update the url when user clicks cancel in confirm popup.
History.replaceItem(currentToken, 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