Skip to content

Commit

Permalink
Merge pull request #77 from asadm/improved-callback-handler
Browse files Browse the repository at this point in the history
Centralized Callback Manager
  • Loading branch information
momintlh authored Jun 4, 2024
2 parents e39c646 + 6b92072 commit 2f2896d
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 42 deletions.
60 changes: 28 additions & 32 deletions Assets/PlayroomKit/PlayroomKit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,20 @@ public class MatchMakingOptions
[DllImport("__Internal")]
private static extern void InsertCoinInternal(
string options,
Action onLaunchCallback,
Action<string> onLaunchCallback,
Action<string> onQuitInternalCallback,
Action onDisconnectCallback,
Action<string> onError);
Action<string> onDisconnectCallback,
Action<string> onError,
string onLaunchCallBackKey,
string onDisconnectCallBackKey
);

[MonoPInvokeCallback(typeof(Action))]
private static void InvokeInsertCoin()
[MonoPInvokeCallback(typeof(Action<string>))]
private static void InvokeInsertCoin(string key)
{
InsertCoinCallback?.Invoke();
CallbackManager.InvokeCallback(key);


#if UNITY_WEBGL && !UNITY_EDITOR
WebGLInput.captureAllKeyboardInput = true;
#endif
Expand All @@ -90,8 +95,13 @@ public static void InsertCoin(InitOptions options = null, Action onLaunchCallBac
if (IsRunningInBrowser())
{
isPlayRoomInitialized = true;
InsertCoinCallback = onLaunchCallBack;
OnDisconnectCallback = onDisconnectCallback;


string onLaunchCallBackKey = CallbackManager.RegisterCallback(onLaunchCallBack, "onLaunchCallBack");
string onDisconnectCallBackKey = CallbackManager.RegisterCallback(onDisconnectCallback, "onDisconnectCallBack");

Debug.Log(onLaunchCallBackKey);

string optionsJson = null;
if (options != null)
{
Expand All @@ -106,7 +116,9 @@ public static void InsertCoin(InitOptions options = null, Action onLaunchCallBac
#endif
}

InsertCoinInternal(optionsJson, InvokeInsertCoin, __OnQuitInternalHandler, onDisconnectCallbackHandler, InvokeOnErrorInsertCoin);
InsertCoinInternal(
optionsJson, InvokeInsertCoin, __OnQuitInternalHandler, onDisconnectCallbackHandler,
InvokeOnErrorInsertCoin, onLaunchCallBackKey, onDisconnectCallBackKey);
}
else
{
Expand Down Expand Up @@ -213,7 +225,6 @@ private static JSONNode ConvertValueToJSON(object value)
[DllImport("__Internal")]
private static extern void UnsubscribeOnPlayerJoinInternal(string id);

// private static Action<Player> onPlayerJoinCallback = null;
private static List<Action<Player>> OnPlayerJoinCallbacks = new();


Expand All @@ -224,9 +235,9 @@ private static void __OnPlayerJoinCallbackHandler(string id)
}

[MonoPInvokeCallback(typeof(Action<string>))]
private static void onDisconnectCallbackHandler()
private static void onDisconnectCallbackHandler(string key)
{
OnDisconnectCallback?.Invoke();
CallbackManager.InvokeCallback(key);
}


Expand Down Expand Up @@ -399,12 +410,12 @@ public static Player Me()


[DllImport("__Internal")]
private static extern void OnDisconnectInternal(Action callback);
private static extern void OnDisconnectInternal(Action<string> callback);


public static void OnDisconnect(Action callback)
{
OnDisconnectCallback = callback;
CallbackManager.RegisterCallback(callback);
OnDisconnectInternal(onDisconnectCallbackHandler);
}

Expand Down Expand Up @@ -747,33 +758,18 @@ public static Dictionary<string, T> GetState<T>(string key, bool isReturnDiction
[DllImport("__Internal")]
private static extern void WaitForStateInternal(string stateKey, Action<string, string> onStateSetCallback);

private static Dictionary<string, Action<string>> OnStateChangeCallBacks = new();

[MonoPInvokeCallback(typeof(Action<string, string>))]
private static void InvokeCallback(string stateVal, string stateKey)
private static void InvokeCallback(string stateKey, string stateVal)
{
if (OnStateChangeCallBacks.TryGetValue(stateKey, out Action<string> callback))
{
callback?.Invoke(stateVal);
}
else
{
Debug.LogWarning($"[WaitForState]: No callback found for state key: {stateKey}");
}
CallbackManager.InvokeCallback(stateKey, stateVal);
}

public static void WaitForState(string stateKey, Action<string> onStateSetCallback = null)
{
if (IsRunningInBrowser())
{
if (!OnStateChangeCallBacks.ContainsKey(stateKey))
{
OnStateChangeCallBacks.Add(stateKey, onStateSetCallback);
}
else
{
OnStateChangeCallBacks[stateKey] = onStateSetCallback;
}
CallbackManager.RegisterCallback(onStateSetCallback, stateKey);

WaitForStateInternal(stateKey, InvokeCallback);
}
Expand Down
60 changes: 60 additions & 0 deletions Assets/PlayroomKit/modules/CallbackManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Playroom
{
public static class CallbackManager
{
private static Dictionary<string, Delegate> callbacks = new();

public static string RegisterCallback(Delegate callback, string key = null)
{
if (string.IsNullOrEmpty(key))
key = GenerateKey();


if (!callbacks.ContainsKey(key))
{
callbacks.Add(key, callback);
}
else
{
callbacks[key] = callback;
}

return key;
}


public static void InvokeCallback(string key, string arg1 = null)
{
if (callbacks.TryGetValue(key, out Delegate callback))
{
if (callback is Action action) action?.Invoke();
else if (callback is Action<string> stringAction) stringAction?.Invoke(arg1);
else Debug.LogError($"Callback with key {key} is of unsupported type!");
}
else
{
Debug.LogError($"Callback with key {key} not found!");
}
}

private static string GenerateKey()
{
return Guid.NewGuid().ToString();
}



/// <summary>
/// Calls an external method to convert a string associated with a given key, called from the JS side only.
/// </summary>
/// <param name="key">The key associated with the string to be converted.</param>
[DllImport("__Internal")]
private static extern void ConvertString(string key);

}
}
11 changes: 11 additions & 0 deletions Assets/PlayroomKit/modules/CallbackManager.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 26 additions & 10 deletions Assets/PlayroomKit/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@ mergeInto(LibraryManager.library, {
onLaunchCallBack,
onQuitInternalCallback,
onDisconnectCallback,
onError
onError,
onLaunchCallBackKey,
onQuitInternalCallbackKey
) {
onLaunchCallBackKey = UTF8ToString(onLaunchCallBackKey);
onQuitInternalCallbackKey = UTF8ToString(onQuitInternalCallbackKey);

function OnLaunchCallBack() {
dynCall("v", onLaunchCallBack, []);
var key = _ConvertString(onLaunchCallBackKey);
dynCall("vi", onLaunchCallBack, [key]);
}

function OnDisconnectCallback() {
dynCall("v", onDisconnectCallback, []);
var key = _ConvertString(onQuitInternalCallbackKey);
dynCall("vi", onDisconnectCallback, [key]);
}

this.onPlayerJoinCallBacks = {};
var options = optionsJson ? JSON.parse(UTF8ToString(optionsJson)) : {};

Expand Down Expand Up @@ -711,15 +717,11 @@ mergeInto(LibraryManager.library, {
stateKey = UTF8ToString(stateKey);
Playroom.waitForState(stateKey)
.then((stateVal) => {

var bufferSize = lengthBytesUTF8(stateKey) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(stateKey, buffer, bufferSize);

stateVal = JSON.stringify(stateVal);

var key = _ConvertString(stateKey);

dynCall("vii", onStateSetCallback, [stringToNewUTF8(stateVal), buffer]);
dynCall("vii", onStateSetCallback, [key, stringToNewUTF8(stateVal)]);
})
.catch((error) => {
console.error("Error Waiting for state:", error);
Expand Down Expand Up @@ -909,4 +911,18 @@ mergeInto(LibraryManager.library, {
console.error(`JS: Error starting match making ${error}`);
});
},

// UTILS
/**
* Converts a given string into a UTF-8 encoded string and stores it in memory.
*
* @param {string} str - The string to be converted.
* @returns {number} The memory address of the buffer where the converted string is stored.
*/
ConvertString: function (str) {
var bufferSize = lengthBytesUTF8(str) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(str, buffer, bufferSize);
return buffer;
},
});

0 comments on commit 2f2896d

Please sign in to comment.