elemental.events.Event Java Examples

The following examples show how to use elemental.events.Event. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerEventObject.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Collect extra data for element event if any has been sent from the
 * server. Note! Data is sent in the array in the same order as defined on
 * the server side.
 *
 * @param event
 *            The fired Event
 * @param methodName
 *            Method name that is called
 * @param node
 *            Target node
 * @return Array of extra event data
 */
private JsonArray getEventData(Event event, String methodName,
        StateNode node) {

    if (node.getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
            .hasPropertyValue(methodName)) {
        JsonArray dataArray = Json.createArray();
        ConstantPool constantPool = node.getTree().getRegistry()
                .getConstantPool();
        String expressionConstantKey = (String) node
                .getMap(NodeFeatures.POLYMER_EVENT_LISTENERS)
                .getProperty(methodName).getValue();

        JsArray<String> dataExpressions = constantPool
                .get(expressionConstantKey);

        for (int i = 0; i < dataExpressions.length(); i++) {
            String expression = dataExpressions.get(i);

            dataArray.set(i, getExpressionValue(event, node, expression));
        }
        return dataArray;
    }

    return null;
}
 
Example #2
Source File: Connection.java    From ThinkMap with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a connect to the plugin at the address. Calls the callback once the connection succeeds.
 *
 * @param address
 *         The address to connect to, may include the port
 * @param handler
 *         The handler to handle received events
 * @param callback
 *         The Runnable to call once the connection is completed
 */
public Connection(String address, ServerPacketHandler handler, final Runnable callback) {
    this.address = address;
    this.handler = handler;
    webSocket = Browser.getWindow().newWebSocket("ws://" + address + "/server/ws");
    // Work in binary instead of strings
    webSocket.setBinaryType("arraybuffer");
    webSocket.setOnopen(new EventListener() {
        @Override
        public void handleEvent(Event evt) {
            System.out.println("Connected to server");
            send(new InitConnection());
            if (callback != null) callback.run();
        }
    });
    webSocket.setOnmessage(this);
}
 
Example #3
Source File: ScrollPositionHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private void onBeforeUnload(Event event) {
    captureCurrentScrollPositions();

    JsonObject stateObject = createStateObjectWithHistoryIndexAndToken();

    JsonObject sessionStorageObject = Json.createObject();
    sessionStorageObject.put(X_POSITIONS,
            convertArrayToJsonArray(xPositions));
    sessionStorageObject.put(Y_POSITIONS,
            convertArrayToJsonArray(yPositions));

    Browser.getWindow().getHistory().replaceState(stateObject, "",
            Browser.getWindow().getLocation().getHref());
    try {
        Browser.getWindow().getSessionStorage().setItem(
                createSessionStorageKey(historyResetToken),
                sessionStorageObject.toJson());
    } catch (JavaScriptException e) {
        Console.error("Failed to get session storage: " + e.getMessage());
    }
}
 
Example #4
Source File: SystemErrorHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Shows an error notification for an error which is unrecoverable, using
 * the given parameters.
 *
 * @param caption
 *            the caption of the message
 * @param message
 *            the message body
 * @param details
 *            message details or {@code null} if there are no details
 * @param url
 *            a URL to redirect to when the user clicks the message or
 *            {@code null} to refresh on click
 * @param querySelector
 *            query selector to find the element under which the error will
 *            be added . If element is not found or the selector is
 *            {@code null}, body will be used
 */
public void handleUnrecoverableError(String caption, String message,
        String details, String url, String querySelector) {
    if (caption == null && message == null && details == null) {
        if (!isWebComponentMode()) {
            WidgetUtil.redirect(url);
        }
        return;
    }

    Element systemErrorContainer = handleError(caption, message, details,
            querySelector);
    if (!isWebComponentMode()) {
        systemErrorContainer.addEventListener("click",
                e -> WidgetUtil.redirect(url), false);
        Browser.getDocument().addEventListener(Event.KEYDOWN, e -> {
            int keyCode = ((KeyboardEvent) e).getKeyCode();
            if (keyCode == KeyCode.ESC) {
                e.preventDefault();
                WidgetUtil.redirect(url);
            }
        }, false);
    }
}
 
Example #5
Source File: RouterLinkHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void handleRouterLinkClick(Event clickEvent, String baseURI,
        String href, Registry registry) {
    clickEvent.preventDefault();

    String location = URIResolver.getBaseRelativeUri(baseURI, href);
    if (location.contains("#")) {
        // make sure fragment event gets fired after response
        new FragmentHandler(Browser.getWindow().getLocation().getHref(),
                href, registry).bind();

        // don't send hash to server
        location = location.split("#", 2)[0];
    }

    JsonObject state = createNavigationEventState(href);

    sendServerNavigationEvent(registry, location, state, true);
}
 
Example #6
Source File: RouterLinkHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the anchor element, if a router link was found between the click
 * target and the event listener.
 *
 * @param clickEvent
 *            the click event
 * @return the target anchor if found, <code>null</code> otherwise
 */
private static AnchorElement getAnchorElement(Event clickEvent) {
    assert "click".equals(clickEvent.getType());

    Element target = getTargetElement(clickEvent);
    EventTarget eventListenerElement = clickEvent.getCurrentTarget();
    // Target can become null if another click handler detaches the element
    while (target != null && target != eventListenerElement) {
        if (isAnchorElement(target)) {
            return (AnchorElement) target;
        }
        target = target.getParentElement();
    }

    return null;
}
 
Example #7
Source File: RouterLinkHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private static boolean hasModifierKeys(Event clickEvent) {
    assert "click".equals(clickEvent.getType());

    MouseEvent event = (MouseEvent) clickEvent;
    return event.isAltKey() || event.isCtrlKey() || event.isMetaKey()
            || event.isShiftKey();
}
 
Example #8
Source File: CubaGridWidget.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEventHandlerShouldHandleEvent(Element targetElement, GridEvent<JsonObject> event) {
    if (!event.getDomEvent().getType().equals(Event.MOUSEDOWN)
            && !event.getDomEvent().getType().equals(Event.CLICK)) {
        return super.isEventHandlerShouldHandleEvent(targetElement, event);
    }

    // By default, clicking on widget renderer prevents cell focus changing
    // for some widget renderers we want to allow focus changing
    Widget widget = WidgetUtil.findWidget(targetElement, null);
    return !(isWidgetOrParentFocusable(widget))
            || isClickThroughEnabled(targetElement);
}
 
Example #9
Source File: Client.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
private void clicked(Event e) {
	button.setAttribute("disabled", "");
	thinking.getStyle().setProperty("display", "");

	XMLHttpRequest xhr = XMLHttpRequest.create();
	xhr.setOnReadyStateChange(a -> {
		if (xhr.getReadyState() == 4 && xhr.getStatus() == 200) {
			responsed(xhr.getResponseText());
		}
	});
	xhr.open("POST", url);
	xhr.send();
}
 
Example #10
Source File: PopStateHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private void onPopStateEvent(Event e) {
    // refresh page if application has stopped
    if (!registry.getUILifecycle().isRunning()) {
        WidgetUtil.refresh();
        return;
    }

    final String path = Browser.getWindow().getLocation().getPathname();
    final String query = Browser.getWindow().getLocation().getSearch();

    assert pathAfterPreviousResponse != null : "Initial response has not ended before pop state event was triggered";

    // don't visit server on pop state events caused by fragment change
    boolean requiresServerSideRoundtrip =
            !(Objects.equals(path, pathAfterPreviousResponse)
                    && Objects.equals(query, queryAfterPreviousResponse));
    registry.getScrollPositionHandler().onPopStateEvent((PopStateEvent) e,
            requiresServerSideRoundtrip);
    if (!requiresServerSideRoundtrip) {
        return;
    }

    String location = URIResolver.getCurrentLocationRelativeToBaseUri();
    // don't send hash to server
    if (location.contains("#")) {
        location = location.split("#", 2)[0];
    }
    Object stateObject = WidgetUtil.getJsProperty(e, "state");
    RouterLinkHandler.sendServerNavigationEvent(registry, location,
            stateObject, false);
}
 
Example #11
Source File: ServerEventObject.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject getExpressionValue(Event event, StateNode node,
        String expression) {
    JsonObject expressionValue;

    if (serverExpectsNodeId(expression)) {
        return getPolymerPropertyObject(event, node, expression);
    }

    ServerEventDataExpression dataExpression = getOrCreateExpression(
            expression);
    expressionValue = dataExpression.evaluate(event, this);

    return expressionValue;
}
 
Example #12
Source File: ServerEventObject.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject getPolymerPropertyObject(Event event, StateNode node,
        String expression) {
    if (expression.startsWith(EVENT_PREFIX)) {
        return createPolymerPropertyObject(event, expression);
    } else {
        return getPolymerPropertyObject(node.getDomNode(), expression);
    }
}
 
Example #13
Source File: ServerEventObject.java    From flow with Apache License 2.0 5 votes vote down vote up
private JsonObject createPolymerPropertyObject(Event event,
        String expression) {
    ServerEventDataExpression dataExpression = getOrCreateExpression(
            expression);
    JsonObject expressionValue = dataExpression.evaluate(event, this);
    JsonObject object = Json.createObject();
    object.put(NODE_ID, expressionValue.getNumber(NODE_ID));
    return object;
}
 
Example #14
Source File: RouterLinkHandler.java    From flow with Apache License 2.0 5 votes vote down vote up
private static native Element getTargetElement(Event clickEvent)
/*-{
    if(clickEvent.composed) {
        return clickEvent.composedPath()[0];
    }
    return clickEvent.target;
}-*/;
 
Example #15
Source File: CubaTreeGridWidget.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEventHandlerShouldHandleEvent(Element targetElement, GridEvent<JsonObject> event) {
    if (!event.getDomEvent().getType().equals(Event.MOUSEDOWN)
            && !event.getDomEvent().getType().equals(Event.CLICK)) {
        return super.isEventHandlerShouldHandleEvent(targetElement, event);
    }

    // By default, clicking on widget renderer prevents cell focus changing
    // for some widget renderers we want to allow focus changing
    Widget widget = WidgetUtil.findWidget(targetElement, null);
    return !(isWidgetOrParentFocusable(widget))
            || isClickThroughEnabled(targetElement);
}
 
Example #16
Source File: ClientWorld.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
/**
 * Triggers an async request to load the chunk. The chunk is forwarded to all workers to be processed before being returned to the client
 *
 * @param x
 *         The chunk x position
 * @param z
 *         The chunk z position
 */
private void loadChunk(final int x, final int z) {
    final String key = chunkKey(x, z);
    if (loadingChunks.contains(key) || isLoaded(x, z)) {
        return;
    }
    final XMLHttpRequest xmlHttpRequest = Browser.getWindow().newXMLHttpRequest();
    xmlHttpRequest.open("POST", "http://" + mapViewer.getConnection().getAddress() + "/server/chunk", true);
    xmlHttpRequest.setResponseType("arraybuffer");
    xmlHttpRequest.setOnreadystatechange(new EventListener() {
        @Override
        public void handleEvent(Event evt) {
            if (xmlHttpRequest.getReadyState() != 4) return;
            if (xmlHttpRequest.getStatus() == 200) {
                // Got the chunk successfully, move on
                // to processing the chunk
                ArrayBuffer data = (ArrayBuffer) xmlHttpRequest.getResponse();
                ViewBuffer dataStream = JavascriptViewBuffer.create(data, false, 0, data.getByteLength());
                if (dataStream.getInt8(0) == 0) {
                    loadingChunks.remove(key);
                    return;
                }
                UByteBuffer sendableData = JavascriptUByteBuffer.create(data, 0, data.getByteLength());
                mapViewer.getWorkerPool().sendMessage(new ChunkLoadMessage(x, z, sendableData), true);
            } else {
                // Request failed (e.g. non-existing chunk)
                // remove from the loadingChunks set so
                // that it may be tried again
                loadingChunks.remove(key);
            }
        }
    });
    xmlHttpRequest.send(key);
}
 
Example #17
Source File: Connection.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
/**
 * Internal method to receive websocket messages
 *
 * @param evt
 *         Event
 */
@Override
public void handleEvent(Event evt) {
    MessageEvent event = (MessageEvent) evt;

    DataPacketStream packetStream = new DataPacketStream((ArrayBuffer) event.getData());
    int id = packetStream.readUByte();
    Packet<ServerPacketHandler> packet = Packets.createServerPacket(id);
    packet.read(packetStream);
    packet.handle(handler);
}
 
Example #18
Source File: TextureLoadHandler.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event event) {
    if (mapViewer.getRenderer() == null) {
        mapViewer.earlyTextures.add(this);
    } else {
        load();
    }
}
 
Example #19
Source File: WorkerPool.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event evt) {
    noOfTasks--;
    JsObjectSerializer serializer = JsObjectSerializer.from(((MessageEvent) evt).getData());
    Message message = Messages.read(serializer);
    if (message instanceof WorkerMessage) {
        ((WorkerMessage) message).setSender(id);
    }
    message.handle(mapViewer.getMessageHandler());
}
 
Example #20
Source File: MapViewer.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
/**
 * Internal method
 *
 * @param event
 *         Event
 */
@Override
public void handleEvent(Event event) {
    loaded++;
    if (loaded == 1) {
        TextureMap tmap = new TextureMap();
        tmap.deserialize(JsObjectSerializer.from(Json.parse((String) xhr.getResponse())));
        tmap.copyTextures(textures);
        tmap.copyGrassColormap(Model.grassBiomeColors);
        tmap.copyFoliageColormap(Model.foliageBiomeColors);
        // Sync to workers
        getWorkerPool().sendMessage(new TextureMessage(tmap), true);
        noTextures = tmap.getNumberVirtuals();
        virtualTextures = new VirtualTexture[noTextures];
        for (int i = 0; i < noTextures; i++) {
            virtualTextures[i] = new VirtualTexture(this, i);
        }
        imageElements = new ImageElement[tmap.getNumberOfImages()];
        for (int i = 0; i < tmap.getNumberOfImages(); i++) {
            ImageElement texture = imageElements[i] = (ImageElement) Browser.getDocument().createElement("img");
            texture.setOnload(new TextureLoadHandler(this, i, texture));
            texture.setCrossOrigin("anonymous");
            texture.setSrc("http://" + getConfigAdddress() + "/resources/blocks_" + i + ".png");
        }
        inputManager.hook();

        connection = new Connection(getConfigAdddress(), this, null);
    }
}
 
Example #21
Source File: Worker.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
@Override
public void handleEvent(Event evt) {
    MessageEvent event = (MessageEvent) evt;
    JsObjectSerializer serializer = JsObjectSerializer.from(event.getData());
    Message message = Messages.read(serializer);
    message.handle(this);
}
 
Example #22
Source File: Controller.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
public void onMenuHome(Fluent __, Event ___) {
	// Push model to view
	view.stateAndSyncMenu("home"); // the view handles this model

	// Note that old available data is already shown before any answer
	store.getTotals(this::setTotals);
}
 
Example #23
Source File: Controller.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
public void onMenuBills(Fluent __, Event ___) {
	// Push model to view
	view.stateAndSyncMenu("bills");// the view handles this model

	// Note that old available data is already shown before any answer
	store.getBills(this::setBills);
}
 
Example #24
Source File: Pojofy.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
public static <O> boolean socketReceive(String url, Event e, ObjectMapper<O> outMapper, Consumer<O> handler) {
	Object me = ((MessageEvent) e).getData();
	String meString = me.toString();
	if (meString.equals("[object ArrayBuffer]")) { // websockets
		meString = socketToString((ArrayBuffer) me);
	}
	if (!meString.startsWith("{\"url\":\"" + url + "\"")) {
		return false;
	}
	JsonObject json = Json.parse(meString);
	handler.accept(out(json.getString("body"), outMapper));
	return true;
}
 
Example #25
Source File: Controller.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
public void onMenuGrocery(Fluent __, Event ___) {
	// Push model to view
	view.stateAndSyncMenu("grocery");// the view handles this model

	// Note that old available data is already shown before any answer
	store.getGrocery(this::setGrocery);
}
 
Example #26
Source File: FluentRenderer.java    From vertxui with GNU General Public License v3.0 4 votes vote down vote up
public void b(Fluent __, Event e) {
}
 
Example #27
Source File: GwtPropertyElementBinderTest.java    From flow with Apache License 2.0 4 votes vote down vote up
private static native Event createEvent(String type)
/*-{
    return new Event(type);
 }-*/;
 
Example #28
Source File: RouterLinkHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
private static void handleClick(Registry registry, Event clickEvent) {
    if (hasModifierKeys(clickEvent)
            || !registry.getUILifecycle().isRunning()) {
        return;
    }

    AnchorElement anchor = getAnchorElement(clickEvent);
    if (anchor == null) {
        return;
    }

    final String href = anchor.getHref();
    final String baseURI = ((Element) clickEvent.getCurrentTarget())
            .getOwnerDocument().getBaseURI();

    // verify that the link is actually for this application
    if (!href.startsWith(baseURI)) {
        // scroll position is stored by a beforeunload handler in
        // ScrollPositionHandler
        return;
    }

    // special case: inside page navigation doesn't cause server side
    // round trip but need to store the scroll positions since browser adds
    // another history state
    if (isInsidePageNavigation(anchor)) {
        // there is no pop state if the hashes are exactly the same
        String currentHash = Browser.getDocument().getLocation().getHash();
        if (!currentHash.equals(anchor.getHash())) {
            registry.getScrollPositionHandler()
                    .beforeClientNavigation(href);
        }

        // the browser triggers a fragment change & pop state event
        registry.getScrollPositionHandler()
                .setIgnoreScrollRestorationOnNextPopStateEvent(true);
        return;
    }

    if (!isRouterLinkAnchorElement(anchor)) {
        return;
    }

    handleRouterLinkClick(clickEvent, baseURI, href, registry);
}
 
Example #29
Source File: FluentRenderer.java    From vertxui with GNU General Public License v3.0 4 votes vote down vote up
public void c(Fluent __, Event e) {
}
 
Example #30
Source File: FluentRenderer.java    From vertxui with GNU General Public License v3.0 4 votes vote down vote up
public void a(Fluent __, Event e) {
}