1717
1818import com .diffplug .common .base .Preconditions ;
1919import java .util .ArrayList ;
20- import java .util .List ;
2120import java .util .concurrent .atomic .AtomicReference ;
2221import java .util .function .Consumer ;
2322import org .jetbrains .annotations .Nullable ;
2423
24+ /**
25+ * - immediately on app startup, call `MacDeepLink.startCapturingBeforeSwt()`
26+ * - once SWT has initialized, call `MacDeepLink.swtHasInitializedBeginReceiving(Consumer<String>)`
27+ *
28+ * That's all! Don't do anything else.
29+ */
2530public class MacDeepLink {
26- private static volatile @ Nullable Consumer <String > urlHandler ;
27- private static final AtomicReference <@ Nullable List <String >> backlogUrls = new AtomicReference <>();
31+ private static final AtomicReference <@ Nullable Object > state = new AtomicReference <>();
2832
2933 static {
3034 // Load the native library - try multiple strategies
@@ -36,22 +40,19 @@ public class MacDeepLink {
3640 }
3741 }
3842
39- public static void setURLHandler (Consumer <String > handler ) {
40- Preconditions .checkArgument (urlHandler == null , "URL handler can only be set once" );
41- urlHandler = handler ;
42- }
43-
44- public static void applicationStartBeforeSwt () {
45- Preconditions .checkArgument (urlHandler != null , "Call `setURLHandler()` first" );
46- backlogUrls .set (new ArrayList <>());
43+ public static void startCapturingBeforeSwt () {
44+ var was = state .getAndSet (new ArrayList <>());
45+ Preconditions .checkArgument (was == null , "`startCapturingBeforeSwt() should be called first`" );
4746 nativeBeforeSwt ();
4847 }
4948
50- public static void applicationStartAfterSwt () {
51- Preconditions .checkArgument (backlogUrls .get () != null , "Call `applicationStartBeforeSwt()` first." );
49+ public static void swtHasInitializedBeginReceiving (Consumer <String > handler ) {
50+ var was = state .getAndSet (handler );
51+ Preconditions .checkArgument (was instanceof ArrayList <?>, "Call `applicationStartBeforeSwt()` first." );
52+
53+ var backlog = (ArrayList <String >) was ;
54+ backlog .forEach (handler );
5255 nativeAfterSwt ();
53- var accumulatedBacklog = backlogUrls .getAndSet (null );
54- accumulatedBacklog .forEach (urlHandler );
5556 }
5657
5758 // Native method declarations - implemented in DeepLinkBridge.m
@@ -66,11 +67,13 @@ public static void applicationStartAfterSwt() {
6667 * @param url The URL string received from the operating system
6768 */
6869 public static void deliverURL (String url ) {
69- var backlog = backlogUrls .get ();
70- if (backlog != null ) {
71- backlog .add (url );
70+ var was = state .get ();
71+ if (was instanceof Consumer ) {
72+ ((Consumer <String >) was ).accept (url );
73+ } else if (was instanceof ArrayList <?>) {
74+ ((ArrayList <String >) was ).add (url );
7275 } else {
73- urlHandler . accept ( url );
76+ throw new IllegalStateException ( "Expected Consumer or ArrayList, was " + was );
7477 }
7578 }
7679}
0 commit comments