Skip to content

Commit

Permalink
Merge pull request #85 from cs-util-com/feature/debugUis
Browse files Browse the repository at this point in the history
Feature/debug uis
  • Loading branch information
cs-util committed Aug 18, 2022
2 parents f109906 + 7ba4c6f commit aa84561
Show file tree
Hide file tree
Showing 117 changed files with 6,304 additions and 428 deletions.
4 changes: 2 additions & 2 deletions CsCore/CsCore.sln
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31410.357
# Visual Studio Version 17
VisualStudioVersion = 17.2.32630.192
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlainNetClassLib", "PlainNetClassLib\PlainNetClassLib.csproj", "{CBE8E932-8FC5-4EEB-9285-C9EE981668CD}"
EndProject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ private void Update() {

public static void Invoke(Action a) { instance.ExecuteOnMainThread(a); }

public static T Invoke<T>(Func<T> a) { return instance.ExecuteOnMainThread(a); }

public static Task<T> Invoke<T>(Func<Task<T>> a) { return instance.ExecuteOnMainThreadAsync(a); }

public static Task Invoke<T>(Func<Task> a) {
return instance.ExecuteOnMainThreadAsync(async () => {
await a();
return true;
});
}

public void ExecuteOnMainThread(Action a) {
if (ApplicationV2.isPlaying) { AssertV2.IsNotNull(mainThreadRef, "mainThreadRef"); }
if (WasInitializedWhilePlaying) {
Expand All @@ -70,14 +81,30 @@ public void ExecuteOnMainThread(Action a) {
public T ExecuteOnMainThread<T>(Func<T> f) {
if (isMainThread) { return f(); }
TaskCompletionSource<T> src = new TaskCompletionSource<T>();
ExecuteOnMainThread(() => { try { src.SetResult(f()); } catch (Exception e) { src.SetException(e); } });
ExecuteOnMainThread(() => {
try {
src.SetResult(f());
} catch (Exception e) {
src.SetException(e);
}
});
return src.Task.Result;
}

public Task<T> ExecuteOnMainThreadAsync<T>(Func<Task<T>> f) {
return ExecuteOnMainThread(() => f());
public async Task<T> ExecuteOnMainThreadAsync<T>(Func<Task<T>> f) {
if (isMainThread) { return await f(); }
TaskCompletionSource<Task<T>> tcs = new TaskCompletionSource<Task<T>>();
ExecuteOnMainThread(() => {
try {
tcs.SetResult(f());
} catch (Exception e) {
tcs.SetException(e);
}
});
var taskT = await tcs.Task; // Wait for the tcs to be set
return await taskT; // Wait for the async task itself to be complete
}

}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ namespace com.csutil.async {
class TaskV2WebGL : TaskV2 {

protected override async Task DelayTask(int millisecondsDelay, CancellationToken cancellationToken) {
cancellationToken.ThrowIfCancellationRequested();
await StartCoroutineAsTask(DelayCoroutine(millisecondsDelay));
cancellationToken.ThrowIfCancellationRequested();
if (!ApplicationV2.isPlaying) {
await base.DelayTask(millisecondsDelay, cancellationToken);
} else {
cancellationToken.ThrowIfCancellationRequested();
await StartCoroutineAsTask(DelayCoroutine(millisecondsDelay));
cancellationToken.ThrowIfCancellationRequested();
}
}

private IEnumerator DelayCoroutine(int ms) { yield return new WaitForSeconds(ms / 1000f); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public static bool HasComponent<T>(this GameObject self, out T existingComp) {
existingComp = self.GetComponentV2<T>();
return existingComp != null;
}

public static bool HasComponent<T>(this Component self, out T existingComp) {
existingComp = self.GetComponentV2<T>();
return existingComp != null;
}

/// <summary> Searches recursively upwards in all parents until a comp of type T is found </summary>
public static T GetComponentInParents<T>(this GameObject gameObject) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace com.csutil.http {

[Obsolete("Use UnityRestFactoryV2 instead")]
public class UnityRestFactory : RestFactory {

protected override void InitFactory() { }
Expand All @@ -20,14 +21,14 @@ public override RestRequest SendRequest(Uri uri, HttpMethod method) {
});
}

public override Task<long> GetCurrentPing(string ipOrUrl = "8.8.8.8", int timeoutInMs = 1000) {
public override Task<long> GetCurrentPing(string ipOrUrl = DEFAULT_PING_IP, int timeoutInMs = DEFAULT_PING_TIMEOUT) {
if (ApplicationV2.platform.IsAnyOf(RuntimePlatform.WebGLPlayer)) {
return GetCurrentPingViaHeadRequest(ipOrUrl);
}
return base.GetCurrentPing(ipOrUrl, timeoutInMs);
}

public Task<long> GetCurrentPingViaHeadRequest(string ipOrUrl = "8.8.8.8", int timeoutInMs = 1000) {
public Task<long> GetCurrentPingViaHeadRequest(string ipOrUrl = DEFAULT_PING_IP, int timeoutInMs = DEFAULT_PING_TIMEOUT) {
Stopwatch t = Stopwatch.StartNew();
return WebRequestRunner.GetInstance(this).StartCoroutineAsTask(SendHeadReqTo(ipOrUrl), () => {
t.Stop();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace com.csutil.http {

public class UnityRestFactoryV2 : RestFactory {

public override RestRequest SendRequest(Uri uri, HttpMethod method) {
if (ApplicationV2.platform.IsAnyOf(RuntimePlatform.WebGLPlayer)) {
return MainThread.instance.ExecuteOnMainThread(() => {
if (method.ToString() == "GET") {
return new UnityRestRequest(UnityWebRequest.Get(uri));
}
return new UnityRestRequest(new UnityWebRequest(uri, method.ToString()));
});
}
return base.SendRequest(uri, method);
}

public override async Task<long> GetCurrentPing(string ipOrUrl = DEFAULT_PING_IP, int timeoutInMs = DEFAULT_PING_TIMEOUT) {
if (ApplicationV2.platform.IsAnyOf(RuntimePlatform.WebGLPlayer) && ApplicationV2.isPlaying) {
return await GetCurrentPingViaHeadRequest(ipOrUrl, timeoutInMs);
}
#if !UNITY_WEBGL
var ping = await GetCurrentPingViaUnityPing(ipOrUrl, timeoutInMs);
if (ping > 0) { return ping; }
#endif
// If Unity.Ping did not work, eg because a URL was used instead of an IP fallback to default ping approach:
return await base.GetCurrentPing(ipOrUrl, timeoutInMs);
}

public static async Task<long> GetCurrentPingViaHeadRequest(string ipOrUrl, int timeoutInMs = DEFAULT_PING_TIMEOUT) {
if (!ipOrUrl.StartsWith("http")) { ipOrUrl = "https://" + ipOrUrl; }
Stopwatch timer = Stopwatch.StartNew();
var result = await new Uri(ipOrUrl).SendHEAD().GetResult<HttpStatusCode>().WithTimeout(timeoutInMs);
AssertV2.AreEqual(HttpStatusCode.OK, result);
return timer.ElapsedMilliseconds;
}

#if !UNITY_WEBGL
private static async Task<long> GetCurrentPingViaUnityPing(string ip, int timeoutInMs = DEFAULT_PING_TIMEOUT) {
var ping = new UnityEngine.Ping(ip);
var timer = Stopwatch.StartNew();
while (!ping.isDone && timer.ElapsedMilliseconds < timeoutInMs) { await TaskV2.Delay(10); }
return ping.isDone ? ping.time : -1;
}
#endif

}

}

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

Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using com.csutil.http.cookies;
using System;
using System.Collections;
using System.Collections.Generic;
Expand Down Expand Up @@ -30,6 +29,9 @@ public class UnityRestRequest : RestRequest {

public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();

/// <summary> The timeout for the request, the default is no timeout </summary>
public TimeSpan? Timeout { get; set; } = null;

public UnityRestRequest(UnityWebRequest request) { this.request = request; }

public Task<T> GetResult<T>() {
Expand Down Expand Up @@ -66,6 +68,7 @@ private IEnumerator PrepareRequest<T>(Response<T> response) {
request.uploadHandler = new UploadHandlerRaw(streamToSend.ToByteArray());
}
request.SetRequestHeaders(h);
if (Timeout != null) { request.timeout = (int)Timeout.Value.TotalSeconds; }
yield return request.SendWebRequestV2(response);
}

Expand Down Expand Up @@ -140,6 +143,11 @@ private async Task WaitForRequestToFinish() {
}
}

public RestRequest WithTimeoutInMs(int timeoutInMs) {
Timeout = TimeSpan.FromMilliseconds(timeoutInMs);
return this;
}

public void Dispose() {
CancellationTokenSource.Cancel();
try { request.Abort(); } catch (Exception e) { Log.d("Could not abort request: " + e); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ public static IPreferences NewPreferencesUsingPlayerPrefs() {
private IJsonReader jsonReader = TypedJsonHelper.NewTypedJsonReader();
private IJsonWriter jsonWriter = TypedJsonHelper.NewTypedJsonWriter();

public void Dispose() { fallbackStore?.Dispose(); }
public DisposeState IsDisposed { get; private set; } = DisposeState.Active;

public void Dispose() {
IsDisposed = DisposeState.DisposingStarted;
fallbackStore?.Dispose();
IsDisposed = DisposeState.Disposed;
}

public async Task<T> Get<T>(string key, T defaultValue) {
var s = this.StartFallbackStoreGetTimer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ public static void ResetAllStaticObjects() {
IoC.inject.SetSingleton<EnvironmentV2>(new EnvironmentV2Unity(), true);
if (EnvironmentV2.isWebGL) { IoC.inject.SetSingleton<TaskV2>(new TaskV2WebGL(), true); }

{ // Setup an UnityRestFactory only if there is not already a RestFactory injected
var restFactory = IoC.inject.GetOrAddSingleton<RestFactory>(null, () => new UnityRestFactory());
if (!(restFactory is UnityRestFactory)) {
Log.d($"Will NOT use {nameof(UnityRestFactory)} since a {restFactory.GetType().Name} was already present");
{ // Setup an UnityRestFactoryV2 only if there is not already a RestFactory injected
var restFactory = IoC.inject.GetOrAddSingleton<IRestFactory>(null, () => new UnityRestFactoryV2());
if (!(restFactory is UnityRestFactoryV2)) {
Log.d($"Will NOT use {nameof(UnityRestFactoryV2)} since a {restFactory.GetType().Name} was already present");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

Expand Down Expand Up @@ -60,6 +61,16 @@ public void SimulateButtonClickOn(string buttonName) {
}
}

public Task SimulateButtonClickOn(string buttonName, IList<Task> buttonClicks) {
return SimulateButtonClickOn(buttonName, buttonClicks.Last());
}

public Task SimulateButtonClickOn(string buttonName, Task buttonClickWaitTask) {
AssertV2.IsFalse(buttonClickWaitTask.IsCompleted, "buttonClickWaitTask was already completed");
SimulateButtonClickOn(buttonName);
return buttonClickWaitTask;
}

public static IEnumerable<Link> FindAllActiveLinks() {
return ResourcesV2.FindAllInScene<Link>().Filter(x => x.isActiveAndEnabled);
}
Expand All @@ -68,4 +79,4 @@ public static IEnumerable<Link> FindAllActiveLinks() {

}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ private static SnackbarsUi InitSnackbarsUi() {

}

public class SnackbarsUi : MonoBehaviour, IsDisposable {
public class SnackbarsUi : MonoBehaviour, IDisposableV2 {

private GameObject snackbarsContainer;

Expand All @@ -40,15 +40,19 @@ public GameObject Show(string snackbarMsg, string buttonMsg, Action<GameObject>
map.Get<Text>("Message").text = snackbarMsg;
if (snackbarAction != null && !buttonMsg.IsNullOrEmpty()) {
map.Get<Text>("SnackbarButton").text = buttonMsg;
map.Get<Button>("SnackbarButton").SetOnClickAction(snackbarAction);
map.Get<Button>("SnackbarButton").SetOnClickAction(delegate { snackbarAction(newSnackbar); });
} else {
map.Get<GameObject>("SnackbarButton").Destroy();
}
newSnackbar.GetComponentV2<MonoBehaviour>().ExecuteDelayed(() => newSnackbar.Destroy(), displayDurationInMs);
if (displayDurationInMs > 0) {
newSnackbar.GetComponentV2<MonoBehaviour>().ExecuteDelayed(() => newSnackbar.Destroy(), displayDurationInMs);
}
snackbarsContainer.AddChild(newSnackbar);
return newSnackbar;
}

public void Dispose() { this.gameObject.Destroy(); }

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ private static ToastsUi InitToastsUi() {

}

public class ToastsUi : MonoBehaviour, IsDisposable {
public class ToastsUi : MonoBehaviour, IDisposableV2 {

private GameObject toastsContainer;

Expand All @@ -47,6 +47,7 @@ private static void InitText(Dictionary<string, Link> map, string id, string tex
if (text.IsNullOrEmpty()) { map.Get<GameObject>(id).SetActiveV2(false); } else { map.Get<Text>(id).text = text; }
}

public void Dispose() { this.gameObject.Destroy(); }
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public abstract class ToggleGroupListener : MonoBehaviour, IToggleGroupListener
/// <summary> Can be changed to define how quick after a new tab was selected the logic should be executed to
/// select and switch to that selected tab. Typically the default value does not need to be changed </summary>
public double debounceDelayInMs = 50;
private Action<IEnumerable<Toggle>> OnActiveToggleInGroupChangedAction;
private Action OnActiveToggleInGroupChangedAction;

protected virtual void OnEnable() {
AssertChildrenHaveCorrectMonosAttached();
Expand All @@ -33,23 +33,23 @@ private void AssertChildrenHaveCorrectMonosAttached() {
}

public void OnActiveToggleInGroupChanged() {
if (OnActiveToggleInGroupChangedAction == null) {
OnActiveToggleInGroupChangedAction = OnActiveToggleInGroupChangedDelayed;
OnActiveToggleInGroupChangedAction = OnActiveToggleInGroupChangedAction.AsThrottledDebounce(debounceDelayInMs, true);
}
OnActiveToggleInGroupChangedAction();
}

private void OnActiveToggleInGroupChangedDelayed() {
AssertChildrenHaveCorrectMonosAttached();
var newActiveToggles = GetComponent<ToggleGroup>().ActiveToggles();
if (!newActiveToggles.SequenceReferencesEqual(activeToggles)) {
activeToggles = new List<Toggle>(newActiveToggles);
HandleActiveToggleInGroupChanged(activeToggles);
}
}

private void HandleActiveToggleInGroupChanged(IEnumerable<Toggle> activeToggles) {
if (OnActiveToggleInGroupChangedAction == null) {
OnActiveToggleInGroupChangedAction = OnActiveToggleInGroupChanged2;
OnActiveToggleInGroupChangedAction = OnActiveToggleInGroupChangedAction.AsThrottledDebounce(debounceDelayInMs, true);
OnActiveToggleInGroupChanged(activeToggles);
}
OnActiveToggleInGroupChangedAction(activeToggles);
}

protected abstract void OnActiveToggleInGroupChanged2(IEnumerable<Toggle> activeToggles);
protected abstract void OnActiveToggleInGroupChanged(IEnumerable<Toggle> activeToggles);

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ private void OnEnable() {
InformParentToggleGroupListenerIfFound();
return true;
}, skipChangesByLogic: false);
InformParentToggleGroupListenerIfFound();
OnToggleStateChanged(GetComponent<Toggle>().isOn);
InformParentToggleGroupListenerIfFound();
}

protected virtual void InformParentToggleGroupListenerIfFound() {
Expand Down
Loading

0 comments on commit aa84561

Please sign in to comment.