-
Notifications
You must be signed in to change notification settings - Fork 434
/
Copy pathUIHandler.cs
280 lines (249 loc) · 10.3 KB
/
UIHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Firebase.Sample.RemoteConfig {
using Firebase.Extensions;
using System;
using System.Threading.Tasks;
using UnityEngine;
// Handler for UI buttons on the scene. Also performs some
// necessary setup (initializing the firebase app, etc) on
// startup.
public
class UIHandler : MonoBehaviour {
public GUISkin fb_GUISkin;
private Vector2 controlsScrollViewVector = Vector2.zero;
private Vector2 scrollViewVector = Vector2.zero;
bool UIEnabled = true;
private string logText = "";
const int kMaxLogSize = 16382;
Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther;
protected bool isFirebaseInitialized = false;
// When the app starts, check to make sure that we have
// the required dependencies to use Firebase, and if not,
// add them if possible.
protected virtual void Start() {
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available) {
InitializeFirebase();
} else {
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
// Initialize remote config, and set the default values.
void InitializeFirebase() {
// [START set_defaults]
System.Collections.Generic.Dictionary<string, object> defaults =
new System.Collections.Generic.Dictionary<string, object>();
// These are the values that are used if we haven't fetched data from the
// server
// yet, or if we ask for values that the server doesn't have:
defaults.Add("config_test_string", "default local string");
defaults.Add("config_test_int", 1);
defaults.Add("config_test_float", 1.0);
defaults.Add("config_test_bool", false);
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.SetDefaultsAsync(defaults)
.ContinueWithOnMainThread(task => {
// [END set_defaults]
DebugLog("RemoteConfig configured and ready!");
isFirebaseInitialized = true;
});
}
// Exit if escape (or back, on mobile) is pressed.
protected virtual void Update() {
if (Input.GetKeyDown(KeyCode.Escape)) {
Application.Quit();
}
}
// Display the currently loaded data. If fetch has been called, this will be
// the data fetched from the server. Otherwise, it will be the defaults.
// Note: Firebase will cache this between sessions, so even if you haven't
// called fetch yet, if it was called on a previous run of the program, you
// will still have data from the last time it was run.
public void DisplayData() {
DebugLog("Current Data:");
DebugLog("config_test_string: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance
.GetValue("config_test_string").StringValue);
DebugLog("config_test_int: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance
.GetValue("config_test_int").LongValue);
DebugLog("config_test_float: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance
.GetValue("config_test_float").DoubleValue);
DebugLog("config_test_bool: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance
.GetValue("config_test_bool").BooleanValue);
}
public void DisplayAllKeys() {
DebugLog("Current Keys:");
System.Collections.Generic.IEnumerable<string> keys =
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.Keys;
foreach (string key in keys) {
DebugLog(" " + key);
}
DebugLog("GetKeysByPrefix(\"config_test_s\"):");
keys = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.GetKeysByPrefix("config_test_s");
foreach (string key in keys) {
DebugLog(" " + key);
}
}
public void EnableAutoFetch() {
DebugLog("Enabling auto-fetch:");
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.OnConfigUpdateListener
+= ConfigUpdateListenerEventHandler;
}
public void DisableAutoFetch() {
DebugLog("Disabling auto-fetch:");
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.OnConfigUpdateListener
-= ConfigUpdateListenerEventHandler;
}
private void ConfigUpdateListenerEventHandler(
object sender, Firebase.RemoteConfig.ConfigUpdateEventArgs args) {
if (args.Error != Firebase.RemoteConfig.RemoteConfigError.None) {
DebugLog(String.Format("Error occurred while listening: {0}", args.Error));
return;
}
DebugLog(String.Format("Auto-fetch has received a new config. Updated keys: {0}",
string.Join(", ", args.UpdatedKeys)));
var info = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.Info;
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.ActivateAsync()
.ContinueWithOnMainThread(task => {
DebugLog(String.Format("Remote data loaded and ready (last fetch time {0}).",
info.FetchTime));
});
}
// [START fetch_async]
// Start a fetch request.
// FetchAsync only fetches new data if the current data is older than the provided
// timespan. Otherwise it assumes the data is "recent enough", and does nothing.
// By default the timespan is 12 hours, and for production apps, this is a good
// number. For this example though, it's set to a timespan of zero, so that
// changes in the console will always show up immediately.
public Task FetchDataAsync() {
DebugLog("Fetching data...");
System.Threading.Tasks.Task fetchTask =
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.FetchAsync(
TimeSpan.Zero);
return fetchTask.ContinueWithOnMainThread(FetchComplete);
}
//[END fetch_async]
void FetchComplete(Task fetchTask) {
if (fetchTask.IsCanceled) {
DebugLog("Fetch canceled.");
} else if (fetchTask.IsFaulted) {
DebugLog("Fetch encountered an error.");
} else if (fetchTask.IsCompleted) {
DebugLog("Fetch completed successfully!");
}
var info = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.Info;
switch (info.LastFetchStatus) {
case Firebase.RemoteConfig.LastFetchStatus.Success:
Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.ActivateAsync()
.ContinueWithOnMainThread(task => {
DebugLog(String.Format("Remote data loaded and ready (last fetch time {0}).",
info.FetchTime));
});
break;
case Firebase.RemoteConfig.LastFetchStatus.Failure:
switch (info.LastFetchFailureReason) {
case Firebase.RemoteConfig.FetchFailureReason.Error:
DebugLog("Fetch failed for unknown reason");
break;
case Firebase.RemoteConfig.FetchFailureReason.Throttled:
DebugLog("Fetch throttled until " + info.ThrottledEndTime);
break;
}
break;
case Firebase.RemoteConfig.LastFetchStatus.Pending:
DebugLog("Latest Fetch call still pending.");
break;
}
}
// Output text to the debug log text field, as well as the console.
public void DebugLog(string s) {
print(s);
logText += s + "\n";
while (logText.Length > kMaxLogSize) {
int index = logText.IndexOf("\n");
logText = logText.Substring(index + 1);
}
scrollViewVector.y = int.MaxValue;
}
void DisableUI() {
UIEnabled = false;
}
void EnableUI() {
UIEnabled = true;
}
// Render the log output in a scroll view.
void GUIDisplayLog() {
scrollViewVector = GUILayout.BeginScrollView(scrollViewVector);
GUILayout.Label(logText);
GUILayout.EndScrollView();
}
// Render the buttons and other controls.
void GUIDisplayControls() {
if (UIEnabled) {
controlsScrollViewVector =
GUILayout.BeginScrollView(controlsScrollViewVector);
GUILayout.BeginVertical();
if (GUILayout.Button("Display Current Data")) {
DisplayData();
}
if (GUILayout.Button("Display All Keys")) {
DisplayAllKeys();
}
if (GUILayout.Button("Fetch Remote Data")) {
FetchDataAsync();
}
if (GUILayout.Button("Enable Auto-Fetch")) {
EnableAutoFetch();
}
if (GUILayout.Button("Disable Auto-Fetch")) {
DisableAutoFetch();
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
}
}
// Render the GUI:
void OnGUI() {
GUI.skin = fb_GUISkin;
if (dependencyStatus != Firebase.DependencyStatus.Available) {
GUILayout.Label("One or more Firebase dependencies are not present.");
GUILayout.Label("Current dependency status: " + dependencyStatus.ToString());
return;
}
Rect logArea, controlArea;
if (Screen.width < Screen.height) {
// Portrait mode
controlArea = new Rect(0.0f, 0.0f, Screen.width, Screen.height * 0.5f);
logArea = new Rect(0.0f, Screen.height * 0.5f, Screen.width, Screen.height * 0.5f);
} else {
// Landscape mode
controlArea = new Rect(0.0f, 0.0f, Screen.width * 0.5f, Screen.height);
logArea = new Rect(Screen.width * 0.5f, 0.0f, Screen.width * 0.5f, Screen.height);
}
GUILayout.BeginArea(logArea);
GUIDisplayLog();
GUILayout.EndArea();
GUILayout.BeginArea(controlArea);
GUIDisplayControls();
GUILayout.EndArea();
}
}
}