Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java
Original file line number Diff line number Diff line change
Expand Up @@ -11081,12 +11081,39 @@ protected final void sendRegisteredForPush(String id) {
}
}

protected final void pushReceived(String data) {
if (callback != null) {
/// One push handed to `PushDispatcher` by `#pushReceived(String)`.
private static final class PushDelivery implements Runnable {
private final PushCallback callback;
private final String data;

PushDelivery(PushCallback callback, String data) {
this.callback = callback;
this.data = data;
}

@Override
public void run() {
callback.push(data);
}
}

protected final void pushReceived(final String data) {
if (callback != null) {
// Through PushDispatcher like every port path, so a push is held while a
// blocking call is in progress. Inside a delivery (a port path that ends here)
// it is the same push, so deliver it in place -- on the EDT only, which is the one
// thread that delivers. A caller on another thread is marshalled to the EDT, so its
// delivery is asynchronous where master called the callback in place; no port
// calls this off the EDT today.
final PushCallback c = callback;
if (Display.getInstance().isEdt() && PushDispatcher.isDelivering()) {
c.push(data);
return;
}
PushDispatcher.dispatch(new PushDelivery(c, data));
}
}

/// Sets the frequency for polling the server in case of polling based push notification
///
/// #### Parameters
Expand Down
294 changes: 294 additions & 0 deletions CodenameOne/src/com/codename1/impl/PushDispatcher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
/*
* Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.impl;

import com.codename1.io.Log;
import com.codename1.push.PushContent;
import com.codename1.ui.Display;

import java.util.ArrayList;
import java.util.Timer;

/// Delivers incoming push messages to the application at a point where it is safe to act on them.
///
/// A push can arrive while the application is still inside a blocking call on the EDT: a modal
/// `Dialog` shown from `start()`, an `invokeAndBlock()`, a `NetworkManager.addToQueueAndWait()`.
/// The EDT keeps serving events inside such a call, so a push delivered there runs in the middle
/// of the code that blocked -- typically before the login or main form exists. That is the
/// "crashes before login, works with a delay sometimes" race.
///
/// The ports therefore hand every push to `#dispatch(java.lang.Runnable)` instead of calling the
/// callback themselves. While no blocking call is in progress the push runs at once, exactly as
/// before. While one is, the push is held and runs, in arrival order, as soon as the outermost
/// blocking call returns. No push is held longer than 15 seconds, so a dialog left open while
/// the application is in the background cannot make a push miss the completion deadline the OS
/// imposes on it.
///
/// A held push keeps its own copy of `PushContent` (and the `pushType` property), taken when the
/// push reaches the EDT: the ports write those globals when a push arrives, so a second push
/// arriving during the hold would otherwise be what the first one reads when it is finally
/// delivered. Two pushes whose content is written before either reaches the EDT share the later
/// content, as they always have; the iOS replay path and the Android pending path write the
/// content inside the delivery and are exact.
///
/// The deferral can be switched off with `com.codename1.push.Push#setDeliveryDeferred(boolean)`.
///
/// Everything here is touched on the EDT only: `#dispatch(java.lang.Runnable)` marshals a call
/// from another thread onto it, and `Display` calls the blocking hooks from the EDT.
///
/// This is an implementation class used by the ports; applications use `Push`.
public final class PushDispatcher {
private static final ArrayList<Runnable> HELD = new ArrayList<Runnable>();
private static int blockingDepth;
/// The blocking depth at which the delivery now running started, or -1 when none is running.
private static int deliveryDepth = -1;
private static boolean deferred = true;
private static boolean drainScheduled;

/// The longest a push is held, in milliseconds. Counted from when the push reaches the EDT
/// and enforced through the EDT, so it is not a hard bound on the time since the OS handed the
/// push over. It is kept well below the roughly 30 seconds iOS allows a background push before
/// completion must be reported, leaving room for the queueing on either side.
static final int MAX_HOLD_MS = 15000;

/// The limit in force; `#MAX_HOLD_MS` except in tests, which cannot wait that long.
static int holdLimitMs = MAX_HOLD_MS;

/// Identifies the current hold-limit timer. A timeout whose runnable was already queued when
/// the hold ended must not act on a later hold, so each timer carries the generation it was
/// armed with and does nothing unless it is still the current one.
private static int holdGeneration;
private static boolean holdArmed;
private static Timer holdTimer;

private PushDispatcher() {
}

/// Switches the deferral on (the default) or off. Off, a push is delivered as soon as it
/// reaches the EDT, even inside a blocking call. Pushes already held are then delivered too.
///
/// #### Parameters
///
/// - `defer`: true to hold pushes while a blocking call is in progress
public static void setDeferred(boolean defer) {
deferred = defer;
if (!defer && !HELD.isEmpty() && Display.isInitialized()) {
scheduleDrain();
}
}

/// #### Returns
///
/// true if pushes are held while a blocking call is in progress
public static boolean isDeferred() {
return deferred;
}

/// Runs `delivery` -- the port's whole delivery of one push, callback call included -- on the
/// EDT, now if that is safe and otherwise once the blocking call in progress returns.
///
/// #### Parameters
///
/// - `delivery`: the code that delivers the push to the application
public static void dispatch(final Runnable delivery) {
Display d = Display.getInstance();
if (!d.isEdt()) {
d.callSerially(new Runnable() {
@Override
public void run() {
dispatch(delivery);
}
});
return;
}
// While a delivery is running, a new push waits for it to finish, however it got here:
// through a blocking call in the handler, or through a serial call pumped by flushEdt()
// before a modal Dialog raises the blocking depth. (The generic pushReceived path, which
// a port delivery may end in, checks isDelivering() and calls the callback directly.)
if (!deferred || (deliveryDepth < 0 && blockingDepth == 0 && HELD.isEmpty())) {
run(delivery);
return;
}
HELD.add(withContent(delivery));
armHoldLimit(d);
if (blockingDepth == 0) {
scheduleDrain();
}
}

/// Called by `Display` on the EDT when a blocking call starts.
public static void blockingStarted() {
blockingDepth++;
}

/// Called by `Display` on the EDT when a blocking call returns, normally or not.
public static void blockingEnded() {
if (blockingDepth > 0) {
blockingDepth--;
}
if (blockingDepth == 0 && !HELD.isEmpty()) {
scheduleDrain();
}
}

private static void run(Runnable delivery) {
int saved = deliveryDepth;
deliveryDepth = blockingDepth;
try {
delivery.run();
} finally {
deliveryDepth = saved;
if (deliveryDepth < 0 && blockingDepth == 0 && !HELD.isEmpty()) {
scheduleDrain();
}
}
}

/// #### Returns
///
/// true while a push delivery is running on the EDT; a port path that ends in the generic
/// `pushReceived` uses it to deliver in place instead of queueing the same push again
public static boolean isDelivering() {
return deliveryDepth >= 0;
}

/// Wraps `delivery` so it runs with the PushContent and pushType that were current when it
/// was held. Paths that set those inside the delivery simply overwrite the restored values.
private static Runnable withContent(final Runnable delivery) {
final PushContent content = PushContent.get();
final String pushType = Display.getInstance().getProperty("pushType", null);
restore(content, pushType);
return new Runnable() {
@Override
public void run() {
restore(content, pushType);
delivery.run();
}
};
}

/// Puts back what the snapshot had, so a held push looks the same to the application as one
/// delivered at once: no PushContent type written where there was none.
private static void restore(PushContent c, String pushType) {
// Null as well: getProperty reads a null value as absent, and a held push must not see
// the pushType a later push wrote during the hold.
Display.getInstance().setProperty("pushType", pushType);
PushContent.reset();
if (c == null) {
return;
}
PushContent.setTitle(c.getTitle());
PushContent.setBody(c.getBody());
PushContent.setImageUrl(c.getImageUrl());
PushContent.setCategory(c.getCategory());
PushContent.setMetaData(c.getMetaData());
PushContent.setActionId(c.getActionId());
PushContent.setActionTitle(c.getActionTitle());
PushContent.setTextResponse(c.getTextResponse());
if (c.getType() != 0) {
PushContent.setType(c.getType());
}
}

private static void armHoldLimit(Display d) {
if (holdArmed) {
return;
}
holdArmed = true;
final int generation = ++holdGeneration;
holdTimer = d.setTimeout(holdLimitMs, new Runnable() {
@Override
public void run() {
if (!holdArmed || holdGeneration != generation) {
return;
}
endHoldLimit();
deliverHeldNow();
}
});
}

/// Stops the current hold-limit timer, which also ends its thread: `Display.setTimeout` gives
/// every timer a thread of its own, and one never cancelled keeps it.
private static void endHoldLimit() {
holdArmed = false;
Timer t = holdTimer;
holdTimer = null;
if (t != null) {
t.cancel();
}
}

private static void scheduleDrain() {
if (drainScheduled) {
return;
}
drainScheduled = true;
// A fresh EDT task rather than delivering from blockingEnded(): the code that blocked
// gets to finish (show its form, store its state) before the push sees the app.
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
drainScheduled = false;
drain(false);
}
});
}

/// The hold limit expired with a blocking call still in progress: deliver what is held
/// regardless, as releases without the deferral would have.
private static void deliverHeldNow() {
if (HELD.isEmpty()) {
return;
}
Log.p("PushDispatcher: a push waited " + holdLimitMs + "ms for a blocking call "
+ "to return and is delivered inside it. Keep blocking calls out of start() and "
+ "push(); see Lifecycle.onReady(boolean).", Log.WARNING);
drain(true);
}

private static void drain(boolean force) {
// Re-checked per push: a delivery that itself blocks (a push handler showing a modal
// Dialog) holds the ones behind it until it returns, as any other blocking call does.
// Never from inside a running delivery either: a drain task pumped by flushEdt() in a
// handler's modal Dialog show would otherwise deliver there.
while (!HELD.isEmpty() && (force || !deferred || (blockingDepth == 0 && deliveryDepth < 0))) {
Runnable next = HELD.remove(0);
boolean ok = false;
try {
run(next);
ok = true;
} finally {
if (!ok && !HELD.isEmpty()) {
// The exception goes on to the EDT's handler as it always did; the pushes
// behind the failed one are still delivered, and still bounded.
scheduleDrain();
armHoldLimit(Display.getInstance());
}
}
}
if (HELD.isEmpty()) {
endHoldLimit();
}
}
}
29 changes: 29 additions & 0 deletions CodenameOne/src/com/codename1/push/Push.java
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,35 @@ private static ConnectionRequest createPushMessage(String body, String deviceKey
throw new RuntimeException("The old push servers no longer work! Please migrate to the new Push servers!");
}

/// Chooses whether an incoming push may interrupt a blocking call.
///
/// By default (`true`) a push that arrives while the application is inside a blocking call on
/// the EDT -- a modal `Dialog` shown from `start()`, `invokeAndBlock()`,
/// `NetworkManager.addToQueueAndWait()` -- is held, and `PushCallback.push(String)` is called
/// as soon as the outermost blocking call returns. Pushes are delivered in arrival order and
/// none is dropped. A push is never held longer than about 15 seconds -- below the time iOS allows a
/// background push -- after which it is delivered inside the blocking call after all. This keeps a push from running before the form it needs exists, which is
/// what happens when an application is launched by tapping a notification while `start()` is
/// still showing a dialog or waiting on the network.
///
/// Pass `false` to deliver every push as soon as it reaches the EDT, even in the middle of a
/// blocking call, as releases before this setting did. Call it from `init(Object)` so it is in
/// force before the first push.
///
/// #### Parameters
///
/// - `deferred`: true to hold pushes while a blocking call is in progress
public static void setDeliveryDeferred(boolean deferred) {
com.codename1.impl.PushDispatcher.setDeferred(deferred);
}

/// #### Returns
///
/// true if pushes are held while a blocking call is in progress, see `#setDeliveryDeferred(boolean)`
public static boolean isDeliveryDeferred() {
return com.codename1.impl.PushDispatcher.isDeferred();
}

/// Returns the push device key if the device was previously successfully registered for push
/// otherwise returns null
///
Expand Down
Loading
Loading