Example usage for com.google.gwt.user.client Window addWindowClosingHandler

List of usage examples for com.google.gwt.user.client Window addWindowClosingHandler

Introduction

In this page you can find the example usage for com.google.gwt.user.client Window addWindowClosingHandler.

Prototype

public static HandlerRegistration addWindowClosingHandler(final ClosingHandler handler) 

Source Link

Document

Adds a Window.ClosingEvent handler.

Usage

From source file:org.opencms.ui.client.CmsWindowCloseConnector.java

License:Open Source License

/**
 * @see com.vaadin.client.extensions.AbstractExtensionConnector#extend(com.vaadin.client.ServerConnector)
 *///from w w  w  . jav a  2 s. c  o m
@Override
protected void extend(ServerConnector target) {

    Window.addWindowClosingHandler(new ClosingHandler() {

        public void onWindowClosing(ClosingEvent event) {

            handleClose();
        }
    });
}

From source file:org.openremote.web.console.util.BrowserUtils.java

License:Open Source License

/**
 * History management - currently this just disables the back button
 * need full history support for screen history.
 *//*from w  w  w  .j  a v a2s .c o m*/
public static void setupHistory() {
    final String initToken = History.getToken();
    if (initToken.length() == 0) {
        History.newItem("main");
    }

    // Add history listener
    HandlerRegistration historyHandlerRegistration = History
            .addValueChangeHandler(new ValueChangeHandler<String>() {
                @Override
                public void onValueChange(ValueChangeEvent<String> event) {
                    String token = event.getValue();
                    if (initToken.equals(token)) {
                        History.newItem(initToken);
                    }
                }
            });

    // Now that we've setup our listener, fire the initial history state.
    History.fireCurrentHistoryState();

    Window.addWindowClosingHandler(new ClosingHandler() {
        boolean reloading = false;

        @Override
        public void onWindowClosing(ClosingEvent event) {
            if (!reloading) {
                String userAgent = Window.Navigator.getUserAgent();
                if (userAgent.contains("MSIE")) {
                    if (!Window.confirm("Do you really want to exit?")) {
                        reloading = true;
                        Window.Location.reload(); // For IE
                    }
                } else {
                    event.setMessage("Web Console"); // For other browser
                }
            }
        }
    });
}

From source file:org.pentaho.mantle.client.solutionbrowser.tabs.MantleTabPanel.java

License:Open Source License

public MantleTabPanel() {
    setupNativeHooks(this);
    // add window close listener
    Window.addWindowClosingHandler(new ClosingHandler() {

        public void onWindowClosing(ClosingEvent event) {
            // close only if we have stuff open
            if (getTabBar().getTabCount() > 0) {
                event.setMessage(Messages.getString("windowCloseWarning")); //$NON-NLS-1$
            }/*from  ww w. ja  v a2 s . c om*/
        }
    });

    addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() {
        public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {
            previousIndex = getTabBar().getSelectedTab();
        }
    });

    addSelectionHandler(new SelectionHandler<Integer>() {

        public void onSelection(SelectionEvent<Integer> event) {
            int tabIndex = event.getSelectedItem();
            SolutionBrowserPerspective.getInstance().fireSolutionBrowserListenerEvent(
                    SolutionBrowserListener.EventType.DESELECT, previousIndex);
            SolutionBrowserPerspective.getInstance()
                    .fireSolutionBrowserListenerEvent(SolutionBrowserListener.EventType.SELECT, tabIndex);
            if (previousIndex != tabIndex) {
                Widget tabPanel = getWidget(tabIndex);
                Window.setTitle(Messages.getString("productName") + " - " + getCurrentTab().getText()); //$NON-NLS-1$ //$NON-NLS-2$

                if (tabPanel instanceof IFrameTabPanel) {
                    NamedFrame frame = ((IFrameTabPanel) tabPanel).getFrame();
                    frame.setVisible(true);
                    refreshIfPDF();
                }
            }
            for (int i = 0; i < tabIndex; i++) {
                hideFrame(i);
            }
            for (int i = tabIndex + 1; i < getTabBar().getTabCount(); i++) {
                hideFrame(i);
            }
        }
    });
    setHeight("100%"); //$NON-NLS-1$
    setWidth("100%"); //$NON-NLS-1$
}

From source file:org.pentaho.mantle.client.ui.tabs.MantleTabPanel.java

License:Open Source License

public MantleTabPanel(boolean setupNativeHooks) {
    super();//w  ww.  java 2s  . c o m
    if (setupNativeHooks) {
        setupNativeHooks(this);
    }
    // add window close listener
    Window.addWindowClosingHandler(new ClosingHandler() {

        public void onWindowClosing(ClosingEvent event) {
            // close only if we have stuff open
            if (getTabCount() > 0) {
                for (int i = 0; i < getTabCount(); i++) {
                    Element frameElement = getFrameElement(getTab(i));
                    if (hasUnsavedChanges(frameElement)) {
                        event.setMessage(Messages.getString("windowCloseWarning")); //$NON-NLS-1$
                        return;
                    }
                }
            }
        }
    });
}

From source file:org.rstudio.studio.client.common.rstudioapi.AskSecretManager.java

License:Open Source License

@Inject
public AskSecretManager(final RStudioAPIServerOperations server, EventBus eventBus,
        final GlobalDisplay globalDisplay, final Satellite satellite, final SatelliteManager satelliteManager,
        final DependencyManager dependencyManager) {

    eventBus.addHandler(AskSecretEvent.TYPE, new AskSecretEvent.Handler() {
        private boolean handleAskSecret(String targetWindow) {
            // calculate the current window name
            String window = StringUtil.notNull(satellite.getSatelliteName());

            // handle it if the target is us
            if (window.equals(targetWindow))
                return true;

            // also handle if we are the main window and the specified
            // satellite doesn't exist
            if (!Satellite.isCurrentWindowSatellite() && !satelliteManager.satelliteWindowExists(targetWindow))
                return true;

            // othewise don't handle
            else//w w w  .ja  v a2s  .c om
                return false;
        }

        @Override
        public void onAskSecret(final AskSecretEvent e) {
            if (!handleAskSecret(e.getWindow()))
                return;

            asksecretPending_ = true;

            AskSecretDialog dialog = new AskSecretDialog(e.getTitle(), e.getPrompt(), e.getCanRemember(),
                    e.getHasSecret(), dependencyManager,
                    new ProgressOperationWithInput<AskSecretDialogResult>() {
                        @Override
                        public void execute(final AskSecretDialogResult result,
                                final ProgressIndicator indicator) {
                            asksecretPending_ = false;

                            RSAEncrypt.encrypt_ServerOnly(server, result.getSecret(),
                                    new RSAEncrypt.ResponseCallback() {
                                        @Override
                                        public void onSuccess(String encryptedData) {
                                            server.askSecretCompleted(encryptedData, result.getRemember(),
                                                    result.getHasChanged(),
                                                    new VoidServerRequestCallback(indicator));

                                        }

                                        @Override
                                        public void onFailure(ServerError error) {
                                            Debug.logError(error);
                                            server.askSecretCompleted(null, false, false,
                                                    new SimpleRequestCallback<Void>());
                                        }
                                    });
                        }
                    }, new Operation() {
                        @Override
                        public void execute() {
                            asksecretPending_ = false;

                            server.askSecretCompleted(null, false, false, new SimpleRequestCallback<Void>());
                        }
                    });
            dialog.showModal();
        }
    });

    // if there is an asksecret pending when the window closes then send an
    // asksecret cancel
    Window.addWindowClosingHandler(new ClosingHandler() {

        @Override
        public void onWindowClosing(ClosingEvent event) {
            if (asksecretPending_) {
                asksecretPending_ = false;

                server.askSecretCompleted(null, false, false, new SimpleRequestCallback<Void>());
            }

        }
    });

}

From source file:org.rstudio.studio.client.common.satellite.Satellite.java

License:Open Source License

public void initialize(String name, CommandWithArg<JavaScriptObject> onReactivated) {
    onReactivated_ = onReactivated;/* w  w w .j av  a  2s. c o m*/
    initializeNative(name);

    // NOTE: Desktop doesn't seem to get onWindowClosing events in Qt 4.8
    // so we instead rely on an explicit callback from the desktop frame
    // to notifyRStudioSatelliteClosing
    if (!Desktop.isDesktop()) {
        Window.addWindowClosingHandler(new ClosingHandler() {
            @Override
            public void onWindowClosing(ClosingEvent event) {
                fireCloseEvent();
            }
        });
    }
}

From source file:org.rstudio.studio.client.common.vcs.AskPassManager.java

License:Open Source License

@Inject
public AskPassManager(final VCSServerOperations server, EventBus eventBus, final GlobalDisplay globalDisplay,
        final Satellite satellite, final SatelliteManager satelliteManager) {

    eventBus.addHandler(AskPassEvent.TYPE, new AskPassEvent.Handler() {
        private boolean handleAskPass(String targetWindow) {
            // calculate the current window name
            String window = StringUtil.notNull(satellite.getSatelliteName());

            // handle it if the target is us
            if (window.equals(targetWindow))
                return true;

            // also handle if we are the main window and the specified
            // satellite doesn't exist
            if (!satellite.isCurrentWindowSatellite() && !satelliteManager.satelliteWindowExists(targetWindow))
                return true;

            // othewise don't handle
            else//from  w  w w. j av a2 s.  co m
                return false;
        }

        @Override
        public void onAskPass(final AskPassEvent e) {
            if (!handleAskPass(e.getWindow()))
                return;

            askpassPending_ = true;

            globalDisplay.promptForPassword("Password", e.getPrompt(), "", e.getRememberPasswordPrompt(),
                    rememberByDefault_, new ProgressOperationWithInput<PromptWithOptionResult>() {
                        @Override
                        public void execute(final PromptWithOptionResult result,
                                final ProgressIndicator indicator) {
                            askpassPending_ = false;

                            rememberByDefault_ = result.extraOption;

                            RSAEncrypt.encrypt_ServerOnly(server, result.input,
                                    new RSAEncrypt.ResponseCallback() {
                                        @Override
                                        public void onSuccess(String encryptedData) {
                                            server.askpassCompleted(encryptedData,
                                                    !StringUtil.isNullOrEmpty(e.getRememberPasswordPrompt())
                                                            && result.extraOption,
                                                    new VoidServerRequestCallback(indicator));

                                        }

                                        @Override
                                        public void onFailure(ServerError error) {
                                            Debug.logError(error);
                                        }
                                    });
                        }
                    }, new Operation() {
                        @Override
                        public void execute() {
                            askpassPending_ = false;

                            server.askpassCompleted(null, false, new SimpleRequestCallback<Void>());
                        }
                    });
        }
    });

    // if there is an askpass pending when the window closes then send an
    // askpass cancel
    Window.addWindowClosingHandler(new ClosingHandler() {

        @Override
        public void onWindowClosing(ClosingEvent event) {
            if (askpassPending_) {
                askpassPending_ = false;

                server.askpassCompleted(null, false, new SimpleRequestCallback<Void>());
            }

        }
    });

}

From source file:org.rstudio.studio.client.server.remote.RemoteServerEventListener.java

License:Open Source License

public RemoteServerEventListener(RemoteServer server, ClientEventHandler externalEventHandler) {
    server_ = server;//from w  ww .j a  va 2 s.  co  m
    externalEventHandler_ = externalEventHandler;
    eventDispatcher_ = new ClientEventDispatcher(server_.getEventBus());
    lastEventId_ = -1;
    listenCount_ = 0;
    listenErrorCount_ = 0;
    isListening_ = false;
    sessionWasQuit_ = false;

    // we take the liberty of stopping ourselves if the window is on 
    // the verge of being closed. this allows us to prevent the scenario:
    //
    //  - window closes and the browser terminates the listener connection
    //  - onError is called when the connection is terminated -- this results
    //    in another call to listen() which starts a new connection
    //  - now we have a "leftover" connection still active with the server
    //    even after the user has left the page
    //
    // we can't use Window CloseEvent because this occurs *after* the 
    // connection is terminated and restarted in onError. we currently
    // don't handle the ClosingEvent elsewhere in the application so calling
    // stop() here is as good as calling it in CloseEvent. however, even
    // if we did handle ClosingEvent and show a prompt which resulted in
    // the window NOT closing this would still be OK as the event listener
    // would still be restarted as necessary by the call to ensureEvents
    // 
    // note that in the future if we need to make sure event listening
    // is preserved even in the close cancelled case described above
    // (e.g. for multi-user cases) then we would need to make sure there
    // is another way to restart the listener (perhaps a global timer
    // that checks for isListening every few seconds, or perhaps some
    // abstraction over addWindowClosingHandler that allows "undo" of 
    // things which were closed or shutdown during closing
    Window.addWindowClosingHandler(new ClosingHandler() {
        public void onWindowClosing(ClosingEvent event) {
            stop();
        }
    });
}

From source file:org.rstudio.studio.client.workbench.views.source.editors.text.ChunkSatelliteWindow.java

License:Open Source License

@Override
protected void onInitialize(LayoutPanel mainPanel, JavaScriptObject params) {
    chunkWindowParams_ = params.cast();/*w  ww  . ja  v a 2 s .  c om*/

    String title = "RStudio: Notebook Output";
    Window.setTitle(title);

    ChunkOutputHost chunkOutputHost = new ChunkOutputHost() {
        @Override
        public void onOutputRemoved(final ChunkOutputWidget widget) {
        }

        @Override
        public void onOutputHeightChanged(ChunkOutputWidget widget, int height, boolean ensureVisible) {
        }
    };

    chunkOutputWidget_ = new ChunkOutputWidget(chunkWindowParams_.getDocId(), chunkWindowParams_.getChunkId(),
            RmdChunkOptions.create(), ChunkOutputWidget.EXPANDED, false, // can close
            chunkOutputHost, ChunkOutputSize.Full);

    Element ele = chunkOutputWidget_.getElement();
    ele.addClassName(ThemeStyles.INSTANCE.selectableText());

    // Append the chunkOutputWidget as an HTML element, not as a widget.
    // Why? Chunks are widgets that are attached to the ACE editor as HTML
    // elements, not as widgets. The reason being that GWT does not support
    // triggering events for widgets that are not attached to their hierarchy.
    // Therefore, if we attach this element as a widget, GWT will remove 
    // events in some cases which will cause functionality to be lost.
    mainPanel.getElement().appendChild(chunkOutputWidget_.getElement());

    chunkOutputWidget_.getElement().getStyle().setHeight(100, Unit.PCT);

    mainPanel.addStyleName("ace_editor_theme");

    pEventBus_.get().addHandler(ChunkSatelliteCodeExecutingEvent.TYPE, this);
    pEventBus_.get().addHandler(ChunkSatelliteCacheEditorStyleEvent.TYPE, this);
    pEventBus_.get().addHandler(ChunkPlotRefreshedEvent.TYPE, this);
    pEventBus_.get().addHandler(ChunkPlotRefreshFinishedEvent.TYPE, this);
    pEventBus_.get().addHandler(ChunkChangeEvent.TYPE, this);
    pEventBus_.get().addHandler(RmdChunkOutputFinishedEvent.TYPE, this);
    pEventBus_.get().addHandler(RmdChunkOutputEvent.TYPE, this);

    Window.addWindowClosingHandler(new ClosingHandler() {
        @Override
        public void onWindowClosing(ClosingEvent arg0) {
            server_.cleanReplayNotebookChunkPlots(chunkWindowParams_.getDocId(),
                    chunkWindowParams_.getChunkId(), new ServerRequestCallback<Void>() {
                        @Override
                        public void onError(ServerError error) {
                        }
                    });
        }
    });

    pEventBus_.get().fireEventToMainWindow(new ChunkSatelliteWindowOpenedEvent(chunkWindowParams_.getDocId(),
            chunkWindowParams_.getChunkId()));
}

From source file:org.rstudio.studio.client.workbench.views.source.model.DocUpdateSentinel.java

License:Open Source License

public DocUpdateSentinel(SourceServerOperations server, DocDisplay docDisplay, SourceDocument sourceDoc,
        ProgressIndicator progress, DirtyState dirtyState, EventBus events) {
    server_ = server;//from  w w w  . jav a  2  s .  com
    docDisplay_ = docDisplay;
    sourceDoc_ = sourceDoc;
    progress_ = progress;
    dirtyState_ = dirtyState;
    eventBus_ = events;
    changeTracker_ = docDisplay.getChangeTracker();

    bufferedCommand_ = new TimeBufferedCommand(2000) {
        @Override
        protected void performAction(boolean shouldSchedulePassive) {
            assert !shouldSchedulePassive;
            maybeAutoSave();
        }
    };

    docDisplay_.addValueChangeHandler(this);
    docDisplay_.addFoldChangeHandler(this);

    // Web only
    closeHandlerReg_ = Window.addWindowClosingHandler(new ClosingHandler() {
        public void onWindowClosing(ClosingEvent event) {
            if (changesPending_)
                event.setMessage("Some of your source edits are still being "
                        + "backed up. If you continue, your latest "
                        + "changes may be lost. Do you want to continue?");
        }
    });

    // Desktop only
    lastChanceSaveHandlerReg_ = events.addHandler(LastChanceSaveEvent.TYPE, new LastChanceSaveHandler() {
        public void onLastChanceSave(LastChanceSaveEvent event) {
            // We're quitting. Save one last time.
            final Token token = event.acquire();
            boolean saving = doSave(null, null, null, new ProgressIndicator() {
                public void onProgress(String message) {
                }

                public void clearProgress() {
                    // alternate way to signal completion. safe to quit
                    token.release();
                }

                public void onCompleted() {
                    // We saved successfully. We're safe to quit now.
                    token.release();
                }

                public void onError(String message) {
                    // The save didn't succeed. Oh well. Nothing we can
                    // do but quit.
                    token.release();
                }
            });

            if (!saving) {
                // No save was performed (not needed). We're safe to quit
                // now, no need to wait for server requests to complete.
                token.release();
            }
        }
    });
}