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.rstudio.studio.client.workbench.views.source.SourceWindow.java

License:Open Source License

@Inject
public SourceWindow(Provider<DesktopHooks> pDesktopHooks, Satellite satellite, EventBus events,
        MacZoomHandler zoomHandler, SourceShim shim, SnippetServerOperations snippetServer,
        ApplicationCommandManager appCommandManager, EditorCommandManager editorCommandManager) {
    sourceShim_ = shim;//from  w  w  w . j  a v  a 2 s  . c  om
    events_ = events;
    satellite_ = satellite;

    // this class is for satellite source windows only; if an instance gets
    // created in the main window, don't hook up any of its behaviors
    if (!Satellite.isCurrentWindowSatellite())
        return;

    // add event handlers
    events.addHandler(LastSourceDocClosedEvent.TYPE, this);
    events.addHandler(PopoutDocEvent.TYPE, this);
    events.addHandler(DocTabDragStartedEvent.TYPE, this);

    // set up desktop hooks (required to e.g. process commands issued by 
    // the desktop frame)
    pDesktopHooks.get();

    // export callbacks for main window
    exportFromSatellite();

    // load custom snippets into this window
    snippetServer.getSnippets(new ServerRequestCallback<JsArray<SnippetData>>() {
        @Override
        public void onResponseReceived(JsArray<SnippetData> snippets) {
            if (snippets != null && snippets.length() > 0) {
                events_.fireEvent(new SnippetsChangedEvent((SnippetsChangedEvent.Data) snippets));
            }
        }

        @Override
        public void onError(ServerError error) {
            // log this error, but don't bother the user with it--their own
            // snippets may not work but any real errors should be handled in
            // the main window
            Debug.logError(error);
        }
    });

    // in desktop mode, the frame checks to see if we want to be closed, but
    // in web mode the best we can do is prompt if the user attempts to close
    // a source window with unsaved chaanges.
    if (!Desktop.isDesktop()) {
        Window.addWindowClosingHandler(new ClosingHandler() {
            @Override
            public void onWindowClosing(ClosingEvent event) {
                // ignore window closure if initiated from the main window
                if (satellite_.isClosePending()) {
                    markReadyToClose();
                    return;
                }

                ArrayList<UnsavedChangesTarget> unsaved = sourceShim_
                        .getUnsavedChanges(Source.TYPE_FILE_BACKED);

                // in a source window, we need to look for untitled docs too
                if (!SourceWindowManager.isMainSourceWindow()) {
                    ArrayList<UnsavedChangesTarget> untitled = sourceShim_
                            .getUnsavedChanges(Source.TYPE_UNTITLED);
                    unsaved.addAll(untitled);
                }

                if (unsaved.size() > 0) {
                    String msg = "Your edits to the ";
                    if (unsaved.size() == 1) {
                        msg += "file " + unsavedTargetDesc(unsaved.get(0));
                    } else {
                        msg += "files ";
                        for (int i = 0; i < unsaved.size(); i++) {
                            msg += unsavedTargetDesc(unsaved.get(i));
                            if (i == unsaved.size() - 2)
                                msg += " and ";
                            else if (i < unsaved.size() - 2)
                                msg += ", ";
                        }
                    }
                    msg += " have not been saved.";
                    event.setMessage(msg);
                }
            }
        });
    }
}

From source file:org.thechiselgroup.biomixer.client.workbench.init.WorkbenchInitializer.java

License:Apache License

protected void initWindowClosingConfirmationDialog() {
    Window.addWindowClosingHandler(new ClosingHandler() {
        @Override/*from   ww  w  .  j  av  a 2s  .c  om*/
        public void onWindowClosing(ClosingEvent event) {
            event.setMessage("Unsaved changes to the workspace will be lost.");
        }
    });
}

From source file:org.uberfire.client.mvp.LockManagerImpl.java

License:Apache License

private void releaseLockOnClose() {
    closeHandler = Window.addWindowClosingHandler(new ClosingHandler() {
        @Override//from   ww  w . j ava  2s .c o m
        public void onWindowClosing(ClosingEvent event) {
            releaseLock();
        }
    });
}

From source file:org.uberfire.client.workbench.Workbench.java

License:Apache License

private void bootstrap() {
    logger.info("Starting workbench...");
    ((SessionInfoImpl) currentSession()).setId(((ClientMessageBusImpl) bus).getSessionId());

    layout.setMarginWidgets(isStandaloneMode, headersToKeep);
    layout.onBootstrap();/*from w  w  w.j a v  a 2s  . c om*/

    addLayoutToRootPanel(layout);

    //Lookup PerspectiveProviders and if present launch it to set-up the Workbench
    if (!isStandaloneMode) {
        final PerspectiveActivity homePerspective = getHomePerspectiveActivity();
        if (homePerspective != null) {
            appReady.fire(new ApplicationReadyEvent());
            placeManager.goTo(new DefaultPlaceRequest(homePerspective.getIdentifier()));
        } else {
            logger.error("No home perspective available!");
        }
    } else {
        handleStandaloneMode(Window.Location.getParameterMap());
    }

    // Ensure orderly shutdown when Window is closed (eg. saves workbench state)
    Window.addWindowClosingHandler(new ClosingHandler() {

        @Override
        public void onWindowClosing(ClosingEvent event) {
            workbenchCloseHandler.onWindowClose(workbenchCloseCommand);
        }
    });

    // Resizing the Window should resize everything
    Window.addResizeHandler(new ResizeHandler() {
        @Override
        public void onResize(ResizeEvent event) {
            layout.resizeTo(event.getWidth(), event.getHeight());
        }
    });

    // Defer the initial resize call until widgets are rendered and sizes are available
    Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
        @Override
        public void execute() {
            layout.onResize();
        }
    });
}

From source file:org.unitime.timetable.gwt.client.sectioning.StudentSectioningPage.java

License:Apache License

public StudentSectioningPage(final Mode mode) {
    final UserAuthentication userAuthentication = new UserAuthentication(
            UniTimePageHeader.getInstance().getMiddle(),
            mode.isSectioning() ? !CONSTANTS.isAuthenticationRequired() : false);

    if (Window.Location.getParameter("student") == null)
        iSectioningService.whoAmI(new AsyncCallback<String>() {
            public void onFailure(Throwable caught) {
                if (!mode.isSectioning() || CONSTANTS.isAuthenticationRequired()
                        || CONSTANTS.tryAuthenticationWhenGuest()) {
                    if (CONSTANTS.allowUserLogin())
                        userAuthentication.authenticate();
                    else if (!mode.isSectioning() || CONSTANTS.isAuthenticationRequired())
                        ToolBox.open(GWT.getHostPageBaseURL() + "login.do?target="
                                + URL.encodeQueryString(Window.Location.getHref()));
                    else
                        userAuthentication.authenticated(null);
                }/*from w w  w  .j av  a2  s  .c o  m*/
            }

            public void onSuccess(String result) {
                if (result == null) { // not authenticated
                    if (!mode.isSectioning() || CONSTANTS.isAuthenticationRequired()
                            || CONSTANTS.tryAuthenticationWhenGuest()) {
                        if (CONSTANTS.allowUserLogin())
                            userAuthentication.authenticate();
                        else if (!mode.isSectioning() || CONSTANTS.isAuthenticationRequired())
                            ToolBox.open(GWT.getHostPageBaseURL() + "login.do?target="
                                    + URL.encodeQueryString(Window.Location.getHref()));
                        else
                            userAuthentication.authenticated(result);
                    } else {
                        userAuthentication.authenticated(result);
                    }
                } else {
                    userAuthentication.authenticated(result);
                }
            }
        });

    final AcademicSessionSelector sessionSelector = new AcademicSessionSelector(
            UniTimePageHeader.getInstance().getRight(), mode);

    iSectioningService.getProperties(null, new AsyncCallback<SectioningProperties>() {
        public void onFailure(Throwable caught) {
        }

        public void onSuccess(SectioningProperties result) {
            if (result.isAdmin()) {
                userAuthentication.setAllowLookup(true);
                if (Window.Location.getParameter("session") != null)
                    sessionSelector.selectSession(Long.valueOf(Window.Location.getParameter("session")),
                            new AsyncCallback<Boolean>() {
                                @Override
                                public void onFailure(Throwable caught) {
                                }

                                @Override
                                public void onSuccess(Boolean result) {
                                    if (Window.Location.getParameter("student") != null)
                                        UserAuthentication.personFound(Window.Location.getParameter("student"));
                                }
                            });
            } else {
                userAuthentication.setAllowLookup(false);
            }
        }
    });

    UniTimePageHeader.getInstance().getLeft().setVisible(false);
    UniTimePageHeader.getInstance().getLeft().setPreventDefault(true);

    final StudentSectioningWidget widget = new StudentSectioningWidget(true, sessionSelector,
            userAuthentication, mode, true);

    initWidget(widget);

    UniTimePageHeader.getInstance().getRight().setClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            if (widget.isChanged()) {
                UniTimeConfirmationDialog.confirm(widget.useDefaultConfirmDialog(),
                        MESSAGES.queryLeaveChanges(), new Command() {
                            @Override
                            public void execute() {
                                sessionSelector.selectSession();
                            }
                        });
            } else {
                sessionSelector.selectSession();
            }
        }
    });
    UniTimePageHeader.getInstance().getMiddle().setClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            if (CONSTANTS.allowUserLogin()) {
                if (widget.isChanged()) {
                    UniTimeConfirmationDialog.confirm(widget.useDefaultConfirmDialog(),
                            MESSAGES.queryLeaveChanges(), new Command() {
                                @Override
                                public void execute() {
                                    if (userAuthentication.isLoggedIn())
                                        userAuthentication.logOut();
                                    else
                                        userAuthentication.authenticate();
                                }
                            });
                } else {
                    if (userAuthentication.isLoggedIn())
                        userAuthentication.logOut();
                    else
                        userAuthentication.authenticate();
                }
            } else if (userAuthentication.isAllowLookup()) {
                userAuthentication.doLookup();
            } else if (userAuthentication.isLoggedIn()) {
                ToolBox.open(GWT.getHostPageBaseURL() + "logOut.do");
            } else {
                ToolBox.open(GWT.getHostPageBaseURL() + "login.do?target="
                        + URL.encodeQueryString(Window.Location.getHref()));
            }
        }
    });

    userAuthentication.addUserAuthenticatedHandler(new UserAuthentication.UserAuthenticatedHandler() {
        public void onLogIn(UserAuthenticatedEvent event) {
            if (!mode.isSectioning())
                sessionSelector.selectSession(null, false);
            sessionSelector.selectSession();
        }

        public void onLogOut(UserAuthenticatedEvent event) {
            if (!event.isGuest()) {
                widget.clearMessage();
                widget.clear();
                // sessionSelector.selectSession(null);
            }
            userAuthentication.authenticate();
        }
    });

    sessionSelector.addAcademicSessionChangeHandler(new AcademicSessionProvider.AcademicSessionChangeHandler() {
        public void onAcademicSessionChange(AcademicSessionProvider.AcademicSessionChangeEvent event) {
            if (event.isChanged()) {
                widget.clearMessage();
                widget.clear();
            }
            widget.checkEligibility(event.getNewAcademicSessionId(), null, false, null);
            userAuthentication.setLookupOptions(
                    "mustHaveExternalId,source=students,session=" + event.getNewAcademicSessionId());
        }
    });

    if (Window.Location.getParameter("session") == null)
        iSectioningService.lastAcademicSession(mode.isSectioning(),
                new AsyncCallback<AcademicSessionProvider.AcademicSessionInfo>() {
                    public void onFailure(Throwable caught) {
                        if (!userAuthentication.isShowing() && !UniTimeFrameDialog.hasDialog())
                            sessionSelector.selectSession();
                    }

                    public void onSuccess(AcademicSessionProvider.AcademicSessionInfo result) {
                        sessionSelector.selectSession(result, true);
                    }
                });

    Window.addWindowClosingHandler(new Window.ClosingHandler() {
        @Override
        public void onWindowClosing(ClosingEvent event) {
            if (widget.isChanged()) {
                if (LoadingWidget.getInstance().isShowing())
                    LoadingWidget.getInstance().hide();
                event.setMessage(MESSAGES.queryLeaveChanges());
            }
        }
    });
}

From source file:org.vaadin.alump.beforeunload.gwt.client.connect.BeforeUnloadConnector.java

License:Apache License

protected void init() {
    super.init();

    winCloseRegistration = Window.addWindowClosingHandler(closingHandler);
}

From source file:org.xwiki.gwt.user.client.ui.rta.RichTextArea.java

License:Open Source License

@Override
public void sinkEvents(int eventBitsToAdd) {
    // Events listeners are not registered right away but after the widget is attached to the browser's document for
    // the first time. This deferred sink behavior is not suited for the load event because the load event could be
    // fired before the load listener is registered. This can happen if the underlying element is loaded
    // synchronously (e.g. in-line frame with the source attribute unspecified).
    if (!isOrWasAttached() && (eventBitsToAdd & Event.ONLOAD) != 0) {
        // Sink the load event immediately.
        DOM.sinkEvents(getElement(), eventBitsToAdd | DOM.getEventsSunk(getElement()));
        DOM.setEventListener(getElement(), this);
        // We can't remove the listener on detach so we listen to window closing event to remove the listener.
        Window.addWindowClosingHandler(this);
    } else {// w w w.  j ava  2  s .c  o m
        // Preserve deferred sink behavior.
        super.sinkEvents(eventBitsToAdd);
    }
}

From source file:org.xwiki.gwt.wysiwyg.client.PlainTextEditor.java

License:Open Source License

/**
 * Creates a new plain text editor that wraps the given text area element.
 * /*from  ww  w .jav  a 2s . c o  m*/
 * @param hook the element replaced by the newly created plain text editor
 */
public PlainTextEditor(Element hook) {
    this.hook = hook;

    textArea = new TextArea();
    textArea.setStyleName("xPlainTextEditor");
    textArea.setHeight(Math.max(hook.getOffsetHeight(), 100) + "px");
    textArea.addBlurHandler(this);

    Window.addWindowClosingHandler(this);

    container = new FlowPanel();
    container.add(textArea);

    initWidget(container);
}

From source file:org.xwiki.gwt.wysiwyg.client.plugin.submit.SubmitPlugin.java

License:Open Source License

@Override
public void init(RichTextArea textArea, Config config) {
    super.init(textArea, config);

    String hookId = getConfig().getParameter("hookId");
    getTextArea().getCommandManager().registerCommand(SUBMIT, new SubmitExecutable(textArea, hookId));

    if (getTextArea().getCommandManager().isSupported(SUBMIT)) {
        Element hook = (Element) Document.get().getElementById(hookId);
        // See if the hook is inside an HTML form.
        form = (Element) DOMUtils.getInstance().getFirstAncestor(hook, "form");
        // We don't use hook.hasAttribute because the name attribute appears as unspecified in IE if it has been set
        // from JavaScript.
        if (form != null && !StringUtils.isEmpty(hook.getAttribute(NAME_ATTRIBUTE))) {
            // Put additional hidden data on the HTML form.
            hiddenConfig = new HiddenConfig();
            // All the parameters of this hidden configuration will be prefixed with the name of the hook.
            hiddenConfig.setNameSpace(hook.getAttribute(NAME_ATTRIBUTE));
            // This flag tells the server that the editor output requires HTML conversion.
            if (textArea.isEnabled()) {
                hiddenConfig.addFlag(REQUIRES_HTML_CONVERSION);
            }/*from  w w  w.  java 2  s. c  o  m*/
            // The storage syntax for this rich text area.
            hiddenConfig.setParameter(SYNTAX, config.getParameter(SYNTAX, DEFAULT_SYNTAX));

            rootExtension.addFeature(SUBMIT.toString(), hiddenConfig);
            getUIExtensionList().add(rootExtension);

            // Listen to submit event.
            hookSubmitEvent(form);
        }

        // Save the initial content of the rich text area, after all the plug-ins have been initialized.
        // Note that we can't use the "loaded" action event because event handlers are registered after the current
        // event is processed. In this case the "loaded" action event is fired after all the plug-ins have been
        // initialized but still while the rich text area "load" event is handled (and the reason for this is to
        // ensure the order of the action events).
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
            public void execute() {
                onSubmit();
            }
        });

        // Submit the content when the rich text area looses the focus or the user navigates away.
        saveRegistration(getTextArea().addBlurHandler(this));
        saveRegistration(Window.addWindowClosingHandler(this));

        // Prevent the rich text area from being submitted when it is disabled.
        getTextArea().getCommandManager().addCommandListener(this);
    }
}

From source file:org.xwiki.gwt.wysiwyg.client.WysiwygEditorConfig.java

License:Open Source License

/**
 * Creates a new WYSIWYG editor configuration object based on the given configuration source.
 * /* www.  ja v a2s .  c o m*/
 * @param config the configuration source
 */
public WysiwygEditorConfig(Config config) {
    this.config = config;
    cache = new BackForwardCache(Element.as(DOM.getElementById(config.getParameter("cacheId", ""))));
    Window.addWindowClosingHandler(this);
}