repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestLayerAspNetCore.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
45
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace TestLayerExample { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return new Amazon.S3.Model.ListBucketsRequest().ToString(); } } }
28
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace TestLayerServerless { public class Functions { public string ToUpper(string evnt, ILambdaContext context) { return evnt.ToUpper(); } } }
23
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; namespace NativeAotTest; public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { Func<string, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); } /// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { var class1 = new Class1 { Name = $"MyTest: {input}" }; return class1.Name.ToUpper(); } }
36
aws-extensions-for-dotnet-cli
aws
C#
namespace NativeAotTest; public class Class1 { public string? Name; }
7
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; namespace NativeAotTest; public class Function { /// <summary> /// The main entry point for the custom runtime. /// </summary> /// <param name="args"></param> private static async Task Main(string[] args) { Func<string, ILambdaContext, string> handler = FunctionHandler; await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); } /// <summary> /// A simple function that takes a string and does a ToUpper /// /// To use this handler to respond to an AWS event, reference the appropriate package from /// https://github.com/aws/aws-lambda-dotnet#events /// and change the string input parameter to the desired event type. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public static string FunctionHandler(string input, ILambdaContext context) { return input.ToUpper(); } }
35
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.PowerShellHost; namespace TestPowerShellParallelTest { public class Bootstrap : PowerShellFunctionHost { public Bootstrap() : base("TestPowerShellParallelTest.ps1") { } } }
12
aws-extensions-for-dotnet-cli
aws
C#
using System.IO; using Amazon.Lambda.AspNetCoreServer; using Microsoft.AspNetCore.Hosting; namespace TestServerlessWebApp { public class LambdaFunction : APIGatewayProxyFunction { public const string BinaryContentType = "application/octet-stream"; protected override void Init(IWebHostBuilder builder) { builder .UseLambdaServer() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>(); } } }
21
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.Core; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace TestServerlessWebApp { public class Middleware { private readonly RequestDelegate _next; public Middleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { LambdaLogger.Log("Middleware Invoked"); context.Response.OnStarting(x => { var lambdaContext = context.Items["LambdaContext"] as ILambdaContext; lambdaContext.Logger.LogLine("OnStarting Called"); return Task.FromResult(0); }, context); await _next(context); } } }
35
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace TestServerlessWebApp { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; namespace TestServerlessWebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo() { Title = "My API", Version = "v1" }); }); services.AddAuthorization(options => { options.AddPolicy("YouAreSpecial", policy => policy.RequireClaim("you_are_special")); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app) { app.UseSwagger(); app.UseMiddleware<Middleware>(); app.UseRouting(); } } }
51
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace TestServerlessWebApp.Controllers { [Route("api/[controller]")] public class AuthTestController : Controller { // GET: api/<controller> [HttpGet] [Authorize(Policy = "YouAreSpecial")] public string Get() { return "You Have Access"; } } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System.IO; using Microsoft.AspNetCore.Mvc; namespace TestServerlessWebApp.Controllers { [Route("api/binary")] public class BinaryContentController : Controller { [HttpGet] public IActionResult Get([FromQuery] string firstName, [FromQuery] string lastName) { var bytes = new byte[byte.MaxValue]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)i; return base.File(bytes, LambdaFunction.BinaryContentType); } } }
20
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestServerlessWebApp.Controllers { [Route("api/[controller]")] public class BodyTestsController : Controller { [HttpPut] public string PutBody([FromBody] Person body) { return $"{body.LastName}, {body.FirstName}"; } public class Person { public string FirstName { get; set; } public string LastName { get; set; } } } }
26
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.IO; using System.Reflection; using Microsoft.AspNetCore.Mvc; namespace TestServerlessWebApp.Controllers { [Route("api/[controller]")] public class ErrorTestsController { [HttpGet] public string Get([FromQuery]string id) { if (id == "typeload-test") { var fnfEx = new FileNotFoundException("Couldn't find file", "System.String.dll"); throw new ReflectionTypeLoadException(new[] { typeof(String) }, new[] { fnfEx }); } var ex = new Exception("Unit test exception, for test conditions."); if (id == "aggregate-test") { throw new AggregateException(ex); } else { throw ex; } } } }
32
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestServerlessWebApp.Controllers { [Route("api/[controller]")] public class QueryStringController : Controller { [HttpGet] public string Get([FromQuery] string firstName, [FromQuery] string lastName) { return $"{firstName}, {lastName}"; } } }
20
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace TestServerlessWebApp.Controllers { [Route("api/[controller]")] public class ResourcePathController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(string id) { return "value=" + id; } } }
27
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; using AWS.GameKit.Runtime.UnitTests; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class FeatureTypeConverterTests : GameKitTestBase { [Test] public void GetEditorData_AllFeatures_HaveEditorData() { // This test ensures every FeatureType has a FeatureTypeEditorData. // FeatureType.GetEditorData() is private, so we test through a proxy of GetDescription() instead. foreach (FeatureType feature in Enum.GetValues(typeof(FeatureType))) { Assert.DoesNotThrow(() => feature.GetDescription()); } } [Test] [TestCase(FeatureType.Main, "Main", "main")] [TestCase(FeatureType.Identity, "Identity & Authentication", "identity")] [TestCase(FeatureType.Authentication, "Authentication", "authentication")] [TestCase(FeatureType.Achievements, "Achievements", "achievements")] [TestCase(FeatureType.GameStateCloudSaving, "Game State Cloud Saving", "gamesaving")] [TestCase(FeatureType.UserGameplayData, "User Gameplay Data", "usergamedata")] public void GetUIStringAndToApiString_AllFeatures_ContainCorrectValues(FeatureType feature, string expectedUIString, string expectedApiString) { Assert.AreEqual(feature.GetDisplayName(), expectedUIString); Assert.AreEqual(feature.GetApiString(), expectedApiString); } [Test] public void GetDocumentationUrlAndToResourcesUIString_AllFeatures_ContainNonEmptyValues() { // Since the urls and resources may change over time, we want only want to ensure they are not empty foreach (FeatureType feature in Enum.GetValues(typeof(FeatureType))) { Assert.True(feature.GetDocumentationUrl().Length > 0); Assert.True(feature.GetResourcesUIString().Length > 0); } } [Test] public void GetDescription_WithEndingPeriod_ContainsSingleEndingPeriod() { foreach (FeatureType feature in Enum.GetValues(typeof(FeatureType))) { // act string description = feature.GetDescription(withEndingPeriod: true); // assert Assert.IsTrue(description.EndsWith(".")); Assert.IsTrue(!description.EndsWith("..")); } } [Test] public void GetDescription_DefaultNoEndingPeriod_ContainsNoEndingPeriod() { foreach (FeatureType feature in Enum.GetValues(typeof(FeatureType))) { // act string description = feature.GetDescription(); // default is no ending period // assert Assert.IsTrue(!description.EndsWith(".")); } } [Test] public void GetDashboardUrl_UserGameplayData_ContainsCorrectValue() { // This test ensures the dashboard URLs are formatted correctly. // It tests User Gameplay Data because it is a feature name that has spaces in it. // arrange FeatureType featureType = FeatureType.UserGameplayData; string gameName = "testgame"; string environmentCode = "dev"; string region = "us-west-2"; string expectedUrl = "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#dashboards:name=GameKit-testgame-dev-us-west-2-UserGameplayData"; // act string actualUrl = featureType.GetDashboardUrl(gameName, environmentCode, region); // assert Assert.AreEqual(expectedUrl, actualUrl); } } }
104
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Windows.Settings; using AWS.GameKit.Runtime.UnitTests; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class PageTests : GameKitTestBase { /// <summary> /// This page does NOT have any tabs. Therefore it does not override the method <see cref="Page.SelectTab"/>. /// </summary> private class PageWithoutTabs : Page { public override string DisplayName => nameof(PageWithoutTabs); protected override void DrawContent() { // do nothing } } /// <summary> /// This page DOES have tabs. Therefore it overrides the method <see cref="Page.SelectTab"/>. /// </summary> private class PageWithTabs : Page { public override string DisplayName => nameof(PageWithoutTabs); public override void SelectTab(string tabName) { // do nothing // all tab names are valid // Note: We are not calling base.SelectTab(), as we are instructed not to call it by the base method's documentation. } protected override void DrawContent() { // do nothing } } private class DummyDrawable : IDrawable { public void OnGUI() { // do nothing } } public void SelectTab_WhenSubclassDoesNotOverride_LogsError() { // arrange Page pageWithoutTabs = new PageWithoutTabs(); string tabName = "DoesNotExist"; string expectedErrorMessage = $"There is no tab named \"{tabName}\" on the page \"{nameof(PageWithoutTabs)}\". The page does not have any tabs."; // act pageWithoutTabs.SelectTab(tabName); // assert Assert.AreEqual(1, Log.Count); Assert.AreEqual(expectedErrorMessage, Log[0]); } public void SelectTab_WhenSubclassOverridesAndTabNameIsValid_DoesNotLogError() { // arrange Page pageWithTabs = new PageWithTabs(); // act pageWithTabs.SelectTab("ValidTabName"); // assert Assert.AreEqual(0, Log.Count); } } }
86
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.IO; // Unity using UnityEngine; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.UnitTests; using AWS.GameKit.Runtime.Utils; // Third Party using Moq; using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class FeatureResourceManagerTests : GameKitTestBase { const string PLUGIN_BASE_DIR = "/AWS_GameKit_Tests/Test Resources"; const string TEST_RESOURCES_FOLDER = "Test Resources"; const string TEST_RESOURCES_DIR = "../AwsGameTechGameKitUnityPackage/Assets/AWS_GameKit_Tests/" + TEST_RESOURCES_FOLDER + "/"; const string SAVE_INFO_DIR = TEST_RESOURCES_DIR + "Editor/CloudResources/InstanceFiles/test_game/"; const string SAVE_INFO_FILE_PATH = SAVE_INFO_DIR + "saveInfo.yml"; const string GAME_NAME = "test_game"; const string ENV = "tst"; const string ENV_VALUE = "tst"; const string ACCOUNT_ID = "test account id"; const string REGION = "test_region"; const string ACCESS_KEY = "test access key"; const string ACCESS_SECRET = "test access secret"; const string TEST_KEY = "test key"; const string TEST_VALUE = "test value"; private class GameKitTestPaths : GameKitPaths { public override string ASSETS_FULL_PATH => Application.dataPath + PLUGIN_BASE_DIR; public override string ASSETS_RELATIVE_PATH => Application.dataPath + PLUGIN_BASE_DIR; } AccountDetails accountDetails = new AccountDetails() { GameName = GAME_NAME, Environment = ENV, AccountId = ACCOUNT_ID, Region = REGION, AccessKey = ACCESS_KEY, AccessSecret = ACCESS_SECRET }; Threader _threader; FeatureResourceManager _target; Mock<ICoreWrapperProvider> _coreWrapperMock; [SetUp] public void SetUp() { // generate the saveInfo.yml file CreateSaveInfoFile(); // mocks _coreWrapperMock = new Mock<ICoreWrapperProvider>(); _coreWrapperMock.Setup(cw => cw.SettingsPopulateAndSave(GAME_NAME, ENV, REGION)).Returns(GameKitErrors.GAMEKIT_SUCCESS); _coreWrapperMock.Setup(cw => cw.SettingsGetGameName()).Returns(GAME_NAME); _coreWrapperMock.Setup(cw => cw.SettingsGetFeatureVariables(FeatureType.Main)).Returns(new Dictionary<string, string>()); _coreWrapperMock.Setup(cw => cw.SettingsSave()).Returns(GameKitErrors.GAMEKIT_SUCCESS); _coreWrapperMock.Setup(cw => cw.SettingsAddCustomEnvironment(ENV, ENV_VALUE)); _coreWrapperMock.Setup(cw => cw.SettingsSetFeatureVariables(FeatureType.Main, new string[] { TEST_KEY }, new string[] { TEST_VALUE }, 1)); _coreWrapperMock.Setup(cw => cw.SettingsGetCustomEnvironments()).Returns(new Dictionary<string, string>() { { TEST_KEY, TEST_VALUE } }); // target _threader = new Threader(); _target = new FeatureResourceManager(_coreWrapperMock.Object, new GameKitTestPaths(), _threader); _target.SetAccountDetails(accountDetails); } [TearDown] public void TearDown() { // clean up saveInfo.yml file DeleteSaveInfoFile(); } [Test] public void SettingsSaveSettings_StandardCase_CallsSuccessfully() { // act uint result = _target.SaveSettings(); // assert _coreWrapperMock.Verify(cw => cw.SettingsPopulateAndSave(GAME_NAME, ENV, REGION), Times.Once); Assert.AreEqual(GameKitErrors.GAMEKIT_SUCCESS, result); Assert.IsTrue(Log.Count == 0); } [Test] public void SettingsSaveSettings_NonSuccessResult_LogsError() { // arrange _coreWrapperMock.Setup(cw => cw.SettingsPopulateAndSave(GAME_NAME, ENV, REGION)).Returns(GameKitErrors.GAMEKIT_ERROR_GENERAL); // act uint result = _target.SaveSettings(); // assert _coreWrapperMock.Verify(cw => cw.SettingsPopulateAndSave(GAME_NAME, ENV, REGION), Times.Once); Assert.AreNotEqual(GameKitErrors.GAMEKIT_SUCCESS, result); Assert.IsTrue(Log.Count == 1); Assert.AreEqual($"Error: FeatureResourceManager.SaveSettings() Failed to save : { GameKitErrors.ToString(GameKitErrors.GAMEKIT_ERROR_GENERAL) }", Log[0]); } [Test] public void SettingsGetGameName_LocalGameNameExists_ReturnsLocal() { // act string result = _target.GetGameName(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetGameName(), Times.Never); Assert.AreEqual(GAME_NAME, result); } [Test] public void SettingsGetGameName_LocalGameNameEmpty_CallsDll() { // arrange _target.SetGameName(string.Empty); // act string result = _target.GetGameName(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetGameName(), Times.Once); Assert.AreEqual(GAME_NAME, result); } [Test] public void GetSettingsEnvironments_SaveInfoNotFound_ReturnsEmptyMap() { // arrange _target.SetGameName(string.Empty); // act Dictionary<string, string> result = _target.GetCustomEnvironments(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetCustomEnvironments(), Times.Never); Assert.IsTrue(result.Count == 0); } [Test] public void GetSettingsEnvironments_SaveInfoExists_CallsDll() { // act Dictionary<string, string> result = _target.GetCustomEnvironments(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetCustomEnvironments(), Times.Once); Assert.IsTrue(result.Count == 1); Assert.AreEqual(TEST_VALUE, result[TEST_KEY]); } [Test] public void SetFeatureVariable_WhenLocalMethodCalledMultipleTime_DllCalledOnlyOnce() { // act _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); // wait for each threaded item to be executed _threader.WaitForThreadedWork_TestOnly(); // assert _coreWrapperMock.Verify(cw => cw.SettingsSetFeatureVariables(FeatureType.Main, new string[] { TEST_KEY }, new string[] { TEST_VALUE }, 1), Times.Exactly(3)); _coreWrapperMock.Verify(cw => cw.SettingsSave(), Times.Once); } [Test] public void SetFeatureVariableIfUnset_WhenLocalMethodCalledMultipleTime_DllCalledOnlyOnce() { // act _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _target.SetFeatureVariable(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); // wait for each threaded item to be executed _threader.WaitForThreadedWork_TestOnly(); // assert _coreWrapperMock.Verify(cw => cw.SettingsSetFeatureVariables(FeatureType.Main, new string[] { TEST_KEY }, new string[] { TEST_VALUE }, 1), Times.Exactly(3)); _coreWrapperMock.Verify(cw => cw.SettingsSave(), Times.Once); } [Test] public void SetFeatureVariableIfUnset_WhenTheValueDoesNotExist_DllIsCalled() { // act _target.SetFeatureVariableIfUnset(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _threader.WaitForThreadedWork_TestOnly(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetFeatureVariables(FeatureType.Main), Times.Once); _coreWrapperMock.Verify(cw => cw.SettingsSave(), Times.Once); } [Test] public void SetFeatureVariableIfUnset_WhenTheValueDoesExist_DllIsNotCalled() { // arrange _coreWrapperMock.Setup(cw => cw.SettingsGetFeatureVariables(FeatureType.Main)).Returns(new Dictionary<string, string>() { { TEST_KEY, TEST_VALUE } }); // act _target.SetFeatureVariableIfUnset(FeatureType.Main, TEST_KEY, TEST_VALUE, () => { }); _threader.WaitForThreadedWork_TestOnly(); // assert _coreWrapperMock.Verify(cw => cw.SettingsGetFeatureVariables(FeatureType.Main), Times.Once); _coreWrapperMock.Verify(cw => cw.SettingsSave(), Times.Never); } [Test] public void SetFeatureVariables_StandardCase_CallsSuccessfully() { // act _target.SetFeatureVariables(new []{ Tuple.Create(FeatureType.Main, TEST_KEY, TEST_VALUE) } , () => { }); // assert _coreWrapperMock.Verify(cw => cw.SettingsSetFeatureVariables(FeatureType.Main, new string[] { TEST_KEY }, new string[] { TEST_VALUE }, 1), Times.Once); _coreWrapperMock.Verify(cw => cw.SettingsSave(), Times.Once); } private void CreateSaveInfoFile() { string contents = "#\n" + "# DO NOT MANUALLY EDIT\n" + "#\n" + "# Autogenerated by AWS GameKit\n" + "#\n" + "game:\n" + $" name: { GAME_NAME }\n" + $" short_name: { GAME_NAME }\n" + "lastUsedEnvironment:\n" + $" code: { ENV }\n" + $"lastUsedRegion: { REGION }\n" + "gamekitPluginVersion: 1.1\n"; Directory.CreateDirectory(SAVE_INFO_DIR); File.WriteAllText(SAVE_INFO_FILE_PATH, contents); } private void DeleteSaveInfoFile() { if (Directory.Exists(TEST_RESOURCES_DIR)) { Directory.Delete(TEST_RESOURCES_DIR, true); } if (File.Exists(TEST_RESOURCES_FOLDER + ".meta")) { File.Delete(TEST_RESOURCES_FOLDER + ".meta"); } } } }
283
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.UnitTests; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class TabWidgetTests : GameKitTestBase { private class DummyDrawable : IDrawable { public void OnGUI() { // do nothing } } [Test] public void Initialize_WhenTabsArrayIsEmpty_ThrowsArgumentException() { // arrange TabWidget tabWidget = new TabWidget(); Tab[] emptyTabArray = new Tab[] { }; // act / assert Assert.Throws<ArgumentException>(() => { tabWidget.Initialize(emptyTabArray, GUI.ToolbarButtonSize.Fixed); } ); } [Test] public void Initialize_WhenTabsArrayNonEmpty_Succeeds() { // arrange TabWidget tabWidget = new TabWidget(); Tab[] nonEmptyTabArray = new Tab[] { new Tab("dummyTab", new DummyDrawable()) }; // act / assert Assert.DoesNotThrow(() => { tabWidget.Initialize(nonEmptyTabArray, GUI.ToolbarButtonSize.Fixed); } ); } [Test] public void SelectTab_WhenTabNameDoesNotExist_LogsError() { // arrange string existingTabName = "dummyTab"; string nonExistentTabName = "nonExistentTabName"; TabWidget tabWidget = new TabWidget(); Tab[] nonEmptyTabArray = new Tab[] { new Tab("dummyTab", new DummyDrawable()) }; tabWidget.Initialize(nonEmptyTabArray, GUI.ToolbarButtonSize.Fixed); string expectedErrorMessage = $"There is no tab named \"{nonExistentTabName}\". Valid tab names are: \"{existingTabName}\". The selected tab will remain \"{existingTabName}\"."; // act tabWidget.SelectTab(nonExistentTabName); // assert Assert.AreEqual(1, Log.Count); Assert.AreEqual(expectedErrorMessage, Log[0]); } [Test] public void SelectTab_WhenTabNameExists_DoesNotLogError() { // arrange TabWidget tabWidget = new TabWidget(); Tab[] nonEmptyTabArray = new Tab[] { new Tab("dummyTab", new DummyDrawable()) }; tabWidget.Initialize(nonEmptyTabArray, GUI.ToolbarButtonSize.Fixed); // act tabWidget.SelectTab("dummyTab"); // assert Assert.AreEqual(0, Log.Count); } } }
105
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Editor.Models; using AWS.GameKit.Runtime.UnitTests; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public abstract class FeatureSettingTests<T> : GameKitTestBase { [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(T expectedDefaultValue) { // act FeatureSetting<T> featureSetting = CreateFeatureSetting("myVariableName", expectedDefaultValue); // assert Assert.AreEqual(expectedDefaultValue, featureSetting.DefaultValue); Assert.AreEqual(featureSetting.DefaultValue, featureSetting.CurrentValue); Assert.AreEqual(featureSetting.DefaultValueString, featureSetting.CurrentValueString); } [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void Constructor_WhenArgumentsAreNull_ThrowsException(string variableName, T defaultValue) { // act / assert Assert.Throws<ArgumentNullException>( () => CreateFeatureSetting(variableName, defaultValue)); } [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(string newValueString, T expectedCurrentValue) { // arrange FeatureSetting<T> featureSetting = CreateDefaultFeatureSetting(); // act featureSetting.SetCurrentValueFromString(newValueString); // assert Assert.AreEqual(expectedCurrentValue, featureSetting.CurrentValue); } [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(string newValueString, Type exceptionType) { // arrange FeatureSetting<T> featureSetting = CreateDefaultFeatureSetting(); // act / assert Assert.Throws(exceptionType, () => featureSetting.SetCurrentValueFromString(newValueString)); } [Test] public void SetCurrentValueFromString_WhenStringIsNull_ThrowsException() { // arrange FeatureSetting<T> featureSetting = CreateDefaultFeatureSetting(); string nullString = null; // act / assert Assert.Throws<ArgumentNullException>( () => featureSetting.SetCurrentValueFromString(nullString)); } [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(T defaultValue, string expectedDefaultValueString) { // This tests the protected method "ValueToString()" // arrange FeatureSetting<T> featureSetting = CreateFeatureSetting("myVariableName", defaultValue); // act / assert Assert.AreEqual(expectedDefaultValueString, featureSetting.DefaultValueString); Assert.AreEqual(expectedDefaultValueString, featureSetting.CurrentValueString); } [Test] // Do not add [TestCase()] to this base class method. // All test cases should be added to child classes. public virtual void CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(T defaultValue, T newValue, string expectedCurrentValueString) { // arrange FeatureSetting<T> featureSetting = CreateFeatureSetting("myVariableName", defaultValue); // act featureSetting.CurrentValue = newValue; // assert Assert.AreEqual(expectedCurrentValueString, featureSetting.CurrentValueString); } protected abstract FeatureSetting<T> CreateFeatureSetting(string variableName, T defaultValue); protected abstract FeatureSetting<T> CreateDefaultFeatureSetting(); } }
116
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class FeatureSettingBoolTests : FeatureSettingTests<bool> { [Test] [TestCase(true)] [TestCase(false)] public override void Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(bool expectedDefaultValue) { // Pass parameters to base test: base.Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(expectedDefaultValue); } [Test] [TestCase(null, true)] // Note: we can't test for "defaultValue: null" because a null boolean gets automatically converted to "false". public override void Constructor_WhenArgumentsAreNull_ThrowsException(string variableName, bool defaultValue) { base.Constructor_WhenArgumentsAreNull_ThrowsException(variableName, defaultValue); } [Test] // These strings are in the format that is written to disk by this AWS GameKit Unity package: [TestCase("true", true)] [TestCase("false", false)] // These other strings are in formats that might be written by a user who is modifying the saveInfo.yml file by hand (not recommended!) [TestCase("true ", true)] [TestCase(" true", true)] [TestCase("True", true)] [TestCase("TRUE", true)] [TestCase("False", false)] [TestCase("FALSE", false)] public override void SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(string newValueString, bool expectedCurrentValue) { base.SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(newValueString, expectedCurrentValue); } [Test] // Incorrectly formatted string: [TestCase("not_a_boolean", typeof(FormatException))] [TestCase("tr ue", typeof(FormatException))] // Numbers that might be used as boolean: [TestCase("1", typeof(FormatException))] [TestCase("0", typeof(FormatException))] // Null [TestCase(null, typeof(ArgumentNullException))] [TestCase("null", typeof(FormatException))] [TestCase("Null", typeof(FormatException))] [TestCase("NULL", typeof(FormatException))] // Whitespace [TestCase("", typeof(FormatException))] [TestCase(" ", typeof(FormatException))] public override void SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(string newValueString, Type exceptionType) { base.SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(newValueString, exceptionType); } [Test] [TestCase(true, "true")] [TestCase(false, "false")] public override void DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(bool defaultValue, string expectedDefaultValueString) { base.DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(defaultValue, expectedDefaultValueString); } [Test] // New value different than default: [TestCase(true, false, "false")] [TestCase(false, true, "true")] // New value same as default: [TestCase(true, true, "true")] [TestCase(false, false, "false")] public override void CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(bool defaultValue, bool newValue, string expectedCurrentValueString) { base.CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(defaultValue, newValue, expectedCurrentValueString); } protected override FeatureSetting<bool> CreateFeatureSetting(string variableName, bool defaultValue) { return new FeatureSettingBool(variableName, defaultValue); } protected override FeatureSetting<bool> CreateDefaultFeatureSetting() { return new FeatureSettingBool("myVariableName", defaultValue: false); } } }
101
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class FeatureSettingFloatTests : FeatureSettingTests<float> { /// <summary> /// This string will cause an <c>OverflowException</c> when parsed to a <c>float</c>.<br/> /// This number is equal to <c>float.MaxValue</c> with one additional zero added. /// </summary> private const string OVERFLOWED_FLOAT_VALUE = "3402823470000000000000000000000000000000"; [Test] [TestCase(-1.1f)] [TestCase(0.0f)] [TestCase(1.1f)] public override void Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(float expectedDefaultValue) { // Pass parameters to base test: base.Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(expectedDefaultValue); } [Test] [TestCase(null, 1f)] // Note: we can't test for "defaultValue: null" because a null float gets automatically converted to "0f". public override void Constructor_WhenArgumentsAreNull_ThrowsException(string variableName, float defaultValue) { base.Constructor_WhenArgumentsAreNull_ThrowsException(variableName, defaultValue); } [Test] // These strings are in the format that is written to disk by this AWS GameKit Unity package: [TestCase("0", 0f)] [TestCase("1", 1f)] [TestCase("1.1", 1.1f)] [TestCase("-1", -1f)] [TestCase("-1.1", -1.1f)] // These other strings are in formats that might be written by a user who is modifying the saveInfo.yml file by hand (not recommended!) [TestCase(" 0", 0f)] [TestCase("0 ", 0f)] [TestCase("0.0", 0f)] [TestCase("0.0000", 0f)] [TestCase("1.0", 1f)] [TestCase("-1.0", -1f)] public override void SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(string newValueString, float expectedCurrentValue) { base.SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(newValueString, expectedCurrentValue); } // [Test] // Incorrectly formatted numbers: [TestCase("not_a_float", typeof(FormatException))] [TestCase("1. 0", typeof(FormatException))] [TestCase("1f", typeof(FormatException))] [TestCase("1F", typeof(FormatException))] [TestCase("1.0f", typeof(FormatException))] // Overflow [TestCase(OVERFLOWED_FLOAT_VALUE, typeof(OverflowException))] // Null [TestCase(null, typeof(ArgumentNullException))] [TestCase("null", typeof(FormatException))] [TestCase("Null", typeof(FormatException))] [TestCase("NULL", typeof(FormatException))] // Whitespace [TestCase("", typeof(FormatException))] [TestCase(" ", typeof(FormatException))] public override void SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(string newValueString, Type exceptionType) { base.SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(newValueString, exceptionType); } [Test] [TestCase(0f, "0")] [TestCase(1f, "1")] [TestCase(1.1f, "1.1")] [TestCase(-1f, "-1")] [TestCase(-1.1f, "-1.1")] public override void DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(float defaultValue, string expectedDefaultValueString) { base.DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(defaultValue, expectedDefaultValueString); } [Test] // New value different than default: [TestCase(0f, 1f, "1")] // New value same as default: [TestCase(0f, 0f, "0")] public override void CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(float defaultValue, float newValue, string expectedCurrentValueString) { base.CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(defaultValue, newValue, expectedCurrentValueString); } protected override FeatureSetting<float> CreateFeatureSetting(string variableName, float defaultValue) { return new FeatureSettingFloat(variableName, defaultValue); } protected override FeatureSetting<float> CreateDefaultFeatureSetting() { return CreateFeatureSetting("myVariableName", defaultValue: 0f); } } }
114
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Models.FeatureSettings; // Third Party using NUnit.Framework; using UnityEngine; using UnityEngine.AI; namespace AWS.GameKit.Editor.UnitTests { public class FeatureSettingIntTests : FeatureSettingTests<int> { [Test] [TestCase(-1)] [TestCase(0)] [TestCase(1)] public override void Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(int expectedDefaultValue) { // Pass parameters to base test: base.Constructor_WhenArgumentsAreNonNull_SetsCurrentValueToDefaultValue(expectedDefaultValue); } [Test] [TestCase(null, 1)] // Note: we can't test for "defaultValue: null" because a null int gets automatically converted to "0". public override void Constructor_WhenArgumentsAreNull_ThrowsException(string variableName, int defaultValue) { base.Constructor_WhenArgumentsAreNull_ThrowsException(variableName, defaultValue); } [Test] // These strings are in the format that is written to disk by this AWS GameKit Unity package: [TestCase("0", 0)] [TestCase("1", 1)] [TestCase("-1", -1)] // These other strings are in formats that might be written by a user who is modifying the saveInfo.yml file by hand (not recommended!) [TestCase(" 0", 0)] [TestCase("0 ", 0)] public override void SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(string newValueString, int expectedCurrentValue) { base.SetCurrentValueFromString_WhenStringHasValidFormat_SuccessfullySetsCurrentValue(newValueString, expectedCurrentValue); } // [Test] // Incorrectly formatted numbers: [TestCase("not_an_int", typeof(FormatException))] [TestCase("1 0", typeof(FormatException))] [TestCase("1,000", typeof(FormatException))] // Overflow [TestCase("2147483648", typeof(OverflowException))] // Null [TestCase(null, typeof(ArgumentNullException))] [TestCase("null", typeof(FormatException))] [TestCase("Null", typeof(FormatException))] [TestCase("NULL", typeof(FormatException))] // Whitespace [TestCase("", typeof(FormatException))] [TestCase(" ", typeof(FormatException))] public override void SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(string newValueString, Type exceptionType) { base.SetCurrentValueFromString_WhenStringHasInvalidFormat_ThrowsException(newValueString, exceptionType); } [Test] [TestCase(0, "0")] [TestCase(1, "1")] [TestCase(-1, "-1")] public override void DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(int defaultValue, string expectedDefaultValueString) { base.DefaultAndCurrentValueString_AfterConstructor_AreCorrectlyFormatted(defaultValue, expectedDefaultValueString); } [Test] // New value different than default: [TestCase(0, 1, "1")] // New value same as default: [TestCase(0, 0, "0")] public override void CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(int defaultValue, int newValue, string expectedCurrentValueString) { base.CurrentValuePropertySetter_WhenCalled_CurrentValueStringIsCorrectlyFormatted(defaultValue, newValue, expectedCurrentValueString); } protected override FeatureSetting<int> CreateFeatureSetting(string variableName, int defaultValue) { return new FeatureSettingInt(variableName, defaultValue); } protected override FeatureSetting<int> CreateDefaultFeatureSetting() { return CreateFeatureSetting("myVariableName", defaultValue: 0); } } }
100
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.UnitTests; using AWS.GameKit.Editor.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class EditorWindowHelperTests : GameKitTestBase { [Test] public void GetInspectorWindowType_Always_ReturnsNonNull() { // act Type inspectorWindowType = EditorWindowHelper.GetInspectorWindowType(); // assert Assert.IsNotNull(inspectorWindowType, "Expected the InspectorWindow's Type to be non-null, but it was null. " + "Please see the warning logged from GetInspectorWindowType() for details on how to fix this failure."); } } }
30
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; // Unity using UnityEngine; // GameKit using AWS.GameKit.Editor.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class LazyLoadedTextureForCurrentResolutionTests { const int TEST_WIDTH = 900; const int TEST_WIDTH_2K = 1900; const int TEST_WIDTH_4K = 3900; const int TEST_WIDTH_8K = 7900; const int TEST_HEIGHT = 500; const string TEST_PATH = "test_path"; const string TEST_PATH_2K = "test_path-2k"; const string TEST_PATH_4K = "test_path-4k"; const string TEST_PATH_8K = "test_path-8k"; [Test] public void Get_WhenAt8KResolutionAndNoTexturesFound_AttemptsToLoadEachTextureStartingWithTheRequested() { // arrange Resolution res = new Resolution { width = TEST_WIDTH_8K, height = TEST_HEIGHT }; List<string> pathsOUT = new List<string>(); LazyLoadedResourceForCurrentResolution<Texture> target = new LazyLoadedResourceForCurrentResolution<Texture>(TEST_PATH, res, (pathIN) => { pathsOUT.Add(pathIN); return null; }); // act target.Get(); // assert Assert.AreEqual(4, pathsOUT.Count); Assert.AreEqual(TEST_PATH_8K, pathsOUT[0]); Assert.AreEqual(TEST_PATH_4K, pathsOUT[1]); Assert.AreEqual(TEST_PATH_2K, pathsOUT[2]); Assert.AreEqual(TEST_PATH, pathsOUT[3]); } [Test] public void Get_WhenAt4KResolutionAndNoTexturesFound_AttemptsToLoadEachTextureStartingWithTheRequested() { // arrange Resolution res = new Resolution { width = TEST_WIDTH_4K, height = TEST_HEIGHT }; List<string> pathsOUT = new List<string>(); LazyLoadedResourceForCurrentResolution<Texture> target = new LazyLoadedResourceForCurrentResolution<Texture>(TEST_PATH, res, (pathIN) => { pathsOUT.Add(pathIN); return null; }); // act target.Get(); // assert Assert.AreEqual(3, pathsOUT.Count); Assert.AreEqual(TEST_PATH_4K, pathsOUT[0]); Assert.AreEqual(TEST_PATH_2K, pathsOUT[1]); Assert.AreEqual(TEST_PATH, pathsOUT[2]); } [Test] public void Get_WhenAt2KResolutionAndNoTexturesFound_AttemptsToLoadEachTextureStartingWithTheRequested() { // arrange Resolution res = new Resolution { width = TEST_WIDTH_2K, height = TEST_HEIGHT }; List<string> pathsOUT = new List<string>(); LazyLoadedResourceForCurrentResolution<Texture> target = new LazyLoadedResourceForCurrentResolution<Texture>(TEST_PATH, res, (pathIN) => { pathsOUT.Add(pathIN); return null; }); // act target.Get(); // assert Assert.AreEqual(2, pathsOUT.Count); Assert.AreEqual(TEST_PATH_2K, pathsOUT[0]); Assert.AreEqual(TEST_PATH, pathsOUT[1]); } [Test] public void Get_WhenAt1KResolutionAndNoTexturesFound_AttemptsToLoadOnlyThe1KTexture() { // arrange Resolution res = new Resolution { width = TEST_WIDTH, height = TEST_HEIGHT }; List<string> pathsOUT = new List<string>(); LazyLoadedResourceForCurrentResolution<Texture> target = new LazyLoadedResourceForCurrentResolution<Texture>(TEST_PATH, res, (pathIN) => { pathsOUT.Add(pathIN); return null; }); // act target.Get(); // assert Assert.AreEqual(1, pathsOUT.Count); Assert.AreEqual(TEST_PATH, pathsOUT[0]); } [Test] public void Get_WhenAt8KResolution_ReturnsOnceTextureFound() { // arrange Resolution res = new Resolution { width = TEST_WIDTH_8K, height = TEST_HEIGHT }; List<string> pathsOUT = new List<string>(); LazyLoadedResourceForCurrentResolution<Texture> target = new LazyLoadedResourceForCurrentResolution<Texture>(TEST_PATH, res, (pathIN) => { pathsOUT.Add(pathIN); return Resources.Load<Texture>("Textures/FeatureStatus-Success"); }); // act target.Get(); // assert Assert.AreEqual(1, pathsOUT.Count); Assert.AreEqual(TEST_PATH_8K, pathsOUT[0]); } } }
162
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; // GameKit using AWS.GameKit.Runtime.UnitTests; using AWS.GameKit.Editor.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class StringHelperTests : GameKitTestBase { [Test] public void RemoveWhitespace_WhenInputHasWhitespace_RemovesAllWhitespace() { // arrange string input = " \t\n this \t\n is \t\n a \t\n string \t\n "; string expectedOutput = "thisisastring"; // act string actualOutput = StringHelper.RemoveWhitespace(input); // assert Assert.AreEqual(expectedOutput, actualOutput); } [Test] public void RemoveWhitespace_WhenInputHasNoWhitespace_ReturnsUnmodifiedString() { // arrange string input = "StringWithNoWhitespace"; // act string output = StringHelper.RemoveWhitespace(input); // assert Assert.AreEqual(input, output); } [Test] public void MakeCommaSeparatedList_WhenInputListIsEmpty_ReturnsEmptyString() { // arrange List<string> emptyInputList = new List<string>(); string expectedValue = string.Empty; // act string actualValue = StringHelper.MakeCommaSeparatedList(emptyInputList); // assert Assert.AreEqual(expectedValue, actualValue); } [Test] public void MakeCommaSeparatedList_WhenInputListIsNonEmpty_ReturnsJoinedString() { // arrange string first = "first"; string second = "second"; string third = "third"; List<string> nonEmptyInputList = new List<string>() { first, second, third }; string expectedValue = $"\"{first}\", \"{second}\", \"{third}\""; // act string actualValue = StringHelper.MakeCommaSeparatedList(nonEmptyInputList); // assert Assert.AreEqual(expectedValue, actualValue); } [Test] public void MakeCommaSeparatedList_WhenInputListContainsQuotes_ReturnValueProperlyEscapesTheQuotes() { // arrange string withoutQuotes = "foo"; string withQuotes = "\"bar\""; List<string> nonEmptyInputList = new List<string>() { withoutQuotes, withQuotes }; string expectedValue = $"\"{withoutQuotes}\", \"{withQuotes}\""; // act string actualValue = StringHelper.MakeCommaSeparatedList(nonEmptyInputList); // assert Assert.AreEqual(expectedValue, actualValue); } } }
102
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKIt using AWS.GameKit.Editor.Windows.Settings; using AWS.GameKit.Runtime.UnitTests; // Third Party using NUnit.Framework; namespace AWS.GameKit.Editor.UnitTests { public class AllPagesTests : GameKitTestBase { [Test] public void GetPage_EveryPageType_Exists() { // Arrange AllPages allPages = new AllPages(); // Act/Assert foreach (PageType pageType in Enum.GetValues(typeof(PageType))) { Assert.DoesNotThrow(() => allPages.GetPage(pageType)); } } } }
31
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; using Moq; namespace AWS.GameKit.Runtime.UnitTests { public class GameKitFeatureBaseTests : GameKitTestBase { const string TEST_DESCRIPTION = "test description"; Func<string, string> _testSimpleFunction = (x) => string.Empty; Func<string> _testSimpleWithNoDescriptionFunction = () => string.Empty; Action<string> _testSimpleWithNoResultFunction = (x) => { }; Action _testSimpleWithNoDescriptionOrResultFunction = () => { }; Func<string, Action<string>, string> _testRecurringFunction = (x, y) => string.Empty; Action<string> _testCallback = (x) => { }; Action _testNoResultCallback = () => { }; GameKitFeatureBaseTarget _target; Mock<Threader> _threaderMock; [SetUp] public void SetUp() { _threaderMock = new Mock<Threader>(); _target = new GameKitFeatureBaseTarget(); _target.SetThreader(_threaderMock.Object); } [Test] public void Awake_StandardCase_CallsSuccessfully() { // act _target.OnInitialize(); // assert _threaderMock.Verify(m => m.Awake(), Times.Once, "Expected Awake for threader to be called once"); Assert.IsTrue(_target.IsReady); Assert.AreEqual(1, _target.InitializedCallCount, $"Expected Initialize called one time. Count = {_target.InitializedCallCount}"); } [Test] public void OnDestroy_StandardCase_CallsSuccessfully() { // act _target.OnDispose(); // assert Assert.IsFalse(_target.IsReady); Assert.AreEqual(1, _target.DestroyCallCount, $"Expected Destroy called one time. Count = {_target.DestroyCallCount}"); Assert.AreEqual(1, _target.FeatureWrapper.ReleaseCallCount, $"Expected the feature wrapper's Release method called one time. Count = {_target.FeatureWrapper.ReleaseCallCount}"); } [Test] public void Update_WhenClassIsReady_CallsSuccessfully() { // arrange _target.OnInitialize(); // act _target.Update(); // assert _threaderMock.Verify(m => m.Update(), Times.Once, "Expected Update for threader to be called once"); Assert.IsTrue(_target.IsReady); Assert.AreEqual(1, _target.UpdateCallCount, $"Expected Update called one time. Count = {_target.UpdateCallCount}"); } [Test] public void Update_WhenClassIsNotReady_IsNotCalled() { // act _target.Update(); // assert _threaderMock.Verify(m => m.Update(), Times.Never, "Expected Update for threader never called"); Assert.IsFalse(_target.IsReady); Assert.AreEqual(0, _target.UpdateCallCount, $"Expected Update called zero times. Count = {_target.UpdateCallCount}"); } [Test] public void CallSimple_WhenClassIsReady_CalledSuccessfully() { // arrange _target.OnInitialize(); // act _target.Call(_testSimpleFunction, TEST_DESCRIPTION, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleFunction, TEST_DESCRIPTION, _testCallback), Times.Once, "Expected one Threader Call"); Assert.IsTrue(_target.IsReady); } [Test] public void CallSimple_WhenClassIsNotReady_IsNotCalled() { // arrange string errorMessage = $"The Call method of the AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTarget feature, called in the CallSimple_WhenClassIsNotReady_IsNotCalled method " + "of AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTests class, has not been initialized yet. Please make sure AWS.GameKit.Runtime.Core.GameKitManager is attached as a component and enabled."; // act _target.Call(_testSimpleFunction, TEST_DESCRIPTION, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleFunction, TEST_DESCRIPTION, _testCallback), Times.Never, "Expected no Threader Call"); Assert.IsFalse(_target.IsReady); Assert.IsTrue(Log.Count == 1); Assert.AreEqual(errorMessage, Log[0]); } [Test] public void CallSimpleWithNoDescription_WhenClassIsReady_CalledSuccessfully() { // arrange _target.OnInitialize(); // act _target.Call(_testSimpleWithNoDescriptionFunction, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoDescriptionFunction, _testCallback), Times.Once, "Expected one Threader Call"); Assert.IsTrue(_target.IsReady); } [Test] public void CallSimpleWithNoDescription_WhenClassIsNotReady_IsNotCalled() { // arrange string errorMessage = $"The Call method of the AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTarget feature, called in the CallSimpleWithNoDescription_WhenClassIsNotReady_IsNotCalled method " + "of AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTests class, has not been initialized yet. Please make sure AWS.GameKit.Runtime.Core.GameKitManager is attached as a component and enabled."; // act _target.Call(_testSimpleWithNoDescriptionFunction, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoDescriptionFunction, _testCallback), Times.Never, "Expected no Threader Call"); Assert.IsFalse(_target.IsReady); Assert.IsTrue(Log.Count == 1); Assert.AreEqual(errorMessage, Log[0]); } [Test] public void CallSimpleWithNoResult_WhenClassIsReady_CalledSuccessfully() { // arrange _target.OnInitialize(); // act _target.Call(_testSimpleWithNoResultFunction, TEST_DESCRIPTION, _testNoResultCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoResultFunction, TEST_DESCRIPTION, _testNoResultCallback), Times.Once, "Expected one Threader Call"); Assert.IsTrue(_target.IsReady); } [Test] public void CallSimpleWithNoResult_WhenClassIsNotReady_IsNotCalled() { // arrange string errorMessage = $"The Call method of the AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTarget feature, called in the CallSimpleWithNoResult_WhenClassIsNotReady_IsNotCalled method " + "of AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTests class, has not been initialized yet. Please make sure AWS.GameKit.Runtime.Core.GameKitManager is attached as a component and enabled."; // act _target.Call(_testSimpleWithNoResultFunction, TEST_DESCRIPTION, _testNoResultCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoResultFunction, TEST_DESCRIPTION, _testNoResultCallback), Times.Never, "Expected no Threader Call"); Assert.IsFalse(_target.IsReady); Assert.IsTrue(Log.Count == 1); Assert.AreEqual(errorMessage, Log[0]); } [Test] public void CallSimpleWithNoDescriptionOrResult_WhenClassIsReady_CalledSuccessfully() { // arrange _target.OnInitialize(); // act _target.Call(_testSimpleWithNoDescriptionOrResultFunction, _testNoResultCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoDescriptionOrResultFunction, _testNoResultCallback), Times.Once, "Expected one Threader Call"); Assert.IsTrue(_target.IsReady); } [Test] public void CallSimpleWithNoDescriptionOrResult_WhenClassIsNotReady_IsNotCalled() { // arrange string errorMessage = $"The Call method of the AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTarget feature, called in the CallSimpleWithNoDescriptionOrResult_WhenClassIsNotReady_IsNotCalled method " + "of AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTests class, has not been initialized yet. Please make sure AWS.GameKit.Runtime.Core.GameKitManager is attached as a component and enabled."; // act _target.Call(_testSimpleWithNoDescriptionOrResultFunction, _testNoResultCallback); // assert _threaderMock.Verify(m => m.Call(_testSimpleWithNoDescriptionOrResultFunction, _testNoResultCallback), Times.Never, "Expected no Threader Call"); Assert.IsFalse(_target.IsReady); Assert.IsTrue(Log.Count == 1); Assert.AreEqual(errorMessage, Log[0]); } [Test] public void CallRecurring_WhenClassIsReady_CalledSuccessfully() { // arrange _target.OnInitialize(); // act _target.Call(_testRecurringFunction, TEST_DESCRIPTION, _testCallback, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testRecurringFunction, TEST_DESCRIPTION, _testCallback, _testCallback), Times.Once, "Expected one Threader Call"); Assert.IsTrue(_target.IsReady); } [Test] public void CallRecurring_WhenClassIsNotReady_IsNotCalled() { // arrange string errorMessage = $"The Call method of the AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTarget feature, called in the CallRecurring_WhenClassIsNotReady_IsNotCalled method " + "of AWS.GameKit.Runtime.UnitTests.GameKitFeatureBaseTests class, has not been initialized yet. Please make sure AWS.GameKit.Runtime.Core.GameKitManager is attached as a component and enabled."; // act _target.Call(_testRecurringFunction, TEST_DESCRIPTION, _testCallback, _testCallback); // assert _threaderMock.Verify(m => m.Call(_testRecurringFunction, TEST_DESCRIPTION, _testCallback, _testCallback), Times.Never, "Expected no Threader Call"); Assert.IsFalse(_target.IsReady); Assert.IsTrue(Log.Count == 1); Assert.AreEqual(errorMessage, Log[0]); } } public class GameKitFeatureBaseTarget : GameKitFeatureBase { public override FeatureType FeatureType => FeatureType.Main; public class GameKitFeatureWrapperBaseStub : GameKitFeatureWrapperBase { public int ReleaseCallCount = 0; public override void Release() => ++ReleaseCallCount; protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) => IntPtr.Zero; protected override void Release(IntPtr instance) { } } public int InitializedCallCount = 0; public int UpdateCallCount = 0; public int DestroyCallCount = 0; public GameKitFeatureWrapperBaseStub FeatureWrapper = new GameKitFeatureWrapperBaseStub(); public void SetThreader(Threader threader) => _threader = threader; public new void Call<DESCRIPTION, RESULT>(Func<DESCRIPTION, RESULT> function, DESCRIPTION description, Action<RESULT> callback) => base.Call(function, description, callback); public new void Call<RESULT>(Func<RESULT> function, Action<RESULT> callback) => base.Call(function, callback); public new void Call<DESCRIPTION>(Action<DESCRIPTION> function, DESCRIPTION description, Action callback) => base.Call(function, description, callback); public new void Call(Action function, Action callback) => base.Call(function, callback); public new void Call<DESCRIPTION, RESULT, RETURN_RESULT>( Func<DESCRIPTION, Action<RESULT>, RETURN_RESULT> function, DESCRIPTION description, Action<RESULT> callback, Action<RETURN_RESULT> onCompleteCallback) => base.Call<DESCRIPTION, RESULT, RETURN_RESULT>(function, description, callback, onCompleteCallback); protected override void InitializeFeature() => ++InitializedCallCount; protected override void UpdateFeature() => ++UpdateCallCount; protected override void DestroyFeature() => ++DestroyCallCount; protected override GameKitFeatureWrapperBase GetFeatureWrapperBase() => FeatureWrapper; } }
299
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class GameKitFeatureWrapperBaseTests : GameKitTestBase { GameKitFeatureWrapperBaseTarget _target; [SetUp] public void SetUp() { _target = new GameKitFeatureWrapperBaseTarget(); } [Test] public void GetInstance_StandardCase_ReturnsPointer() { // act IntPtr valueReturned = _target.GetInstance(); // assert Assert.AreEqual(1, _target.CreateCallCount, $"Expected that Create is called one time. Count = {_target.CreateCallCount}"); Assert.AreEqual(_target.TestIntPtr, valueReturned); } [Test] public void GetInstance_WhenInstanceIsNotZero_CreateIsNotCalled() { // arrange IntPtr valueReturnedFirstCall = _target.GetInstance(); // act IntPtr valueReturnedSecondCall = _target.GetInstance(); // assert Assert.AreEqual(1, _target.CreateCallCount, $"Expected that Create is called one time. Count = {_target.CreateCallCount}"); Assert.AreEqual(valueReturnedFirstCall, valueReturnedSecondCall); Assert.AreEqual(_target.TestIntPtr, valueReturnedSecondCall); } [Test] public void Release_StandardCase_CallsSuccessfully() { // arrange _target.GetInstance(); // act _target.Release(); // assert Assert.AreEqual(1, _target.ReleaseCallCount, $"Expected that Release is called one time. Count = {_target.ReleaseCallCount}"); } [Test] public void Release_WhenInstanceIsNotZero_ReleaseIsNotCalled() { // act _target.Release(); // assert Assert.AreEqual(0, _target.ReleaseCallCount, $"Expected that Release is called zero times. Count = {_target.ReleaseCallCount}"); } } public class GameKitFeatureWrapperBaseTarget : GameKitFeatureWrapperBase { public int CreateCallCount = 0; public int ReleaseCallCount = 0; public IntPtr TestIntPtr => _testPtr; private IntPtr _testPtr; private GCHandle _handle; public GameKitFeatureWrapperBaseTarget() { GCHandle _handle = GCHandle.Alloc(this); _testPtr = (IntPtr)_handle; } ~GameKitFeatureWrapperBaseTarget() { _handle.Free(); } public new IntPtr GetInstance() => base.GetInstance(); protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { ++CreateCallCount; return _testPtr; } protected override void Release(IntPtr instance) { ++ReleaseCallCount; } } }
112
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; // Third Party using Moq; using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class GameKitManagerTests : GameKitTestBase { public Mock<SessionManager> _sessionManagerMock = new Mock<SessionManager>(); GameObject _gameObject; GameKitManagerTarget _target; [SetUp] public void SetUp() { _sessionManagerMock.Setup(m => m.Release()).Verifiable(); _target = new GameKitManagerTarget(_sessionManagerMock.Object); } [TearDown] public void TearDown() { _target.FeaturesClear(); } [Test] public void EnsureFeaturesAreInitialized_StandardCase_CallsFeaturesAwakeMethodOnce() { // arrange Mock<GameKitFeatureBase> gameKitFeatureMock = new Mock<GameKitFeatureBase>(); _target.FeatureAdd(gameKitFeatureMock.Object); // act _target.EnsureFeaturesAreInitialized(); // assert gameKitFeatureMock.Verify(m => m.OnInitialize(), Times.Once, "Expected Awake for feature to be called once"); Assert.AreEqual(1, _target.FeatureCount, $"Expected one feature in feature list, feature count = { _target.FeatureCount}"); } [Test] public void Dispose_StandardCase_CallsFeaturesOnDestroyMethod() { // arrange Mock<GameKitFeatureBase> gameKitFeatureMock = new Mock<GameKitFeatureBase>(); _target.FeatureAdd(gameKitFeatureMock.Object); // act _target.Dispose(); // assert gameKitFeatureMock.Verify(m => m.OnDispose(), Times.Once, "Expected OnDestroy for feature to be called once"); Assert.AreEqual(1, _target.FeatureCount, $"Expected one feature in feature list, feature count = {_target.FeatureCount}"); _sessionManagerMock.Verify(m => m.Release(), Times.Once); } [Test] public void OnDestroy_WhenThereIsAnException_FeatureListIsKept() { // arrange Mock<GameKitFeatureBase> gameKitFeatureMock = new Mock<GameKitFeatureBase>(); gameKitFeatureMock.Setup(m => m.OnDispose()).Throws<System.Exception>(); _target.FeatureAdd(gameKitFeatureMock.Object); // act Assert.Throws<System.Exception>(() => _target.Dispose()); // assert gameKitFeatureMock.Verify(m => m.OnDispose(), Times.Once, "Expected OnDestroy for feature to be called once"); Assert.AreEqual(1, _target.FeatureCount, $"Expected one feature in feature list, feature count = {_target.FeatureCount}"); } [Test] public void Update_StandardCase_CallsFeaturesUpdateMethod() { // arrange Mock<GameKitFeatureBase> gameKitFeatureMock = new Mock<GameKitFeatureBase>(); _target.FeatureAdd(gameKitFeatureMock.Object); // act _target.Update(); // assert gameKitFeatureMock.Verify(m => m.Update(), Times.Once, "Expected Update for feature to be called once"); Assert.AreEqual(1, _target.FeatureCount, $"Expected one feature in feature list, feature count = {_target.FeatureCount}"); } } public class GameKitManagerTarget : GameKitManager { public GameKitManagerTarget(SessionManager sessionManager) { SetSessionManager(sessionManager); } public void FeaturesClear() => _features.Clear(); public void FeatureAdd(GameKitFeatureBase feature) => _features.Add(feature); public new void Update() => base.Update(); protected override void AddFeatures() { /* add nothing */ } } }
121
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit using AWS.GameKit.Runtime.Core; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class SessionManagerTests : GameKitTestBase { [Test] public void DoesConfigFileExist_PartOfPathMissing_DoesNotRaiseException() { #if UNITY_EDITOR // arrange SessionManager sessionManager = SessionManager.Get(); // act / assert Assert.DoesNotThrow(() => { sessionManager.DoesConfigFileExist("nonExistentGameAlias", "dev"); }); #endif } [Test] public void DoesConfigFileExist_PartOfPathMissing_DoesNotLogError() { #if UNITY_EDITOR // arrange SessionManager sessionManager = SessionManager.Get(); int expectedLogCount = 0; // act sessionManager.DoesConfigFileExist("nonExistentGameAlias", "dev"); // assert Assert.AreEqual(expectedLogCount, Log.Count); #endif } [Test] public void DoesConfigFileExist_PartOfPathMissing_ReturnsFalse() { #if UNITY_EDITOR // arrange SessionManager sessionManager = SessionManager.Get(); // act bool result = sessionManager.DoesConfigFileExist("nonExistentGameAlias", "dev"); // assert Assert.False(result); #endif } } }
61
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Features.GameKitGameSaving; using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class GameSavingWrapperTests : GameKitTestBase { const uint TEST_CALL_STATUS = 42; Slot[] _testSlots; [SetUp] public void SetUp() { _testSlots = new Slot[] { new Slot() { SlotName = "slot name 0", MetadataLocal = "meta data local 0", MetadataCloud = "meta data cloud 0", LastModifiedCloud = 1, LastModifiedLocal = 2, LastSync = 3, SizeCloud = 4, SizeLocal = 5, SlotSyncStatus = 8 }, new Slot() { SlotName = "slot name 1", MetadataLocal = "meta data local 1", MetadataCloud = "meta data cloud 1", LastModifiedCloud = 11, LastModifiedLocal = 22, LastSync = 33, SizeCloud = 44, SizeLocal = 55, SlotSyncStatus = 16 }, new Slot() { SlotName = "slot name 2", MetadataLocal = "meta data local 2", MetadataCloud = "meta data cloud 2", LastModifiedCloud = 111, LastModifiedLocal = 222, LastSync = 333, SizeCloud = 444, SizeLocal = 555, SlotSyncStatus = 32 } }; } [Test] public void GameSavingResponseCallback_StandardCase_CallsSuccessfully() { // arrange SlotListResult result = new SlotListResult(); IntPtr pSlots = Marshaller.ArrayToIntPtr(_testSlots); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameSavingWrapperTarget.GameSavingResponseCallback(dispatchReceiver, pSlots, (uint)_testSlots.Length, true, TEST_CALL_STATUS)); // assert Assert.AreEqual(TEST_CALL_STATUS, result.ResultCode); Assert.AreEqual(_testSlots.Length, result.CachedSlots.Length); for (uint i = 0; i < _testSlots.Length; ++i) { AssertSlotsAreEqual(_testSlots[i], result.CachedSlots[i]); } // cleanup Marshal.FreeHGlobal(pSlots); } [Test] public void GameSavingSlotActionResponseCallback_StandardCase_CallsSuccessfully() { // arrange SlotActionResult result = new SlotActionResult(); IntPtr pSlots = Marshaller.ArrayToIntPtr(_testSlots); IntPtr activeSlotPtr = Marshal.AllocHGlobal(Marshal.SizeOf(_testSlots[0])); Marshal.StructureToPtr(_testSlots[0], activeSlotPtr, false); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameSavingWrapperTarget.GameSavingSlotActionResponseCallback(dispatchReceiver, pSlots, (uint)_testSlots.Length, activeSlotPtr, TEST_CALL_STATUS)); // assert Assert.AreEqual(TEST_CALL_STATUS, result.ResultCode); Assert.AreEqual(_testSlots.Length, result.CachedSlots.Length); AssertSlotsAreEqual(_testSlots[0], result.ActionedSlot); for (uint i = 0; i < _testSlots.Length; ++i) { AssertSlotsAreEqual(_testSlots[i], result.CachedSlots[i]); } // cleanup Marshal.FreeHGlobal(pSlots); Marshal.FreeHGlobal(activeSlotPtr); } [Test] public void GameSavingDataResponseCallback_StandardCase_CallsSuccessfully() { // arrange byte[] data = new byte[] { 1, 1, 0, 1, 0, 1, 1 }; SlotDataResult result = new SlotDataResult(); IntPtr pSlots = Marshaller.ArrayToIntPtr(_testSlots); IntPtr slotPtr = Marshal.AllocHGlobal(Marshal.SizeOf(_testSlots[0])); Marshal.StructureToPtr(_testSlots[0], slotPtr, false); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameSavingWrapperTarget.GameSavingDataResponseCallback(dispatchReceiver, pSlots, (uint)_testSlots.Length, slotPtr, data, (uint)data.Length, TEST_CALL_STATUS)); // assert Assert.AreEqual(TEST_CALL_STATUS, result.ResultCode); Assert.AreEqual(_testSlots.Length, result.CachedSlots.Length); Assert.AreEqual(data.Length, result.DataSize); Assert.AreEqual(data, result.Data); AssertSlotsAreEqual(_testSlots[0], result.ActionedSlot); for (uint i = 0; i < _testSlots.Length; ++i) { AssertSlotsAreEqual(_testSlots[i], result.CachedSlots[i]); } // cleanup Marshal.FreeHGlobal(pSlots); Marshal.FreeHGlobal(slotPtr); } void AssertSlotsAreEqual (Slot expected, Slot actual) { Assert.AreEqual(expected.SlotName, actual.SlotName); Assert.AreEqual(expected.MetadataLocal, actual.MetadataLocal); Assert.AreEqual(expected.MetadataCloud, actual.MetadataCloud); Assert.AreEqual(expected.LastModifiedCloud, actual.LastModifiedCloud); Assert.AreEqual(expected.LastModifiedLocal, actual.LastModifiedLocal); Assert.AreEqual(expected.LastSync, actual.LastSync); Assert.AreEqual(expected.SizeCloud, actual.SizeCloud); Assert.AreEqual(expected.SizeLocal, actual.SizeLocal); Assert.AreEqual(expected.SlotSyncStatus, actual.SlotSyncStatus); } } public class GameSavingWrapperTarget : GameSavingWrapper { public new static void GameSavingResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, bool complete, uint callStatus) => GameSavingWrapper.GameSavingResponseCallback( dispatchReceiver, cachedSlots, slotCount, complete, callStatus); public new static void GameSavingSlotActionResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr activeSlot, uint callStatus) => GameSavingWrapper.GameSavingSlotActionResponseCallback( dispatchReceiver, cachedSlots, slotCount, activeSlot, callStatus); public new static void GameSavingDataResponseCallback(IntPtr dispatchReceiver, IntPtr cachedSlots, uint slotCount, IntPtr slot, byte[] data, uint dataSize, uint callStatus) => GameSavingWrapper.GameSavingDataResponseCallback( dispatchReceiver, cachedSlots, slotCount, slot, data, dataSize, callStatus); } }
191
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Features.GameKitIdentity; using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class IdentityWrapperTests : GameKitTestBase { [Test] public void IdentityGetUserResponseCallback_StandardCase_CallsSuccessfully() { // arrange GetUserResponse getUserResponse = new GetUserResponse() { CreatedAt = "created at", Email = "email", FacebookExternalId = "facebooxk external id", FacebookRefId = "facebook ref id", UpdatedAt = "update at", UserId = "user id", UserName = "user name" }; IntPtr pGetUserResponse = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GetUserResponse))); Marshal.StructureToPtr<GetUserResponse>(getUserResponse, pGetUserResponse, false); GetUserResult result = new GetUserResult(); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => IdentityWrapperTarget.IdentityGetUserResponseCallback(dispatchReceiver, pGetUserResponse)); // assert Assert.AreEqual(getUserResponse.CreatedAt, result.Response.CreatedAt); Assert.AreEqual(getUserResponse.Email, result.Response.Email); Assert.AreEqual(getUserResponse.FacebookExternalId, result.Response.FacebookExternalId); Assert.AreEqual(getUserResponse.FacebookRefId, result.Response.FacebookRefId); Assert.AreEqual(getUserResponse.UpdatedAt, result.Response.UpdatedAt); Assert.AreEqual(getUserResponse.UserId, result.Response.UserId); Assert.AreEqual(getUserResponse.UserName, result.Response.UserName); // cleanup Marshal.FreeHGlobal(pGetUserResponse); } } public class IdentityWrapperTarget : IdentityWrapper { public new static void IdentityGetUserResponseCallback(IntPtr dispatchReceiver, IntPtr getUserResponse) => IdentityWrapper.IdentityGetUserResponseCallback(dispatchReceiver, getUserResponse); } }
61
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Features.GameKitUserGameplayData; using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class UserGameplayDataWrapperTests : GameKitTestBase { const string CONNECTION_CLIENT = "connection client"; [Test] public void NetworkStatusChangeCallback_StandardCase_CallsSuccessfully() { UserGameplayDataWrapperTarget.SetNetworkChangedDelegate((NetworkStatusChangeResults result) => { Assert.True(result.IsConnectionOk); Assert.AreEqual(result.ConnectionClient, CONNECTION_CLIENT); }); // act UserGameplayDataWrapperTarget.NetworkStatusChangeCallback(IntPtr.Zero, true, CONNECTION_CLIENT); // assertion handled in callback above } [Test] public void CacheProcessedCallback_StandardCase_CallsSuccessfully() { // arrange UserGameplayDataWrapperTarget.SetCacheProcessedDelegate((CacheProcessedResults result) => { Assert.True(result.IsCacheProcessed); }); // act UserGameplayDataWrapperTarget.CacheProcessedCallback(IntPtr.Zero, true); // assertion handled in callback above } } public class UserGameplayDataWrapperTarget : UserGameplayDataWrapper { public static void SetCacheProcessedDelegate(UserGameplayData.CacheProcessedDelegate cacheProcessedDelegate) => UserGameplayDataWrapper._cacheProcessedDelegate = cacheProcessedDelegate; public static void SetNetworkChangedDelegate(UserGameplayData.NetworkChangedDelegate networkChangedDelegate) => UserGameplayDataWrapper._networkCallbackDelegate = networkChangedDelegate; public new static void NetworkStatusChangeCallback(IntPtr dispatchReceiver, bool isConnectionOk, string connectionClient) => UserGameplayDataWrapper.NetworkStatusChangeCallback( dispatchReceiver, isConnectionOk, connectionClient); public new static void CacheProcessedCallback(IntPtr dispatchReceiver, bool isCacheProcessed) => UserGameplayDataWrapper.CacheProcessedCallback(dispatchReceiver, isCacheProcessed); } }
65
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class GameKitCallbackTests : GameKitTestBase { const string TEST_KEY = "test key"; const string TEST_VALUE = "test value"; const string TEST_RESULT = "test result"; [Test] public void KeyValueStringCallback_StandardCase_CallsSuccessfully() { // arrange KeyValueStringCallbackResult result = new KeyValueStringCallbackResult(); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.KeyValueStringCallback(dispatchReceiver, TEST_KEY, TEST_VALUE)); // assert Assert.AreEqual(TEST_KEY, result.ResponseKey); Assert.AreEqual(TEST_VALUE, result.ResponseValue); } [Test] public void MultiKeyValueStringCallback_StandardCase_CallsSuccessfully() { // arrange MultiKeyValueStringCallbackResult result = new MultiKeyValueStringCallbackResult(); Dictionary<string, string> testMap = new Dictionary<string, string> { { "test key 1", "test value 1" }, { "test key 2", "test value 2" }, { "test key 3", "test value 3" } }; // act foreach (KeyValuePair<string, string> entry in testMap) { Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.MultiKeyValueStringCallback(dispatchReceiver, entry.Key, entry.Value)); } // assert Assert.AreEqual(result.ResponseValues.Length, result.ResponseKeys.Length); Assert.AreEqual(result.ResponseValues.Length, testMap.Count); for (uint i = 0; i < testMap.Count; ++i) { Assert.AreEqual(testMap[result.ResponseKeys[i]], result.ResponseValues[i]); } } [Test] public void RecurringCallStringCallback_StandardCase_CallsSuccessfully() { // arrange StringCallbackResult actionOutput = new StringCallbackResult(); Action<StringCallbackResult> action = (stringCallbackResult) => { actionOutput = stringCallbackResult; }; // act Marshaller.Dispatch(action, (IntPtr dispatchReceiver) => GameKitCallbacks.RecurringCallStringCallback(dispatchReceiver, TEST_VALUE)); // assert Assert.AreEqual(TEST_VALUE, actionOutput.ResponseValue); } [Test] public void StringCallback_StandardCase_CallsSuccessfully() { // arrange StringCallbackResult result = new StringCallbackResult(); // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.StringCallback(dispatchReceiver, TEST_VALUE)); // assert Assert.AreEqual(TEST_VALUE, result.ResponseValue); } [Test] public void MultiStringCallback_StandardCase_CallsSuccessfully() { // arrange MultiStringCallbackResult result = new MultiStringCallbackResult(); string[] testArray = new string[] { "test value 1", "test value 2", "test value 3" }; // act foreach (string entry in testArray) { Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.MultiStringCallback(dispatchReceiver, entry)); } // assert Assert.AreEqual(testArray.Length, result.ResponseValues.Length); for (uint i = 0; i < testArray.Length; ++i) { Assert.AreEqual(testArray[i], result.ResponseValues[i]); } } [Test] public void ResourceInfoCallback_StandardCase_CallsSuccessfully() { // arrange ResourceInfoCallbackResult result = new ResourceInfoCallbackResult(); const string TEST_ID = "test id"; const string TEST_TYPE = "test type"; const string TEST_STATUS = "test status"; // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.ResourceInfoCallback(dispatchReceiver, TEST_ID, TEST_TYPE, TEST_STATUS)); // assert Assert.AreEqual(TEST_ID, result.LogicalResourceId); Assert.AreEqual(TEST_TYPE, result.ResourceType); Assert.AreEqual(TEST_STATUS, result.ResourceStatus); } [Test] public void DeploymentResponseCallback_StandardCase_CallsSuccessfully() { // arrange DeploymentResponseCallbackResult result = new DeploymentResponseCallbackResult(); FeatureType[] features = new FeatureType[] { FeatureType.Main, FeatureType.Identity }; FeatureStatus[] statuses = new FeatureStatus[] { FeatureStatus.Deployed, FeatureStatus.Undeployed }; uint resultCode = GameKitErrors.GAMEKIT_SUCCESS; // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.DeploymentResponseCallback(dispatchReceiver, features, statuses, (uint)features.Length, resultCode)); // assert Assert.AreEqual(features, result.Features); Assert.AreEqual(statuses, result.FeatureStatuses); Assert.AreEqual(resultCode, result.ResultCode); } [Test] public void CanExecuteDeploymentActionCallback_StandardCase_CallsSuccessfully() { // arrange CanExecuteDeploymentActionResult result = new CanExecuteDeploymentActionResult(); FeatureType targetFeature = FeatureType.GameStateCloudSaving; bool canExecuteAction = false; DeploymentActionBlockedReason reason = DeploymentActionBlockedReason.DependenciesMustBeCreated; FeatureType[] blockingFeatures = new FeatureType[] { FeatureType.Identity }; // act Marshaller.Dispatch(result, (IntPtr dispatchReceiver) => GameKitCallbacks.CanExecuteDeploymentActionCallback(dispatchReceiver, targetFeature, canExecuteAction, reason, blockingFeatures, (uint) blockingFeatures.Length)); // assert Assert.AreEqual(targetFeature, result.TargetFeature); Assert.AreEqual(canExecuteAction, result.CanExecuteAction); Assert.AreEqual(reason, result.Reason); Assert.AreEqual(blockingFeatures, result.BlockingFeatures); } } }
179
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class FeatureDeploymentStatusTests : GameKitTestBase { [Test] public void AllEnumValues_HaveFeatureDeploymentStatusData() { // This test ensures every FeatureDeploymentStatus enum is labeled with a FeatureDeploymentStatusData attribute. foreach (FeatureStatus deploymentStatus in Enum.GetValues(typeof(FeatureStatus))) { // act/assert Assert.DoesNotThrow(() => deploymentStatus.GetDisplayName(), $"Expected enum {deploymentStatus} to have a DisplayName, but found none. " + $"This means the enum is not labeled with a {nameof(FeatureStatusData)} attribute."); } } [Test] public void GetDisplayName_AllFeatures_HaveNonEmptyName() { foreach (FeatureStatus deploymentStatus in Enum.GetValues(typeof(FeatureStatus))) { // act string displayName = deploymentStatus.GetDisplayName(); // assert Assert.False(String.IsNullOrWhiteSpace(displayName)); } } } }
45
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard using System.Collections.Generic; // GameKit using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class GameKitTestBase { public List<string> Log; [SetUp] public void LoggingSetUp() { Log = new List<string>(); Logging.LogCb = (level, message, size) => { Log.Add(message); }; Logging.IsUnityLoggingEnabled = false; Logging.ClearLogQueue(); } [TearDown] public void LoggingTearDown() { Logging.ClearLogQueue(); Logging.IsUnityLoggingEnabled = true; Logging.LogCb = Logging.DefaultLogCb; } } }
37
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Third Party using NUnit.Framework; // Game Kit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.UnitTests { public class AwsGameKitPersistentSettingsTests { private const string UNIT_TEST_KEY = "UnitTestingEntry"; private const string UNIT_TEST_VALUE = "GameKit"; private const string UNIT_TEST_VALUE_DEFAULT = "Default"; [TearDown] public void TearDown() { AwsGameKitPersistentSettings.Delete(UNIT_TEST_KEY); } [Test] public void SaveString_WhenCalledWithAnExistingKey_SavesTheNewValue() { // arrange AwsGameKitPersistentSettings.SaveString(UNIT_TEST_KEY, UNIT_TEST_VALUE); const string NEW_TEST_VALUE = "Aws"; // act AwsGameKitPersistentSettings.SaveString(UNIT_TEST_KEY, NEW_TEST_VALUE); string valueReturned = AwsGameKitPersistentSettings.LoadString(UNIT_TEST_KEY, UNIT_TEST_VALUE_DEFAULT); // assert Assert.AreEqual(NEW_TEST_VALUE, valueReturned); } [Test] public void LoadString_WhenCalledWithAnExistingKey_ReturnsTheExpectedValue() { // arrange AwsGameKitPersistentSettings.SaveString(UNIT_TEST_KEY, UNIT_TEST_VALUE); // act string valueReturned = AwsGameKitPersistentSettings.LoadString(UNIT_TEST_KEY, UNIT_TEST_VALUE_DEFAULT); // assert Assert.AreEqual(UNIT_TEST_VALUE, valueReturned); } [Test] public void LoadString_WhenCalledWithANonExistingKey_ReturnsTheDefaultValue() { // act string valueReturned = AwsGameKitPersistentSettings.LoadString(UNIT_TEST_KEY, UNIT_TEST_VALUE_DEFAULT); // assert Assert.AreEqual(UNIT_TEST_VALUE_DEFAULT, valueReturned); } [Test] public void Delete_WhenCalledWithANonExistingKey_FailsQuietly() { // act AwsGameKitPersistentSettings.Delete("fake key"); } [Test] public void Delete_WhenCalledWithAnExistingKey_RemovesTheKeyValuePair() { // arrange AwsGameKitPersistentSettings.SaveString(UNIT_TEST_KEY, UNIT_TEST_VALUE); // act AwsGameKitPersistentSettings.Delete(UNIT_TEST_KEY); string valueReturned = AwsGameKitPersistentSettings.LoadString(UNIT_TEST_KEY, UNIT_TEST_VALUE_DEFAULT); // assert Assert.AreEqual(UNIT_TEST_VALUE_DEFAULT, valueReturned); } } }
84
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // GameKit using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class DllLoaderTests : GameKitTestBase { const int TEST_RETURN_VALUE = 42; const int TEST_ERROR_VALUE = -1; const string TEST_ERROR_STRING = "DLL not linked"; int _tryDllCallCount = 0; GameKitFeatureWrapperBaseTarget _target; [SetUp] public void SetUp() { _tryDllCallCount = 0; _target = new GameKitFeatureWrapperBaseTarget(); } [Test] public void TryDllWithNoReturn_StandardCase_CallsSuccessfully() { // act DllLoader.TryDll(TestDllMethod, nameof(TestDllMethod)); // assert Assert.AreEqual(1, _tryDllCallCount, $"Expected TestDllMethod called one time. Count = {_tryDllCallCount}"); } [Test] public void TryDllWithNoReturn_WhenDllMethodExceptionThrown_EatsTheException() { // act Assert.DoesNotThrow(() => DllLoader.TryDll(TestDllMethodException, nameof(TestDllMethodException)), "Expected TryDll eats the DllNotFoundException."); //assert LinkedList<string> exceptionLogs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(exceptionLogs.Count == 1); Assert.IsTrue(exceptionLogs.First.Value.Contains(TEST_ERROR_STRING)); } [Test] public void TryDllWithReturn_StandardCase_CallsSuccessfully() { // act int valueReturned = DllLoader.TryDll(TestDllMethodWithReturn, nameof(TestDllMethodWithReturn), TEST_ERROR_VALUE); // assert Assert.AreEqual(1, _tryDllCallCount, $"Expected TestDllMethodWithReturn called one time. Count = {_tryDllCallCount}"); Assert.AreEqual(TEST_RETURN_VALUE, valueReturned); } [Test] public void TryDllWithReturn_WhenDllMethodExceptionThrown_EatsTheException() { // act int valueReturned = DllLoader.TryDll(TestDllMethodWithReturnException, nameof(TestDllMethodWithReturnException), TEST_ERROR_VALUE); // assert Assert.AreEqual(TEST_ERROR_VALUE, valueReturned); LinkedList<string> exceptionLogs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(exceptionLogs.Count == 1); Assert.IsTrue(exceptionLogs.First.Value.Contains(TEST_ERROR_STRING)); } void TestDllMethod() { ++_tryDllCallCount; } int TestDllMethodWithReturn() { ++_tryDllCallCount; return TEST_RETURN_VALUE; } void TestDllMethodException() { throw new DllNotFoundException(); } int TestDllMethodWithReturnException() { throw new DllNotFoundException(); } } }
104
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Text.RegularExpressions; // Third Party using NUnit.Framework; // Unity using UnityEngine; // Game Kit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.UnitTests { public class LoggingTests { private const int MAX_LOG_QUEUE_SIZE_FOR_TEST = 100; private const string INFO_LOG = "This is a test of Unity INFO Logging"; private const string WARNING_LOG = "This is a test of Unity WARNING Logging"; private const string ERROR_LOG = "This is a test of Unity ERROR Logging"; private const string EXCEPTION_LOG = "This is a test of Unity EXCEPTION Logging"; private static int _currentQueueSize = Logging.MaxLogQueueSize; private static bool _currentUnityLoggingEnabled = Logging.IsUnityLoggingEnabled; private static Logging.Level _currentLoggingLevel = Logging.MinimumUnityLoggingLevel; [SetUp] public void SetUp() { Logging.IsUnityLoggingEnabled = true; Logging.MinimumUnityLoggingLevel = Logging.Level.INFO; Logging.MaxLogQueueSize = MAX_LOG_QUEUE_SIZE_FOR_TEST; Logging.ClearLogQueue(); } [TearDown] public void TearDown() { Logging.ClearLogQueue(); Logging.MaxLogQueueSize = _currentQueueSize; Logging.MinimumUnityLoggingLevel = _currentLoggingLevel; Logging.IsUnityLoggingEnabled = _currentUnityLoggingEnabled; } [Test] public void LoggingCallback_WhenMinimumUnityLoggingLevelIsSetToLowestLevel_AllLogsAreSeen() { // act Logging.LogInfo(INFO_LOG); Logging.LogWarning(WARNING_LOG); Logging.LogError(ERROR_LOG); // assert UnityEngine.TestTools.LogAssert.Expect(LogType.Log, $"AWS GameKit: {INFO_LOG}"); UnityEngine.TestTools.LogAssert.Expect(LogType.Warning, $"AWS GameKit: {WARNING_LOG}"); UnityEngine.TestTools.LogAssert.Expect(LogType.Error, $"AWS GameKit: {ERROR_LOG}"); } [Test] public void LoggingCallback_WhenMinimumUnityLoggingLevelIsSetToHighestLevel_OnlyErrorLogsAreSeen() { // act Logging.LogInfo(INFO_LOG); Logging.LogWarning(WARNING_LOG); Logging.LogError(ERROR_LOG); // assert UnityEngine.TestTools.LogAssert.Expect(LogType.Error, $"AWS GameKit: {ERROR_LOG}"); } [Test] public void LoggingCallback_WhenUnityLoggingIsNotEnabled_OnlyLogToLoggingQueue() { // arrange Logging.IsUnityLoggingEnabled = false; // act Logging.LogError(ERROR_LOG); // assert // No Unity logs should be expected, this test will fail if there are any Assert.AreEqual(1, Logging.LogQueue.Count); LinkedList<string> logs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(logs.First.Value.Contains(ERROR_LOG)); } [Test] public void LoggingCallback_WhenMaxLogQueueSizeIsReached_TheOldestLogIsRemoved() { // arrange const int EXPECT_LOGS = 2; Logging.MaxLogQueueSize = EXPECT_LOGS; // act Logging.LogInfo(INFO_LOG); Logging.LogWarning(WARNING_LOG); Logging.LogError(ERROR_LOG); // assert UnityEngine.TestTools.LogAssert.Expect(LogType.Log, $"AWS GameKit: {INFO_LOG}"); UnityEngine.TestTools.LogAssert.Expect(LogType.Warning, $"AWS GameKit: {WARNING_LOG}"); UnityEngine.TestTools.LogAssert.Expect(LogType.Error, $"AWS GameKit: {ERROR_LOG}"); Assert.AreEqual(EXPECT_LOGS, Logging.LogQueue.Count); LinkedList<string> logs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(logs.First.Value.Contains(WARNING_LOG)); Assert.IsTrue(logs.Last.Value.Contains(ERROR_LOG)); } [Test] public void LogException_WhenEverythingIsEnabled_BothALogQueueEntryAndUnityLogIsSeen() { // arrange Exception e = new Exception(EXCEPTION_LOG); // act Logging.LogException("Testing the log queue for an exception", e); // assert Regex regex = new Regex(EXCEPTION_LOG); UnityEngine.TestTools.LogAssert.Expect(LogType.Exception, regex); LinkedList<string> logs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(logs.First.Value.Contains(EXCEPTION_LOG)); } [Test] public void LogException_WhenUnityLoggingIsDisabled_OnlyALogQueueEntryIsSeen() { // arrange Logging.IsUnityLoggingEnabled = false; Exception e = new Exception(EXCEPTION_LOG); // act Logging.LogException("Testing the log queue for an exception", e); // assert LinkedList<string> logs = new LinkedList<string>(Logging.LogQueue); Assert.IsTrue(logs.First.Value.Contains(EXCEPTION_LOG)); } } }
154
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class MarshallerTests : GameKitTestBase { public struct TestStruct { public string Result; } const string TEST_MARSHAL_VALUE = "test marshal value"; [Test] public void IntPtrToArray_StandardCase_CallsSuccessfully() { // arrange byte[] testArray = new byte[] { 0, 1, 2, 3, 4, 5 }; IntPtr pointerToArray = Marshal.AllocHGlobal(testArray.Length); Marshal.Copy(testArray, 0, pointerToArray, testArray.Length); // act byte[] result = Marshaller.IntPtrToArray<byte>(pointerToArray, (uint)testArray.Length); // assert Assert.AreEqual(testArray, result); // cleanup Marshal.FreeHGlobal(pointerToArray); } [Test] public void ArrayToIntPtr_StandardCase_CallsSuccessfully() { // arrange TestStruct[] testStructs = new TestStruct[] { new TestStruct(), new TestStruct(), new TestStruct() }; testStructs[0].Result = "result 0"; testStructs[1].Result = "result 1"; testStructs[2].Result = "result 2"; // act IntPtr result = Marshaller.ArrayToIntPtr(testStructs); // assert Assert.AreNotEqual(IntPtr.Zero, result); // cleanup Marshal.FreeHGlobal(result); } [Test] public void ArrayToIntPtr_WhenArrayHasZeroElements_ZeroPointerIsReturned() { // arrange TestStruct[] testStructs = new TestStruct[0]; // act IntPtr result = Marshaller.ArrayToIntPtr(testStructs); // assert Assert.AreEqual(IntPtr.Zero, result); } [Test] public void ArrayOfStringsToArrayOfPointers_StandardCase_CallsSuccessfully() { // arrange string[] testArray = new string[] { "1", "22", "333", "4444" }; // act IntPtr[] result = Marshaller.ArrayOfStringsToArrayOfIntPtr(testArray); // assert Assert.AreEqual(testArray.Length, result.Length, "Expected that the size of the IntPtr array will be equal to the size of the string array."); for (uint i = 0; i < result.Length; ++i) { Assert.NotNull(result[i], "Expected that the IntPtr is allocated"); } // cleanup for (uint i = 0; i < result.Length; ++i) { Marshal.FreeHGlobal(result[i]); } } [Test] public void FreeArrayOfPointers_StandardCase_CallsSuccessfully() { // arrange string[] originalArray = new string[] { "1", "22", "333", "4444" }; IntPtr[] testArray = Marshaller.ArrayOfStringsToArrayOfIntPtr(originalArray); // act Marshaller.FreeArrayOfIntPtr(testArray); // assert for (uint i = 0; i < testArray.Length; ++i) { Assert.AreEqual(IntPtr.Zero, testArray[i]); } } } }
123
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.IO; // Third Party using NUnit.Framework; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.UnitTests { public class SerializableDictionaryTests { public static string TEST_ASSET_PATH = "Assets/AWS_GameKit_Tests/UnitTests/TemporaryFiles/serializableDictionaryTest.asset"; [TearDown] public void TearDown() { #if UNITY_EDITOR FileUtil.DeleteFileOrDirectory(TEST_ASSET_PATH); AssetDatabase.Refresh(); #endif } [Test] public void SerializableDictionary_WhenSettingNotExistentValue_CorrectlyAddsValueToDictionary() { // arrange const string testKey = "testKey"; SerializableDictionary<string, Vector2> testSerializableDictionary = new SerializableDictionary<string, Vector2>(); // act testSerializableDictionary.SetValue(testKey, Vector2.up); // assert Assert.AreEqual(1, testSerializableDictionary.Count); Assert.AreEqual(Vector2.up, testSerializableDictionary.GetValue(testKey)); } [Test] public void SerializableDictionary_GetNotExistentKey_CorrectlyAddsEmptyValue() { // arrange SerializableDictionary<int, float> testSerializableDictionary = new SerializableDictionary<int, float>(); // act testSerializableDictionary.GetValue(1); // assert Assert.AreEqual(0f, testSerializableDictionary.GetValue(1)); } [Test] public void SerializableDictionary_SaveSerializedJSONToDiskThenReload_CorrectlyDeserializesDictionary() { #if UNITY_EDITOR // arrange SerializableDictionary<string, Vector2> testSerializableDictionary = new SerializableDictionary<string, Vector2>(); // act testSerializableDictionary.SetValue("Hello", Vector2.up); testSerializableDictionary.SetValue("World", Vector2.down); string jsonString = JsonUtility.ToJson(testSerializableDictionary); File.WriteAllText(TEST_ASSET_PATH, jsonString); string fileContents = File.ReadAllText(TEST_ASSET_PATH); SerializableDictionary<string, Vector2> serializableDictionaryFromFile = JsonUtility.FromJson<SerializableDictionary<string, Vector2>>(fileContents); // assert Assert.AreEqual(2, serializableDictionaryFromFile.Count); Assert.True(serializableDictionaryFromFile.ContainsKey("Hello")); Assert.AreEqual(Vector2.up, serializableDictionaryFromFile["Hello"]); Assert.True(serializableDictionaryFromFile.ContainsKey("World")); Assert.AreEqual(Vector2.down, serializableDictionaryFromFile["World"]); #endif } } }
87
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Globalization; using System.Linq; // Third Party using NUnit.Framework; // Unity using UnityEngine; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Runtime.UnitTests { public class SerializableOrderedDictionaryTests { [Test] public void SerializableOrderedDictionary_WhenSerializedToJsonAndBack_DeserializedDictionaryRemembersOriginalOrderOfElements( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); List<KeyValuePair<string, int>> originalElements = dict.KeyValuePairs.ToList(); // act string serializedDict = JsonUtility.ToJson(dict); SerializableOrderedDictionary<string, int> deserializedDict = JsonUtility.FromJson<SerializableOrderedDictionary<string, int>>(serializedDict); // assert Assert.AreEqual(numStartingElements, deserializedDict.Count); for (int i = 0; i < numStartingElements; ++i) { originalElements[i] = deserializedDict.KeyValuePairs.ToList()[i]; } } [Test] public void ContainsKey_WhenKeyExists_ReturnsTrue( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); foreach (string key in dict.Keys) { // act bool doesContainKey = dict.ContainsKey(key); // assert Assert.True(doesContainKey); } Assert.AreEqual(numStartingElements, dict.Count); } [Test] public void ContainsKey_WhenKeyNotExists_ReturnsFalse( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act bool doesContainKey = dict.ContainsKey("does not exist"); // assert Assert.False(doesContainKey); } [Test] public void ContainsKey_WhenKeyIsNull_RaisesArgumentNullException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<ArgumentNullException>(() => { dict.ContainsKey(null); }); } [Test] public void Add_WhenKeyNotAlreadyExists_NewElementIsAddedToEnd( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string newKey = "newKey"; int newValue = 10; // act dict.Add(newKey, newValue); // assert KeyValuePair<string, int> lastEntry = dict.KeyValuePairs.Last(); Assert.AreEqual(newKey, lastEntry.Key); Assert.AreEqual(newValue, lastEntry.Value); Assert.AreEqual(numStartingElements + 1, dict.Count); } [Test] public void Add_WhenMultipleElementsAdded_NewElementsAreRememberedInSequentialOrder( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string newKey1 = "newKey1"; string newKey2 = "newKey2"; string newKey3 = "newKey3"; int newValue1 = 10; int newValue2 = 20; int newValue3 = 30; int newElement1Index = dict.Count + 0; int newElement2Index = dict.Count + 1; int newElement3Index = dict.Count + 2; // act dict.Add(newKey1, newValue1); dict.Add(newKey2, newValue2); dict.Add(newKey3, newValue3); // assert List<KeyValuePair<string, int>> elements = dict.KeyValuePairs.ToList(); Assert.AreEqual(newKey1, elements[newElement1Index].Key); Assert.AreEqual(newKey2, elements[newElement2Index].Key); Assert.AreEqual(newKey3, elements[newElement3Index].Key); Assert.AreEqual(newValue1, elements[newElement1Index].Value); Assert.AreEqual(newValue2, elements[newElement2Index].Value); Assert.AreEqual(newValue3, elements[newElement3Index].Value); Assert.AreEqual(numStartingElements + 3, dict.Count); } [Test] public void Add_WhenKeyAlreadyExists_RaisesArgumentException( [Values(1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); KeyValuePair<string, int> firstEntry = dict.KeyValuePairs.First(); // act / assert Assert.Throws<ArgumentException>(() => { dict.Add(firstEntry.Key, 0); }); } [Test] public void Add_WhenKeyIsNull_RaisesArgumentNullException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<ArgumentNullException>(() => { dict.Add(null, 0); }); } [Test] public void SetValue_WhenKeyNotAlreadyExists_NewElementIsAddedToEnd( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string newKey = "newKey"; int newValue = 10; // act dict.SetValue(newKey, newValue); // assert KeyValuePair<string, int> lastEntry = dict.KeyValuePairs.Last(); Assert.AreEqual(newKey, lastEntry.Key); Assert.AreEqual(newValue, lastEntry.Value); Assert.AreEqual(numStartingElements + 1, dict.Count); } [Test] public void SetValue_WhenKeyAlreadyExists_ExistingElementIsUpdated( [Values(1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); KeyValuePair<string, int> firstEntry = dict.KeyValuePairs.First(); int newValue = firstEntry.Value + 10; // act dict.SetValue(firstEntry.Key, newValue); // assert Assert.AreEqual(newValue, dict.GetValue(firstEntry.Key)); Assert.AreEqual(numStartingElements, dict.Count); } [Test] public void SetValue_WhenMultipleElementsAdded_NewElementsAreRememberedInSequentialOrder( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string newKey1 = "newKey1"; string newKey2 = "newKey2"; string newKey3 = "newKey3"; int newValue1 = 10; int newValue2 = 20; int newValue3 = 30; int newElement1Index = dict.Count + 0; int newElement2Index = dict.Count + 1; int newElement3Index = dict.Count + 2; // act dict.SetValue(newKey1, newValue1); dict.SetValue(newKey2, newValue2); dict.SetValue(newKey3, newValue3); // assert List<KeyValuePair<string, int>> elements = dict.KeyValuePairs.ToList(); Assert.AreEqual(newKey1, elements[newElement1Index].Key); Assert.AreEqual(newKey2, elements[newElement2Index].Key); Assert.AreEqual(newKey3, elements[newElement3Index].Key); Assert.AreEqual(newValue1, elements[newElement1Index].Value); Assert.AreEqual(newValue2, elements[newElement2Index].Value); Assert.AreEqual(newValue3, elements[newElement3Index].Value); Assert.AreEqual(numStartingElements + 3, dict.Count); } [Test] public void SetValue_WhenKeyIsNull_RaisesArgumentNullException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<ArgumentNullException>(() => { dict.SetValue(null, 0); }); } [Test] public void GetValue_WhenKeyExists_ReturnsCorrectValue( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string newKey = "newKey"; int newValue = 10; dict.Add(newKey, newValue); // act int fetchedValue = dict.GetValue(newKey); // assert Assert.AreEqual(newValue, fetchedValue); } [Test] public void GetValue_WhenKeyIsNull_RaisesArgumentNullException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<ArgumentNullException>(() => { dict.GetValue(null); }); } [Test] public void GetValue_WhenKeyNotAlreadyExists_RaisesKeyNotFoundException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<KeyNotFoundException>(() => { dict.GetValue("does not exist"); }); } [Test] public void Remove_WhenKeyExists_CorrespondingElementIsRemoved( [Values(1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); KeyValuePair<string, int> lastEntry = dict.KeyValuePairs.Last(); // assume Assume.That(dict.ContainsKey(lastEntry.Key)); Assume.That(dict.Keys.Contains(lastEntry.Key)); Assume.That(dict.Values.Contains(lastEntry.Value)); Assume.That(dict.KeyValuePairs.Contains(lastEntry)); Assume.That(numStartingElements == dict.Count); // act dict.Remove(lastEntry.Key); // assert Assert.False(dict.ContainsKey(lastEntry.Key)); Assert.False(dict.Keys.Contains(lastEntry.Key)); Assert.False(dict.Values.Contains(lastEntry.Value)); Assert.False(dict.KeyValuePairs.Contains(lastEntry)); Assert.AreEqual(numStartingElements - 1, dict.Count); } [Test] public void Remove_WhenKeyNotExists_NoElementIsRemoved( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); string nonExistentKey = "does not exist"; // assume Assume.That(!dict.ContainsKey(nonExistentKey)); Assume.That(!dict.Keys.Contains(nonExistentKey)); Assume.That(numStartingElements == dict.Count); // act dict.Remove(nonExistentKey); // assert Assert.False(dict.ContainsKey(nonExistentKey)); Assert.False(dict.Keys.Contains(nonExistentKey)); Assert.AreEqual(numStartingElements, dict.Count); } [Test] public void Remove_WhenElementIsRemovedFromMiddle_OrderOfElementsBeforeAndAfterIsPreserved() { // arrange int numStartingElements = 5; SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); KeyValuePair<string, int> middleElement = dict.KeyValuePairs.ElementAt(2); List<KeyValuePair<string, int>> expectedElementsAfterRemove = new List<KeyValuePair<string, int>>() { dict.KeyValuePairs.ElementAt(0), dict.KeyValuePairs.ElementAt(1), // dict.KeyValuePairs.ElementAt(2), // <-- this element will get removed dict.KeyValuePairs.ElementAt(3), dict.KeyValuePairs.ElementAt(4), }; // act dict.Remove(middleElement.Key); // assert Assert.False(dict.ContainsKey(middleElement.Key)); Assert.AreEqual(numStartingElements - 1, dict.Count); for (int i = 0; i < numStartingElements - 1; ++i) { Assert.AreEqual(expectedElementsAfterRemove[i], dict.KeyValuePairs.ToList()[i]); } } [Test] public void Remove_WhenKeyIsNull_RaisesArgumentNullException( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); // act / assert Assert.Throws<ArgumentNullException>(() => { dict.Remove(null); }); } [Test] public void Clear_WhenFinished_DictionaryIsEmpty( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); List<KeyValuePair<string, int>> elementsBeforeClearing = dict.KeyValuePairs.ToList(); // assume Assume.That(dict.Count == numStartingElements); Assume.That(dict.Keys.Count() == numStartingElements); Assume.That(dict.Values.Count() == numStartingElements); Assume.That(dict.KeyValuePairs.Count() == numStartingElements); foreach (KeyValuePair<string, int> originalElement in elementsBeforeClearing) { Assert.True(dict.ContainsKey(originalElement.Key)); } // act dict.Clear(); // assert Assert.AreEqual(0, dict.Count); Assert.AreEqual(0, dict.Keys.Count()); Assert.AreEqual(0, dict.Values.Count()); Assert.AreEqual(0, dict.KeyValuePairs.Count()); foreach (KeyValuePair<string, int> originalElement in elementsBeforeClearing) { Assert.False(dict.ContainsKey(originalElement.Key)); } } [Test] public void Sort_WhenFinished_NewOrderIsRemembered( [Values(0, 1, 5)] int numStartingElements) { // arrange SerializableOrderedDictionary<string, int> dict = CreateDictionaryWith(numStartingElements); IEnumerable<string> originalOrderKeys = dict.Keys.ToList(); IEnumerable<int> originalOrderValues = dict.Values.ToList(); IEnumerable<KeyValuePair<string, int>> originalOrderKeyValuePairs = dict.KeyValuePairs.ToList(); // act dict.Sort( elements => elements.Reverse()); // assert Assert.AreEqual(originalOrderKeys.Reverse(), dict.Keys); Assert.AreEqual(originalOrderValues.Reverse(), dict.Values); Assert.AreEqual(originalOrderKeyValuePairs.Reverse(), dict.KeyValuePairs); } private SerializableOrderedDictionary<string, int> CreateDictionaryWith(int numElements) { SerializableOrderedDictionary<string, int> dict = new SerializableOrderedDictionary<string, int>(); for (int i = 0; i < numElements; ++i) { string key = i.ToString(CultureInfo.CurrentCulture); int value = i; dict.Add(key, value); } return dict; } } }
452
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit using AWS.GameKit.Common; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class SingletonTests : GameKitTestBase { [Test] public void Get_StandardCase_ReturnsPointerToInstance() { // act string valueReturned = Singleton<FakeClass>.Get().GetTestValue(); // assert Assert.AreEqual(FakeClass.TEST_VALUE, valueReturned); } [Test] public void Get_WhenCalledTwice_AlwaysReturnsSameInstance() { // assert Assert.IsTrue(ReferenceEquals(Singleton<FakeClass>.Get(), Singleton<FakeClass>.Get()), "The instance that is assigned should be the same between calls"); } } public class FakeClass { public const string TEST_VALUE = "test value"; public string GetTestValue() { return TEST_VALUE; } } }
42
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Utils; // Third Party using NUnit.Framework; namespace AWS.GameKit.Runtime.UnitTests { public class ThreaderTests : GameKitTestBase { const string TEST_DESCRIPTION = "test description"; static int _callCount; Threader _target; Func<string, string> _simpleFunction = (description) => string.Empty; Func<string> _simpleNoDescriptionFunction = () => string.Empty; Action<string> _simpleNoResultFunction = (description) => { }; Action _simpleNoDescriptionOrResultFunction = () => { }; Action<string> _callback = (result) => { ++_callCount; }; Action _callbackNoResult = () => { ++_callCount; }; Action<string> _callback_exception = (result) => { throw new Exception(); }; Func<string, Action<string>, string> _recurringFunction = (description, callback) => { callback(description); return string.Empty; }; [SetUp] public void SetUp() { _target = new Threader(); _callCount = 0; } [Test] public void WaitForThreadedWork_CallsSuccessfully() { // arrange _target.Call((string param) => { System.Threading.Thread.Sleep(250); }, TEST_DESCRIPTION, _callbackNoResult); Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); // act _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(1, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void CallSimple_StandardCase_CallsSuccessfully() { // act _target.Call(_simpleFunction, TEST_DESCRIPTION, _callback); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(1, _target.WaitingQueueCount, $"Expected one callback in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void CallRecurring_StandardCase_CallsSuccessfully() { // act _target.Call(_recurringFunction, TEST_DESCRIPTION, _callback, _callback); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(2, _target.WaitingQueueCount, $"Expected two callbacks in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void CallSimpleWithNoDescription_StandardCase_CallsSuccessfully() { // act _target.Call(_simpleNoDescriptionFunction, _callback); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(1, _target.WaitingQueueCount, "Expected one callback in waiting queue, count = {0}", _target.WaitingQueueCount); } [Test] public void CallSimpleJobNoResult_StandardCase_CallsSuccessfully() { // act _target.Call(_simpleNoResultFunction, TEST_DESCRIPTION, _callbackNoResult); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(1, _target.WaitingQueueCount, "Expected one callback in waiting queue, count = {0}", _target.WaitingQueueCount); } [Test] public void CallSimpleJobNoDescriptionOrResult_StandardCase_CallsSuccessfully() { // act _target.Call(_simpleNoDescriptionOrResultFunction, _callbackNoResult); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(1, _target.WaitingQueueCount, "Expected one callback in waiting queue, count = {0}", _target.WaitingQueueCount); } [Test] public void Awake_StandardCase_CallsSuccessfully() { // arrange _target.Call(_simpleFunction, TEST_DESCRIPTION, _callback); _target.WaitForThreadedWork_TestOnly(); Assert.AreEqual(1, _target.WaitingQueueCount, $"Expected one callback in waiting queue during test set up, count = {_target.WaitingQueueCount}"); // act _target.Awake(); // assert Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void Awake_StandardCase_NoAsyncWorkRaceConditions() { // arrange _target.Call((string param) => { System.Threading.Thread.Sleep(250); }, TEST_DESCRIPTION, _callbackNoResult); Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); // act _target.Awake(); _target.WaitForThreadedWork_TestOnly(); // assert Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void Update_StandardCase_CallsSuccessfully() { // arrange _target.Call(_simpleFunction, TEST_DESCRIPTION, _callback); _target.WaitForThreadedWork_TestOnly(); Assert.AreEqual(1, _target.WaitingQueueCount, $"Expected one callback in waiting queue during test set up, count = {_target.WaitingQueueCount}"); // act _target.Update(); // assert Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); Assert.AreEqual(1, _callCount, "Expected callback called 1 time, count = {0}", _callCount); } [Test] public void Update_WhenAndExceptionIsThrown_TheQueueIsStillCleared() { // arrange _target.Call(_simpleFunction, TEST_DESCRIPTION, _callback_exception); _target.WaitForThreadedWork_TestOnly(); Assert.AreEqual(1, _target.WaitingQueueCount, $"Expected one callback in waiting queue during test set up, count = {_target.WaitingQueueCount}"); // act Assert.Throws<Exception>(() => _target.Update()); // assert Assert.AreEqual(0, _target.WaitingQueueCount, $"Expected zero callbacks in waiting queue, count = {_target.WaitingQueueCount}"); } [Test] public void Update_WithASimpleJobNoResult_CallsSuccessfully() { // arrange _target.Call(_simpleNoResultFunction, TEST_DESCRIPTION, _callbackNoResult); _target.WaitForThreadedWork_TestOnly(); Assert.AreEqual(1, _target.WaitingQueueCount, "Expected one callback in waiting queue during test set up, count = {0}", _target.WaitingQueueCount); // act _target.Update(); // assert Assert.AreEqual(0, _target.WaitingQueueCount, "Expected zero callbacks in waiting queue, count = {0}", _target.WaitingQueueCount); Assert.AreEqual(1, _callCount, "Expected callback called 1 time, count = {0}", _callCount); } } }
188
aws-gamekit-unity
aws
C#
// // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // System using System; using System.Linq; using System.Threading; //Unity using UnityEditor; using UnityEditor.PackageManager; using UnityEditor.PackageManager.Requests; using UnityEngine; namespace Internal.Editor { // https://docs.unity3d.com/ScriptReference/BuildPipeline.BuildPlayer.html public sealed class PackageBuilder : MonoBehaviour { private static PackRequest CURRENT_PACK_REQUEST; public static void BuildPackage() { var path = EditorUtility.SaveFolderPanel("Package Destination", "", ""); if (path != null) { ExportPackage(path); } } public static bool IsNoPackageBuildInProgress() { return CURRENT_PACK_REQUEST == null; } /// <summary> /// Exports Unity package, using the last command line arg as the destination path. /// </summary> public static void ExportPackage() { var path = Environment.GetCommandLineArgs().Last(); ExportPackage(path); } private static void ExportPackage(string path) { Debug.LogFormat($"Exporting package to {path}"); CURRENT_PACK_REQUEST = Client.Pack("Packages/com.amazonaws.gamekit", path); while (CURRENT_PACK_REQUEST.Status == StatusCode.InProgress) { Thread.Sleep(TimeSpan.FromSeconds(1)); } switch (CURRENT_PACK_REQUEST.Status) { case StatusCode.Success: Debug.Log($"Finished exporting package to {CURRENT_PACK_REQUEST.Result.tarballPath}"); CURRENT_PACK_REQUEST = null; return; case StatusCode.Failure: CURRENT_PACK_REQUEST = null; throw new Exception("Failed to create package"); default: throw new ArgumentOutOfRangeException(); } } } }
68
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Common { /// <summary> /// This class lists all the paths used by GameKit /// </summary> public class GameKitPaths : Singleton<GameKitPaths>, IGameKitPathsProvider { #region Files public virtual string README_FILE_NAME => "README.md"; public virtual string SETTINGS_WINDOW_STATE_FILE_NAME => "SettingsWindowState.asset"; public virtual string GIT_IGNORE_FILE_NAME => ".gitignore"; public virtual string SAVE_INFO_FILE_NAME => "saveInfo.yml"; #endregion #region Folders public virtual string ASSETS_DATA_FOLDER_NAME => "Assets"; public virtual string PACKAGES_FOLDER_NAME => "Packages"; public virtual string GAME_KIT_FOLDER_NAME => "com.amazonaws.gamekit"; public virtual string EDITOR_FOLDER_NAME => "Editor"; public virtual string SECURITY_FOLDER_NAME => "Security"; public virtual string CERTIFICATES_FOLDER_NAME => "Certs"; public virtual string RESOURCE_FOLDER_NAME => "Resources"; public virtual string CLOUD_RESOURCES_FOLDER_NAME => "CloudResources"; public virtual string BASE_TEMPLATES_FOLDER_NAME => ".BaseTemplates"; public virtual string INSTANCE_FILES_FOLDER_NAME => "InstanceFiles"; public virtual string WINDOWS_STATE_FOLDER_NAME => "WindowState"; public virtual string GAMEKIT_ART_FOLDER => "Art"; public virtual string GAMEKIT_ICONS_FOLDER => "icons"; public virtual string PLUGINS_FOLDER_NAME => "Plugins"; public virtual string ANDROID_FOLDER_NAME => "Android"; public virtual string GAMEKIT_CONFIG_ANDROID_LIB_FOLDER_NAME => "GameKitConfig.androidlib"; public virtual string GAMEKIT_CONFIG_ASSETS_FOLDER_NAME => "assets"; public virtual string RAW_FOLDER_NAME => "raw"; public virtual string CERT_FILE_NAME => "cacert.pem"; public virtual string ANDROID_MANIFEST_FILE_NAME => "AndroidManifest.xml"; #endregion #region ASSETS Paths public virtual string ASSETS_RELATIVE_PATH => Path(ASSETS_DATA_FOLDER_NAME, GAME_KIT_FOLDER_NAME); public virtual string ASSETS_FULL_PATH => CleanPath(System.IO.Path.GetFullPath(ASSETS_RELATIVE_PATH)); public virtual string ASSETS_EDITOR_RELATIVE_PATH => Path(ASSETS_RELATIVE_PATH, EDITOR_FOLDER_NAME); public virtual string ASSETS_EDITOR_FULL_PATH => Path(ASSETS_FULL_PATH, EDITOR_FOLDER_NAME); public virtual string ASSETS_EDITOR_RESOURCES_RELATIVE_PATH => Path(ASSETS_EDITOR_RELATIVE_PATH, RESOURCE_FOLDER_NAME); public virtual string ASSETS_EDITOR_RESOURCES_FULL_PATH => Path(ASSETS_EDITOR_FULL_PATH, RESOURCE_FOLDER_NAME); public virtual string ASSETS_RESOURCES_RELATIVE_PATH => Path(ASSETS_RELATIVE_PATH, RESOURCE_FOLDER_NAME); public virtual string ASSETS_RESOURCES_FULL_PATH => Path(ASSETS_FULL_PATH, RESOURCE_FOLDER_NAME); public virtual string ASSETS_README_RELATIVE_PATH => Path(ASSETS_RESOURCES_RELATIVE_PATH, README_FILE_NAME); public virtual string ASSETS_EDITOR_RESOURCES_README_RELATIVE_PATH => Path(ASSETS_EDITOR_RESOURCES_RELATIVE_PATH, README_FILE_NAME); public virtual string ASSETS_CLOUD_RESOURCES_RELATIVE_PATH => Path(ASSETS_EDITOR_RELATIVE_PATH, CLOUD_RESOURCES_FOLDER_NAME); public virtual string ASSETS_CLOUD_RESOURCES_FULL_PATH => Path(ASSETS_EDITOR_FULL_PATH, CLOUD_RESOURCES_FOLDER_NAME); public virtual string ASSETS_CLOUD_RESOURCES_README_RELATIVE_PATH => Path(ASSETS_CLOUD_RESOURCES_RELATIVE_PATH, README_FILE_NAME); public virtual string ASSETS_INSTANCE_FILES_RELATIVE_PATH => Path(ASSETS_CLOUD_RESOURCES_RELATIVE_PATH, INSTANCE_FILES_FOLDER_NAME); public virtual string ASSETS_INSTANCE_FILES_FULL_PATH => Path(ASSETS_CLOUD_RESOURCES_FULL_PATH, INSTANCE_FILES_FOLDER_NAME); public virtual string ASSETS_INSTANCE_FILES_README_RELATIVE_PATH => Path(ASSETS_INSTANCE_FILES_RELATIVE_PATH, README_FILE_NAME); public virtual string ASSETS_WINDOW_STATE_RELATIVE_PATH => Path(ASSETS_EDITOR_RELATIVE_PATH, WINDOWS_STATE_FOLDER_NAME); public virtual string ASSETS_WINDOW_STATE_README_RELATIVE_PATH => Path(ASSETS_WINDOW_STATE_RELATIVE_PATH, README_FILE_NAME); public virtual string ASSETS_SETTINGS_WINDOW_STATE_RELATIVE_PATH => Path(ASSETS_WINDOW_STATE_RELATIVE_PATH, SETTINGS_WINDOW_STATE_FILE_NAME); public virtual string ASSETS_GIT_IGNORE_RELATIVE_PATH => Path(ASSETS_RELATIVE_PATH, GIT_IGNORE_FILE_NAME); public virtual string ASSETS_GAMEKIT_ART_PATH => Path(ASSETS_EDITOR_RELATIVE_PATH, GAMEKIT_ART_FOLDER); public virtual string ASSETS_GAMEKIT_ICONS_PATH => Path(ASSETS_GAMEKIT_ART_PATH, GAMEKIT_ICONS_FOLDER); public virtual string ASSETS_GAMEKIT_ANDROID_PATH => Path(new string[] { ASSETS_RELATIVE_PATH, PLUGINS_FOLDER_NAME, ANDROID_FOLDER_NAME}); public virtual string ASSETS_GAMEKIT_RAW_RELATIVE_PATH => Path(new string[] { ASSETS_GAMEKIT_ANDROID_PATH, GAMEKIT_CONFIG_ANDROID_LIB_FOLDER_NAME, GAMEKIT_CONFIG_ASSETS_FOLDER_NAME, RAW_FOLDER_NAME }); public virtual string ASSETS_GAMEKIT_RAW_CERT_RELATIVE_PATH => Path(new string[] { ASSETS_GAMEKIT_ANDROID_PATH, GAMEKIT_CONFIG_ANDROID_LIB_FOLDER_NAME, GAMEKIT_CONFIG_ASSETS_FOLDER_NAME, RAW_FOLDER_NAME, CERT_FILE_NAME }); public virtual string ASSETS_GAMEKIT_ANDROID_MANIFEST_RELATIVE_PATH => Path(new string[] { ASSETS_GAMEKIT_ANDROID_PATH, GAMEKIT_CONFIG_ANDROID_LIB_FOLDER_NAME, ANDROID_MANIFEST_FILE_NAME }); #endregion #region PACKAGES Paths public virtual string PACKAGES_RELATIVE_PATH => Path(PACKAGES_FOLDER_NAME, GAME_KIT_FOLDER_NAME); public virtual string PACKAGES_FULL_PATH => CleanPath(System.IO.Path.GetFullPath(PACKAGES_RELATIVE_PATH)); public virtual string PACKAGES_EDITOR_RELATIVE_PATH => Path(PACKAGES_RELATIVE_PATH, EDITOR_FOLDER_NAME); public virtual string PACKAGES_EDITOR_FULL_PATH => Path(PACKAGES_FULL_PATH, EDITOR_FOLDER_NAME); public virtual string PACKAGES_CERTIFICATES_FULL_PATH => Path(PACKAGES_FULL_PATH, SECURITY_FOLDER_NAME, CERTIFICATES_FOLDER_NAME); public virtual string PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH => Path(PACKAGES_EDITOR_RELATIVE_PATH, RESOURCE_FOLDER_NAME); public virtual string PACKAGES_EDITOR_RESOURCES_FULL_PATH => Path(PACKAGES_EDITOR_FULL_PATH, RESOURCE_FOLDER_NAME); public virtual string PACKAGES_EDITOR_RESOURCES_README_RELATIVE_PATH => Path(PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, README_FILE_NAME); public virtual string PACKAGES_RESOURCES_README_RELATIVE_PATH => Path(PACKAGES_RELATIVE_PATH, RESOURCE_FOLDER_NAME, README_FILE_NAME); public virtual string PACKAGES_CLOUD_RESOURCES_RELATIVE_PATH => Path(PACKAGES_EDITOR_RELATIVE_PATH, CLOUD_RESOURCES_FOLDER_NAME); public virtual string PACKAGES_CLOUD_RESOURCES_FULL_PATH => Path(PACKAGES_EDITOR_FULL_PATH, CLOUD_RESOURCES_FOLDER_NAME); public virtual string PACKAGES_CLOUD_RESOURCES_README_RELATIVE_PATH => Path(PACKAGES_CLOUD_RESOURCES_RELATIVE_PATH, README_FILE_NAME); public virtual string PACKAGES_BASE_TEMPLATES_RELATIVE_PATH => Path(PACKAGES_CLOUD_RESOURCES_RELATIVE_PATH, BASE_TEMPLATES_FOLDER_NAME); public virtual string PACKAGES_BASE_TEMPLATES_FULL_PATH => Path(PACKAGES_CLOUD_RESOURCES_FULL_PATH, BASE_TEMPLATES_FOLDER_NAME); public virtual string PACKAGES_WINDOW_STATE_README_RELATIVE_PATH => Path(PACKAGES_EDITOR_RELATIVE_PATH, WINDOWS_STATE_FOLDER_NAME, README_FILE_NAME); public virtual string PACKAGES_INSTANCE_FILES_README_RELATIVE_PATH => Path(PACKAGES_CLOUD_RESOURCES_RELATIVE_PATH, INSTANCE_FILES_FOLDER_NAME, README_FILE_NAME); public virtual string PACKAGES_CACERT_RELATIVE_PATH => Path(new string[] { PACKAGES_RELATIVE_PATH, SECURITY_FOLDER_NAME, CERTIFICATES_FOLDER_NAME, CERT_FILE_NAME}); public virtual string PACKAGES_GIT_IGNORE_RELATIVE_PATH => Path(PACKAGES_RELATIVE_PATH, GIT_IGNORE_FILE_NAME); public virtual string PACKAGES_ANDROID_MANIFEST_RELATIVE_PATH => Path(new string[] { PACKAGES_RELATIVE_PATH, PLUGINS_FOLDER_NAME, ANDROID_FOLDER_NAME, GAMEKIT_CONFIG_ANDROID_LIB_FOLDER_NAME, ANDROID_MANIFEST_FILE_NAME }); #endregion private static string Path(string path1, string path2) { return CleanPath(System.IO.Path.Combine(path1, path2)); } private static string Path(string path1, string path2, string path3) { return CleanPath(System.IO.Path.Combine(path1, path2, path3)); } private static string Path(string[] path) { return CleanPath(System.IO.Path.Combine(path)); } private static string CleanPath(string path) { return path.Replace("\\", "/"); } } }
113
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Common { /// <summary> /// Interface for providing GameKit paths /// </summary> public interface IGameKitPathsProvider { #region Files public string README_FILE_NAME { get; } public string SETTINGS_WINDOW_STATE_FILE_NAME { get; } public string GIT_IGNORE_FILE_NAME { get; } public string SAVE_INFO_FILE_NAME { get; } #endregion #region Folders public string ASSETS_DATA_FOLDER_NAME { get; } public string PACKAGES_FOLDER_NAME { get; } public string GAME_KIT_FOLDER_NAME { get; } public string EDITOR_FOLDER_NAME { get; } public string RESOURCE_FOLDER_NAME { get; } public string CLOUD_RESOURCES_FOLDER_NAME { get; } public string BASE_TEMPLATES_FOLDER_NAME { get; } public string INSTANCE_FILES_FOLDER_NAME { get; } public string WINDOWS_STATE_FOLDER_NAME { get; } #endregion #region ASSETS Paths public string ASSETS_RELATIVE_PATH { get; } public string ASSETS_FULL_PATH { get; } public string ASSETS_EDITOR_RELATIVE_PATH { get; } public string ASSETS_EDITOR_FULL_PATH { get; } public string ASSETS_EDITOR_RESOURCES_RELATIVE_PATH { get; } public string ASSETS_EDITOR_RESOURCES_FULL_PATH { get; } public string ASSETS_RESOURCES_RELATIVE_PATH { get; } public string ASSETS_RESOURCES_FULL_PATH { get; } public string ASSETS_README_RELATIVE_PATH { get; } public string ASSETS_EDITOR_RESOURCES_README_RELATIVE_PATH { get; } public string ASSETS_CLOUD_RESOURCES_RELATIVE_PATH { get; } public string ASSETS_CLOUD_RESOURCES_FULL_PATH { get; } public string ASSETS_CLOUD_RESOURCES_README_RELATIVE_PATH { get; } public string ASSETS_INSTANCE_FILES_RELATIVE_PATH { get; } public string ASSETS_INSTANCE_FILES_FULL_PATH { get; } public string ASSETS_INSTANCE_FILES_README_RELATIVE_PATH { get; } public string ASSETS_WINDOW_STATE_RELATIVE_PATH { get; } public string ASSETS_WINDOW_STATE_README_RELATIVE_PATH { get; } public string ASSETS_SETTINGS_WINDOW_STATE_RELATIVE_PATH { get; } public string ASSETS_GIT_IGNORE_RELATIVE_PATH { get; } #endregion #region PACKAGES Paths public string PACKAGES_RELATIVE_PATH { get; } public string PACKAGES_FULL_PATH { get; } public string PACKAGES_EDITOR_RELATIVE_PATH { get; } public string PACKAGES_EDITOR_FULL_PATH { get; } public string PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH { get; } public string PACKAGES_EDITOR_RESOURCES_FULL_PATH { get; } public string PACKAGES_EDITOR_RESOURCES_README_RELATIVE_PATH { get; } public string PACKAGES_RESOURCES_README_RELATIVE_PATH { get; } public string PACKAGES_CLOUD_RESOURCES_RELATIVE_PATH { get; } public string PACKAGES_CLOUD_RESOURCES_FULL_PATH { get; } public string PACKAGES_CLOUD_RESOURCES_README_RELATIVE_PATH { get; } public string PACKAGES_BASE_TEMPLATES_RELATIVE_PATH { get; } public string PACKAGES_BASE_TEMPLATES_FULL_PATH { get; } public string PACKAGES_WINDOW_STATE_README_RELATIVE_PATH { get; } public string PACKAGES_INSTANCE_FILES_README_RELATIVE_PATH { get; } public string PACKAGES_GIT_IGNORE_RELATIVE_PATH { get; } #endregion } }
73
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Common.Models { /// <summary> /// This enum describes a type of GameKit feature. /// </summary> public enum FeatureType : uint { Main, Identity, Authentication, Achievements, GameStateCloudSaving, UserGameplayData } }
19
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // Standard Library using System; using System.IO; using System.Linq; namespace AWS.GameKit.Common { /// <summary> /// This class provides a basic implementation of IFileManager. /// </summary> public class FileManager : IFileManager { public string GetGameKitSaveDirectory() { return Path.GetFullPath($"{Application.persistentDataPath}/AWSGameKit"); } public string[] ListFiles(string filePath, string searchPattern) { if (!Directory.Exists(filePath)) { return Array.Empty<string>(); } return Directory.EnumerateFiles(filePath, searchPattern).Select(file => Path.GetFullPath(file)).ToArray<string>(); } public byte[] ReadAllBytes(string filePath) { return File.ReadAllBytes(filePath); } public void WriteAllBytes(string filePath, byte[] data) { // Ensure the parent directory exists - if not, create it now FileInfo fileInfo = new FileInfo(filePath); if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } File.WriteAllBytes(filePath, data); } public long GetFileLastModifiedMilliseconds(string filePath) { FileInfo info = new FileInfo(filePath); DateTimeOffset offset = new DateTimeOffset(info.LastWriteTimeUtc); return offset.ToUnixTimeMilliseconds(); } public void DeleteFile(string filePath) { File.Delete(filePath); } public bool FileExists(string filePath) { return File.Exists(filePath); } } }
69
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // AWS GameKit using AWS.GameKit.Common.Models; namespace AWS.GameKit.Common { /// <summary> /// Manages common file access patterns for AWS GameKit samples. /// </summary> public interface IFileManager { /// <summary> /// Gets the directory used by GameKit to store any metadata, should be broken down further according to your use-case. /// </summary> /// <returns>The file path for the GameKit save directory.</returns> public string GetGameKitSaveDirectory(); /// <summary> /// Enumerates all files in a directory with a name that matches the provided pattern. /// </summary> /// <param name="filePath">The relative or absolute path to the directory to search.</param> /// <param name="pattern">The search pattern to match against file names in the specified path. Allows literal characters, as well as * and ? wildcards.</param> /// <returns>An array of matching file names within the specified directory.</returns> public string[] ListFiles(string filePath, string pattern); /// <summary> /// Reads the contents of the specified file into a byte array. /// </summary> /// <param name="filePath">The absolute or relative path to the file.</param> /// <returns>The raw contents of the file, in the form of a byte array.</returns> public byte[] ReadAllBytes(string filePath); /// <summary> /// Writes the contents of the provided byte array to the specified file. /// </summary> /// <param name="filePath">The absolute or relative path to the file.</param> /// <param name="data">The raw data to be written to the file.</param> public void WriteAllBytes(string filePath, byte[] data); /// <summary> /// Gets the Linux epoch time that the file was last modified in milliseconds. /// </summary> /// <param name="filePath">The absolute or relative path to the file.</param> /// <returns>Epoch time when the file was last modified, in milliseconds</returns> public long GetFileLastModifiedMilliseconds(string filePath); /// <summary> /// Deletes the specified file. /// </summary> /// <param name="filePath">The absolute or relative path to the file.</param> public void DeleteFile(string filePath); /// <summary> /// Checks if the specified file exists. /// </summary> /// <param name="filePath">The absolute or relative path to the file.</param> /// <returns>True if the file specified exists, false otherwise.</returns> public bool FileExists(string filePath); } }
63
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Common { /// <summary> /// Utility class that wraps class T in a singleton pattern. Use Get() to initialize and return an instance of the wrapped class. /// </summary> public abstract class Singleton<T> where T : new() { private static Lazy<T> _instance = new Lazy<T>(); /// <summary> /// Instantiates a class of type T if it has not already been instantiated, then returns the pointer to that instance. /// </summary> /// <return>The instance of class T</return> public static T Get() { return _instance.Value; } /// <summary> /// Gets the current initialized state of the held singleton. /// </summary> /// <remarks>To initialize, call Get().</remarks> /// <return>True if the instance is initialized.</return> public static bool IsInitialized() { return _instance.IsValueCreated; } } }
36
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; using System.IO; // Unity using UnityEditor; using UnityEngine; using UnityEngine.Events; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Windows.QuickAccess; using AWS.GameKit.Editor.Windows.Settings; using AWS.GameKit.Runtime; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Features.GameKitAchievements; using AWS.GameKit.Runtime.Features.GameKitGameSaving; using AWS.GameKit.Runtime.Features.GameKitIdentity; using AWS.GameKit.Runtime.Features.GameKitUserGameplayData; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor { [InitializeOnLoad] public class GameKitEditorManager : Singleton<GameKitEditorManager> { public SettingsController SettingsWindowController { get; } public QuickAccessController QuickAccessWindowController { get; } public bool CredentialsSubmitted = false; private readonly GameKitManager _gameKitManager; private readonly FeatureResourceManager _featureResourceManager; private readonly CredentialsManager _credentialsManager; private readonly FeatureDeploymentOrchestrator _featureDeploymentOrchestrator; private readonly Threader _threader = new Threader(); private bool _isReady = false; /// <summary> /// Initialize the GameKitEditorManager singleton and bootstrap the AWS GameKit package.<br/><br/> /// /// This static constructor is called whenever the scripts are recompiled (also known as a Domain Reload).<br/> /// This happens when Unity first loads, when scripts are re-compiled, and when entering Play Mode.<br/><br/> /// /// For more details, see: https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html /// </summary> static GameKitEditorManager() { // Create the singleton instance Get(); } /// <summary> /// Create a new GameKitEditorManager and bootstrap the AWS GameKit package. /// </summary> public GameKitEditorManager() { // validate that the Asset folder file structure is set up correctly CreateNeededFolders(); CopyInitialAssetFiles(); // This calls the static Update method several times a minute EditorApplication.update += Update; // Declare and initialize class fields _gameKitManager = Singleton<GameKitManager>.Get(); _featureResourceManager = new FeatureResourceManager(CoreWrapper.Get(), GameKitPaths.Get(), _threader); _credentialsManager = new CredentialsManager(); _featureDeploymentOrchestrator = new FeatureDeploymentOrchestrator(_featureResourceManager.Paths.PACKAGES_BASE_TEMPLATES_FULL_PATH, _featureResourceManager.Paths.ASSETS_INSTANCE_FILES_FULL_PATH); // Handle initial saveInfo.yml logic BootstrapExistingState(); // Post-bootstrap member initialization AchievementsAdmin.AchievementsAdmin achievementsAdmin = GameKitFeature<AchievementsAdmin.AchievementsAdmin>.Get(); achievementsAdmin.Initialize(_featureResourceManager, _credentialsManager); _gameKitManager.AddEditorOnlyFeature(achievementsAdmin); SettingsDependencyContainer settingsDependencyContainer = new SettingsDependencyContainer { // Editor GameKitEditorManager = this, CredentialsManager = _credentialsManager, // Runtime GameKitManager = _gameKitManager, CoreWrapper = CoreWrapper.Get(), FileManager = new FileManager(), // Feature management FeatureResourceManager = _featureResourceManager, FeatureDeploymentOrchestrator = _featureDeploymentOrchestrator, // Features Achievements = GameKitFeature<Achievements>.Get(), AchievementsAdmin = achievementsAdmin, GameSaving = GameKitFeature<GameSaving>.Get(), Identity = GameKitFeature<Identity>.Get(), UserGameplayData = GameKitFeature<UserGameplayData>.Get(), // User State UserInfo = new UserInfo(), // Events OnEnvironmentOrRegionChange = new UnityEvent() }; SettingsWindowController = new SettingsController(settingsDependencyContainer); QuickAccessWindowController = new QuickAccessController(SettingsWindowController, settingsDependencyContainer); // Declare the GameKitEditorContext to be in a ready to use state _isReady = true; } /// <summary> /// Execute the callback functions queued by Threader /// </summary> public void Update() { // do not execute while the application is running if (!Application.isPlaying) { // Validate that the GameKitRuntimeManager script is present and active GameKitRuntimeManager.KeepGameKitObjectAlive(); } // force update to be called more frequently in editor mode EditorApplication.delayCall += EditorApplication.QueuePlayerLoopUpdate; if (_isReady) { _threader.Update(); _featureDeploymentOrchestrator.Update(); SettingsWindowUpdateController.Update(); } } /// <summary> /// Create feature resource manager and bootstrap account /// </summary> /// <param name="saveInfoFile">File path location of the saveInfo.yml file</param> public void PopulateInformation(string saveInfoFile) { string gameName = Path.GetFileName(Path.GetDirectoryName(saveInfoFile)); _featureResourceManager.SetGameName(gameName); // Create accountDetails which will be used to populate accountInfo and accountCredentials using SetAccountDetails AccountDetails accountDetails = new AccountDetails(); accountDetails.GameName = gameName; accountDetails.Environment = _featureResourceManager.GetLastUsedEnvironment(); accountDetails.Region = _featureResourceManager.GetLastUsedRegion(); // CredentialsManager retrieves access key and secret key based on the game and environment _credentialsManager.SetGameName(accountDetails.GameName); _credentialsManager.SetEnv(accountDetails.Environment); // Populate accountDetails with the keys generated by the credentialsManager // and the accountId retrieved using featureResourceManager if (!_credentialsManager.CheckAwsProfileExists(accountDetails.GameName, accountDetails.Environment)) { Debug.LogWarning(L10n.Tr($"The credentials associated with the last used environment, {accountDetails.Environment}, for {accountDetails.GameName} could not be found. It is possible they have been deleted from the ~/.aws/credentials file.")); return; } accountDetails.AccessKey = _credentialsManager.GetAccessKey(); accountDetails.AccessSecret = _credentialsManager.GetSecretAccessKey(); GetAWSAccountIdDescription accountCredentials; accountCredentials.AccessKey = accountDetails.AccessKey; accountCredentials.AccessSecret = accountDetails.AccessSecret; StringCallbackResult result = CoreWrapper.Get().GetAWSAccountId(accountCredentials); if (result.ResultCode != GameKitErrors.GAMEKIT_SUCCESS) { Debug.LogError("AWS Account ID could not be retrieved, this may be due to the IAM role for your last used environment being changed or deleted."); return; } accountDetails.AccountId = result.ResponseValue; _featureResourceManager.SetAccountDetails(accountDetails); } /// <summary> /// Reload all feature settings for all settings tabs that exist in session /// </summary> public void ReloadAllFeatureSettings() { foreach (var featureSettingsTab in FeatureSettingsTab.FeatureSettingsTabsInstances) { featureSettingsTab.ReloadFeatureSettings(); } } /// <summary> /// Create feature resource manager and bootstrap account /// </summary> private void BootstrapExistingState() { string instanceFilesFolder = _featureResourceManager.Paths.ASSETS_INSTANCE_FILES_RELATIVE_PATH; ICollection<string> saveInfoFiles = Directory.GetFiles(instanceFilesFolder, GameKitPaths.Get().SAVE_INFO_FILE_NAME, SearchOption.AllDirectories); if (saveInfoFiles.Count <= 0) { return; } IEnumerator<string> itr = saveInfoFiles.GetEnumerator(); itr.MoveNext(); // Call PopulateInformation Asynchronously _threader.Call(PopulateInformation, itr.Current, () => { // The following code needs to be run on Unity's main thread because it calls AssetDatabase.ImportAsset() and uses Application.dataPath. // Copy over the config file in case Unity was closed during a feature deployment _gameKitManager.CopyAndReloadConfigFile(_featureResourceManager.GetGameName(), _featureResourceManager.GetLastUsedEnvironment()); Debug.Log("GameKitEditorContext::PopulateInformation completed"); }); } private static void CreateNeededFolders() { // Make sure gamekit assets folder(s) exists. if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_RELATIVE_PATH)) { AssetDatabase.CreateFolder(GameKitPaths.Get().ASSETS_DATA_FOLDER_NAME, GameKitPaths.Get().GAME_KIT_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_RESOURCES_RELATIVE_PATH)) { AssetDatabase.CreateFolder(GameKitPaths.Get().ASSETS_RELATIVE_PATH, GameKitPaths.Get().RESOURCE_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_EDITOR_RELATIVE_PATH)) { AssetDatabase.CreateFolder(GameKitPaths.Get().ASSETS_RELATIVE_PATH, GameKitPaths.Get().EDITOR_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_EDITOR_RESOURCES_RELATIVE_PATH)) { AssetDatabase.CreateFolder(Path.Combine(GameKitPaths.Get().ASSETS_EDITOR_RELATIVE_PATH), GameKitPaths.Get().RESOURCE_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_WINDOW_STATE_RELATIVE_PATH)) { AssetDatabase.CreateFolder(Path.Combine(GameKitPaths.Get().ASSETS_EDITOR_RELATIVE_PATH), GameKitPaths.Get().WINDOWS_STATE_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_CLOUD_RESOURCES_RELATIVE_PATH)) { AssetDatabase.CreateFolder(GameKitPaths.Get().ASSETS_EDITOR_RELATIVE_PATH, GameKitPaths.Get().CLOUD_RESOURCES_FOLDER_NAME); } if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_INSTANCE_FILES_RELATIVE_PATH)) { AssetDatabase.CreateFolder(GameKitPaths.Get().ASSETS_CLOUD_RESOURCES_RELATIVE_PATH, GameKitPaths.Get().INSTANCE_FILES_FOLDER_NAME); } #if UNITY_ANDROID if (!AssetDatabase.IsValidFolder(GameKitPaths.Get().ASSETS_GAMEKIT_RAW_RELATIVE_PATH)) { // Recursively create all the directories up to raw folder Directory.CreateDirectory(GameKitPaths.Get().ASSETS_GAMEKIT_RAW_RELATIVE_PATH); } #endif } private static void CopyInitialAssetFiles() { // Copy readme files if they don't yet exist if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_README_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_RESOURCES_README_RELATIVE_PATH, GameKitPaths.Get().ASSETS_README_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_EDITOR_RESOURCES_README_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_README_RELATIVE_PATH, GameKitPaths.Get().ASSETS_EDITOR_RESOURCES_README_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_GIT_IGNORE_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_GIT_IGNORE_RELATIVE_PATH, GameKitPaths.Get().ASSETS_GIT_IGNORE_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_CLOUD_RESOURCES_README_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_CLOUD_RESOURCES_README_RELATIVE_PATH, GameKitPaths.Get().ASSETS_CLOUD_RESOURCES_README_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_WINDOW_STATE_README_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_WINDOW_STATE_README_RELATIVE_PATH, GameKitPaths.Get().ASSETS_WINDOW_STATE_README_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_INSTANCE_FILES_README_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_INSTANCE_FILES_README_RELATIVE_PATH, GameKitPaths.Get().ASSETS_INSTANCE_FILES_README_RELATIVE_PATH); } #if UNITY_ANDROID if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_GAMEKIT_RAW_CERT_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_CACERT_RELATIVE_PATH, GameKitPaths.Get().ASSETS_GAMEKIT_RAW_CERT_RELATIVE_PATH); } if (!File.Exists(Path.GetFullPath(GameKitPaths.Get().ASSETS_GAMEKIT_ANDROID_MANIFEST_RELATIVE_PATH))) { AssetDatabase.CopyAsset(GameKitPaths.Get().PACKAGES_ANDROID_MANIFEST_RELATIVE_PATH, GameKitPaths.Get().ASSETS_GAMEKIT_ANDROID_MANIFEST_RELATIVE_PATH); } #endif } } }
335
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.Utils; namespace AWS.GameKit.Editor { /// <summary> /// The "AWS GameKit" dropdown menu found along the top toolbar (alongside File, Edit, Assets, etc.). /// </summary> public static class ToolbarMenu { /// <summary> /// Names of the items in the dropdown menu. /// </summary> private static class ItemNames { public const string QUICK_ACCESS = AWS_GAMEKIT + "/QuickAccess"; public const string SETTINGS = AWS_GAMEKIT + "/Settings"; public const string DOCUMENTATION = AWS_GAMEKIT + "/Documentation"; private const string AWS_GAMEKIT = "AWS GameKit"; } /// <summary> /// Sort order of the items in the dropdown menu. The menu is sorted in ascending order. /// </summary> private static class ItemPriorities { private const int TOP_OF_LIST = 0; // Unity adds a divider between menu items when their priority is more than 10 apart. private const int ADD_DIVIDER = 11; // First group public const int QUICK_ACCESS = TOP_OF_LIST; public const int SETTINGS = QUICK_ACCESS + 1; // Second group public const int DOCUMENTATION = ADD_DIVIDER + SETTINGS; } [MenuItem(ItemNames.QUICK_ACCESS, priority = ItemPriorities.QUICK_ACCESS)] public static void OpenQuickAccess() { GameKitEditorManager.Get().QuickAccessWindowController.GetOrCreateQuickAccessWindow(); } [MenuItem(ItemNames.SETTINGS, priority = ItemPriorities.SETTINGS)] public static void OpenSettings() { GameKitEditorManager.Get().SettingsWindowController.GetOrCreateSettingsWindow(); } [MenuItem(ItemNames.DOCUMENTATION, priority = ItemPriorities.DOCUMENTATION)] public static void OpenDocumentation() { Application.OpenURL(DocumentationURLs.GAMEKIT_HOME); } } }
67
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.AchievementsAdmin { /// <summary> /// Provides administrative methods for managing a game's Achievements (ex: creating new achievements, tweaking existing achievements, etc.).<br/><br/> /// </summary> public class AchievementsAdmin : GameKitFeatureBase<AchievementsAdminWrapper>, IAchievementsAdminProvider { public override FeatureType FeatureType => FeatureType.Achievements; /// <summary> /// Call to get an instance of the GameKit AchievementsAdmin feature. /// </summary> /// <returns>An instance of the AchievementsAdmin feature that can be used to call AchievementsAdmin related methods.</returns> public static AchievementsAdmin Get() { return GameKitFeature<AchievementsAdmin>.Get(); } /// <summary> /// Initialize this class. This must be called before calling any of the <see cref="AchievementsAdmin"/> APIs, otherwise an <see cref="InvalidOperationException"/> will be thrown. /// </summary> public void Initialize(FeatureResourceManager featureResourceManager, CredentialsManager credentialsManager) { Feature.Initialize(featureResourceManager, credentialsManager); } /// <summary> /// Lists non-hidden achievements, and will call delegates after every page.<br/><br/> /// /// Secret achievements will be included, and developers will be responsible for processing those as they see fit.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="listAchievementsDesc">Object containing call preferences</param> /// <param name="callback">Delegate that is called while the function is executing, once for each page of achievements</param> /// <param name="onCompleteCallback">Delegate that is called once the function has finished executing</param> public void ListAchievementsForGame(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> callback, Action<uint> onCompleteCallback) { Call(Feature.AdminListAchievements, listAchievementsDesc, callback, onCompleteCallback); } /// <summary> /// Add all achievements passed to the games dynamoDB achievements table.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ACHIEVEMENTS_ICON_UPLOAD_FAILED: Was unable to take the local path given of an image and upload it to S3.<br/> /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: The current region isn't in our template of shorthand region codes, unknown if the region is supported.<br/> /// - GAMEKIT_ERROR_SIGN_REQUEST_FAILED: Was unable to sign the internal http request with account credentials and info, possibly because they do not have sufficient permissions.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="addAchievementDesc">Object containing a list of achievements to add</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddAchievementsForGame(AddAchievementDesc addAchievementDesc, Action<uint> callback) { Call(Feature.AdminAddAchievements, addAchievementDesc, callback); } /// <summary> /// Deletes the set of achievements metadata from the game's DynamoDB.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: The current region isn't in our template of shorthand region codes, unknown if the region is supported.<br/> /// - GAMEKIT_ERROR_SIGN_REQUEST_FAILED: Was unable to sign the internal http request with account credentials and info, possibly because they do not have sufficient permissions.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// - GAMEKIT_ERROR_ACHIEVEMENTS_PAYLOAD_TOO_LARGE: The argument list is too large to pass as a query string parameter.<br/> /// </summary> /// <param name="deleteAchievementsDesc">Object containing a list of achievement identifiers to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteAchievementsForGame(DeleteAchievementsDesc deleteAchievementsDesc, Action<uint> callback) { Call(Feature.AdminDeleteAchievements, deleteAchievementsDesc, callback); } /// <summary> /// Changes the credentials used to sign requests and retrieve session tokens for admin requests.<br/><br/> /// /// No result delegate as this isn't a blocking method, only possible failure is an invalid region code which will be logged. /// </summary> /// <param name="changeCredentialsDesc">Object containing information about the new credentials and the account</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ChangeCredentials(ChangeCredentialsDesc changeCredentialsDesc, Action<uint> callback) { Call(Feature.ChangeCredentials, changeCredentialsDesc, callback); } /// <summary> /// Checks whether the passed in ID has invalid characters or length.<br/><br/> /// /// No result delegate as this isn't a blocking method. /// </summary> /// <param name="achievementId">achievement identifier to validate</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void IsAchievementIdValid(string achievementId, Action<bool> callback) { Call(Feature.IsAchievementIdValid, achievementId, callback); } /// <summary> /// Gets the AWS CloudFront url which all achievement icons for this game/environment can be accessed from.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementIconBaseUrl(Action<StringCallbackResult> callback) { Call(Feature.GetAchievementIconsBaseUrl, callback); } } }
130
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // Third Party using Newtonsoft.Json; namespace AWS.GameKit.Editor.AchievementsAdmin { [StructLayout(LayoutKind.Sequential)] public struct AccountCredentials { public string Region; public string AccessKey; public string AccessSecret; public string AccountId; public static implicit operator AccountCredentials(Runtime.Models.AccountCredentials accountCredentials) { return new AccountCredentials() { Region = accountCredentials.Region, AccessKey = accountCredentials.AccessKey, AccessSecret = accountCredentials.AccessSecret, AccountId = accountCredentials.AccountId }; } }; [StructLayout(LayoutKind.Sequential)] public struct AccountInfo { public string Environment; public string AccountId; public string CompanyName; public string GameName; public static implicit operator AccountInfo(Runtime.Models.AccountInfo accountInfo) { return new AccountInfo() { Environment = accountInfo.Environment, AccountId = accountInfo.AccountId, CompanyName = accountInfo.CompanyName, GameName = accountInfo.GameName }; } }; [Serializable] [StructLayout(LayoutKind.Sequential)] public struct AdminAchievement { [JsonProperty("achievement_id")] public string AchievementId; [JsonProperty("title")] public string Title; [JsonProperty("locked_description")] public string LockedDescription; [JsonProperty("unlocked_description")] public string UnlockedDescription; [JsonProperty("locked_icon_url")] public string LockedIcon; [JsonProperty("unlocked_icon_url")] public string UnlockedIcon; [JsonProperty("max_value")] public uint RequiredAmount; [JsonProperty("points")] public uint Points; [JsonProperty("order_number")] public uint OrderNumber; [JsonProperty("is_stateful")] [MarshalAs(UnmanagedType.U1)] public bool IsStateful; [JsonProperty("is_secret")] [MarshalAs(UnmanagedType.U1)] public bool IsSecret; [JsonProperty("is_hidden")] [MarshalAs(UnmanagedType.U1)] public bool IsHidden; }; public struct AccountDesc { public AccountCredentials Credentials; public AccountInfo Info; } public struct ListAchievementsDesc { public uint PageSize; public bool WaitForAllPages; } public struct AddAchievementDesc { public AdminAchievement[] Achievements; public uint BatchSize; } public struct DeleteAchievementsDesc { public string[] AchievementIdentifiers; public uint BatchSize; } public struct ChangeCredentialsDesc { public AccountCredentials AccountCredentials; public AccountInfo AccountInfo; } [Serializable] public class AchievementListResult { [JsonProperty("achievements")] public AdminAchievement[] Achievements; } }
133
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Runtime.InteropServices; // GameKit using AWS.GameKit.Editor.Core; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.FeatureUtils; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; // Third Party using Newtonsoft.Json; namespace AWS.GameKit.Editor.AchievementsAdmin { /// <summary> /// Achievements Admin wrapper for GameKit C++ SDK calls /// </summary> public class AchievementsAdminWrapper : GameKitFeatureWrapperBase { // Select the correct source path based on the platform #if UNITY_IPHONE && !UNITY_EDITOR private const string IMPORT = "__Internal"; #else private const string IMPORT = "aws-gamekit-achievements"; #endif // Dependencies private FeatureResourceManager _featureResourceManager; private CredentialsManager _credentialsManager; // DLL loading [DllImport(IMPORT)] private static extern IntPtr GameKitAdminAchievementsInstanceCreateWithSessionManager(IntPtr sessionManager, string baseTemplatesFolder, AccountCredentials accountCredentials, AccountInfo accountInfo, FuncLoggingCallback logCb); [DllImport(IMPORT)] private static extern void GameKitAdminAchievementsInstanceRelease(IntPtr achievementsInstance); [DllImport(IMPORT)] private static extern uint GameKitAdminListAchievements(IntPtr achievementsInstance, uint pageSize, bool waitForAllPages, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [DllImport(IMPORT)] private static extern uint GameKitAdminAddAchievements(IntPtr achievementsInstance, AdminAchievement[] achievements, uint batchSize); [DllImport(IMPORT)] private static extern uint GameKitAdminDeleteAchievements(IntPtr achievementsInstance, string[] achievementIdentifiers, uint batchSize); [DllImport(IMPORT)] private static extern uint GameKitGetAchievementIconsBaseUrl(IntPtr achievementsInstance, IntPtr dispatchReceiver, FuncStringCallback responseCallback); [DllImport(IMPORT)] private static extern bool GameKitIsAchievementIdValid(string achievementId); [DllImport(IMPORT)] private static extern uint GameKitAdminCredentialsChanged(IntPtr achievementsInstance, AccountCredentials accountCredentials, AccountInfo accountInfo); /// <summary> /// Initialize Achievements wrapper /// </summary> /// <param name="featureResourceManager">Feature resource manager instance.</param> /// <param name="credentialsManager">Credentials manager instance.</param> public void Initialize(FeatureResourceManager featureResourceManager, CredentialsManager credentialsManager) { _featureResourceManager = featureResourceManager; _credentialsManager = credentialsManager; } /// <summary> /// Checks if Achievement ID is valid. /// </summary> /// <param name="achievementId">ID of the achievement to check.</param> /// <returns>True if valid, false if not</returns> public bool IsAchievementIdValid(string achievementId) { return DllLoader.TryDll(() => GameKitIsAchievementIdValid(achievementId), nameof(GameKitIsAchievementIdValid), false); } /// <summary> /// Changes credentials to the indicated ones. /// </summary> /// <param name="changeCredentialsDesc">New credentials.</param> /// <returns>A GameKit status code indicating the result of the API call.</returns> public uint ChangeCredentials(ChangeCredentialsDesc changeCredentialsDesc) { return DllLoader.TryDll(() => GameKitAdminCredentialsChanged( GetInstance(), changeCredentialsDesc.AccountCredentials, changeCredentialsDesc.AccountInfo), nameof(GameKitAdminCredentialsChanged), GameKitErrors.GAMEKIT_ERROR_GENERAL); } /// <summary> /// Lists all the metadata for every achievement for the current game and environment /// </summary> /// <param name="listAchievementsDesc">Struct indicates the number of records to scan or if it should retrieve all items.</param> /// <param name="resultCallback">Callback for the list of achievements.</param> /// <returns>A GameKit status code indicating the result of the API call.</returns> public uint AdminListAchievements(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> resultCallback) { return DllLoader.TryDll(resultCallback, (IntPtr dispatchReceiver) => GameKitAdminListAchievements( GetInstance(), listAchievementsDesc.PageSize, listAchievementsDesc.WaitForAllPages, dispatchReceiver, AchievementListFromRecurringStringCallback), nameof(GameKitAdminListAchievements), GameKitErrors.GAMEKIT_ERROR_GENERAL); } /// <summary> /// Adds or updates the achievements in the backend for the current game and environment to have new metadata items. /// </summary> /// <param name="addAchievementDesc">Contains the list of achievements to add and the batch size.</param> /// <returns>A GameKit status code indicating the result of the API call.</returns> public uint AdminAddAchievements(AddAchievementDesc addAchievementDesc) { return DllLoader.TryDll(() => GameKitAdminAddAchievements( GetInstance(), addAchievementDesc.Achievements, addAchievementDesc.BatchSize), nameof(GameKitAdminAddAchievements), GameKitErrors.GAMEKIT_ERROR_GENERAL); } /// <summary> /// Deletes the achievements in the backend for the current game and environment specified ID's. /// </summary> /// <param name="deleteAchievementsDesc">Contains the achievement ids and batch size.</param> /// <returns>A GameKit status code indicating the result of the API call.</returns> public uint AdminDeleteAchievements(DeleteAchievementsDesc deleteAchievementsDesc) { return DllLoader.TryDll(() => GameKitAdminDeleteAchievements( GetInstance(), deleteAchievementsDesc.AchievementIdentifiers, deleteAchievementsDesc.BatchSize), nameof(GameKitAdminDeleteAchievements), GameKitErrors.GAMEKIT_ERROR_GENERAL); } /// <summary> /// Retrieve base url for achievement icons. /// </summary> /// <returns>StringCallback with base url and GameKit status code indicating the result of the API call.</returns> public StringCallbackResult GetAchievementIconsBaseUrl() { StringCallbackResult result = new StringCallbackResult(); uint status = DllLoader.TryDll(result, (IntPtr dispatchReceiver) => GameKitGetAchievementIconsBaseUrl(GetInstance(), dispatchReceiver, GameKitCallbacks.StringCallback), nameof(GameKitGetAchievementIconsBaseUrl), GameKitErrors.GAMEKIT_ERROR_GENERAL); result.ResultCode = status; return result; } protected override IntPtr Create(IntPtr sessionManager, FuncLoggingCallback logCb) { if (string.IsNullOrEmpty(_featureResourceManager.GetAccountInfo().AccountId)) { throw new InvalidOperationException($"Cannot call {nameof(GameKitAdminAchievementsInstanceCreateWithSessionManager)}. AWS credentials need to be submitted first. This indicates an {nameof(AdminAchievement)} API is being called too early."); } AccountDesc account = new AccountDesc() { Credentials = _featureResourceManager.GetAccountCredentials(), Info = _featureResourceManager.GetAccountInfo() }; string baseTemplatesFolder = _featureResourceManager.Paths.PACKAGES_BASE_TEMPLATES_FULL_PATH; return DllLoader.TryDll<IntPtr>(() => GameKitAdminAchievementsInstanceCreateWithSessionManager(sessionManager, baseTemplatesFolder, account.Credentials, account.Info, logCb), nameof(GameKitAdminAchievementsInstanceCreateWithSessionManager), IntPtr.Zero); } protected override void Release(IntPtr instance) { DllLoader.TryDll(() => GameKitAdminAchievementsInstanceRelease(instance), nameof(GameKitAdminAchievementsInstanceRelease)); } [AOT.MonoPInvokeCallback(typeof(FuncStringCallback))] private static void AchievementListFromRecurringStringCallback(IntPtr dispatchReceiver, string responseValue) { // parse the string response AchievementListResult result = JsonConvert.DeserializeObject<JsonResponse<AchievementListResult>>(responseValue).data; // get a handle to the result callback from the dispatch receiver Action<AchievementListResult> resultCallback = Marshaller.GetDispatchObject<Action<AchievementListResult>>(dispatchReceiver); // call the callback and pass it the result resultCallback(result); } } }
174
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.AchievementsAdmin { /// <summary> /// Interface for the AWS GameKit Achievements feature's admin APIs. /// </summary> public interface IAchievementsAdminProvider { /// <summary> /// Lists non-hidden achievements, and will call delegates after every page.<br/><br/> /// /// Secret achievements will be included, and developers will be responsible for processing those as they see fit.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_NO_ID_TOKEN: The player is not logged in. You must login the player through the Identity and Authentication feature (AwsGameKitIdentity) before calling this method.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="listAchievementsDesc">Object containing call preferences</param> /// <param name="callback">Delegate that is called while the function is executing, once for each page of achievements</param> /// <param name="onCompleteCallback">Delegate that is called once the function has finished executing</param> public void ListAchievementsForGame(ListAchievementsDesc listAchievementsDesc, Action<AchievementListResult> callback, Action<uint> onCompleteCallback); /// <summary> /// Add all achievements passed to the games dynamoDB achievements table.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ACHIEVEMENTS_ICON_UPLOAD_FAILED: Was unable to take the local path given of an image and upload it to S3.<br/> /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: The current region isn't in our template of shorthand region codes, unknown if the region is supported.<br/> /// - GAMEKIT_ERROR_SIGN_REQUEST_FAILED: Was unable to sign the internal http request with account credentials and info, possibly because they do not have sufficient permissions.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="addAchievementDesc">Object containing a list of achievements to add</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void AddAchievementsForGame(AddAchievementDesc addAchievementDesc, Action<uint> callback); /// <summary> /// Deletes the set of achievements metadata from the game's DynamoDB.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: The current region isn't in our template of shorthand region codes, unknown if the region is supported.<br/> /// - GAMEKIT_ERROR_SIGN_REQUEST_FAILED: Was unable to sign the internal http request with account credentials and info, possibly because they do not have sufficient permissions.<br/> /// - GAMEKIT_ERROR_HTTP_REQUEST_FAILED: The backend HTTP request failed. Check the logs to see what the HTTP response code was.<br/> /// - GAMEKIT_ERROR_PARSE_JSON_FAILED: The backend returned a malformed JSON payload. This should not happen. If it does, it indicates there is a bug in the backend code. /// </summary> /// <param name="deleteAchievementsDesc">Object containing a list of achievement identifiers to delete</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void DeleteAchievementsForGame(DeleteAchievementsDesc deleteAchievementsDesc, Action<uint> callback); /// <summary> /// Changes the credentials used to sign requests and retrieve session tokens for admin requests.<br/><br/> /// /// No result delegate as this isn't a blocking method, only possible failure is an invalid region code which will be logged. /// </summary> /// <param name="changeCredentialsDesc">Object containing information about the new credentials and the account</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void ChangeCredentials(ChangeCredentialsDesc changeCredentialsDesc, Action<uint> callback); /// <summary> /// Checks whether the passed in ID has invalid characters or length.<br/><br/> /// /// No result delegate as this isn't a blocking method. /// </summary> /// <param name="achievementId">achievement identifier to validate</param> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void IsAchievementIdValid(string achievementId, Action<bool> callback); /// <summary> /// Gets the AWS CloudFront url which all achievement icons for this game/environment can be accessed from.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </summary> /// <param name="callback">Delegate that is called once the function has finished executing</param> public void GetAchievementIconBaseUrl(Action<StringCallbackResult> callback); } }
89
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.IO; // Unity using UnityEditor; using UnityEditor.Callbacks; #if UNITY_IOS // Unity iOS is for Editor mode using UnityEditor.iOS.Xcode; #endif // GameKit using AWS.GameKit.Common; namespace AWS.GameKit.Editor { /// <summary> /// This class describes steps to be taken after the player is built. /// </summary> public class PostBuild { private const string CERTIFICATES_BUILD_PATH = "Data/Security/Certs/"; /// <summary> /// Post build step for a specific target. /// </summary> /// <param name="target">The target to perform the post build step for.</param> /// <param name="pathToBuiltProject">Path to the built project.</param> [PostProcessBuild] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { if (target == BuildTarget.iOS) OnPostprocessBuildIOS(pathToBuiltProject); } private static void OnPostprocessBuildIOS(string pathToBuiltProject) { #if UNITY_IOS // Unity iOS is for Editor mode string xcodeProjectPath = PBXProject.GetPBXProjectPath(pathToBuiltProject); PBXProject xcodeProject = new PBXProject(); xcodeProject.ReadFromString(File.ReadAllText(xcodeProjectPath)); string unityFrameworkTarget = xcodeProject.GetUnityFrameworkTargetGuid(); Directory.CreateDirectory(Path.Combine(pathToBuiltProject, CERTIFICATES_BUILD_PATH)); string[] certificatesToCopy = new string[] { "cacert.pem" }; for(int i = 0 ; i < certificatesToCopy.Length ; ++i) { string srcPath = Path.Combine(GameKitPaths.Get().PACKAGES_CERTIFICATES_FULL_PATH, certificatesToCopy[i]); string dstLocalPath = CERTIFICATES_BUILD_PATH + certificatesToCopy[i]; string dstPath = Path.Combine(pathToBuiltProject, dstLocalPath); File.Copy(srcPath, dstPath, true); } // Compile with the newest version of libz xcode has available xcodeProject.AddBuildProperty(unityFrameworkTarget, "OTHER_LDFLAGS", "-lz"); File.WriteAllText(xcodeProjectPath, xcodeProject.WriteToString()); #endif } } }
71
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Core { /// <summary> /// Provides read/write access for persisting the user's AWS credentials to the standardized <c>~/.aws/credentials</c> file.<br/><br/> /// /// To learn more about this file, please see <see cref="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html"/>. /// </summary> public class CredentialsManager { private string _gameName = string.Empty; private string _envCode = string.Empty; /// <summary> /// Combines the gamename, environment code and the 'GameKit' phase to create a profile name /// </summary> /// <returns>Profile name that will be used to save/find credentials in the user's AWS credentials ini file</returns> private string GetProfileName() { return $"GameKit-{_gameName}-{_envCode}"; } /// <summary> /// Sets the _gameName variable for the instance of the credentials manager /// </summary> /// <param name="name">The name of the game</param> public void SetGameName(string name) { _gameName = name; } /// <summary> /// Sets the _envCode variable for the instance of the credentials manager /// </summary> /// <param name="environmentCode">A 2 to 3 character environment code</param> public void SetEnv(string environmentCode) { _envCode = environmentCode; } /// <summary> /// Save a new profile to the AWS credentials file. /// </summary> /// <param name="accessKey">The access key of the AWS IAM role we are saving.</param> /// <param name="secretKey">The secret key of the AWS IAM role we are saving.</param> public void SaveCredentials(string accessKey, string secretKey) { uint result = CoreWrapper.Get().SaveAWSCredentials(GetProfileName(), accessKey, secretKey, Logging.LogCb); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError($"CredentialsManager::SaveCredentials() was unable to save profile: {GetProfileName()} to aws credentials file. Error Code: {result}"); } } /// <summary> /// Checks the AWS profile exists. /// </summary> /// <param name="gameName">The game name we are checking an aws profile for.</param> /// <param name="environmentCode">The environment code we are checking an aws profile for.</param> public bool CheckAwsProfileExists(string gameName, string environmentCode) { SetGameName(gameName); SetEnv(environmentCode); return CoreWrapper.Get().AwsProfileExists(GetProfileName()); } /// <summary> /// Sets the AWS access key of an existing profile. /// </summary> /// <remarks> /// If the profile retrieved with GetProfileName does not exist, will not automatically create the profile and will log an error. /// </remarks> /// <param name="accessKey">The new access key of the AWS IAM role we are saving.</param> public void SetAccessKey(string accessKey) { uint result = CoreWrapper.Get().SetAWSAccessKey(GetProfileName(), accessKey, Logging.LogCb); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError($"CredentialsManager::SetAccessKey() was unable to set access key for profile: {GetProfileName()}. Error Code: {result}"); } } /// <summary> /// Sets the AWS secret key of an existing profile. /// </summary> /// <remarks> /// If the profile retrieved with GetProfileName does not exist, will not automatically create the profile and will log an error. /// </remarks> /// <param name="secretKey">The new secret key that will be assigned to this profile.</param> public void SetSecretKey(string secretKey) { uint result = CoreWrapper.Get().SetAWSSecretKey(GetProfileName(), secretKey, Logging.LogCb); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError($"CredentialsManager::SetSecretKey() was unable to set secret key for profile: {GetProfileName()}. Error Code: {result}"); } } /// <summary> /// Gets the access key corresponding to a pre-existing profile in the AWS credentials file. /// </summary> /// <returns>The access key found in the .aws/credentials file for the corresponding profile</returns> public string GetAccessKey() { // KeyValueStringCallbackResult is a struct containing two strings ResponseKey and ResponseValue and and error code, which can be parsed in GameKitErrors.cs. // In this method ResponseKey corresponds to the Access Key and ResponseValue corresponds to the Secret Key KeyValueStringCallbackResult result = CoreWrapper.Get().GetAWSProfile(GetProfileName(), Logging.LogCb); if (result.ResultCode != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError($"CredentialsManager::GetAccessKey() was unable to get access key for profile: {GetProfileName()}. Error Code: {result}"); } return result.ResponseKey; } /// <summary> /// Gets the secret key corresponding to a pre-existing profile in the AWS credentials file. /// </summary> /// <returns>The secret key found in the .aws/credentials file for the corresponding profile</returns> public string GetSecretAccessKey() { // KeyValueStringCallbackResult is a struct containing two strings ResponseKey and ResponseValue and and error code, which can be parsed in GameKitErrors.cs. // In this method ResponseKey corresponds to the Access Key and ResponseValue corresponds to the Secret Key KeyValueStringCallbackResult result = CoreWrapper.Get().GetAWSProfile(GetProfileName(), Logging.LogCb); if (result.ResultCode != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError($"CredentialsManager::GetSecretAccessKey() was unable to get secret key for profile: {GetProfileName()}. Error Code: {result}"); } return result.ResponseValue; } } }
146
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity #if UNITY_EDITOR using UnityEditor; #endif // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Core { /// <summary> /// This class handles the deployment of all GameKit features (i.e. create, re-deploy, delete). /// </summary> public class FeatureDeploymentOrchestrator : IDisposable { private Threader _threader = new Threader(); private ICoreWrapperProvider _coreWrapper; private bool _disposedValue = false; private IDictionary<Guid, string> _enterPlayModeRestrictions = new Dictionary<Guid, string>(); public FeatureDeploymentOrchestrator(ICoreWrapperProvider coreWrapper, string baseTemplatesFolder, string instanceFilesFolder) { _coreWrapper = coreWrapper; _coreWrapper.DeploymentOrchestratorInstanceCreate(baseTemplatesFolder, instanceFilesFolder); #if UNITY_EDITOR EditorApplication.playModeStateChanged += this.OnPlayModeStateChanged; #endif } public FeatureDeploymentOrchestrator(string baseTemplatesFolder, string instanceFilesFolder) : this(CoreWrapper.Get(), baseTemplatesFolder, instanceFilesFolder) { } ~FeatureDeploymentOrchestrator() => Dispose(); public void Dispose() { if (!_disposedValue) { _coreWrapper.DeploymentOrchestratorInstanceRelease(); _disposedValue = true; } GC.SuppressFinalize(this); } public void Update() { _threader.Update(); } /// <summary> /// Set account credentials. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="setCredentialsDesc">Object holding the AccountInfo and AccountCredentials.</param> /// <returns> /// The result status code of the operation (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_DEPLOYMENT_IN_PROGRESS: Cannot change credentials while a deployment is in progress. /// - GAMEKIT_ERROR_REGION_CODE_CONVERSION_FAILED: Could not retrieve the short region code from the mappings file. See the log for details on how to fix this. /// </returns> public uint SetCredentials(SetCredentialsDesc setCredentialsDesc) { return _coreWrapper.DeploymentOrchestratorSetCredentials(setCredentialsDesc); } /// <summary> /// Get the status of a requested feature. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>FeatureStatus enum related to the status of the requested feature.</returns> public FeatureStatus GetFeatureStatus(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorGetFeatureStatus(feature); } /// <summary> /// Get an abridged status of a requested feature. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>FeatureStatusSummary enum related to the abridged status of the requested feature.</returns> public FeatureStatusSummary GetFeatureStatusSummary(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorGetFeatureStatusSummary(feature); } /// <summary> /// Check if the requested feature is currently being created, redeployed, or deleted. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures.<br/><br/> /// /// Unlike DeploymentOrchestratorIsFeatureUpdating, this method returns true while the Main stack is being deployed (before the feature itself is created or redeployed). /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>true if the requested feature is being created, redeployed, or deleted.</returns> public bool IsFeatureDeploymentInProgress(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorIsFeatureDeploymentInProgress(feature); } /// <summary> /// Check if the requested feature is currently updating (i.e. it's FeatureStatus is not Deployed, Undeployed, Error, or RollbackComplete). /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns>true if the requested feature is updating.</returns> public bool IsFeatureUpdating(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorIsFeatureUpdating(feature); } /// <summary> /// Check if any GameKit feature is currently updating (i.e. has a FeatureStatus other than Deployed, Undeployed, Error, or RollbackComplete). /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <returns>true if any feature is updating.</returns> public bool IsAnyFeatureUpdating() { return _coreWrapper.DeploymentOrchestratorIsAnyFeatureUpdating(); } /// <summary> /// Refresh the status of a requested feature. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <param name="callback">Delegate that is called once this method completes. /// It contains the <see cref="FeatureStatus"/> of all features and the result status code for the call. /// </param> public void RefreshFeatureStatus(FeatureType feature, Action<DeploymentResponseResult> callback) { _threader.Call<DeploymentResponseResult>(() => _coreWrapper.DeploymentOrchestratorRefreshFeatureStatus(feature), callback); } /// <summary> /// Refresh the status of all features. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful. /// </remarks> /// <param name="callback">Delegate that is called once this method completes. /// It contains the <see cref="FeatureStatus"/> of all features and the result status code for the call. /// </param> public void RefreshFeatureStatuses(Action<DeploymentResponseResult> callback) { _threader.Call<DeploymentResponseResult>(() => _coreWrapper.DeploymentOrchestratorRefreshFeatureStatuses(), callback); } /// <summary> /// Request if a feature is in a state to be created. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be created.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be created. /// </returns> public CanExecuteDeploymentActionResult CanCreateFeature(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorCanCreateFeature(feature); } /// <summary> /// Request if a feature can be re-deployed. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be redeployed.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be redeployed. /// </returns> public CanExecuteDeploymentActionResult CanRedeployFeature(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorCanRedeployFeature(feature); } /// <summary> /// Request if a feature is in a state where it can be deleted. /// </summary> /// <remarks> /// This is a fast method. It does not invoke any networked procedures. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <returns> /// A <see cref="CanExecuteDeploymentActionResult"/> object describing whether the feature can be deleted.<br/> /// A <see cref="DeploymentActionBlockedReason"/> and list of blocking <see cref="FeatureType"/> are provided in cases where the feature cannot be deleted. /// </returns> public CanExecuteDeploymentActionResult CanDeleteFeature(FeatureType feature) { return _coreWrapper.DeploymentOrchestratorCanDeleteFeature(feature); } /// <summary> /// Create a requested feature. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot create feature as it or one of its dependencies are in an invalid state for deployment. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <param name="callback">Delegate that is called once this method completes. /// It contains the <see cref="FeatureStatus"/> of all features and the result status code for the call. /// </param> public void CreateFeature(FeatureType feature, Action<DeploymentResponseResult> callback) { _threader.Call<DeploymentResponseResult>(() => { Guid taskGuid = Guid.NewGuid(); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Add(taskGuid, $"\"{feature.GetDisplayName()}\" feature deployment is in progress."); DeploymentResponseResult result = _coreWrapper.DeploymentOrchestratorCreateFeature(feature); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Remove(taskGuid); return result; }, callback); } /// <summary> /// Re-deploy a requested feature. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot redeploy feature as it or one of its dependencies are in an invalid state for deployment. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <param name="callback">Delegate that is called once this method completes. /// It contains the <see cref="FeatureStatus"/> of all features and the result status code for the call. /// </param> public void RedeployFeature(FeatureType feature, Action<DeploymentResponseResult> callback) { _threader.Call<DeploymentResponseResult>(() => { Guid taskGuid = Guid.NewGuid(); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Add(taskGuid, $"\"{feature.GetDisplayName()}\" feature redeployment is in progress."); DeploymentResponseResult result = _coreWrapper.DeploymentOrchestratorRedeployFeature(feature); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Remove(taskGuid); return result; }, callback); } /// <summary> /// Delete a requested feature. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_CLOUDFORMATION_STACK_DELETE_FAILED: Failed to delete the stack, check output log for exact reason.<br/> /// - GAMEKIT_ERROR_ORCHESTRATION_INVALID_FEATURE_STATE: Cannot delete feature as it or one of its downstream dependencies are in an invalid state for deletion. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <param name="callback">Delegate that is called once this method completes. /// It contains the <see cref="FeatureStatus"/> of all features and the result status code for the call.</param> public void DeleteFeature(FeatureType feature, Action<DeploymentResponseResult> callback) { _threader.Call<DeploymentResponseResult>(() => { Guid taskGuid = Guid.NewGuid(); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Add(taskGuid, $"\"{feature.GetDisplayName()}\" feature deletion is in progress."); DeploymentResponseResult result = _coreWrapper.DeploymentOrchestratorDeleteFeature(feature); lock (_enterPlayModeRestrictions) _enterPlayModeRestrictions.Remove(taskGuid); return result; }, callback); } #if UNITY_EDITOR private void OnPlayModeStateChanged(PlayModeStateChange stateChange) { // Don't allow transitioning from Edit mode to Play mode when a restrictive operation is running. if (stateChange == PlayModeStateChange.ExitingEditMode) { lock (_enterPlayModeRestrictions) { if (_enterPlayModeRestrictions.Count == 0) { return; } EditorUtility.DisplayDialog("Change to Play Mode", "You can't switch to Play mode while AWS GameKit features are deploying or updating. See logs for more details.", "Ok"); foreach (var restrictionKvp in _enterPlayModeRestrictions) { Logging.Log(Logging.Level.WARNING, $"Cannot enter Play mode, {restrictionKvp.Value}"); } // Revert to Edit mode EditorApplication.isPlaying = false; } } } #endif /// <summary> /// Gets the deployment status of each AWS resource within the specified feature. /// </summary> /// <remarks> /// This is a long running operation.<br/><br/> /// /// Result status codes returned in the callback function (from GameKitErrors.cs):<br/> /// - GAMEKIT_SUCCESS: The API call was successful.<br/> /// - GAMEKIT_ERROR_CLOUDFORMATION_DESCRIBE_RESOURCE_FAILED: If status of the resources could not be determined. /// </remarks> /// <param name="feature">The GameKit feature to work with.</param> /// <param name="callback">Delegate that is called once this method completes. /// It contains the resource id, resource type, and resource status of each AWS resource within the specified feature. /// Additionally it contains the result status code for the call.</param> public void DescribeFeatureResources(FeatureType feature, Action<MultiResourceInfoCallbackResult> callback) { _threader.Call<MultiResourceInfoCallbackResult>(() => _coreWrapper.DeploymentOrchestratorDescribeFeatureResources(feature), callback); } } }
366
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.IO; using System.Threading; // Unity using UnityEditor; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Core { public class FeatureResourceManager : IDisposable { private static int _threadSafeCounter = 0; /// <summary> /// Provider for all needed GameKit paths. /// </summary> public IGameKitPathsProvider Paths; private AccountInfo _accountInfo = new AccountInfo() { AccountId = string.Empty, CompanyName = string.Empty, Environment = string.Empty, GameName = string.Empty }; private AccountCredentials _accountCredentials = new AccountCredentials(); private ICoreWrapperProvider _coreWrapper; private Threader _threader; private bool _disposedValue = false; public FeatureResourceManager(ICoreWrapperProvider coreWrapper, IGameKitPathsProvider gameKitPathsProvider, Threader threader) { _coreWrapper = coreWrapper; Paths = gameKitPathsProvider; _accountInfo.Environment = Constants.EnvironmentCodes.DEVELOPMENT; _threader = threader; } ~FeatureResourceManager() { Dispose(); _coreWrapper.AccountInstanceRelease(); } public void Dispose() { _threader.WaitForThreadedWork(); if (!_disposedValue) { _coreWrapper.SettingsInstanceRelease(); _disposedValue = true; } GC.SuppressFinalize(this); } /// <summary> /// Sets Game name and reinitializes settings. /// </summary> /// <param name="gameName">Name of the game.</param> public void SetGameName(string gameName) { _accountInfo.GameName = gameName; InitializeSettings(true); } /// <summary> /// Sets environment code and reinitializes settings. /// </summary> /// <param name="environment">Environment code in use.</param> public void SetEnvironment(string environment) { if (!string.IsNullOrEmpty(_accountInfo.GameName)) { _accountInfo.Environment = environment; InitializeSettings(true); } } /// <summary> /// Get the last used deployment environment or returns dev on failure. /// </summary> /// <returns>Deployment environment code.</returns> public string GetLastUsedEnvironment() { return _coreWrapper.SettingsGetLastUsedEnvironment(); } /// <summary> /// Get the last used deployment region or returns us-west-2 on failure. /// </summary> /// <returns>Deployment region.</returns> public string GetLastUsedRegion() { return _coreWrapper.SettingsGetLastUsedRegion(); } /// <summary> /// Populates accountInfo and accountCredentials. /// </summary> /// <param name="accountDetails">Account Details.</param> /// <returns>Deployment environment.</returns> public void SetAccountDetails(AccountDetails accountDetails) { _accountInfo = accountDetails.CreateAccountInfo(); _accountCredentials = accountDetails.CreateAccountCredentials(); InitializeSettings(true); } /// <summary> /// Gets the current account info variable stored in FeatureResourceManager. /// </summary> /// <returns>Account info that is currently stored in FeatureResourceManager.</returns> public AccountInfo GetAccountInfo() { return _accountInfo; } /// <summary> /// Gets the current account credentials variable stored in FeatureResourceManager. /// </summary> /// <returns>Account credentials that is currently stored in FeatureResourceManager.</returns> public AccountCredentials GetAccountCredentials() { return _accountCredentials; } /// <summary> /// Bootstrap account by creating appropriate S3 buckets. /// </summary> /// <returns>AWSGameKit result. /// GAMEKIT_SUCCESS : Bootstrap Account was successful. /// </returns> public uint BootstrapAccount() { _coreWrapper.AccountInstanceRelease(); _coreWrapper.AccountInstanceCreateWithRootPaths(_accountInfo, _accountCredentials, Paths.ASSETS_INSTANCE_FILES_FULL_PATH, Paths.PACKAGES_BASE_TEMPLATES_FULL_PATH, Logging.LogCb); uint result = _coreWrapper.AccountInstanceBootstrap(); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError(L10n.Tr($"Error: FeatureResourceManager::BootstrapAccount() Failed to create bucket. Error Code: { result }")); } return result; } /// <summary> /// Checks if the user's current account info is valid, does not permanently set accountDetails as that should only be done on submit. /// </summary> /// <param name="accountDetails">Account Details of the account we are checking for validity.</param> /// <returns></returns> public bool IsAccountInfoValid(AccountDetails accountDetails) { _coreWrapper.AccountInstanceRelease(); _coreWrapper.AccountInstanceCreateWithRootPaths(accountDetails.CreateAccountInfo(), accountDetails.CreateAccountCredentials(), Paths.ASSETS_INSTANCE_FILES_FULL_PATH, Paths.PACKAGES_BASE_TEMPLATES_FULL_PATH, Logging.LogCb); bool isAccountValid = _coreWrapper.AccountHasValidCredentials(); return isAccountValid; } /// <summary> /// Creates or Reinitializes settings instance handle. /// </summary> /// <param name="reinitialize">It determines if the settings instance should be reinitialized or not.</param> public void InitializeSettings(bool reinitialize) { if (reinitialize) { _coreWrapper.SettingsInstanceRelease(); } _coreWrapper.SettingsInstanceCreate(Paths.ASSETS_INSTANCE_FILES_FULL_PATH, GetPluginVersion(), _accountInfo.GameName, _accountInfo.Environment, Logging.LogCb); } /// <summary> /// Gets AWS GameKit plugin version. /// </summary> /// <returns>Plugin version.</returns> private string GetPluginVersion() { return "1.1"; } /// <summary> /// Add a custom deployment environment to the AWS GameKit settings menu. /// </summary> /// <remarks> /// This custom environment will be available to select from the dropdown menu in the Environment and Credentials section of the settings menu, /// alongside the default environments of "Development", "QA", "Staging", and "Production". /// </remarks> /// <param name="envCode">Two to Three letter code for the environment name. This code will be prefixed on all AWS resources that are /// deployed to this environment.Ex: "gam" for "Gamma".</param> /// <param name="envDescription">envDescription The environment name that will be displayed in the Environment and Credentials section of the settings menu. Ex: "Gamma".</param> public void SaveCustomEnvironment(string envCode, string envDescription) { _coreWrapper.SettingsAddCustomEnvironment(envCode, envDescription); uint result = _coreWrapper.SettingsSave(); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError(L10n.Tr($"Error: FeatureResourceManager.SaveCustomEnvironment() Failed to save : { GameKitErrors.ToString(result) }")); } } /// <summary> /// Get all of the feature's variables as key-value pairs. /// </summary> /// <param name="featureType">The feature to get the variables for.</param> /// <returns>A result object containing a map of variable key value pairs.</returns> public Dictionary<string, string> GetFeatureVariables(FeatureType featureType) { return _coreWrapper.SettingsGetFeatureVariables(featureType); } /// <summary> /// Get the value of the specified feature variable. /// </summary> /// <param name="featureType">The feature to get the variable for.</param> /// <param name="varName">The key for the variable.</param> /// <param name="varValue">When this method returns, contains the value of the feature variable, if the key is found; otherwise, an empty string. This parameter is passed in uninitialized.</param> /// <returns><c>true</c> if the feature variable exists; otherwise, <c>false</c>.</returns> public bool TryGetFeatureVariable(FeatureType featureType, string varName, out string varValue) { Dictionary<string, string> featureVars = GetFeatureVariables(featureType); return featureVars.TryGetValue(varName, out varValue); } /// <summary> /// Write a variable for a setting to the saveInfo.yml file if that variable is not already present. /// </summary> /// <remarks>This method will NOT overwrite an existing variable if present.</remarks> /// <param name="featureType">The feature that is using the variable pair.</param> /// <param name="varName">key for the variable.</param> /// <param name="varValue">value for the variable.</param> /// <param name="callback">callback that is executed once this method is complete, it is executed even if the new variables are saved.</param> public void SetFeatureVariableIfUnset(FeatureType featureType, string varName, string varValue, Action callback) { Dictionary<string, string> featureVars = GetFeatureVariables(featureType); if (!featureVars.ContainsKey(varName)) { SetFeatureVariable(featureType, varName, varValue, callback); return; } // call the callback to signify the completion of this method and return an empty job handle callback(); } /// <summary> /// Get AWS Account Id using the access and secret key. /// </summary> /// <param name="accountCredentials">Structure containing both the AWS Access Key and the AWS Secret Key.</param> /// <param name="callback">Callback that is executed once this method is complete, returning a string.</param> /// <returns>AWSGameKit Account Id.</returns> public void GetAccountId(GetAWSAccountIdDescription accountCredentials, Action<StringCallbackResult> callback) { _threader.Call(_coreWrapper.GetAWSAccountId, accountCredentials, callback); } /// <summary> /// Write a variable for a setting to the saveInfo.yml file. /// </summary> /// <remarks>This method will overwrite an existing variable if present.</remarks> /// <param name="featureType">The feature that is using the variable pair.</param> /// <param name="varName">key for the variable.</param> /// <param name="varValue">value for the variable.</param> /// <param name="callback">callback that is executed once this method is complete.</param> public void SetFeatureVariable(FeatureType featureType, string varName, string varValue, Action callback) { _coreWrapper.SettingsSetFeatureVariables(featureType, new string[] { varName }, new string[] { varValue }, 1); // Debounce our writes so we don't thresh on IO int currentValue = Interlocked.Increment(ref _threadSafeCounter); _threader.Call(() => { Thread.Sleep(3000); if (currentValue == Volatile.Read(ref _threadSafeCounter)) { _coreWrapper.SettingsSave(); Interlocked.Exchange(ref _threadSafeCounter, 0); } }, callback); } /// <summary> /// Write several variable at once to the saveInfo.yml file. /// </summary> /// <remarks>This method will overwrite an existing variable if present.</remarks> /// <param name="variables">IEnumerable of variables in the form Tuple<FeatureType, string, string> where Item1 is a FeatureType, Item2 is the variable name and Item3 is the variable value.</param> /// <param name="callback">callback that is executed once this method is complete.</param> public void SetFeatureVariables(IEnumerable<Tuple<FeatureType, string, string>> variables, Action callback) { foreach (var variableTuple in variables) { _coreWrapper.SettingsSetFeatureVariables(variableTuple.Item1, new string[] { variableTuple.Item2 }, new string[] { variableTuple.Item3 }, 1); } _coreWrapper.SettingsSave(); callback(); } /// <summary> /// Get all the custom environment key-value pairs (ex: "gam", "Gamma").<br/><br/> /// /// The custom environments are returned through the callback and receiver.<br/> /// The callback is invoked once for each custom environment.<br/> /// The returned keys are 3-letter environment codes(ex: "gam"), and the values are corresponding environment descriptions(ex: "Gamma"). /// </summary> /// <returns>A result object containing a map of environment key value pairs.</returns> public Dictionary<string, string> GetCustomEnvironments() { string settingsFile = Path.Combine(Paths.ASSETS_INSTANCE_FILES_FULL_PATH, _accountInfo.GameName, Paths.SAVE_INFO_FILE_NAME); FileInfo fileInfo = new FileInfo(settingsFile); if (fileInfo == null || fileInfo.Exists == false) { return new Dictionary<string, string>(); } return _coreWrapper.SettingsGetCustomEnvironments(); } /// <summary> /// Get the game's full name, example: "Stevie goes to the moon". /// </summary> /// <returns>A string containing the name of the game.</returns> public string GetGameName() { return _accountInfo.GameName.Length > 0 ? _accountInfo.GameName : _coreWrapper.SettingsGetGameName(); } /// <summary> /// Set the Game's name, environment, and region, then save settings. /// </summary> /// <remarks> /// Use this method to create the settings file directory, set the game's name, set the games environment, set the games region, and then persist the settings. /// </remarks> /// <returns>The result code of the operation. GAMEKIT_SUCCESS if successful, else a non-zero value in case of error. Consult errors.h file for details.</returns> public uint SaveSettings() { uint result = _coreWrapper.SettingsPopulateAndSave(_accountInfo.GameName, _accountInfo.Environment, _accountCredentials.Region); if (result != GameKitErrors.GAMEKIT_SUCCESS) { Logging.LogError(L10n.Tr($"Error: FeatureResourceManager.SaveSettings() Failed to save : { GameKitErrors.ToString(result) }")); } return result; } /// <summary> /// See ICoreWrapperProvider.ResourcesCreateEmptyConfigFile() for details. /// </summary> public uint CreateEmptyClientConfigFile() { _coreWrapper.ResourcesInstanceCreateWithRootPaths(_accountInfo, _accountCredentials, FeatureType.Main, Paths.ASSETS_INSTANCE_FILES_FULL_PATH, Paths.ASSETS_FULL_PATH, Logging.LogCb); uint result = _coreWrapper.ResourcesCreateEmptyConfigFile(); _coreWrapper.ResourcesInstanceRelease(); return result; } } }
383
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.IO; // Unity using UnityEngine; // GameKit using AWS.GameKit.Common; using AWS.GameKit.Editor.Utils; namespace AWS.GameKit.Editor.FileStructure { /// <summary> /// Gives access to the assets stored in the "com.amazonaws.gamekit/Editor/Resources" folder. /// </summary> public static class EditorResources { public static class Textures { private const string TEXTURES = "Textures/"; public static readonly IGettable<Texture> WindowIcon = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "WindowIcon-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "WindowIcon-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> FeatureStatusSuccess = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "FeatureStatus-Success.png").Replace("\\","/")); public static readonly IGettable<Texture> FeatureStatusError = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "FeatureStatus-Error.png").Replace("\\","/")); public static readonly IGettable<Texture> FeatureStatusWorking = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "FeatureStatus-Working.png").Replace("\\","/")); public static readonly IGettable<Texture> FeatureStatusRefresh = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "FeatureStatus-Refresh.png").Replace("\\","/")); public static readonly IGettable<Texture> FeatureStatusWaiting = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "FeatureStatus-Waiting.png").Replace("\\","/")); public static readonly IGettable<Texture> Unsynchronized = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "unsynchronized.png").Replace("\\","/")); public static class Colors { private const string COLORS = TEXTURES + "Colors/"; public static readonly IGettable<Texture> Transparent = new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, TEXTURES, "Transparent.png").Replace("\\","/")); public static readonly IGettable<Texture2D> GUILayoutDivider = new LazyLoadedEditorThemeAwareResource<Texture2D>( Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, COLORS, "GUILayoutDivider-Dark.png").Replace("\\","/"), Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, COLORS, "GUILayoutDivider-Light.png").Replace("\\","/")); } public static class SettingsWindow { private const string SETTINGS_TEXTURES = TEXTURES + "SettingsWindow/"; public static readonly IGettable<Texture> ExternalLinkIcon = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "ExternalLink-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "ExternalLink-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> PlusIcon = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "PlusIcon-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "PlusIcon-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> MinusIcon = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "MinusIcon-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, SETTINGS_TEXTURES, "MinusIcon-Light.png").Replace("\\","/"))); } public static class QuickAccessWindow { private const string QUICK_ACCESS_TEXTURES = TEXTURES + "QuickAccessWindow/"; private const string QUICK_ACCESS_COLORS = QUICK_ACCESS_TEXTURES + "Colors/"; // Feature Icons: public static readonly IGettable<Texture> FeatureIconAchievements = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-Achievements-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-Achievements-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> FeatureIconGameStateCloudSaving = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-GameStateCloudSaving-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-GameStateCloudSaving-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> FeatureIconIdentity = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-Identity-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-Identity-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture> FeatureIconUserGameplayData = new LazyLoadedEditorThemeAwareResource<Texture>( new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-UserGameplayData-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_TEXTURES, "FeatureIcon-UserGameplayData-Light.png").Replace("\\","/"))); public static class Colors { public static readonly IGettable<Texture2D> QuickAccessBackground = new LazyLoadedEditorThemeAwareResource<Texture2D>( new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-Background-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-Background-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture2D> QuickAccessButtonNormal = new LazyLoadedEditorThemeAwareResource<Texture2D>( new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-ButtonNormal-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-ButtonNormal-Light.png").Replace("\\","/"))); public static readonly IGettable<Texture2D> QuickAccessButtonHover = new LazyLoadedEditorThemeAwareResource<Texture2D>( new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-ButtonHover-Dark.png").Replace("\\","/")), new LazyLoadedResource<Texture2D>(Path.Combine(GameKitPaths.Get().PACKAGES_EDITOR_RESOURCES_RELATIVE_PATH, QUICK_ACCESS_COLORS, "QuickAccessWindow-ButtonHover-Light.png").Replace("\\","/"))); } } } } }
109
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; using UnityEngine; namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// Common GUIStyles used throughout AWS GameKit. /// </summary> public static class CommonGUIStyles { public const int PIXELS_PER_INDENTATION_LEVEL = 20; public const int DEFAULT_PIXELS_LEFT_MARGIN = 4; public const float INLINE_ICON_SIZE = 12; /// <summary> /// Create a copy of the provided GUIStyle which has the requested level of indentation. /// </summary> /// <param name="style">The GUIStyle to copy.</param> /// <param name="indentationLevel">The level of indentation to set.</param> /// <param name="pixelsPerIndentationLevel">The number of pixels in each indentation level.</param> /// <returns>A copy of the provided GUIStyle.</returns> public static GUIStyle SetIndentationLevel(GUIStyle style, int indentationLevel, int pixelsPerIndentationLevel = PIXELS_PER_INDENTATION_LEVEL) { // When provided with a left margin of 0, the following element will be misaligned. // Use the default pixel value instead, which will ensure alignment of all fields. int leftMargin = indentationLevel == 0 ? DEFAULT_PIXELS_LEFT_MARGIN : indentationLevel * pixelsPerIndentationLevel; return new GUIStyle(style) { margin = new RectOffset(leftMargin, style.margin.right, style.margin.top, style.margin.bottom) }; } /// <summary> /// Create a copy of the provided GUIStyle which has the requested content offset added to the existing content offset. /// </summary> /// <param name="originalStyle">The GUIStyle to copy.</param> /// <param name="addedContentOffset">The content offset to add to the existing content offset.</param> /// <returns>A copy of the provided GUIStyle.</returns> public static GUIStyle AddContentOffset(GUIStyle originalStyle, Vector2 addedContentOffset) { return new GUIStyle(originalStyle) { contentOffset = new Vector2( originalStyle.contentOffset.x + addedContentOffset.x, originalStyle.contentOffset.y + addedContentOffset.y ) }; } public static readonly GUIStyle SectionHeader = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold, wordWrap = true }; public static readonly GUIStyle SectionHeaderWithDescription = new GUIStyle(EditorStyles.label) { wordWrap = true, richText = true }; public static readonly GUIStyle Description = new GUIStyle(EditorStyles.label) { wordWrap = true, richText = true }; public static readonly GUIStyle PlaceholderLabel = new GUIStyle(EditorStyles.label) { padding = new RectOffset(4, 0, 0, 0) }; public static readonly GUIStyle PlaceholderTextArea = new GUIStyle(EditorStyles.textArea) { padding = new RectOffset(4, 0, 0, 0) }; public static readonly GUIStyle InputLabel = new GUIStyle(EditorStyles.label) { margin = new RectOffset(PIXELS_PER_INDENTATION_LEVEL, 10, EditorStyles.label.margin.top, EditorStyles.label.margin.bottom), wordWrap = true, }; public static readonly GUIStyle DeploymentStatus = new GUIStyle(GUI.skin.label) { imagePosition = ImagePosition.ImageLeft, alignment = TextAnchor.MiddleCenter, clipping = TextClipping.Overflow, stretchHeight = true, fontSize = 16, margin = new RectOffset(0, 11, 0, 0), padding = new RectOffset(0, 0, 0, 0), }; public static readonly GUIStyle DeploymentStatusIcon = new GUIStyle(DeploymentStatus) { fixedWidth = INLINE_ICON_SIZE, fixedHeight = INLINE_ICON_SIZE, margin = new RectOffset(0, 0, 0, 0), contentOffset = new Vector2(0, 3), }; public static readonly GUIStyle DeploymentStatusText = new GUIStyle(DeploymentStatus) { fontSize = GUI.skin.label.fontSize, fontStyle = GUI.skin.label.fontStyle, margin = new RectOffset(5, 5, 0, 0), }; public static readonly GUIStyle RefreshIcon = new GUIStyle(DeploymentStatus) { fixedWidth = INLINE_ICON_SIZE, fixedHeight = INLINE_ICON_SIZE, contentOffset = new Vector2(0, 3), margin = new RectOffset(10, 0, 0, 0), }; public static readonly float SpaceBetweenSections = 20f; public static readonly GUIStyle UserLoginButtonStyle = new GUIStyle() { margin = new RectOffset(0, 0, 5, 5) }; public static readonly Color ErrorRed = new Color(0.851f, 0.082f, 0.082f, 1f); } }
136
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.Windows.Settings; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// Provides new types of GUI elements for Unity's EditorGUILayout class. /// /// See: https://docs.unity3d.com/ScriptReference/EditorGUILayout.html /// </summary> public static class EditorGUILayoutElements { private const string INFO_ICON_ID = "console.infoicon"; // Icon ids provided by Unity that can be retrieved with EditorGUIUtility.IconContent private const string EMPTY_PREFIX_SPACE = " "; // If we use string.Empty, the prefix label won't take up any space in the layout - use a single space instead private const int HELP_ICON_HEIGHT = 35; private const int OVERRIDE_SLIDER_TEXT_WIDTH = 50; private static string SELECT_FILE = L10n.Tr("Select file"); /// <summary> /// Make a vertical divider.<br/> /// /// A vertical divider is a thin line used to separate two sections inside an <c>EditorGUILayout.BeginHorizontal()</c> and <c>EditorGUILayout.EndHorizontal()</c> block.<br/><br/> /// /// The divider color changes automatically when the user changes their Editor Theme between dark and light mode. /// </summary> /// <param name="width">The width of the divider line.</param> /// <param name="verticalPadding">The amount of padding around the top and bottom of the divider line.</param> public static void VerticalDivider(float width = 1f, int verticalPadding = 0) { GUIStyle lineStyle = new GUIStyle { fixedWidth = width, stretchHeight = true, stretchWidth = false, margin = new RectOffset(0, 0, verticalPadding, verticalPadding), normal = { background = EditorResources.Textures.Colors.GUILayoutDivider.Get() } }; GUILayout.Box(GUIContent.none, lineStyle); } /// <summary> /// Make a horizontal divider.<br/> /// /// A horizontal divider is a thin line used to separate two sections inside an <c>EditorGUILayout.BeginVertical()</c> and <c>EditorGUILayout.EndVertical()</c> block.<br/><br/> /// /// The divider color changes automatically when the user changes their Editor Theme between dark and light mode. /// </summary> /// <param name="height">The height of the divider line.</param> /// <param name="verticalPadding">The amount of padding around the top and bottom of the divider line.</param> public static void HorizontalDivider(float height = 1f, int verticalPadding = 0) { GUIStyle lineStyle = new GUIStyle { fixedHeight = height, stretchHeight = false, stretchWidth = true, margin = new RectOffset(0, 0, verticalPadding, verticalPadding), normal = { background = EditorResources.Textures.Colors.GUILayoutDivider.Get() } }; GUILayout.Box(GUIContent.none, lineStyle); } /// <summary> /// Creates a toolbar that persists which tab of the toolbar is selected across sessions. /// </summary> /// <param name="selectedTabId">A reference to the selectedTabId that is used to determine which tab should be draw in DrawTabContent.</param> /// <param name="tabNames">The names of the tabs that should be added to the toolbar.</param> /// <param name="tabSelectorButtonSize">Determines how the toolbar buttons will be sized.</param> /// <param name="tabSelectorStyle">The style of the toolbar.</param> public static int CreateFeatureToolbar(int selectedTabId, string[] tabNames, GUI.ToolbarButtonSize tabSelectorButtonSize, GUIStyle tabSelectorStyle) { return GUILayout.Toolbar(selectedTabId, tabNames, tabSelectorStyle, tabSelectorButtonSize); } /// <summary> /// Make a help box with a similar style to Unity's default help box, except this help box has a read more link. /// </summary> /// <param name="message">The message that should be displayed in the help box.</param> /// <param name="url">The url that the read more link should redirect to.</param> public static void HelpBoxWithReadMore(string message, string url) { LinkWidget.Options options = new LinkWidget.Options() { OverallStyle = SettingsGUIStyles.Page.CustomHelpBoxText, ContentOffset = new Vector2( x: -4, y: -4 ), Alignment = LinkWidget.Alignment.Right }; LinkWidget _readMoreLinkWidget = new LinkWidget(L10n.Tr("Read more"), url, options); using (EditorGUILayout.HorizontalScope horizontalScope = new EditorGUILayout.HorizontalScope(EditorStyles.helpBox)) { Rect helpBoxRect = horizontalScope.rect; using (new EditorGUILayout.VerticalScope()) { GUIStyle style = new GUIStyle(); float centeredContentOffset = (helpBoxRect.height - HELP_ICON_HEIGHT)/2 - 1; style.contentOffset = new Vector2(0, centeredContentOffset); GUILayout.Box(EditorGUIUtility.IconContent(INFO_ICON_ID).image, style, GUILayout.Height(HELP_ICON_HEIGHT)); } using (new EditorGUILayout.VerticalScope()) { EditorGUILayout.LabelField(message, SettingsGUIStyles.Page.CustomHelpBoxText); using (new EditorGUILayout.HorizontalScope()) { _readMoreLinkWidget.OnGUI(); } } } } /// <summary> /// Make a GUI element that is tinted with a color.<br/><br/> /// /// Use this when you need to change the color of a GUI element without changing it's <c>GUIStyle</c>. /// </summary> /// <param name="color">The color to tint the GUI element.</param> /// <param name="createElement">A callback function which creates the GUI element.</param> public static void TintedElement(Color color, Action createElement) { Color originalBackgroundColor = GUI.backgroundColor; GUI.backgroundColor = color; createElement(); GUI.backgroundColor = originalBackgroundColor; } /// <summary> /// Make a GUI element that is tinted with a color.<br/><br/> /// /// Use this when you need to change the color of a GUI element without changing it's <c>GUIStyle</c>. /// </summary> /// <typeparam name="T">The return type of the <c>createElement()</c> callback function.</typeparam> /// <param name="color">The color to tint the GUI element.</param> /// <param name="createElement">A callback function which creates the GUI element.</param> /// <returns>The return value of the <c>createElement()</c> callback function. This should be the new value entered by the user in the GUI element.</returns> public static T TintedElement<T>(Color color, Func<T> createElement) { Color originalBackgroundColor = GUI.backgroundColor; GUI.backgroundColor = color; T result = createElement(); GUI.backgroundColor = originalBackgroundColor; return result; } /// <summary> /// Make a stylized single press button that can be colored and disabled. /// </summary> /// <param name="text">The text to display on the button.</param> /// <param name="isEnabled">Whether the button is enabled or not. By default the button is enabled.</param> /// <param name="tooltip">The tooltip to display on the button. By default no tooltip is displayed.</param> /// <param name="colorWhenEnabled">The color to make the button when it is enabled. By default the button is Unity's default button color (grey). The button is grey when disabled.</param> /// <param name="image">An image to display before the text. By default no image is displayed.</param> /// <param name="imageSize">The size to make the image. By default the image is be drawn at it's full size (i.e. not scaled).</param> /// <param name="minWidth">Custom value for the minimum width of the button, if not provided then a common default is used.</param> /// <returns>True when the user clicks the button.</returns> public static bool Button( string text, bool isEnabled = true, string tooltip = "", Nullable<Color> colorWhenEnabled = null, Texture image = null, Nullable<Vector2> imageSize = null, float minWidth = SettingsGUIStyles.Buttons.MIN_WIDTH_NORMAL) { Vector2 finalImageSize = imageSize ?? EditorGUIUtility.GetIconSize(); GUIContent buttonContent = new GUIContent(text, image, tooltip); using (new EditorGUIUtility.IconSizeScope(finalImageSize)) { using (new EditorGUI.DisabledScope(!isEnabled)) { if (isEnabled && colorWhenEnabled.HasValue) { return TintedElement(colorWhenEnabled.Value, () => GUILayout.Button(buttonContent, SettingsGUIStyles.Buttons.ColoredButtonNormal, GUILayout.MinWidth(minWidth))); } else { return GUILayout.Button(buttonContent, SettingsGUIStyles.Buttons.GreyButtonNormal, GUILayout.MinWidth(minWidth)); } } } } /// <summary> /// Make a stylized single press button, that is half the size of normal buttons, that can be colored and disabled. /// </summary> /// <param name="text">The text to display on the button.</param> /// <param name="isEnabled">Whether the button is enabled or not. By default the button is enabled.</param> /// <param name="tooltip">The tooltip to display on the button. By default no tooltip is displayed.</param> /// <param name="colorWhenEnabled">The color to make the button when it is enabled. By default the button is Unity's default button color (grey). The button is grey when disabled.</param> /// <param name="image">An image to display before the text. By default no image is displayed.</param> /// <param name="imageSize">The size to make the image. By default the image is be drawn at it's full size (i.e. not scaled).</param> /// <param name="minWidth">Custom value for the minimum width of the button, if not provided then a common default is used.</param> /// <returns>True when the user clicks the button.</returns> public static bool SmallButton( string text, bool isEnabled = true, string tooltip = "", Nullable<Color> colorWhenEnabled = null, Texture image = null, Nullable<Vector2> imageSize = null, float minWidth = SettingsGUIStyles.Buttons.MIN_WIDTH_SMALL) { Vector2 finalImageSize = imageSize ?? EditorGUIUtility.GetIconSize(); GUIContent buttonContent = new GUIContent(text, image, tooltip); using (new EditorGUIUtility.IconSizeScope(finalImageSize)) { using (new EditorGUI.DisabledScope(!isEnabled)) { if (isEnabled && colorWhenEnabled.HasValue) { return TintedElement(colorWhenEnabled.Value, () => GUILayout.Button(buttonContent, SettingsGUIStyles.Buttons.ColoredButtonSmall, GUILayout.MinWidth(minWidth))); } else { return GUILayout.Button(buttonContent, SettingsGUIStyles.Buttons.GreyButtonSmall, GUILayout.MinWidth(minWidth)); } } } } /// <summary> /// Make a section header. /// </summary> /// <param name="title">The string to display.</param> /// <param name="indentationLevel">The level of indentation to place in front of the title.</param> /// <param name="textAnchor">Where to anchor the text.</param> public static void SectionHeader(string title, int indentationLevel = 0, TextAnchor textAnchor = TextAnchor.MiddleLeft) { GUIStyle headerStyle = CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.SectionHeader, indentationLevel); headerStyle.alignment = textAnchor; EditorGUILayout.LabelField(title, headerStyle); } /// <summary> /// Make a section header with a description on the same line. The text is formatted as <c>Title: Description</c> with <c>Title</c> in bold. /// </summary> /// <param name="title">The title string to display in bold.</param> /// <param name="description">The description string to display after the title and colon.</param> /// <param name="indentationLevel">The level of indentation to place in front of the title.</param> /// <param name="textAnchor">Where to anchor the text.</param> public static void SectionHeaderWithDescription(string title, string description, int indentationLevel = 0, TextAnchor textAnchor = TextAnchor.MiddleLeft) { GUIStyle headerStyle = CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.SectionHeaderWithDescription, indentationLevel); headerStyle.alignment = textAnchor; string text = $"<b>{title}:</b> {description}"; EditorGUILayout.LabelField(text, headerStyle); } /// <summary> /// Make a vertical gap between the previous and next GUI sections. /// </summary> /// <param name="extraPixels">Number of additional pixels to add/subtract from the gap.</param> public static void SectionSpacer(float extraPixels = 0) { EditorGUILayout.Space(CommonGUIStyles.SpaceBetweenSections + extraPixels); } /// <summary> /// Make a horizontal line to divide two sections. /// </summary> public static void SectionDivider() { SectionSpacer(extraPixels: -10); HorizontalDivider(); SectionSpacer(extraPixels: -10); } /// <summary> /// Make a prefix label for a user input. /// </summary> /// <param name="inputLabel">The string to display.</param> /// <param name="indentationLevel">The level of indentation to place in front of the prefix label.</param> public static void PrefixLabel(string inputLabel, int indentationLevel = 1) { GUIStyle labelStyle = CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.InputLabel, indentationLevel); EditorGUILayout.PrefixLabel(inputLabel, labelStyle, labelStyle); KeepPreviousPrefixLabelEnabled(); } /// <summary> /// Make a custom field. /// </summary> /// <param name="inputLabel">A string to display before the custom field.</param> /// <param name="createField">A callback function which creates the field.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <param name="guiStyle">Used to add a custom GUIStyle, else defaults to EditorStyles.textArea</param> public static void CustomField(string inputLabel, Action createField, int indentationLevel = 1, bool isEnabled = true, GUIStyle guiStyle = null) { GUIStyle labelStyle = CommonGUIStyles.SetIndentationLevel(guiStyle ?? CommonGUIStyles.InputLabel, indentationLevel); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel(inputLabel, labelStyle); KeepPreviousPrefixLabelEnabled(); using (new EditorGUI.DisabledScope(!isEnabled)) { createField(); } } } /// <summary> /// Make a custom field and temporarily override the labelWidth variable in the editor. /// </summary> /// <param name="inputLabel">A string to display before the custom field.</param> /// <param name="labelWidth">A float that will override EditorGUIUtility.labelWidth for the life of this method.</param> /// <param name="createField">A callback function which creates the field.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <param name="guiStyle">Used to add a custom GUIStyle, else defaults to EditorStyles.textArea</param> public static void CustomField(string inputLabel, float labelWidth, Action createField, int indentationLevel = 1, bool isEnabled = true, GUIStyle guiStyle = null) { float originalLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = labelWidth; CustomField(inputLabel, createField, indentationLevel, isEnabled, guiStyle); EditorGUIUtility.labelWidth = originalLabelWidth; } /// <summary> /// Make a custom field. /// </summary> /// <typeparam name="T">The type of data the field contains.</typeparam> /// <param name="inputLabel">A string to display before the custom field.</param> /// <param name="createField">A callback function which creates the field and returns the field's new value.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <param name="guiStyle">Used to add a custom GUIStyle, else defaults to EditorStyles.textArea</param> /// <returns>The field's new value entered by the user.</returns> public static T CustomField<T>(string inputLabel, Func<T> createField, int indentationLevel = 1, bool isEnabled = true, GUIStyle guiStyle = null) { GUIStyle labelStyle = CommonGUIStyles.SetIndentationLevel(guiStyle ?? CommonGUIStyles.InputLabel, indentationLevel); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel(inputLabel, labelStyle, labelStyle); KeepPreviousPrefixLabelEnabled(); using (new EditorGUI.DisabledScope(!isEnabled)) { return createField(); } } } /// <summary> /// Make a text input field. /// </summary> /// <param name="inputLabel">A string to display before the text input area.</param> /// <param name="currentText">The current text in the text input area.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="placeholderText">Optional placeholder text to display when the input field is empty.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The text entered by the user.</returns> public static string TextField(string inputLabel, string currentText, int indentationLevel = 1, string placeholderText = "", bool isEnabled = true) { return CustomField(inputLabel, () => { string newText = EditorGUILayout.TextField(currentText); if (!String.IsNullOrEmpty(placeholderText) && String.IsNullOrEmpty(newText)) { DisplayPlaceholderTextOverLastField(placeholderText); } return newText; }, indentationLevel, isEnabled); } /// <summary> /// Make a text input area that handles multiple lines. /// </summary> /// <param name="inputLabel">A string to display before the text input area.</param> /// <param name="currentText">The current text in the text input area.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="placeholderText">Optional placeholder text to display when the input field is empty.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <param name="labelGuiStyle">Used to add a custom GUIStyle to the fields label, else defaults to CommonGUIStyles.InputLabel</param> /// <param name="textAreaGuiStyle">Used to add a custom GUIStyle to the text area, else defaults to EditorStyles.textArea</param> /// <param name="options">(Optional) Additional GUILayout params to apply to the text area.</param> /// <returns>The text entered by the user.</returns> public static string DescriptionField( string inputLabel, string currentText, int indentationLevel = 1, string placeholderText = "", bool isEnabled = true, GUIStyle labelGuiStyle = null, GUIStyle textAreaGuiStyle = null, params GUILayoutOption[] options) { return CustomField(inputLabel, () => { string newText = EditorGUILayout.TextArea(currentText, textAreaGuiStyle ?? EditorStyles.textArea, options); if (!String.IsNullOrEmpty(placeholderText) && String.IsNullOrEmpty(newText)) { using (new EditorGUI.DisabledScope(true)) { EditorGUI.TextArea(GUILayoutUtility.GetLastRect(), placeholderText, CommonGUIStyles.PlaceholderTextArea); } } return newText; }, indentationLevel, isEnabled, labelGuiStyle); } /// <summary> /// Make a key-value dictionary field that will display a list of keys and a list of values. /// </summary> /// <typeparam name="K">The type of the key List. This type must be serializable.</typeparam> /// <typeparam name="V">The type of the value List. This type must be serializable.</typeparam> /// <param name="serializedKeysListProperty">The serialized property corresponding to the keys list.</param> /// <param name="serializedValuesListProperty">The serialized property corresponding to the values list.</param> /// <param name="keysList">The list of keys to be drawn.</param> /// <param name="valuesList">The list of values to be drawn.</param> /// <param name="keysLabel">The label that should be shown above the list of keys.</param> /// <param name="valuesLabel">The label that should be shown above the list of values.</param> /// <param name="isReadonly">Optional field is set to true if the GUI should be disabled for typing into and the options to add. Subtract fields will also be removed if isReadonly is true.</param> /// <param name="paddingBetweenKeyAndValue">When true, allows editing of the dictionary.</param> /// <param name="paddingBetweenPairs">Optional field for adding spacing between each pair in a vertical section.</param> public static void SerializableExamplesDictionary<K,V>( SerializedProperty serializedKeysListProperty, SerializedProperty serializedValuesListProperty, List<K> keysList, List<V> valuesList, string keysLabel, string valuesLabel, bool isReadonly = false, int paddingBetweenKeyAndValue = 2, int paddingBetweenPairs = 4) { using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.FeatureExamplesTab.DictionaryKeyValues)) { EditorGUILayout.LabelField(keysLabel, GUILayout.MinWidth(0)); EditorGUILayout.LabelField(valuesLabel, GUILayout.MinWidth(0)); if (!isReadonly) { GUILayout.Space(CommonGUIStyles.INLINE_ICON_SIZE); } } using (new EditorGUI.DisabledScope(isReadonly)) { using (new EditorGUILayout.VerticalScope()) { for (int i = 0; i < serializedKeysListProperty.arraySize; i++) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PropertyField(serializedKeysListProperty.GetArrayElementAtIndex(i), GUIContent.none); GUILayout.Space(paddingBetweenKeyAndValue); EditorGUILayout.PropertyField(serializedValuesListProperty.GetArrayElementAtIndex(i), GUIContent.none); if (!isReadonly) { using (new EditorGUI.DisabledScope(serializedKeysListProperty.arraySize <= 1)) { GUILayout.Box(EditorResources.Textures.SettingsWindow.MinusIcon.Get(), SettingsGUIStyles.Icons.InlineIcons); Rect minusButtonRect = GUILayoutUtility.GetLastRect(); // Create a button with no text but spans the length of both the icon created above if (GUI.Button(minusButtonRect, "", GUIStyle.none)) { keysList.RemoveAt(i); valuesList.RemoveAt(i); } if (serializedKeysListProperty.arraySize > 1) { EditorGUIUtility.AddCursorRect(minusButtonRect, MouseCursor.Link); } } } } GUILayout.Space(paddingBetweenPairs); } } if (!isReadonly) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.Box(EditorResources.Textures.SettingsWindow.PlusIcon.Get(), SettingsGUIStyles.Icons.NormalSize); Rect plusButtonRect = GUILayoutUtility.GetLastRect(); // Create a button with no text but spans the length of both the icon created above if (GUI.Button(plusButtonRect, "", GUIStyle.none)) { keysList.Add(default); valuesList.Add(default); } EditorGUIUtility.AddCursorRect(plusButtonRect, MouseCursor.Link); GUILayout.FlexibleSpace(); } EditorGUILayout.Space(5); } } } /// <summary> /// Creates a UI element that will display a list in the same style as the SerializableExamplesDictionary /// </summary> /// <param name="serializedListProperty">The serialized property corresponding to the keys list.</param> /// <param name="list">The list of values to be drawn.</param> /// <param name="label">The label that should be shown above the list of keys.</param> /// <param name="isReadonly">When true, allows editing of the list.</param> /// <param name="paddingBetweenElements">Optional field for adding spacing between each element in a vertical section.</param> public static void SerializableExamplesList<T>( SerializedProperty serializedListProperty, List<T> list, string label, bool isReadonly = false, int paddingBetweenElements = 4) { using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.FeatureExamplesTab.DictionaryKeyValues)) { EditorGUILayout.LabelField(label, GUILayout.MinWidth(0)); if (!isReadonly) { GUILayout.Space(CommonGUIStyles.INLINE_ICON_SIZE); } } using (new EditorGUI.DisabledScope(isReadonly)) { using (new EditorGUILayout.VerticalScope()) { for (int i = 0; i < serializedListProperty.arraySize; i++) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PropertyField(serializedListProperty.GetArrayElementAtIndex(i), GUIContent.none); if (!isReadonly) { using (new EditorGUI.DisabledScope(serializedListProperty.arraySize <= 1)) { GUILayout.Box(EditorResources.Textures.SettingsWindow.MinusIcon.Get(), SettingsGUIStyles.Icons.InlineIcons); Rect minusButtonRect = GUILayoutUtility.GetLastRect(); // Create a button with no text but spans the length of both the icon created above if (GUI.Button(minusButtonRect, "", GUIStyle.none)) { list.RemoveAt(i); } if (serializedListProperty.arraySize > 1) { EditorGUIUtility.AddCursorRect(minusButtonRect, MouseCursor.Link); } } } } GUILayout.Space(paddingBetweenElements); } } if (!isReadonly) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.Box(EditorResources.Textures.SettingsWindow.PlusIcon.Get(), SettingsGUIStyles.Icons.NormalSize); Rect plusButtonRect = GUILayoutUtility.GetLastRect(); // Create a button with no text but spans the length of both the text and the icon if (GUI.Button(plusButtonRect, "", GUIStyle.none)) { list.Add(default); } EditorGUIUtility.AddCursorRect(plusButtonRect, MouseCursor.Link); GUILayout.FlexibleSpace(); } EditorGUILayout.Space(5); } } } /// <summary> /// Make a label field. Useful for displaying read only information. /// </summary> /// <param name="labelKey">A string to display in the label key (left) field.</param> /// <param name="labelValue">A string to display in the label value (right) field.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label key.</param> public static void LabelField(string labelKey, string labelValue, int indentationLevel = 1) { CustomField(labelKey, () => EditorGUILayout.LabelField(labelValue), indentationLevel); } /// <summary> /// Make a password input field. All characters entered are displayed as '*'. /// </summary> /// <param name="inputLabel">A string to display before the password input area.</param> /// <param name="currentPassword">The current password in the password input area.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="placeholderText">Optional placeholder text to display when the input field is empty.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The password entered by the user.</returns> public static string PasswordField(string inputLabel, string currentPassword, int indentationLevel = 1, string placeholderText = "", bool isEnabled = true) { return CustomField(inputLabel, () => { string newPassword = EditorGUILayout.PasswordField(currentPassword); if (!String.IsNullOrEmpty(placeholderText) && String.IsNullOrEmpty(newPassword)) { DisplayPlaceholderTextOverLastField(placeholderText); } return newPassword; }, indentationLevel, isEnabled); } /// <summary> /// Make a property field. /// </summary> /// <param name="inputLabel">A string to display before the property input area.</param> /// <param name="property">The serialized property to edit.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="placeholderText">Optional placeholder text to display when the input field is empty.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <param name="options">(Optional) Additional GUILayout params to apply to the field.</param> public static void PropertyField(string inputLabel, SerializedProperty property, int indentationLevel = 1, string placeholderText = "", bool isEnabled = true, params GUILayoutOption[] options) { CustomField(inputLabel, () => { EditorGUILayout.PropertyField(property, GUIContent.none, options); if (!String.IsNullOrEmpty(placeholderText) && String.IsNullOrEmpty(property.stringValue)) { DisplayPlaceholderTextOverLastField(placeholderText); } }, indentationLevel, isEnabled); } /// <summary> /// Make a description field. /// </summary> /// <param name="description">The description to display.</param> /// <param name="indentationLevel">The level of indentation to place in front of the description.</param> /// <param name="textAnchor">Where to anchor the text.</param> public static void Description(string description, int indentationLevel = 1, TextAnchor textAnchor = TextAnchor.MiddleLeft) { GUIStyle descriptionStyle = CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.Description, indentationLevel); descriptionStyle.alignment = textAnchor; descriptionStyle.wordWrap = true; EditorGUILayout.LabelField(description, descriptionStyle); } public static void ErrorText(string error, int indentationLevel = 1) { GUIStyle errorStyle = CommonGUIStyles.SetIndentationLevel(CommonGUIStyles.Description, indentationLevel); errorStyle.normal.textColor = CommonGUIStyles.ErrorRed; EditorGUILayout.LabelField(error, errorStyle); } /// <summary> /// Make an on/off toggle field. /// </summary> /// <param name="inputLabel">A string to display before the toggle field.</param> /// <param name="currentValue">The current value of the toggle field.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The new value of the toggle field.</returns> public static bool ToggleField(string inputLabel, bool currentValue, int indentationLevel = 1, bool isEnabled = true) { return CustomField(inputLabel, () => { bool newValue = GUILayout.Toggle(currentValue, string.Empty); // Make the toggle field only be selectable when the mouse is directly on it, rather than anywhere on it's row. // Otherwise, the user can accidentally toggle this field without knowing it. GUILayout.FlexibleSpace(); return newValue; }, indentationLevel, isEnabled); } /// <summary> /// Make an on/off toggle with a label to the left of the checkbox. /// </summary> /// <param name="inputLabel">A string to display before after the checkbox.</param> /// <param name="currentValue">The current value of the toggle.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The new value of the toggle.</returns> public static bool ToggleLeft(string inputLabel, bool currentValue, bool isEnabled = true) { using (new EditorGUI.DisabledScope(!isEnabled)) { float originalLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = GUI.skin.label.CalcSize(new GUIContent(inputLabel)).x; bool result = EditorGUILayout.ToggleLeft(inputLabel, currentValue); EditorGUIUtility.labelWidth = originalLabelWidth; return result; } } /// <summary> /// Make an int slider field. /// </summary> /// <param name="inputLabel">A string to display before the int slider field.</param> /// <param name="currentValue">The current value of the slider.</param> /// <param name="minValue">The minimum value of the slider.</param> /// <param name="maxValue">The maximum value of the slider.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The new value of the int slider.</returns> public static int IntSlider(string inputLabel, int currentValue, int minValue, int maxValue, int indentationLevel = 1, bool isEnabled = true) { return CustomField(inputLabel, () => { return EditorGUILayout.IntSlider(currentValue, minValue, maxValue); }, indentationLevel, isEnabled); } /// <summary> /// Make a slider that allows a user to override the min or max by using the text field value. /// </summary> /// <param name="inputLabel">A string to display before the int slider field.</param> /// <param name="currentValue">The current value of the slider.</param> /// <param name="minValue">The minimum value of the slider.</param> /// <param name="maxValue">The maximum value of the slider.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and and non-interactable.</param> /// <returns>The new value of the int slider.</returns> public static int OverrideSlider(string inputLabel, int currentValue, int minValue, int maxValue, int indentationLevel = 1, bool isEnabled = true) { return CustomField(inputLabel, () => { float sliderValue = GUILayout.HorizontalSlider(currentValue, minValue, maxValue); float finalValue = sliderValue; string textValue = GUILayout.TextField(finalValue.ToString(), GUILayout.Width(OVERRIDE_SLIDER_TEXT_WIDTH)); if (!float.TryParse(textValue, out finalValue)) { finalValue = string.IsNullOrEmpty(textValue) ? minValue : sliderValue; } return (int)finalValue; }, indentationLevel, isEnabled); } /// <summary> /// Make a text field that can also be populated by a file selector, accessible via an inline button. /// </summary> /// <param name="inputLabel">A string to display before the text field and file selector button.</param> /// <param name="currentValue">The current value of the text field.</param> /// <param name="filePanelTitle">The title of the file selection panel.</param> /// <param name="fileExtension">The file extension which can be selected.</param> /// <param name="indentationLevel">The level of indentation to place in front of the label.</param> /// <param name="isEnabled">When set to false, the input field will be greyed-out and non-interactable.</param> /// <param name="openingFile">Whether to open a file selection screen that opens existing files, or lets you enter the name of a non-existing file.</param> /// <returns>The new value of the text field.</returns> public static string FileSelection(string inputLabel, string currentValue, string filePanelTitle, string fileExtension = "*", int indentationLevel = 1, bool isEnabled = true, bool openingFile = true) { CustomField(inputLabel, () => { using (new EditorGUILayout.HorizontalScope()) { currentValue = EditorGUILayout.TextField(currentValue); if (GUILayout.Button(SELECT_FILE, GUILayout.Width(GUI.skin.button.CalcSize(new GUIContent(SELECT_FILE)).x + 16))) { if (openingFile) { currentValue = EditorUtility.OpenFilePanel(filePanelTitle, string.Empty, fileExtension); } else { currentValue = EditorUtility.SaveFilePanel(filePanelTitle, string.Empty, string.Empty, fileExtension); } // If the above TextField has focus before clicking the Select File button, it will not update after a file is selected. Forcing it to loose focus afterwards will force it to update. GUI.FocusControl(null); } }; }, indentationLevel, isEnabled); return currentValue; } /// <summary> /// Make an empty prefix label. /// </summary> /// <remarks> /// Useful for aligning unlabeled fields with inputs. /// </remarks> public static void EmptyPrefixLabel() { PrefixLabel(EMPTY_PREFIX_SPACE); } /// <summary> /// Keep the previous <c>EditorGUILayout.PrefixLabel()</c> from getting disabled when the GUI element it labels is disabled.<br/><br/> /// /// This method must be called between <c>EditorGUILayout.PrefixLabel()</c> and the next <c>EditorGUILayout</c> or <c>GUILayout</c> function. /// See below for an example.<br/><br/> /// /// Explanation: PrefixLabels automatically get disabled when the GUI element they label is disabled. /// This happens even if the PrefixLabel itself is wrapped in a <c>using EditorGUI.DisabledScope(true){}</c> block. /// This method creates an invisible, zero-width label field between the PrefixLabel and the GUI element which it labels. /// The invisible label field is never disabled, so the PrefixLabel remains enabled. /// </summary> /// <example> /// This shows how to use this method to keep a prefix label from getting disabled. /// <code> /// EditorGUILayout.PrefixLabel("Foo:"); /// EditorGUILayoutElements.KeepPreviousPrefixLabelEnabled(); /// using (new EditorGUI.DisabledScope(!_isFooInputFieldDisabled)) /// { /// _currentFoo = EditorGUILayout.TextField(currentFoo); /// } /// </code> /// </example> public static void KeepPreviousPrefixLabelEnabled() { // Surprisingly, Width(0f) is not actually zero width. EditorGUILayout.LabelField(string.Empty, new GUIStyle(), GUILayout.Width(-3f)); } /// <summary> /// Draw an icon representing a feature's deployment status. /// </summary> /// <param name="deploymentStatus">The current deployment status of a feature.</param> public static void DeploymentStatusIcon(FeatureStatus deploymentStatus) { Texture icon = GetDeploymentStatusIcon(deploymentStatus); if (icon != null) { GUILayout.Box(icon, CommonGUIStyles.DeploymentStatusIcon); } } /// <summary> /// Draw an icon button for hard refreshing feature deployment statuses. /// </summary> /// <param name="isRefreshing">Indicates if feature refresh is in progress.</param> /// <remarks>A box will be rendered instead of a button if the refresh is in progress. During refresh the method will always return false.</remarks> /// <returns>True when the user clicks the button.</returns> public static bool DeploymentRefreshIconButton(bool isRefreshing) { Texture icon; if (isRefreshing) { icon = EditorResources.Textures.FeatureStatusWaiting.Get(); GUILayout.Box(new GUIContent(icon, L10n.Tr("Refreshing deployment status of all features.")), CommonGUIStyles.RefreshIcon); return false; } icon = EditorResources.Textures.FeatureStatusRefresh.Get(); return GUILayout.Button(new GUIContent(icon, L10n.Tr("Refresh deployment status of all features.")), CommonGUIStyles.RefreshIcon); } /// <summary> /// Displays a tooltip under the users mouse pointer when the mouse pointer is inside of the last element rendered before this call. /// </summary> /// <param name="message">Tooltip to display</param> public static void DrawToolTip(string message) { if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) { Vector3 mousePos = Event.current.mousePosition; Vector2 size = GUI.skin.box.CalcSize(new GUIContent(message)); GUI.Label(new Rect(mousePos.x - size.x, mousePos.y - size.y, size.x, size.y), message, SettingsGUIStyles.Tooltip.Text); } } internal static Texture GetDeploymentStatusIcon(FeatureStatus deploymentStatus) { switch (deploymentStatus) { case FeatureStatus.Undeployed: // fall through case FeatureStatus.Unknown: return null; case FeatureStatus.Deployed: return EditorResources.Textures.FeatureStatusSuccess.Get(); case FeatureStatus.Error: // fall through case FeatureStatus.RollbackComplete: return EditorResources.Textures.FeatureStatusError.Get(); default: return EditorResources.Textures.FeatureStatusWorking.Get(); } } private static void DisplayPlaceholderTextOverLastField(string placeholderText) { using (new EditorGUI.DisabledScope(true)) { EditorGUI.LabelField(GUILayoutUtility.GetLastRect(), placeholderText, CommonGUIStyles.PlaceholderLabel); } } } }
953
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// Interface for a GUI element which can be drawn on the screen with Unity's EditorGUILayout or GUILayout. /// </summary> public interface IDrawable { /// <summary> /// Draw this element on the screen using functions in UnityEditor.EditorGUILayout or UnityEditor.GUILayout. /// </summary> public void OnGUI(); } }
16
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.FileStructure; namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// A GUI element which displays a link followed by an external icon, optionally prepended with a label. /// </summary> public class LinkWidget : IDrawable { // Data private readonly string _prependedText; private readonly float _spaceAfterPrependedText; private readonly string _linkLabel; private readonly Options _options; private readonly Action _onClick; // Styles private GUIStyle _linkTextStyle; private GUIStyle _prependedTextStyle; private GUIStyle _iconStyle; private GUIStyle _iconStyleWithoutOffset; /// <summary> /// Create a new LinkWidget. /// </summary> /// <param name="linkLabel">The link text to display.</param> /// <param name="onClick">The action to execute when clicking on the link.</param> /// <param name="options">Styling options to apply.</param> public LinkWidget(string linkLabel, Action onClick, Options options = null) { _linkLabel = linkLabel; _onClick = onClick; _options = options ?? new Options(); } /// <summary> /// Create a new LinkWidget with a label placed before it. /// </summary> /// <param name="prependedText">The text to place directly before the <c>linkLabel</c>.</param> /// <param name="linkLabel">The link text to display.</param> /// <param name="onClick">The action to execute when clicking on the link.</param> /// <param name="options">Styling options to apply.</param> /// <param name="spaceAfterPrependedText">The amount of space to place between the <c>prependedText</c> and <c>linkLabel</c>.</param> public LinkWidget(string prependedText, string linkLabel, Action onClick, Options options = null, float spaceAfterPrependedText = 0f) : this(linkLabel, onClick, options) { _prependedText = prependedText; _spaceAfterPrependedText = spaceAfterPrependedText; } /// <summary> /// Create a new LinkWidget. /// </summary> /// <param name="linkLabel">The text to display in place of the URL.</param> /// <param name="url">The link that clicking the label text will route to.</param> /// <param name="options">Styling options to apply.</param> public LinkWidget(string linkLabel, string url, Options options = null) : this(linkLabel, () => Application.OpenURL(url), options) { } /// <summary> /// Create a new LinkWidget with a label placed before it. /// </summary> /// <param name="prependedText">The text to place directly before the <c>linkLabel</c>.</param> /// <param name="linkLabel">The text to display in place of the URL.</param> /// <param name="url">The link that clicking the label text will route to.</param> /// <param name="options">Styling options to apply.</param> /// <param name="spaceAfterPrependedText">The amount of space to place between the <c>prependedText</c> and <c>linkLabel</c>.</param> public LinkWidget(string prependedText, string linkLabel, string url, Options options = null, float spaceAfterPrependedText = 0f) : this(linkLabel, url, options) { _prependedText = prependedText; _spaceAfterPrependedText = spaceAfterPrependedText; } /// <summary> /// Styling options for the LinkWidget class. /// </summary> public class Options { /// <summary> /// A GUIStyle to apply to the horizontal layout section which contains the entire link widget (the prepended text, link label, and icon). /// </summary> public GUIStyle OverallStyle = GUIStyle.none; /// <summary> /// Whether to enable/disable word wrapping for the <c>linkLabel</c> parameter's text. /// </summary> public bool ShouldWordWrapLinkLabel = true; /// <summary> /// Number of pixels to shift the entire link widget (prepended text, link label, and icon). /// </summary> public Vector2 ContentOffset = Vector2.zero; /// <summary> /// Alignment of the entire link widget (prepended text, link label, and icon). /// </summary> public Alignment Alignment = Alignment.Left; /// <summary> /// The tooltip to show when the mouse is hovering over the link. By default no tooltip is shown. /// </summary> public string Tooltip = string.Empty; /// <summary> /// Whether to draw the external icon after the link label. /// </summary> public bool ShouldDrawExternalIcon = true; } /// <summary> /// The alignment of the entire link widget (prepended text, link label, and icon). /// </summary> public enum Alignment { /// <summary> /// The LinkWidget is aligned to the left, by placing a GUILayout.FlexibleSpace() at the end of it's horizontal layout group. /// </summary> Left, /// <summary> /// The LinkWidget is aligned to the right by placing a GUILayout.FlexibleSpace() at the beginning of it's horizontal layout group. /// </summary> Right, /// <summary> /// The LinkWidget is placed in the default manner for a horizontal layout group. /// It does not use a GUILayout.FlexibleSpace() to position itself. /// </summary> None, } /// <summary> /// Draw the LinkWidget. /// </summary> public void OnGUI() { SetGUIStyles(); using (new EditorGUILayout.HorizontalScope(_options.OverallStyle)) { if (_options.Alignment == Alignment.Right) { GUILayout.FlexibleSpace(); } DrawPrependedText(); DrawLinkWithExternalIcon(); if (_options.Alignment == Alignment.Left) { GUILayout.FlexibleSpace(); } } } // Avoid a null-reference exception by creating the GUIStyles during OnGUI instead of the constructor. // The exception happens because EditorStyles (ex: EditorStyles.label) are null until the first frame of the GUI. private void SetGUIStyles() { _linkTextStyle = new GUIStyle(LinkWidgetStyles.LinkLabelStyle) { wordWrap = _options.ShouldWordWrapLinkLabel }; Vector2 totalContentOffset = _options.ContentOffset + LinkWidgetStyles.BaselineContentOffset; _linkTextStyle = CommonGUIStyles.AddContentOffset(_linkTextStyle, totalContentOffset); _linkTextStyle.fontSize = _options.OverallStyle.fontSize; _prependedTextStyle = CommonGUIStyles.AddContentOffset(LinkWidgetStyles.PrependedTextStyle, totalContentOffset); _iconStyleWithoutOffset = _linkTextStyle.fontSize == 10 ? LinkWidgetStyles.IconStyleSmall : LinkWidgetStyles.IconStyleNormal; _iconStyle = CommonGUIStyles.AddContentOffset(_iconStyleWithoutOffset, totalContentOffset); } private void DrawPrependedText() { if (string.IsNullOrEmpty(_prependedText)) { return; } EditorGUILayout.LabelField(_prependedText, _prependedTextStyle); if (_spaceAfterPrependedText != 0) { // We only create this Space() element if non-zero, because Space(0) actually creates a non zero-width space. EditorGUILayout.Space(_spaceAfterPrependedText); } } /// <summary> /// Draws a button, that is styled to look like a hyperlink, followed by an external link Icon. /// </summary> private void DrawLinkWithExternalIcon() { GUILayout.Label(_linkLabel, _linkTextStyle); Rect buttonRect = GUILayoutUtility.GetLastRect(); buttonRect.x += _options.ContentOffset.x; buttonRect.y += _options.ContentOffset.y; buttonRect.width = _linkTextStyle.CalcSize(new GUIContent(_linkLabel)).x; if (_options.ShouldDrawExternalIcon) { // Draw icon GUILayout.Box(EditorResources.Textures.SettingsWindow.ExternalLinkIcon.Get(), _iconStyle); buttonRect.width += GUILayoutUtility.GetLastRect().width + _iconStyleWithoutOffset.fixedWidth / 3f; } // Create a button with no text but spans the length of both the text and the icon (if drawn) GUIContent buttonContent = new GUIContent(string.Empty, _options.Tooltip); if (GUI.Button(buttonRect, buttonContent, GUIStyle.none)) { _onClick(); } // Change mouse cursor to a "pointer" when hovering over the button EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link); } /// <summary> /// Subclass containing all specific styles for the LinkWidget. /// </summary> private static class LinkWidgetStyles { // The link widget is 2 pixels higher than other text on it's same line. // This offset brings it back down to where it should be. public static readonly Vector2 BaselineContentOffset = new Vector2(0, 2); private static readonly GUIStyleState LinkLabelStyleState = new GUIStyleState() { background = EditorStyles.label.normal.background, scaledBackgrounds = EditorStyles.label.normal.scaledBackgrounds, textColor = EditorStyles.linkLabel.normal.textColor }; public static readonly GUIStyle LinkLabelStyle = new GUIStyle(EditorStyles.label) { active = EditorStyles.linkLabel.active, hover = EditorStyles.linkLabel.hover, normal = LinkLabelStyleState, stretchWidth = false, }; public static readonly GUIStyle PrependedTextStyle = new GUIStyle(EditorStyles.label) { wordWrap = true }; public static readonly GUIStyle IconStyleNormal = new GUIStyle() { contentOffset = new Vector2(2, 3), fixedWidth = 14, fixedHeight = 14 }; public static readonly GUIStyle IconStyleSmall = new GUIStyle() { contentOffset = new Vector2(0, 2), fixedWidth = 10, fixedHeight = 10 }; } } }
281
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// A tab to be displayed in a TabViewWidget. /// </summary> public class Tab { public string DisplayName { get; } public IDrawable TabContent { get; } /// <summary> /// Create a new Tab. /// </summary> /// <param name="displayName">The string to show on this tab's button in the tab selector.</param> /// <param name="tabContent">The content to draw while this tab is selected in the TabViewWidget.</param> public Tab(string displayName, IDrawable tabContent) { DisplayName = displayName; TabContent = tabContent; } } }
25
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Libraries using System; using System.Linq; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.GUILayoutExtensions { /// <summary> /// A GUI element which displays a tab selector at the top and the selected tab's contents below. /// /// This is a wrapper around the GUILayout.Toolbar() function: https://docs.unity3d.com/ScriptReference/GUILayout.Toolbar.html /// </summary> [Serializable] public class TabWidget : IDrawable { // State [SerializeField] private int _selectedTabId; // Data private string[] _tabNames; private IDrawable[] _tabContents; private GUI.ToolbarButtonSize _tabSelectorButtonSize; /// <summary> /// Initializes a tab widget. /// /// See Unity's GUILayout.Toolbar() for details on the parameters: https://docs.unity3d.com/ScriptReference/GUILayout.Toolbar.html /// </summary> /// <param name="tabs">An array of all the tabs to display with this tab widget. It must contain at least one element.</param> /// <param name="tabSelectorButtonSize">Determines how the toolbar button size is calculated.</param> /// <exception cref="ArgumentException">Thrown when the <see cref="tabs"/> array is empty.</exception> public void Initialize(Tab[] tabs, GUI.ToolbarButtonSize tabSelectorButtonSize) { if (tabs.Length == 0) { throw new ArgumentException($"The '{nameof(tabs)}' parameter is empty. It must contain at least one element."); } // Data _tabNames = tabs.Select(tab => tab.DisplayName).ToArray(); _tabContents = tabs.Select(tab => tab.TabContent).ToArray(); // Clamp the selected tab id in case our previously selected tab is out of bounds _selectedTabId = Mathf.Clamp(_selectedTabId, 0, tabs.Length); _tabSelectorButtonSize = tabSelectorButtonSize; } /// <summary> /// Change the currently selected tab to the named tab. /// </summary> /// <param name="tabName">The name of the tab to select. Must be the name of one of the tabs passed into the constructor. /// Otherwise, an Error will be logged and the tab selection will not change.</param> public void SelectTab(string tabName) { int nextTabId = Array.IndexOf(_tabNames, tabName); if (nextTabId < 0) { // Wrap the tab names in quotes, like: "NameOne", "NameTwo", "NameThree" string validTabNames = $"\"{string.Join("\", \"", _tabNames)}\""; string currentTabName = _tabNames[_selectedTabId]; Logging.LogError($"There is no tab named \"{tabName}\". Valid tab names are: {validTabNames}. The selected tab will remain \"{currentTabName}\"."); return; } _selectedTabId = nextTabId; } /// <summary> /// Draw the tab selector and the contents of the selected tab. /// /// The tab selector buttons will use the default <c>button</c> style from the current UnityEngine.GUISkin. /// </summary> public void OnGUI() { OnGUI(GUI.skin.button); } /// <summary> /// Draw the tab selector and the contents of the selected tab. /// </summary> /// <param name="tabSelectorStyle">The style to use for the tab selector buttons.</param> public void OnGUI(GUIStyle tabSelectorStyle) { DrawTabSelector(tabSelectorStyle); DrawTabContent(); } private void DrawTabSelector(GUIStyle tabSelectorStyle) { using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); _selectedTabId = EditorGUILayoutElements.CreateFeatureToolbar(_selectedTabId, _tabNames, _tabSelectorButtonSize, tabSelectorStyle); GUILayout.FlexibleSpace(); } } private void DrawTabContent() { IDrawable selectedTab = _tabContents[_selectedTabId]; selectedTab.OnGUI(); } } }
117
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Models { public class AccountDetails { public string GameName { get; set; } public string Environment { get; set; } public string AccountId { get; set; } public string Region { get; set; } public string AccessKey { get; set; } public string AccessSecret { get; set; } public AccountCredentials CreateAccountCredentials() { AccountCredentials accountCredentials = new AccountCredentials(); accountCredentials.AccountId = AccountId; accountCredentials.AccessKey = AccessKey; accountCredentials.AccessSecret = AccessSecret; accountCredentials.Region = Region; return accountCredentials; } public AccountInfo CreateAccountInfo() { AccountInfo accountInfo = new AccountInfo(); accountInfo.AccountId = AccountId; accountInfo.GameName = GameName; accountInfo.Environment = String.IsNullOrEmpty(Environment) ? Constants.EnvironmentCodes.DEVELOPMENT : Environment; accountInfo.CompanyName = ""; return accountInfo; } } }
44
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Libraries using System; namespace AWS.GameKit.Editor.Models { /// <summary> /// A generic feature setting.<br/><br/> /// /// Feature settings are configured by the user through the AWS GameKit Settings window. Each feature has it's own settings to configure.<br/><br/> /// /// Feature settings are applied during deployment in the form of CloudFormation template parameters.<br/><br/> /// </summary> /// <typeparam name="T">The data type of this feature setting. This type is used to convert to/from a string when communicating with the AWS GameKit C++ SDK.</typeparam> [Serializable] public abstract class FeatureSetting<T> : IFeatureSetting { public string VariableName { get; } /// <summary> /// The current value of this setting as configured in the UI. /// </summary> public T CurrentValue; /// <summary> /// The default value that will be used for this setting if the user does not change it. /// </summary> public T DefaultValue { get; } public string CurrentValueString => ValueToString(CurrentValue); public string DefaultValueString => ValueToString(DefaultValue); /// <summary> /// Create a new instance of FeatureSetting which has it's current value set to the default value. /// </summary> /// <exception cref="System.ArgumentNullException">Thrown when any constructor argument is null.</exception> protected FeatureSetting(string variableName, T defaultValue) { VariableName = variableName ?? throw new ArgumentNullException(nameof(variableName)); DefaultValue = defaultValue ?? throw new ArgumentNullException(nameof(defaultValue)); CurrentValue = defaultValue; } /// <summary> /// Set the <c>CurrentValue</c> to a new value specified by a string. /// </summary> /// <param name="value">The new current value.</param> /// <exception cref="System.ArgumentNullException">Thrown when the <c>value</c> argument is null.</exception> public void SetCurrentValueFromString(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } CurrentValue = ValueFromString(value); } /// <summary> /// Convert the provided value to its string representation. /// </summary> /// <param name="value">The value to convert to a string.</param> /// <returns>A string representation of the provided value.</returns> protected abstract string ValueToString(T value); /// <summary> /// Convert the provided string to a type <c>T</c> object. /// </summary> /// <param name="value">The string to convert to type <c>T</c>.</param> /// <returns>A type <c>T</c> object created from the provided string.</returns> protected abstract T ValueFromString(string value); } }
77
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Collections.ObjectModel; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Editor.Windows.Settings; namespace AWS.GameKit.Editor.Models { /// <summary> /// Editor metadata associated with a FeatureType enum. /// </summary> public class FeatureTypeEditorData { /// <summary> /// All of the features which are displayed in the UI, in the order they should be displayed. /// </summary> public static readonly IEnumerable<FeatureType> FeaturesToDisplay = new List<FeatureType>() { FeatureType.Identity, FeatureType.GameStateCloudSaving, FeatureType.Achievements, FeatureType.UserGameplayData, }; public readonly string DisplayName; public readonly string ApiString; public readonly string Description; public readonly string VerboseDescription; public readonly string DocumentationUrl; public readonly string ResourcesUIString; public readonly IGettable<Texture> Icon; public readonly PageType PageType; public FeatureTypeEditorData(string displayName, string apiString, string description, string verboseDescription, string documentationUrl, string resourceUIString, IGettable<Texture> icon, PageType pageType) { DisplayName = displayName; ApiString = apiString; Description = description; VerboseDescription = verboseDescription; DocumentationUrl = documentationUrl; ResourcesUIString = resourceUIString; Icon = icon; PageType = pageType; } } /// <summary> /// Extension methods for the FeatureType enum which provide access to each enum's FeatureTypeEditorData. /// </summary> public static class FeatureTypeConverter { public static string GetDisplayName(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.DisplayName; } public static string GetApiString(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.ApiString; } public static string GetDescription(this FeatureType featureType, bool withEndingPeriod = false) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return withEndingPeriod ? editorData.Description + "." : editorData.Description; } public static string GetVerboseDescription(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.VerboseDescription; } public static string GetDocumentationUrl(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.DocumentationUrl; } public static string GetResourcesUIString(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.ResourcesUIString; } public static Texture GetIcon(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.Icon.Get(); } public static PageType GetPageType(this FeatureType featureType) { FeatureTypeEditorData editorData = featureType.GetEditorData(); return editorData.PageType; } /// <summary> /// Get the feature's dashboard URL. /// </summary> /// <param name="featureType">The feature to get the dashboard for.</param> /// <param name="gameName">The game's alias.</param> /// <param name="environmentCode">The short environment code where the feature and dashboard are deployed. Example: "dev", "qa".</param> /// <param name="region">The AWS region where the feature and dashboard are deployed. Example: "us-west-2"</param> /// <returns></returns> public static string GetDashboardUrl(this FeatureType featureType, string gameName, string environmentCode, string region) { string featureName = StringHelper.RemoveWhitespace(featureType.GetDisplayName()) .Replace("&", "And"); return $"https://console.aws.amazon.com/cloudwatch/home?region={region}#dashboards:name=GameKit-{gameName}-{environmentCode}-{region}-{featureName}"; } private static FeatureTypeEditorData GetEditorData(this FeatureType featureType) { if (_featureTypeToEditorData.TryGetValue(featureType, out FeatureTypeEditorData editorData)) { return editorData; } throw new ArgumentException($"No FeatureTypeEditorData found for FeatureType: {featureType}. This error should not be possible at runtime. It should be caught by unit tests."); } private static readonly ReadOnlyDictionary<FeatureType, FeatureTypeEditorData> _featureTypeToEditorData = new ReadOnlyDictionary<FeatureType, FeatureTypeEditorData>( new Dictionary<FeatureType, FeatureTypeEditorData>() { { FeatureType.Main, new FeatureTypeEditorData( displayName: "Main", apiString: "main", description: L10n.Tr("The Main feature does not have a description"), verboseDescription: L10n.Tr("The Main feature does not have a verbose description"), documentationUrl: DocumentationURLs.GAMEKIT_HOME, resourceUIString: "The Main feature does not have a resources UI String. ", icon: EditorResources.Textures.Colors.Transparent, pageType: PageType.EnvironmentAndCredentialsPage) }, { FeatureType.Identity, new FeatureTypeEditorData( displayName: "Identity & Authentication", apiString: "identity", description: L10n.Tr("Create unique identities for each player and allow players to sign into your game. Verify player identities and manage player sessions"), verboseDescription: L10n.Tr("Sign players into your game to create player IDs, authenticate players to prevent cheating and fraud."), documentationUrl: DocumentationURLs.IDENTITY, resourceUIString: "API Gateway, CloudWatch, Cognito, DynamoDB, IAM, Key Management Service, and Lambda. ", icon: EditorResources.Textures.QuickAccessWindow.FeatureIconIdentity, pageType: PageType.IdentityAndAuthenticationPage) }, { FeatureType.Authentication, new FeatureTypeEditorData( displayName: "Authentication", apiString: "authentication", description: L10n.Tr("The Authentication feature does not have a description"), verboseDescription: L10n.Tr("The Authentication feature does not have a verbose description"), documentationUrl: DocumentationURLs.IDENTITY, resourceUIString: "The Authentication feature does not have a resources UI String. ", icon: EditorResources.Textures.Colors.Transparent, pageType: PageType.IdentityAndAuthenticationPage) }, { FeatureType.Achievements, new FeatureTypeEditorData( displayName: "Achievements", apiString: "achievements", description: L10n.Tr("Track and display game-related rewards earned by players"), verboseDescription: L10n.Tr("Add an achievement system where players can earn awards for their gameplay prowess."), documentationUrl: DocumentationURLs.ACHIEVEMENTS, resourceUIString: "API Gateway, CloudFront, CloudWatch, Cognito, DynamoDB, Lambda, S3, and Security Token Service. ", icon: EditorResources.Textures.QuickAccessWindow.FeatureIconAchievements, pageType: PageType.AchievementsPage) }, { FeatureType.GameStateCloudSaving, new FeatureTypeEditorData( displayName: "Game State Cloud Saving", apiString: "gamesaving", description: L10n.Tr("Maintain a synchronized copy of player game progress in the cloud to allow players to resume gameplay across sessions"), verboseDescription: L10n.Tr("Synchronize game saves in the cloud to let players seamlessly resume gameplay across sessions and multiple devices."), documentationUrl: DocumentationURLs.GAME_STATE_SAVING, resourceUIString: "API Gateway, CloudWatch, Cognito, DynamoDB, Lambda, and S3. ", icon: EditorResources.Textures.QuickAccessWindow.FeatureIconGameStateCloudSaving, pageType: PageType.GameStateCloudSavingPage) }, { FeatureType.UserGameplayData, new FeatureTypeEditorData( displayName: "User Gameplay Data", apiString: "usergamedata", description: L10n.Tr("Maintain game-related data for each player, such as inventory, statistics, cross-play persistence, etc"), verboseDescription: L10n.Tr("Maintain player game data in the cloud, available when and where the player signs into the game."), documentationUrl: DocumentationURLs.USER_GAMEPLAY_DATA, resourceUIString: "API Gateway, CloudWatch, Cognito, DynamoDB, and Lambda. ", icon: EditorResources.Textures.QuickAccessWindow.FeatureIconUserGameplayData, pageType: PageType.UserGameplayDataPage) }, } ); } }
218
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Models { /// <summary> /// A string-based feature setting.<br/><br/> /// /// This is intended for use with the AWS GameKit C++ SDK, which treats all feature settings as strings. /// </summary> public interface IFeatureSetting { /// <summary> /// The setting's variable name in the feature's CloudFormation parameters.yml file.<br/><br/> /// /// Feature settings are marked in parameters.yml files by a placeholder that looks like: <c>{{AWSGAMEKIT::VARS::my_variable}}</c>, /// where <c>my_variable</c> is specified by <c>VariableName</c>.<br/><br/> /// /// <c>VariableName</c> should be used when calling:<br/> /// - <c>FeatureResourceManager.SetFeatureVariable(..., varName=MySetting.VariableName, ...)</c><br/> /// - <c>FeatureResourceManager.SetFeatureVariableIfUnset(..., varName=MySetting.VariableName, ...)</c><br/> /// - As keys in the dictionary response from <c>FeatureResourceManager.GetFeatureVariables()</c> /// </summary> public string VariableName { get; } /// <summary> /// The current value of this setting represented as a string. /// </summary> public string CurrentValueString { get; } /// <summary> /// The default value of this setting represented as a string. /// </summary> public string DefaultValueString { get; } /// <summary> /// Set the current value of this setting to the provided string. /// </summary> /// <param name="value">The new current value.</param> public void SetCurrentValueFromString(string value); } }
43
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Models { /// <summary> /// Class for saving secrets in settings /// </summary> public class SecretSetting { public string SecretIdentifier { get; set; } public string SecretValue { get; set; } public bool IsStoredInCloud { get; set; } public SecretSetting(string secretIdentifier, string secretValue, bool isStoredInCloud) { SecretIdentifier = secretIdentifier; SecretValue = secretValue; IsStoredInCloud = isStoredInCloud; } } }
22
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // GameKit using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Models { public enum AwsRegion { [AwsRegionData(regionKey: "us-east-1", regionDescription: "us-east-1: US East (N. Virginia)", isSupported: true)] US_EAST_1, [AwsRegionData(regionKey: "us-east-2", regionDescription: "us-east-2: US East (Ohio)", isSupported: true)] US_EAST_2, [AwsRegionData(regionKey: "us-west-1", regionDescription: "us-west-1: US West (N. California)", isSupported: true)] US_WEST_1, [AwsRegionData(regionKey: "us-west-2", regionDescription: "us-west-2: US West (Oregon)", isSupported: true)] US_WEST_2, [AwsRegionData(regionKey: "af-south-1", regionDescription: "af-south-1: Africa (Cape Town)", isSupported: false)] AF_SOUTH_1, [AwsRegionData(regionKey: "ap-east-1", regionDescription: "ap-east-1: Asia Pacific (Hong Kong)", isSupported: false)] AP_EAST_1, [AwsRegionData(regionKey: "ap-south-1", regionDescription: "ap-south-1: Asia Pacific (Mumbai)", isSupported: true)] AP_SOUTH_1, [AwsRegionData(regionKey: "ap-northeast-3", regionDescription: "ap-northeast-3: Asia Pacific (Osaka)", isSupported: false)] AP_NORTHEAST_3, [AwsRegionData(regionKey: "ap-northeast-2", regionDescription: "ap-northeast-2: Asia Pacific (Seoul)", isSupported: true)] AP_NORTHEAST_2, [AwsRegionData(regionKey: "ap-southeast-1", regionDescription: "ap-southeast-1: Asia Pacific (Singapore)", isSupported: true)] AP_SOUTHEAST_1, [AwsRegionData(regionKey: "ap-southeast-2", regionDescription: "ap-southeast-2: Asia Pacific (Sydney)", isSupported: true)] AP_SOUTHEAST_2, [AwsRegionData(regionKey: "ap-northeast-1", regionDescription: "ap-northeast-1: Asia Pacific (Tokyo)", isSupported: true)] AP_NORTHEAST_1, [AwsRegionData(regionKey: "ca-central-1", regionDescription: "ca-central-1: Canada (Central)", isSupported: true)] CA_CENTRAL_1, [AwsRegionData(regionKey: "eu-central-1", regionDescription: "eu-central-1: Europe (Frankfurt)", isSupported: true)] EU_CENTRAL_1, [AwsRegionData(regionKey: "eu-west-1", regionDescription: "eu-west-1: Europe (Ireland)", isSupported: true)] EU_WEST_1, [AwsRegionData(regionKey: "eu-west-2", regionDescription: "eu-west-2: Europe (London)", isSupported: true)] EU_WEST_2, [AwsRegionData(regionKey: "eu-south-1", regionDescription: "eu-south-1: Europe (Milan)", isSupported: false)] EU_SOUTH_1, [AwsRegionData(regionKey: "eu-west-3", regionDescription: "eu-west-3: Europe (Paris)", isSupported: true)] EU_WEST_3, [AwsRegionData(regionKey: "eu-north-1", regionDescription: "eu-north-1: Europe (Stockholm)", isSupported: true)] EU_NORTH_1, [AwsRegionData(regionKey: "me-south-1", regionDescription: "me-south-1: Middle East (Bahrain)", isSupported: true)] ME_SOUTH_1, [AwsRegionData(regionKey: "sa-east-1", regionDescription: "sa-east-1: South America (Sao Paulo)", isSupported: true)] SA_EAST_1 } [AttributeUsage(AttributeTargets.Field)] public class AwsRegionData : Attribute { public readonly string RegionKey; public readonly string RegionDescription; public readonly bool IsSupported; public AwsRegionData(string regionKey, string regionDescription, bool isSupported) { RegionKey = regionKey; RegionDescription = regionDescription; IsSupported = isSupported; } } /// <summary> /// Extension methods for <c>AwsRegion</c> which give access to it's enum metadata. /// </summary> /// <example> /// This shows how to use the extension methods. /// <code> /// // On the enum class: /// AwsRegion.AP_SOUTHEAST_2.GetRegionKey(); /// /// // On an enum variable: /// AwsRegion myRegion = AwsRegion.US_EAST_1 /// myRegion.GetRegionKey(); /// </code> /// </example> public static class AwsRegionConverter { public static string GetRegionKey(this AwsRegion awsRegion) { return awsRegion.GetAttribute<AwsRegionData>().RegionKey; } public static string GetRegionDescription(this AwsRegion awsRegion) { return awsRegion.GetAttribute<AwsRegionData>().RegionDescription; } public static bool IsRegionSupported(this AwsRegion awsRegion) { return awsRegion.GetAttribute<AwsRegionData>().IsSupported; } } }
125
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Libraries using System; using System.Globalization; namespace AWS.GameKit.Editor.Models.FeatureSettings { /// <summary> /// A feature setting that is a <c>bool</c>. /// </summary> [Serializable] public class FeatureSettingBool : FeatureSetting<bool> { public FeatureSettingBool(string variableName, bool defaultValue) : base(variableName, defaultValue) { } protected override string ValueToString(bool value) => value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(); protected override bool ValueFromString(string value) => bool.Parse(value); } }
24
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Libraries using System; using System.Globalization; namespace AWS.GameKit.Editor.Models.FeatureSettings { /// <summary> /// A feature setting that is a <c>float</c>. /// </summary> [Serializable] public class FeatureSettingFloat : FeatureSetting<float> { public FeatureSettingFloat(string variableName, float defaultValue) : base(variableName, defaultValue) { } protected override string ValueToString(float value) => value.ToString(CultureInfo.InvariantCulture); protected override float ValueFromString(string value) => float.Parse(value, CultureInfo.InvariantCulture); } }
24
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Libraries using System; using System.Globalization; namespace AWS.GameKit.Editor.Models.FeatureSettings { /// <summary> /// A feature setting that is an <c>int</c>. /// </summary> [Serializable] public class FeatureSettingInt : FeatureSetting<int> { public FeatureSettingInt(string variableName, int defaultValue) : base(variableName, defaultValue) { } protected override string ValueToString(int value) => value.ToString(CultureInfo.InvariantCulture); protected override int ValueFromString(string value) => int.Parse(value, CultureInfo.InvariantCulture); } }
25
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; namespace AWS.GameKit.Editor.Models.FeatureSettings { /// <summary> /// A feature setting that is a <c>string</c>. /// </summary> [Serializable] public class FeatureSettingString : FeatureSetting<string> { public FeatureSettingString(string variableName, string defaultValue) : base(variableName, defaultValue) { } protected override string ValueToString(string value) => value; protected override string ValueFromString(string value) => value; } }
23
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; namespace AWS.GameKit.Editor.Utils { public static class DocumentationURLs { public const string GAMEKIT_HOME = "https://docs.aws.amazon.com/gamekit/index.html"; public const string CREATE_ACCOUNT = "https://aws.amazon.com"; public const string FREE_TIER_INTRO = "http://aws.amazon.com/free/"; public const string FREE_TIER_REFERENCE = "https://aws.amazon.com/getting-started/hands-on/control-your-costs-free-tier-budgets"; public const string BACKUP_DYNAMO_REFERENCE = "https://aws.amazon.com/premiumsupport/knowledge-center/back-up-dynamodb-s3"; public const string IDENTITY = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/identity-auth.html"; public const string ACHIEVEMENTS = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/achievements.html"; public const string GAME_STATE_SAVING = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/game-save.html"; public const string USER_GAMEPLAY_DATA = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/gameplay-data.html"; public const string INTRO_COSTS = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/intro-costs.html"; public const string SETTING_UP_CREDENTIALS = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/setting-up-credentials.html"; public const string DELETE_INSTANCE_REFERENCE = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/plugin-project-delete.html"; public const string CLOUDWATCH_DASHBOARDS_REFERENCE = "https://docs.aws.amazon.com/gamekit/latest/DevGuide/monitoring-dashboards.html"; } }
27
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; namespace AWS.GameKit.Editor.Utils { /// <summary> /// A wrapper for a pair of dark-theme and light-theme objects. /// /// Use this class when you need to use one of two objects depending on whether the Unity Editor Theme is Dark or Light. /// </summary> /// <typeparam name="T">The type of object to wrap.</typeparam> public class EditorThemeAware<T> : IGettable<T> { /// <summary> /// The object to use when the Unity Editor theme is Dark. /// </summary> public T DarkThemeObject { get; } /// <summary> /// The object to use when the Unity Editor theme is Light. /// </summary> public T LightThemeObject { get; } /// <summary> /// Create a new EditorThemeAware wrapper for the two provided objects. /// </summary> /// <param name="darkThemeObject">The object to use when the Unity Editor theme is Dark.</param> /// <param name="lightThemeObject">The object to use when the Unity Editor theme is Light.</param> public EditorThemeAware(T darkThemeObject, T lightThemeObject) { DarkThemeObject = darkThemeObject; LightThemeObject = lightThemeObject; } /// <summary> /// Get the object matching the current Unity Editor theme. /// </summary> /// <returns>The DarkThemeObject if the Unity Editor theme is "Dark", otherwise the LightThemeObject.</returns> public virtual T Get() { return EditorGUIUtility.isProSkin ? DarkThemeObject : LightThemeObject; } } }
47
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Reflection; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.Windows.Settings; namespace AWS.GameKit.Editor.Utils { /// <summary> /// Helper methods for Unity's EditorWindows class. /// /// See: https://docs.unity3d.com/ScriptReference/EditorWindow.html /// </summary> public static class EditorWindowHelper { private const string INSPECTOR_WINDOW_TYPE_NAME = "UnityEditor.InspectorWindow"; /// <summary> /// Set the background color of the editor window. /// /// This method should be called before drawing any other GUI elements in the window, /// because it draws on top of everything drawn previously. /// </summary> /// <param name="window">The window to set the background color of.</param> /// <param name="newBackgroundColorTexture">The color to set the window's background to. This texture will be stretched to fit the entire window.</param> public static void SetBackgroundColor(EditorWindow window, Texture2D newBackgroundColorTexture) { Vector2 windowTopLeft = new Vector2(0, 0); Vector2 windowBottomRight = new Vector2(window.position.width, window.position.height); GUI.DrawTexture(new Rect(windowTopLeft, windowBottomRight), newBackgroundColorTexture, ScaleMode.StretchToFill); } /// <summary> /// Get the Type of Unity's Inspector window. /// /// This type can be used as a desired dock target when calling EditorWindow.GetWindow(desiredDockNextTo). /// /// Warning: This method relies on reflection to get Unity's internal InspectorWindow type. /// If Unity changes the InspectorWindow's type name, this method will log a warning and return null. /// It's safe to pass the null value into EditorWindow.GetWindow(desiredDockNextTo) - the InspectorWindow will /// simply be skipped as a dock target. /// </summary> public static Type GetInspectorWindowType() { Assembly editorAssembly = typeof(UnityEditor.Editor).Assembly; Type inspectorWindowType = editorAssembly.GetType(INSPECTOR_WINDOW_TYPE_NAME); if (inspectorWindowType == null) { Debug.LogWarning($"Could not find the System.Type of Unity's InspectorWindow through reflection. " + $"Tried using the name: \"{INSPECTOR_WINDOW_TYPE_NAME}\". " + $"Unity most likely changed the InspectorWindow's name, namespace, or assembly. " + $"Please update this method to use it's new type. " + $"Last known type: https://github.com/Unity-Technologies/UnityCsReference/blob/e740821767d2290238ea7954457333f06e952bad/Editor/Mono/Inspector/InspectorWindow.cs#L20"); } return inspectorWindowType; } /// <summary> /// Change the window's current size and it's minimum/maximum size. /// /// The window will expand/contract from it's center, instead of it's bottom right corner like it normally would. /// /// If called during window initialization, it should be called during the first OnGUI() call instead of during OnEnable(). /// Otherwise it will expand from it's bottom right corner instead of the center. /// </summary> /// <param name="window">The window to modify.</param> /// <param name="newSize">The width and height to give the window.</param> /// <param name="minSize">The minimum size to give the window.</param> /// <param name="maxSize">The maximum size to give the window.</param> public static void SetWindowSizeAndBounds(EditorWindow window, Vector2 newSize, Vector2 minSize, Vector2 maxSize) { SetWindowSizeExpandingFromCenter(window, newSize); // Bounds must be set after changing the size, otherwise the window will not be centered. window.minSize = minSize; window.maxSize = maxSize; } private static void SetWindowSizeExpandingFromCenter(EditorWindow window, Vector2 newSize) { // To keep the window centered on it's original location, shift it's upper left corner // by half of the increase/decrease in size (deltaWidth & deltaHeight). float newWidth = newSize.x; float newHeight = newSize.y; float deltaWidth = newWidth - window.position.width; float deltaHeight = newHeight - window.position.height; float newXPosition = window.position.x - (deltaWidth / 2f); float newYPosition = window.position.y - (deltaHeight / 2f); window.position = new Rect(newXPosition, newYPosition, newWidth, newHeight); } } }
103
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; namespace AWS.GameKit.Editor.Utils { public static class GUIEditorUtils { /// <summary> /// Generates a 1 pixel texture that can be used to assign to a GUIStyleState's background property. /// </summary> /// <param name="color">Color to use for the background</param> /// <returns>A Texture2D class which can be assigned as a background</returns> public static Texture2D CreateBackground(Color color) { Texture2D result = new Texture2D(1, 1); result.SetPixels(new Color[] { color }); result.Apply(); return result; } } }
26
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Utils { /// <summary> /// Exposes a <c>Get()</c> method which returns an object of the specified type. /// </summary> /// <typeparam name="T">The type of objects that may be returned.</typeparam> public interface IGettable<out T> { /// <summary> /// Get an object of the specified type. See the implementing class for details on the returned object. /// </summary> public T Get(); } }
17
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; namespace AWS.GameKit.Editor.Utils { /// <summary> /// Has an instance of <see cref="SerializedProperty"/> which points to <c>this</c>. /// </summary> public interface IHasSerializedPropertyOfSelf { /// <summary> /// A <see cref="SerializedProperty"/> which points to <c>this</c>. /// </summary> public SerializedProperty SerializedPropertyOfSelf { get; set; } } }
23
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.GameKit.Editor.Utils { /// <summary> /// A lazy loading wrapper for a pair of dark-theme and light-theme assets stored in a "Resources" folder. /// /// The Get() method returns the correct asset based on the Unity Editor theme. /// /// The assets are loaded and cached the first time Get() is called. /// /// For details on Unity's special "Resources" folders and how to load data from them, please read: https://docs.unity3d.com/ScriptReference/Resources.Load.html /// </summary> /// <typeparam name="T">The type to load the assets as.</typeparam> public class LazyLoadedEditorThemeAwareResource<T> : IGettable<T> where T : UnityEngine.Object { private readonly EditorThemeAware<IGettable<T>> _cachedResources; /// <summary> /// Create a new LazyLoadedEditorThemeAwareResource for the specified resource paths. /// /// See official docs for details on the resource paths: https://docs.unity3d.com/ScriptReference/Resources.Load.html /// </summary> /// <param name="darkThemeResourcePath">The path to the Dark-themed resource relative to any Resources folder.</param> /// <param name="lightThemeResourcePath">The path to the Light-themed resource relative to any Resources folder.</param> public LazyLoadedEditorThemeAwareResource(string darkThemeResourcePath, string lightThemeResourcePath) { _cachedResources = new EditorThemeAware<IGettable<T>>( new LazyLoadedResource<T>(darkThemeResourcePath), new LazyLoadedResource<T>(lightThemeResourcePath) ); } /// <summary> /// Create a new LazyLoadedEditorThemeAwareResource for the specified resource paths. /// /// See official docs for details on the resource paths: https://docs.unity3d.com/ScriptReference/Resources.Load.html /// </summary> /// <param name="darkThemeResourceGetter">An IGetter for the dark theme resource.</param> /// <param name="lightThemeResourceGetter">An IGetter for the light theme resource.</param> public LazyLoadedEditorThemeAwareResource(IGettable<T> darkThemeResourceGetter, IGettable<T> lightThemeResourceGetter) { _cachedResources = new EditorThemeAware<IGettable<T>>(darkThemeResourceGetter, lightThemeResourceGetter); } /// <summary> /// Get the asset matching the current Unity Editor theme. /// </summary> /// <returns>The dark-themed asset if the Unity Editor theme is "Dark", otherwise the light-themed asset.</returns> public T Get() { return _cachedResources.Get().Get(); } } }
57
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; namespace AWS.GameKit.Editor.Utils { /// <summary> /// A lazy loading wrapper for an asset stored in a "Resources" folder. /// /// The asset is loaded and cached the first time Get() is called. /// /// For details on Unity's special "Resources" folders and how to load data from them, please read: https://docs.unity3d.com/ScriptReference/Resources.Load.html /// </summary> /// <typeparam name="T">The type to load the asset as.</typeparam> public class LazyLoadedResource<T> : IGettable<T> where T : UnityEngine.Object { private readonly string _path; private Lazy<T> _cachedResource; /// <summary> /// Create a new LazyLoadedResource for the specified resource path. /// </summary> /// <param name="path">The path to the resource relative to any Resources folder. See official docs for details: https://docs.unity3d.com/ScriptReference/Resources.Load.html</param> public LazyLoadedResource(string path) { _path = path; _cachedResource = new Lazy<T>(() => (T)AssetDatabase.LoadAssetAtPath(path, typeof(T))); } /// <summary> /// Get the resource. Cache the resource if this is the first time calling Get(). /// </summary> public T Get() { return _cachedResource.Value; } } }
46
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; namespace AWS.GameKit.Editor.Utils { /// <summary> /// A lazy loading wrapper for an asset stored in a "Resources" folder. /// /// The asset is loaded and cached the first time Get() is called. /// /// For details on Unity's special "Resources" folders and how to load data from them, please read: https://docs.unity3d.com/ScriptReference/Resources.Load.html /// </summary> /// <typeparam name="T">The type to load the asset as.</typeparam> public class LazyLoadedResourceForCurrentResolution<T> : IGettable<T> where T : UnityEngine.Object { public delegate T ResourceLoader(string path); private enum ResourceSize { ONE_K, TWO_K, FOUR_K, EIGHT_K } private const string TWO_K_POSTFIX = "-2k"; private const string FOUR_K_POSTFIX = "-4k"; private const string EIGHT_K_POSTFIX = "-8k"; private readonly string[] _paths = new string[Enum.GetNames(typeof(ResourceSize)).Length]; private Lazy<T> _cachedResource; private Resolution _resolution; private ResourceLoader _resourceLoader; /// <summary> /// Create a new LazyLoadedResource for the specified resource path. /// </summary> /// <param name="path">The path to the resource relative to any Resources folder. See official docs for details: https://docs.unity3d.com/ScriptReference/Resources.Load.html</param> /// <param name="resolution">A Unity object that specifies the height and width of the desktop.</param> /// <param name="resourceLoader">A delegate that takes a string and returns a type T. This delegate is used to perform that actual resource loading.</param> public LazyLoadedResourceForCurrentResolution(string path, Resolution resolution, ResourceLoader resourceLoader) { _resolution = resolution; _resourceLoader = resourceLoader; _paths[(int)ResourceSize.ONE_K] = path; _paths[(int)ResourceSize.TWO_K] = path + TWO_K_POSTFIX; _paths[(int)ResourceSize.FOUR_K] = path + FOUR_K_POSTFIX; _paths[(int)ResourceSize.EIGHT_K] = path + EIGHT_K_POSTFIX; _cachedResource = new Lazy<T>(() => LoadResource(IdealResolution())); } /// <summary> /// Create a new LazyLoadedResource for the specified resource path. /// </summary> /// <param name="path">The path to the resource relative to any Resources folder. See official docs for details: https://docs.unity3d.com/ScriptReference/Resources.Load.html</param> public LazyLoadedResourceForCurrentResolution(string path) : this(path, Screen.currentResolution, (path) => (T)AssetDatabase.LoadAssetAtPath(path, typeof(T))) { } /// <summary> /// Get the resource. Cache the resource if this is the first time calling Get(). /// </summary> public T Get() { return _cachedResource.Value; } private ResourceSize IdealResolution() { // get the longest edge, in case the monitor is rotated - landscape vs portrait double longestEdge = Math.Max(_resolution.width, _resolution.height); // convert to kilos and then determine how many we have double numberOfK = Math.Round(longestEdge / 1000.0); if (numberOfK <= 1) { return ResourceSize.ONE_K; } else if (numberOfK <= 2) { return ResourceSize.TWO_K; } else if (numberOfK <= 4) { return ResourceSize.FOUR_K; } else { return ResourceSize.EIGHT_K; } } private T LoadResource(ResourceSize idealResourceSize) { int size = (int)idealResourceSize; T resource = null; // attempt to load the current ideal resolution for the resource, if nothing loads then decrement and attempt the next best resolution do { resource = _resourceLoader(_paths[size]); --size; } while (size >= (int)ResourceSize.ONE_K && resource == null); return resource; } } }
119
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEditor; using UnityEngine; namespace AWS.GameKit.Editor.Utils { /// <summary> /// A ScriptableObject which survives when the Unity editor restarts or does a Domain Reload. /// /// The object automatically writes itself to disk during OnDisable() and can be loaded with LoadObject(). /// </summary> public class PersistentScriptableObject<T> : ScriptableObject where T : PersistentScriptableObject<T> { private string _assetFilePath; private bool _shouldBeSaved; /// <summary> /// Load the ScriptableObject from a file on disk. /// </summary> /// <param name="assetFilePath">The path where the ScriptableObject's file will be loaded from and written to.</param> /// <returns>The ScriptableObject deserialized from the file.</returns> public static T LoadFromDisk(string assetFilePath) { T scriptableObject = AssetDatabase.LoadAssetAtPath<T>(assetFilePath); if (scriptableObject == null) { scriptableObject = CreateInstance<T>(); AssetDatabase.CreateAsset(scriptableObject, assetFilePath); } if (!string.IsNullOrEmpty(assetFilePath)) { scriptableObject._assetFilePath = assetFilePath; scriptableObject._shouldBeSaved = true; } return scriptableObject; } private void WriteToDisk() { // Implementation note: // We persist a clone instead of the original object to ensure the state is non-null when loaded by LoadAssetAtPath() in LoadFromDisk(). // If we persist the object by other means, then LoadAssetAtPath() returns null when LoadFromDisk() is called immediately after script recompilation. _shouldBeSaved = false; T clonedScriptableObject = (T)Instantiate(this); AssetDatabase.CreateAsset(clonedScriptableObject, _assetFilePath); } private void OnDisable() { if (_shouldBeSaved) { WriteToDisk(); } } } }
64
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; // GameKit using AWS.GameKit.Runtime.Utils; namespace AWS.GameKit.Editor.Utils { /// <summary> /// A version of <see cref="SerializableOrderedDictionary{TKey,TValue}"/> whose <see cref="TValue"/> implements <see cref="IHasSerializedPropertyOfSelf"/>. /// This class takes care of assigning and updating the <see cref="IHasSerializedPropertyOfSelf.SerializedPropertyOfSelf"/> reference whenever this dictionary is modified.<br/><br/> /// /// Make sure to call <see cref="FrameDelayedInitializeNewElements"/> at the beginning of every OnGUI method, before running any code in the dictionary's <see cref="TValue"/> elements. /// </summary> /// <inheritdoc cref="SerializableOrderedDictionary{K,V}"/> [Serializable] public class SerializablePropertyOrderedDictionary<TKey, TValue> : SerializableOrderedDictionary<TKey, TValue> where TValue : IHasSerializedPropertyOfSelf { // Serialization private SerializedProperty _valuesSerializedProperty; private int _numNewElements = 0; /// <summary> /// This method must be the first method called on a new instance of this class. /// </summary> /// <param name="serializedProperty">The <see cref="SerializedProperty"/> of a class's instance variable holding this instance of <see cref="SerializablePropertyOrderedDictionary{TKey,TValue}"/>.</param> public void Initialize(SerializedProperty serializedProperty) { _valuesSerializedProperty = serializedProperty.FindPropertyRelative($"{nameof(_values)}"); UpdateSerializedPropertyForElements(0); } /// <summary> /// This method should be called at the beginning of every OnGUI() frame, before running any code in this collection's <see cref="TValue"/> elements. /// </summary> /// <remarks> /// New elements added to this collection by <see cref="Add"/> or <see cref="SerializablePropertyOrderedDictionary{TKey,TValue}.SetValue"/> will not /// have their <see cref="IHasSerializedPropertyOfSelf.SerializedPropertyOfSelf"/> set until <see cref="FrameDelayedInitializeNewElements"/> is called /// at least one frame after the element was added.<br/><br/> /// /// The <see cref="IHasSerializedPropertyOfSelf.SerializedPropertyOfSelf"/> can't be set during the same frame the element was added to this collection because it doesn't /// exist in Unity's serialization framework until one frame after the element was added to this class's internal <see cref="SerializablePropertyOrderedDictionary{TKey,TValue}._values"/> list. /// </remarks> public void FrameDelayedInitializeNewElements() { UpdateSerializedPropertyForElements(_dict.Count - _numNewElements); } public override void Add(TKey key, TValue value) { base.Add(key, value); ++_numNewElements; } public override void Remove(TKey key) { int indexOfElement = _keys.IndexOf(key); base.Remove(key); if (indexOfElement >= 0) { // All elements after the removed element need to be updated because they have a new position in the _values list. UpdateSerializedPropertyForElements(indexOfElement); } } public override void Clear() { base.Clear(); _numNewElements = 0; } public override void Sort(Func<IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>> sortFunction) { base.Sort(sortFunction); // All elements need to be updated because they have a new position in the _values list. // By changing the _numNewElements to dict length we will cause all the serialized elements to be updated by FrameDelayedInitializeNewElements() in the next GUI frame _numNewElements = _dict.Count; } /// <summary> /// Update the serialized property of all elements in the _values list from the <see cref="startingFromIndex"/> to the end of the list.<br/><br/> /// /// After calling this method, <see cref="_numNewElements"/> is reset to <c>0</c>. /// </summary> /// <param name="startingFromIndex">The first element to update. All elements coming before this index will not be updated.</param> private void UpdateSerializedPropertyForElements(int startingFromIndex) { for (int i = startingFromIndex; i < _dict.Count; ++i) { _values[i].SerializedPropertyOfSelf = _valuesSerializedProperty.GetArrayElementAtIndex(i); } _numNewElements = 0; } } }
109
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; using System.Linq; namespace AWS.GameKit.Editor.Utils { /// <summary> /// Helper methods for working with strings. /// </summary> public static class StringHelper { /// <summary> /// Remove all whitespace from a string. /// </summary> /// <param name="text">The string to remove whitespace from.</param> /// <returns>A copy of the input string with all the whitespace removed.</returns> public static string RemoveWhitespace(string text) { return string.Concat(text.Where(character => !Char.IsWhiteSpace(character))); } /// <summary> /// Join a collection of strings into a single string, which is a comma separated list of quoted elements. Example: <c>"\"First\", \"Second\", \"Third\""</c> /// </summary> /// <param name="values">The collection of strings to join.</param> /// <returns>The joined string, or <see cref="string.Empty"/> if <paramref name="values"/> was empty.</returns> public static string MakeCommaSeparatedList(IEnumerable<string> values) { return string.Join(", ", values.Select(value => $"\"{value}\"")); } } }
36
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Windows.Settings; namespace AWS.GameKit.Editor.Windows.QuickAccess { /// <summary> /// All of the data needed to display a feature's row in the Quick Access window. /// </summary> public class FeatureRowData { public string Name; public string Description; public Texture Icon; public PageType PageType; public FeatureRowData(FeatureType featureType) { Name = featureType.GetDisplayName(); Description = featureType.GetDescription(); Icon = featureType.GetIcon(); PageType = featureType.GetPageType(); } } }
33
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; // GameKit using AWS.GameKit.Editor.Utils; using AWS.GameKit.Editor.Windows.Settings; namespace AWS.GameKit.Editor.Windows.QuickAccess { /// <summary> /// Creates the QuickAccessWindow and provides the rest of AWS GameKit with an interface to access the QuickAccessWindow. /// </summary> public class QuickAccessController { private readonly SettingsController _settingsWindowController; private readonly SettingsDependencyContainer _dependencies; public QuickAccessController(SettingsController settingsWindowController, SettingsDependencyContainer dependencies) { _settingsWindowController = settingsWindowController; _dependencies = dependencies; QuickAccessWindow.Enabled += OnQuickAccessWindowEnabled; } /// <summary> /// Give focus to the existing window instance, or create one if it doesn't exist. /// </summary> /// <returns>The existing or new window instance.</returns> public QuickAccessWindow GetOrCreateQuickAccessWindow() { return EditorWindow.GetWindow<QuickAccessWindow>(GetDesiredDockNextToWindows()); } /// <summary> /// Get the list of editor windows which the Quick Access window wants to dock next to in priority order. /// </summary> private static Type[] GetDesiredDockNextToWindows() { return new Type[] { EditorWindowHelper.GetInspectorWindowType() }; } private void OnQuickAccessWindowEnabled(QuickAccessWindow enabledQuickAccessWindow) { enabledQuickAccessWindow.Initialize(_settingsWindowController, _dependencies); } } }
57
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Unity using UnityEngine; // GameKit using AWS.GameKit.Editor.FileStructure; namespace AWS.GameKit.Editor.Windows.QuickAccess { /// <summary> /// GUIStyles for the AWS GameKit QuickAccess window. /// </summary> public static class QuickAccessGUIStyles { public static class Window { public static readonly float MinWidth = 300f; public static readonly float MinHeight = 200f; public static readonly Texture2D BackgroundColor = EditorResources.Textures.QuickAccessWindow.Colors.QuickAccessBackground.Get(); public static readonly float SpaceBetweenFeatureRows = 7f; } public static class FeatureRow { private static readonly GUIStyleState BackgroundColorNormal = new GUIStyleState() { background = EditorResources.Textures.QuickAccessWindow.Colors.QuickAccessButtonNormal.Get() }; private static readonly GUIStyleState BackgroundColorHover = new GUIStyleState() { background = EditorResources.Textures.QuickAccessWindow.Colors.QuickAccessButtonHover.Get() }; public static readonly GUIStyle HorizontalLayout = new GUIStyle() { padding = new RectOffset(10, 10, 10, 10), normal = BackgroundColorNormal }; public static readonly GUILayoutOption[] HorizontalLayoutOptions = new GUILayoutOption[] { GUILayout.MinHeight(66f) }; public static readonly GUIStyle Button = new GUIStyle(GUI.skin.button) { normal = BackgroundColorNormal, onNormal = BackgroundColorNormal, focused = BackgroundColorNormal, onFocused = BackgroundColorNormal, hover = BackgroundColorHover, onHover = BackgroundColorHover, active = BackgroundColorHover, onActive = BackgroundColorHover }; public static readonly GUIStyle Icon = new GUIStyle() { fixedWidth = 25, fixedHeight = 25, alignment = TextAnchor.UpperCenter }; public static readonly GUIStyle Name = new GUIStyle(GUI.skin.label) { fontSize = GUI.skin.label.fontSize + 6, wordWrap = true }; public static readonly GUIStyle Description = new GUIStyle(GUI.skin.label) { wordWrap = true }; } } }
82
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.FileStructure; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Models; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Editor.Windows.Settings; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Windows.QuickAccess { /// <summary> /// Displays the Quick Access window and receives its UI events. /// </summary> public class QuickAccessWindow : EditorWindow { private const string WINDOW_TITLE = "AWS GameKit"; private enum InitializationLevel { // Initialize() has not been called. The GUI is empty. Uninitialized, // Initialize() has been called. The GUI is drawn. Initialized } // Controllers private SettingsController _settingsWindowController; private SettingsDependencyContainer _dependencies; // State private InitializationLevel _initLevel = InitializationLevel.Uninitialized; // Fields marked with [SerializeField] are persisted & restored whenever Unity is restarted, Play Mode is entered, or the assembly is rebuilt. // However, they are cleared when the window is closed. Unlike the SettingsWindow, we don't want to persist these when the window is closed. [SerializeField] private Vector2 _scrollbarPositions; // Events public static event OnWindowEnabled Enabled; public delegate void OnWindowEnabled(QuickAccessWindow enabledQuickAccessWindow); private void OnEnable() { // Set title string windowTitle = WINDOW_TITLE; Texture windowIcon = EditorResources.Textures.WindowIcon.Get(); titleContent = new GUIContent(windowTitle, windowIcon); // Set minimum size minSize = new Vector2(QuickAccessGUIStyles.Window.MinWidth, QuickAccessGUIStyles.Window.MinHeight); // Publish event Enabled?.Invoke(this); } /// <summary> /// Initialize this window so it can start drawing the GUI. This is effectively the window's constructor. /// </summary> public void Initialize(SettingsController settingsWindowController, SettingsDependencyContainer dependencies) { _settingsWindowController = settingsWindowController; _dependencies = dependencies; _initLevel = InitializationLevel.Initialized; } private void OnGUI() { if (_initLevel == InitializationLevel.Uninitialized) { GUILayout.Space(0f); return; } EditorWindowHelper.SetBackgroundColor(this, QuickAccessGUIStyles.Window.BackgroundColor); _scrollbarPositions = EditorGUILayout.BeginScrollView(_scrollbarPositions); DrawEnvironmentAndCredentials(); DrawFeatureRows(); EditorGUILayout.EndScrollView(); RefreshButtonColors(); } private void DrawEnvironmentAndCredentials() { } private void DrawFeatureRows() { Dictionary<FeatureType, FeatureStatus> featuresStatus = new Dictionary<FeatureType, FeatureStatus>(); foreach (FeatureSettingsTab featureSettingsTab in FeatureSettingsTab.FeatureSettingsTabsInstances) { featuresStatus.Add(featureSettingsTab.FeatureType, featureSettingsTab.GetFeatureStatus()); } foreach (FeatureType featureType in FeatureTypeEditorData.FeaturesToDisplay) { GUILayout.Space(QuickAccessGUIStyles.Window.SpaceBetweenFeatureRows); FeatureStatus status; if (!featuresStatus.TryGetValue(featureType, out status)) { status = _dependencies.FeatureDeploymentOrchestrator.GetFeatureStatus(featureType); } DrawFeatureRow(new FeatureRowData(featureType), status); } } private void DrawFeatureRow(FeatureRowData featureRowData, FeatureStatus deploymentStatus) { using (EditorGUILayout.HorizontalScope horizontalScope = new EditorGUILayout.HorizontalScope(QuickAccessGUIStyles.FeatureRow.HorizontalLayout, QuickAccessGUIStyles.FeatureRow.HorizontalLayoutOptions)) { Rect featureRowRect = horizontalScope.rect; // Background Button Texture buttonTexture = EditorResources.Textures.Colors.Transparent.Get(); GUIStyle buttonStyle = QuickAccessGUIStyles.FeatureRow.Button; if (GUI.Button(featureRowRect, buttonTexture, buttonStyle)) { SettingsWindow.OpenPage(featureRowData.PageType); } // Change mouse cursor to a "pointer" when hovering over the button EditorGUIUtility.AddCursorRect(featureRowRect, MouseCursor.Link); // Icon GUILayout.Box(featureRowData.Icon, QuickAccessGUIStyles.FeatureRow.Icon); GUILayout.Space(3.4f); // Name & Description using (new EditorGUILayout.VerticalScope()) { EditorGUILayout.LabelField(featureRowData.Name, QuickAccessGUIStyles.FeatureRow.Name); GUILayout.Space(1f); EditorGUILayout.LabelField(featureRowData.Description, QuickAccessGUIStyles.FeatureRow.Description); } GUILayout.FlexibleSpace(); GUILayout.Space(10f); // Deployment Status using (new EditorGUILayout.VerticalScope()) { GUILayout.FlexibleSpace(); EditorGUILayoutElements.DeploymentStatusIcon(deploymentStatus); GUILayout.FlexibleSpace(); } using (new EditorGUILayout.VerticalScope()) { GUILayout.FlexibleSpace(); GUILayout.Label(deploymentStatus.GetDisplayName()); GUILayout.FlexibleSpace(); } } } /// <summary> /// Repaint the canvas to make the buttons instantly change their color when the mouse is hovering over them. /// /// This is a workaround for strange behavior by GUI.Button(): /// - An un-styled GUI.Button() is instantly responsive. It changes color the instant the mouse moves on top or off of the button. /// - A styled GUI.Button() is very slow to respond (on the order of 1-2 seconds). /// /// Without this method, it's not possible to have a responsive button with custom colors. /// </summary> private void RefreshButtonColors() { wantsMouseMove = true; if (Event.current.type == EventType.MouseMove) { // It is taxing on the GPU to repaint the GUI every frame. // So we only repaint when the mouse is on the window and it moved during the last frame. // This limits the increased GPU usage so it only occurs while the user is interacting with the Quick Access window. Repaint(); } } } }
195
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; // GameKit using AWS.GameKit.Editor.Windows.Settings.Pages.Achievements; using AWS.GameKit.Editor.Windows.Settings.Pages.AllFeatures; using AWS.GameKit.Editor.Windows.Settings.Pages.EnvironmentAndCredentials; using AWS.GameKit.Editor.Windows.Settings.Pages.GameStateCloudSaving; using AWS.GameKit.Editor.Windows.Settings.Pages.IdentityAndAuthentication; using AWS.GameKit.Editor.Windows.Settings.Pages.Log; using AWS.GameKit.Editor.Windows.Settings.Pages.UserGameplayData; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Holds references to every page that gets displayed in the AWS GameKit Settings window. /// </summary> [Serializable] public class AllPages { // Before features public EnvironmentAndCredentialsPage EnvironmentAndCredentialsPage; public AllFeaturesPage AllFeaturesPage; // Features public IdentityAndAuthenticationPage IdentityAndAuthenticationPage; public GameStateCloudSavingPage GameStateCloudSavingPage; public AchievementsPage AchievementsPage; public UserGameplayDataPage UserGameplayDataPage; // After features public LogPage LogPage; private Dictionary<PageType, Page> PageTypeToPageInstanceMap => new Dictionary<PageType, Page>() { // Before features {PageType.EnvironmentAndCredentialsPage, EnvironmentAndCredentialsPage}, {PageType.AllFeaturesPage, AllFeaturesPage}, // Features {PageType.IdentityAndAuthenticationPage, IdentityAndAuthenticationPage}, {PageType.GameStateCloudSavingPage, GameStateCloudSavingPage}, {PageType.AchievementsPage, AchievementsPage}, {PageType.UserGameplayDataPage, UserGameplayDataPage}, // After features {PageType.LogPage, LogPage}, }; /// <summary> /// Create a default AllPages. /// </summary> public void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { // Before features EnvironmentAndCredentialsPage.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(EnvironmentAndCredentialsPage))); // Features IdentityAndAuthenticationPage.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(IdentityAndAuthenticationPage))); GameStateCloudSavingPage.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(GameStateCloudSavingPage))); AchievementsPage.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(AchievementsPage))); UserGameplayDataPage.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(UserGameplayDataPage))); // Must be intialized after features AllFeaturesPage.Initialize(dependencies); // After features LogPage.Initialize(serializedProperty.FindPropertyRelative(nameof(LogPage))); } /// <summary> /// Get the page instance corresponding to the specified page type. /// </summary> public Page GetPage(PageType pageType) { if (PageTypeToPageInstanceMap.TryGetValue(pageType, out Page page)) { return page; } throw new ArgumentException($"No page instance found for PageType: {pageType}. This error should not be possible at runtime. It should be caught by unit tests."); } } }
92
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; using System.Collections.Generic; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Editor.Utils; using AWS.GameKit.Editor.Windows.Settings; namespace AWS.GameKit.Editor { public class DeleteFeatureWindow : EditorWindow { public Action DeleteCallback; public string FeatureName; public List<string> ResourceDescriptions; private Vector2 _scrollPosition = Vector2.zero; private string _confirmationText = ""; public static void ShowWindow(string featureName, List<string> resourceDescriptions, Action deleteCallback) { DeleteFeatureWindow window = GetWindow<DeleteFeatureWindow>("Delete " + featureName); window.DeleteCallback = deleteCallback; window.FeatureName = featureName; window.ResourceDescriptions = resourceDescriptions; window.minSize = new Vector2(SettingsGUIStyles.DeleteWindow.MIN_SIZE_X, SettingsGUIStyles.DeleteWindow.MIN_SIZE_Y); } private void OnGUI() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("The following resources will be deleted for the " + FeatureName + " feature.", SettingsGUIStyles.DeleteWindow.GeneralText); } using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.DeleteWindow.ResourceList)) { _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); foreach (string line in ResourceDescriptions) { EditorGUILayout.LabelField(line, SettingsGUIStyles.DeleteWindow.ResourceDescriptionLine); } EditorGUILayout.EndScrollView(); } using (new EditorGUILayout.HorizontalScope()) { LinkWidget.Options backupLinkOptions = new LinkWidget.Options() { Alignment = LinkWidget.Alignment.Right, ContentOffset = new Vector2( x: -25, y: 10 ), }; LinkWidget backupLink = new LinkWidget(L10n.Tr("How can I backup a DynamoDB table to Amazon S3 ?"), DocumentationURLs.BACKUP_DYNAMO_REFERENCE, backupLinkOptions); backupLink.OnGUI(); } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("To confirm deletion type 'Yes' below.", SettingsGUIStyles.DeleteWindow.GeneralText); } using (new EditorGUILayout.HorizontalScope()) { _confirmationText = EditorGUILayout.TextField(_confirmationText, SettingsGUIStyles.DeleteWindow.GeneralTextField); } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("This action retains your locally stored GameKit code and configuration files for this feature, which will be used in future deployments. " + "To return this feature to the default GameKit experience, you must delete these files local files manually.", SettingsGUIStyles.DeleteWindow.GeneralText); } LinkWidget.Options learnMoreLinkOptions = new LinkWidget.Options() { ContentOffset = new Vector2( x: 25, y: 0 ) }; LinkWidget learnMoreLink = new LinkWidget(L10n.Tr("Learn More"), DocumentationURLs.DELETE_INSTANCE_REFERENCE, learnMoreLinkOptions); learnMoreLink.OnGUI(); using (new EditorGUILayout.HorizontalScope(SettingsGUIStyles.DeleteWindow.ButtonMargins)) { GUILayout.FlexibleSpace(); if (EditorGUILayoutElements.Button("Ok", _confirmationText.ToLower() == "yes")) { // Todo only enable when text box says yes DeleteCallback(); this.Close(); } if (EditorGUILayoutElements.Button("Cancel")) { // close window this.Close(); } } } } }
111
aws-gamekit-unity
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Standard Library using System; // Unity using UnityEditor; using UnityEngine; // GameKit using AWS.GameKit.Common.Models; using AWS.GameKit.Editor.Core; using AWS.GameKit.Editor.GUILayoutExtensions; using AWS.GameKit.Runtime.Core; using AWS.GameKit.Runtime.Models; namespace AWS.GameKit.Editor.Windows.Settings { /// <summary> /// Base class for all feature-specific example tabs. /// </summary> [Serializable] public abstract class FeatureExamplesTab : IDrawable { private readonly string TO_ENABLE_LOGIN_MESSAGE = L10n.Tr("To enable, deploy Identity and Authentication."); private readonly string TO_ENABLE_DEPLOYED_FEATURE_MESSAGE = L10n.Tr("To enable, login with a player."); /// <summary> /// The feature which these examples are for. /// </summary> public abstract FeatureType FeatureType { get; } protected bool _displayLoginWidget = true; protected FeatureDeploymentOrchestrator _featureDeploymentOrchestrator; protected GameKitManager _gameKitManager; protected GameKitEditorManager _gameKitEditorManager; protected UserInfo _userInfo; [SerializeField] private UserLoginWidget _userLoginWidget; [SerializeField] private Vector2 _scrollPosition; private SerializedProperty _serializedProperty; protected virtual bool RequiresLogin => true; public virtual void Initialize(SettingsDependencyContainer dependencies, SerializedProperty serializedProperty) { _serializedProperty = serializedProperty; _gameKitManager = dependencies.GameKitManager; _gameKitEditorManager = dependencies.GameKitEditorManager; _featureDeploymentOrchestrator = dependencies.FeatureDeploymentOrchestrator; _userInfo = dependencies.UserInfo; _userLoginWidget.Initialize(dependencies, serializedProperty.FindPropertyRelative(nameof(_userLoginWidget)), OnLogout); } public virtual void OnLogout() { // No-op should be overwritten by implementing class if needed } public void OnGUI() { _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); string description = RequiresLogin ? L10n.Tr("Simulate API calls from a game client to the deployed backend for this feature. You must be logged in as a registered player to make test API calls.") : L10n.Tr("Simulate API calls from a game client to the deployed backend for this feature."); EditorGUILayoutElements.Description(description, indentationLevel: 0); EditorGUILayout.Space(); DrawLoginGUI(); DrawExampleGUI(); EditorGUILayout.EndScrollView(); } /// <summary> /// Draw the examples for this feature. /// </summary> protected abstract void DrawExamples(); private void DrawLoginGUI() { if (_displayLoginWidget) { bool isIdentityDeployed = _featureDeploymentOrchestrator.GetFeatureStatus(FeatureType.Identity) == FeatureStatus.Deployed; if (!isIdentityDeployed) { DrawBanner(TO_ENABLE_LOGIN_MESSAGE); } using (new GUILayout.VerticalScope()) { using (new EditorGUI.DisabledScope(!isIdentityDeployed)) { _userLoginWidget.OnGUI(); } } if (!isIdentityDeployed) { EditorGUILayoutElements.DrawToolTip(TO_ENABLE_LOGIN_MESSAGE); } EditorGUILayoutElements.SectionDivider(); } } private void DrawExampleGUI() { bool shouldDisableForNotLoggedIn = _displayLoginWidget && !_userInfo.IsLoggedIn; bool shouldDisableForNotDeployed = _featureDeploymentOrchestrator.GetFeatureStatus(FeatureType) != FeatureStatus.Deployed; bool shouldDisable = shouldDisableForNotLoggedIn || shouldDisableForNotDeployed; string message = shouldDisableForNotLoggedIn ? TO_ENABLE_DEPLOYED_FEATURE_MESSAGE : L10n.Tr($"To enable, deploy {FeatureType}."); if (shouldDisable) { DrawBanner(message); } using (new GUILayout.VerticalScope()) { using (new EditorGUI.DisabledScope(shouldDisable)) { DrawExamples(); } } if (shouldDisable) { EditorGUILayoutElements.DrawToolTip(message); } } private void DrawBanner(string message) { using (new EditorGUILayout.VerticalScope(SettingsGUIStyles.Page.BannerBox)) { GUIStyle style = SettingsGUIStyles.Page.BannerBoxLabel; Texture entryIcon = SettingsGUIStyles.Icons.WarnIcon; GUIContent content = new GUIContent(message, entryIcon); Rect entrySize = GUILayoutUtility.GetRect(content, style); EditorGUI.LabelField(entrySize, content, style); } } } }
156