Commit dd84c12679f14e42682f661d5bcf41d630dfef83

Authored by Mateus Lustosa
1 parent e36e6046

Finishes Trie and JSONParser

Assets/Scripts/Animation List/Trie.cs
... ... @@ -1,80 +0,0 @@
1   -using LAViD.VLibras.Utils;
2   -using System;
3   -using System.Collections.Generic;
4   -using System.Diagnostics;
5   -using System.Linq;
6   -using System.Text;
7   -using System.Text.RegularExpressions;
8   -
9   -namespace LAViD.VLibras.Generic
10   -{
11   - class Node
12   - {
13   - private bool end = false;
14   - private Node[] children = null;
15   - }
16   -
17   - class Trie
18   - {
19   - private Node root;
20   -
21   - public Trie(string json)
22   - {
23   - JSONTrie trie = new JSONTrie(json);
24   - }
25   - }
26   -
27   - class JSONTrie
28   - {
29   - public string[] characters;
30   - public Dictionary<string, int> charactersKeys;
31   - public JSONNode root;
32   -
33   - public JSONTrie(string json)
34   - {
35   - Stopwatch watch = new Stopwatch();
36   - watch.Start();
37   -
38   - // Separate main fields
39   -
40   - GroupCollection mainFields = new Regex("^{\"keys\": (.*), \"trie\": (.*), \"characters\": (.*)}$").Match(Regex.Unescape(json)).Groups;
41   -
42   - string keysJSON = mainFields[1].Value;
43   - string trieJSON = mainFields[2].Value;
44   - string charactersJSON = mainFields[3].Value;
45   -
46   - PlayerLogger.Log("T", "()", "keysJSON: " + keysJSON);
47   - PlayerLogger.Log("T", "()", "trieJSON: " + trieJSON);
48   - PlayerLogger.Log("T", "()", "charactersJSON: " + charactersJSON);
49   -
50   - // Parse characters
51   -
52   - MatchCollection matches = new Regex("\"(.)\"").Matches(charactersJSON);
53   - this.characters = new string[matches.Count];
54   -
55   - for (int i = 0; i < matches.Count; i++)
56   - this.characters[i] = matches[i].Groups[1].Value;
57   -
58   - // Parse keys
59   -
60   - MatchCollection matches = new Regex("\"(.)\"").Matches(charactersJSON);
61   - this.charactersKeys = new Dictionary<string, int>();
62   -
63   -
64   -
65   - watch.Stop();
66   - PlayerLogger.Log("T", "()", "Passed:" + watch.ElapsedMilliseconds);
67   - }
68   - }
69   -
70   - class JSONNode
71   - {
72   - public bool end;
73   - public JSONNode children;
74   -
75   - public JSONNode(string json)
76   - {
77   -
78   - }
79   - }
80   -}
Assets/Scripts/Animation List/Trie.cs.meta
... ... @@ -1,12 +0,0 @@
1   -fileFormatVersion: 2
2   -guid: 3238f46fe9379b2469349a4bce058b65
3   -timeCreated: 1476385070
4   -licenseType: Pro
5   -MonoImporter:
6   - serializedVersion: 2
7   - defaultReferences: []
8   - executionOrder: 0
9   - icon: {instanceID: 0}
10   - userData:
11   - assetBundleName:
12   - assetBundleVariant:
Assets/Scripts/PlayerManager.cs
... ... @@ -3,30 +3,34 @@ using System.Collections;
3 3 using System;
4 4 using UnityEngine.UI;
5 5 using LAViD.VLibras.Utils;
6   -using LAViD.VLibras.Generic;
  6 +using System.Text.RegularExpressions;
  7 +using System.Threading;
  8 +using LAViD.Utils;
  9 +using LAViD.Structures;
  10 +using System.Diagnostics;
7 11  
8 12 public class PlayerManager : GenericPlayerManager {
9 13  
10 14 #if UNITY_IOS
11 15 //private const string BASE_URL = "http://150.165.205.9/anims/IOS/";//old
12   - private const string BASE_URL = "http://dicionario.vlibras.gov.br/IOS/";
  16 + private const string BASE_URL = "http://dicionario.vlibras.gov.br/IOS/";
13 17 #else
14   - //private const string BASE_URL = "http://150.165.205.9/anims/ANDROID/";//old
15   - private const string BASE_URL = "http://dicionario.vlibras.gov.br/ANDROID/";
  18 + //private const string BASE_URL = "http://150.165.205.9/anims/ANDROID/";//old
  19 + private const string BASE_URL = "http://dicionario.vlibras.gov.br/ANDROID/";
16 20 #endif
17 21  
18   - //private const string SERVER_URL = "http://vlibras.lavid.ufpb.br/glosa?texto=";//old
19   - private const string SERVER_URL = "http://traducao.vlibras.gov.br/translate?text=";
20   - private const int VERSION = 1;
  22 + //private const string SERVER_URL = "http://vlibras.lavid.ufpb.br/glosa?texto=";//old
  23 + private const string SERVER_URL = "http://traducao.vlibras.gov.br/translate?text=";
  24 + private const int VERSION = 1;
21 25  
22   - private Trie signs;
  26 + private Trie signs;
23 27  
24   - public enum ERROR_STATUS_MESSAGE
25   - {
26   - INTERNET_CONNECTION_FAILURE,
27   - TRANSLATOR_CONNECTION_FAILURE,
28   - CONNECTION_TIMEOUT_FAILURE
29   - }
  28 + public enum ERROR_STATUS_MESSAGE
  29 + {
  30 + INTERNET_CONNECTION_FAILURE,
  31 + TRANSLATOR_CONNECTION_FAILURE,
  32 + CONNECTION_TIMEOUT_FAILURE
  33 + }
30 34  
31 35 private string[] randomAnimationNames = new string[] {
32 36 "[RELAXAR]",
... ... @@ -35,29 +39,31 @@ public class PlayerManager : GenericPlayerManager {
35 39 "[ESPREGUI_ADA]"
36 40 };
37 41  
38   - protected VoiceRecognition voiceRecognizer;
  42 + protected VoiceRecognition voiceRecognizer;
39 43 public InputField translateScreenText;
40 44 public ScreenManager screenManager;
41 45 private string dictWord = null;
42 46 private string regionPath = "";
43   - private int regionHash = 1;
44   -
45   - public static string get_connection_status_message(ERROR_STATUS_MESSAGE msg)
46   - {
47   - switch(msg)
48   - {
49   - case ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE:
50   - return "Problema na conexão. Usaremos português sinalizado e datilologia.";
51   - case ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE:
52   - return "Não há acesso à internet. Usaremos português sinalizado e datilologia.";
53   - case ERROR_STATUS_MESSAGE.CONNECTION_TIMEOUT_FAILURE:
54   - return "Não há acesso à internet. Usaremos português sinalizado e datilologia.";
55   - //return "A conexão está lenta. Usaremos português sinalizado e datilologia.";
56   - default:
57   - return "Ocorreu um erro. Estamos trabalhando para solucioná-lo!";
58   - }
59   -
60   - }
  47 + private int regionHash = 1;
  48 +
  49 + private static string dictionaryJSON;
  50 +
  51 + public static string get_connection_status_message(ERROR_STATUS_MESSAGE msg)
  52 + {
  53 + switch(msg)
  54 + {
  55 + case ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE:
  56 + return "Problema na conexão. Usaremos português sinalizado e datilologia.";
  57 + case ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE:
  58 + return "Não há acesso à internet. Usaremos português sinalizado e datilologia.";
  59 + case ERROR_STATUS_MESSAGE.CONNECTION_TIMEOUT_FAILURE:
  60 + return "Não há acesso à internet. Usaremos português sinalizado e datilologia.";
  61 + //return "A conexão está lenta. Usaremos português sinalizado e datilologia.";
  62 + default:
  63 + return "Ocorreu um erro. Estamos trabalhando para solucioná-lo!";
  64 + }
  65 +
  66 + }
61 67  
62 68 public override void Start()
63 69 {
... ... @@ -67,32 +73,53 @@ public class PlayerManager : GenericPlayerManager {
67 73 voiceRecognizer = new VoiceRecognition();
68 74  
69 75 #if UNITY_EDITOR
70   - Caching.CleanCache();
  76 + Caching.CleanCache();
71 77 #endif
72 78  
73   - Screen.fullScreen = false;
74   -
75   - StartCoroutine(WaitForResponse(
76   - new WWW("http://dicionario.vlibras.gov.br/signs"),
77   - // Success
78   - delegate(WWW www)
79   - {
80   - this.signs = new Trie(www.text);
81   - },
82   - // Error
83   - delegate (WWW www)
84   - {
85   - if (www.error == null)
86   - PlayerLogger.Log("PM", "S<d>", "Timeout.");
87   - else
88   - PlayerLogger.Log("PM", "S<d>", "WWW error: " + www.error);
89   - }
90   - ));
91   - }
  79 + Screen.fullScreen = false;
  80 +
  81 + StartCoroutine(WaitForResponse(
  82 + new WWW("http://dicionario.vlibras.gov.br/signs"),
  83 + // Success
  84 + delegate(WWW www)
  85 + {
  86 + PlayerManager.dictionaryJSON = www.text;
  87 +
  88 + /*new Thread(
  89 + () => {
  90 + Thread.CurrentThread.IsBackground = true;*/
  91 +
  92 + Stopwatch watch = new Stopwatch();
  93 + watch.Start();
  94 +
  95 + try {
  96 + this.signs = Trie.FromJSON(new JSONParser(Regex.Unescape(PlayerManager.dictionaryJSON)));
  97 +
  98 + PlayerLogger.Log("PM", "S", "Found EU: " + this.signs.Contains("EU"));
  99 + PlayerLogger.Log("PM", "S", "Found EUE: " + this.signs.Contains("EUE"));
  100 + } catch (Exception e) {
  101 + PlayerLogger.Log("PM", "S", "Exception at trie JSON parser: " + e.ToString());
  102 + }
  103 +
  104 + watch.Stop();
  105 + PlayerLogger.Log("T", "FJ", "Parsed in " + watch.ElapsedMilliseconds + " ms.");
  106 + /* }
  107 + ).Start();*/
  108 + },
  109 + // Error
  110 + delegate (WWW www)
  111 + {
  112 + if (www.error == null)
  113 + PlayerLogger.Log("PM", "S<d>", "Timeout.");
  114 + else
  115 + PlayerLogger.Log("PM", "S<d>", "WWW error: " + www.error);
  116 + }
  117 + ));
  118 + }
92 119  
93 120 public void playDict(string word)
94 121 {
95   - PlayerLogger.Log("Requesting dictionary: " + word);
  122 + PlayerLogger.Log("Requesting dictionary: " + word);
96 123  
97 124 this.dictWord = word;
98 125 base.gloss = word;
... ... @@ -105,7 +132,7 @@ public class PlayerManager : GenericPlayerManager {
105 132 public void playTranslate()
106 133 {
107 134 stopTranslation();
108   - base.stopAll();
  135 + base.stopAll();
109 136  
110 137 string text = translateScreenText.text;
111 138 translateScreenText.text = "";
... ... @@ -128,10 +155,10 @@ public class PlayerManager : GenericPlayerManager {
128 155 }
129 156  
130 157 public void setRegion(string path)
131   - {
  158 + {
132 159 this.regionPath = String.IsNullOrEmpty(path) ? "" : path;
133   - this.regionHash = this.regionPath == "" ? 1 : (int)this.regionPath[0] * 255 + (int)this.regionPath[1];
134   - }
  160 + this.regionHash = this.regionPath == "" ? 1 : (int)this.regionPath[0] * 255 + (int)this.regionPath[1];
  161 + }
135 162  
136 163 public void clearRegion() {
137 164 setRegion("");
... ... @@ -139,23 +166,23 @@ public class PlayerManager : GenericPlayerManager {
139 166  
140 167 protected override WWW loadAssetBundle(string aniName)
141 168 {
142   - string address = BASE_URL + this.regionPath + WWW.EscapeURL(aniName);
143   -
144   - PlayerLogger.Log("PM", "lAB", "Requesting bundle: " + address);
  169 + string address = BASE_URL + this.regionPath + WWW.EscapeURL(aniName);
  170 +
  171 + PlayerLogger.Log("PM", "lAB", "Requesting bundle: " + address);
145 172 return WWW.LoadFromCacheOrDownload(address, this.regionHash);
146 173 }
147 174  
148   - public override void onPlayingStateChange() {
  175 + public override void onPlayingStateChange() {
149 176 this.screenManager.changeStates(base.isPlaying(), base.isPaused(), ! String.IsNullOrEmpty(base.gloss));
150 177 }
151 178  
152   - public override void onConnectionError(string gloss, string word)
  179 + public override void onConnectionError(string gloss, string word)
153 180 {
154 181 if (gloss.Equals(this.dictWord))
155 182 {
156   - this.dictWord = "";
157   - this.screenManager.showConnectionErrorDialog(
158   - PlayerManager.ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE);
  183 + this.dictWord = "";
  184 + this.screenManager.showConnectionErrorDialog(
  185 + PlayerManager.ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE);
159 186  
160 187 base.stopAll();
161 188 }
... ... @@ -173,89 +200,89 @@ public class PlayerManager : GenericPlayerManager {
173 200 this.screenManager.switchScreen("translate");
174 201 }
175 202  
176   - protected override WWW getCheckConnectionRequest()
177   - {
178   - return new WWW(BASE_URL);
179   -
180   -
181   - /*WWW connection = new WWW(SERVER_URL);
182   - yield return connection;
183   - //while (!glossRequest.isDone)
184   -
185   - if (connection.error == null)
186   - {
187   - if (connection.responseHeaders.Count > 0)
188   - PlayerLogger.Log(connection.responseHeaders["STATUS"]);
189   - else
190   - PlayerLogger.Log("No STATUS");
191   - }
192   - else PlayerLogger.Log("ERROR: " + connection.error);
193   -
194   - return false;*/
195   -
196   -
197   - /*HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BASE_URL);
198   - request.Method = "HEAD";
199   - request.Timeout = 2000;
200   -
201   - try {
202   - HttpWebResponse response = (HttpWebResponse) request.GetResponse();
203   - }
204   - catch (WebException e)
205   - {
206   - if (e.Response != null)
207   - {
208   - PlayerLogger.Log(((HttpWebResponse)e.Response).StatusCode);
209   - return ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.NotFound;
210   - }
211   - }
212   - catch (Exception)
213   - {
214   - }
215   -
216   - return false;*/
217   - }
218   -
219   - protected delegate void SuccessEvent(WWW request);
220   - protected delegate void ErrorEvent(WWW request);
221   -
222   - protected IEnumerator WaitForResponse(WWW www, SuccessEvent success, ErrorEvent error)
223   - {
224   - PlayerLogger.Log("PM", "WFR", "Stating time check.");
225   -
226   - const float timeoutLimit = 20f;
227   - float timer = 0;
228   -
229   - while (!www.isDone)
230   - {
231   - if (timer > timeoutLimit)
232   - {
233   - PlayerLogger.Log("PM", "WFR", "Timeout (" + timer + ").");
234   - if (error != null) error(www);
235   - yield break;
236   - }
  203 + protected override WWW getCheckConnectionRequest()
  204 + {
  205 + return new WWW(BASE_URL);
  206 +
  207 +
  208 + /*WWW connection = new WWW(SERVER_URL);
  209 + yield return connection;
  210 + //while (!glossRequest.isDone)
  211 +
  212 + if (connection.error == null)
  213 + {
  214 + if (connection.responseHeaders.Count > 0)
  215 + PlayerLogger.Log(connection.responseHeaders["STATUS"]);
  216 + else
  217 + PlayerLogger.Log("No STATUS");
  218 + }
  219 + else PlayerLogger.Log("ERROR: " + connection.error);
  220 +
  221 + return false;*/
  222 +
  223 +
  224 + /*HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BASE_URL);
  225 + request.Method = "HEAD";
  226 + request.Timeout = 2000;
  227 +
  228 + try {
  229 + HttpWebResponse response = (HttpWebResponse) request.GetResponse();
  230 + }
  231 + catch (WebException e)
  232 + {
  233 + if (e.Response != null)
  234 + {
  235 + PlayerLogger.Log(((HttpWebResponse)e.Response).StatusCode);
  236 + return ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.NotFound;
  237 + }
  238 + }
  239 + catch (Exception)
  240 + {
  241 + }
  242 +
  243 + return false;*/
  244 + }
  245 +
  246 + protected delegate void SuccessEvent(WWW request);
  247 + protected delegate void ErrorEvent(WWW request);
  248 +
  249 + protected IEnumerator WaitForResponse(WWW www, SuccessEvent success, ErrorEvent error)
  250 + {
  251 + PlayerLogger.Log("PM", "WFR", "Stating time check.");
  252 +
  253 + const float timeoutLimit = 20f;
  254 + float timer = 0;
  255 +
  256 + while (!www.isDone)
  257 + {
  258 + if (timer > timeoutLimit)
  259 + {
  260 + PlayerLogger.Log("PM", "WFR", "Timeout (" + timer + ").");
  261 + if (error != null) error(www);
  262 + yield break;
  263 + }
237 264  
238 265 #if UNITY_ANDROID
239   - timer += Time.deltaTime;
240   - yield return null;
  266 + timer += Time.deltaTime;
  267 + yield return null;
241 268 #elif UNITY_IOS
242   - timer += 0.1f;
243   - yield return new WaitForSeconds(0.1f);
  269 + timer += 0.1f;
  270 + yield return new WaitForSeconds(0.1f);
244 271 #endif
245   - }
  272 + }
246 273  
247   - PlayerLogger.Log("PM", "WFR", "Done (" + timer + ").");
  274 + PlayerLogger.Log("PM", "WFR", "Done (" + timer + ").");
248 275  
249   - if (www.error == null) {
250   - if (success != null) success(www);
251   - } else {
252   - if (error != null) error(www);
253   - }
254   - }
  276 + if (www.error == null) {
  277 + if (success != null) success(www);
  278 + } else {
  279 + if (error != null) error(www);
  280 + }
  281 + }
255 282  
256   - protected override IEnumerator WaitForResponse(WWW www) {
257   - yield return WaitForResponse(www, null, null);
258   - }
  283 + protected override IEnumerator WaitForResponse(WWW www) {
  284 + yield return WaitForResponse(www, null, null);
  285 + }
259 286  
260 287 private IEnumerator translate(string gloss)
261 288 {
... ... @@ -264,63 +291,63 @@ public class PlayerManager : GenericPlayerManager {
264 291  
265 292 WWW glossRequest = new WWW(SERVER_URL + WWW.EscapeURL(gloss));
266 293  
267   - PlayerLogger.Log("PM", "t", "Gloss: " + gloss);
268   - PlayerLogger.Log("PM", "t", "Request: " + SERVER_URL + WWW.EscapeURL(gloss));
269   -
270   - yield return WaitForResponse(glossRequest);
271   -
272   - try {
273   - if ( ! glossRequest.isDone)
274   - {
275   - this.screenManager.showConnectionErrorDialog(
276   - PlayerManager.ERROR_STATUS_MESSAGE.CONNECTION_TIMEOUT_FAILURE);
277   -
278   - PlayerLogger.Log("PM", "t", "Timeout.");
279   - }
280   - else if (glossRequest.error != null)
281   - {
282   - this.screenManager.showConnectionErrorDialog(
283   - PlayerManager.ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE);
284   -
285   - PlayerLogger.Log("PM", "t", "(WWW) Error: " + glossRequest.error);
286   - }
287   - else if (glossRequest.responseHeaders.Count == 0)
288   - {
289   - PlayerLogger.Log("PM", "t", "Unsuccessful answer (0).");
290   -
291   - this.screenManager.showConnectionErrorDialog(
292   - PlayerManager.ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE);
293   - }
294   - else if (!glossRequest.responseHeaders["STATUS"].Contains("200"))
295   - {
296   - PlayerLogger.Log("PM", "t", "Unsuccessful answer (" + glossRequest.responseHeaders["STATUS"] + ").");
297   -
298   - this.screenManager.showConnectionErrorDialog(
299   - PlayerManager.ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE);
300   - }
301   - else if (String.IsNullOrEmpty(glossRequest.text))
302   - {
303   - PlayerLogger.Log("PM", "t", "Empty answer.");
304   - }
305   - else
306   - {
307   - PlayerLogger.Log("PM", "t", "Answer: " + glossRequest.text);
308   -
309   - gloss = glossRequest.text;
310   -
311   - base.gloss = gloss;
312   - base.playNow(base.gloss);
313   -
314   - yield break;
315   - }
316   -
317   - base.gloss = gloss.ToUpper();
318   - }
319   - finally
320   - {
321   - this.screenManager.setLoadingSnippetState(false);
322   - base.randomAnimations.unlockFor("translate");
323   - }
324   - }
  294 + PlayerLogger.Log("PM", "t", "Gloss: " + gloss);
  295 + PlayerLogger.Log("PM", "t", "Request: " + SERVER_URL + WWW.EscapeURL(gloss));
  296 +
  297 + yield return WaitForResponse(glossRequest);
  298 +
  299 + try {
  300 + if ( ! glossRequest.isDone)
  301 + {
  302 + this.screenManager.showConnectionErrorDialog(
  303 + PlayerManager.ERROR_STATUS_MESSAGE.CONNECTION_TIMEOUT_FAILURE);
  304 +
  305 + PlayerLogger.Log("PM", "t", "Timeout.");
  306 + }
  307 + else if (glossRequest.error != null)
  308 + {
  309 + this.screenManager.showConnectionErrorDialog(
  310 + PlayerManager.ERROR_STATUS_MESSAGE.INTERNET_CONNECTION_FAILURE);
  311 +
  312 + PlayerLogger.Log("PM", "t", "(WWW) Error: " + glossRequest.error);
  313 + }
  314 + else if (glossRequest.responseHeaders.Count == 0)
  315 + {
  316 + PlayerLogger.Log("PM", "t", "Unsuccessful answer (0).");
  317 +
  318 + this.screenManager.showConnectionErrorDialog(
  319 + PlayerManager.ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE);
  320 + }
  321 + else if (!glossRequest.responseHeaders["STATUS"].Contains("200"))
  322 + {
  323 + PlayerLogger.Log("PM", "t", "Unsuccessful answer (" + glossRequest.responseHeaders["STATUS"] + ").");
  324 +
  325 + this.screenManager.showConnectionErrorDialog(
  326 + PlayerManager.ERROR_STATUS_MESSAGE.TRANSLATOR_CONNECTION_FAILURE);
  327 + }
  328 + else if (String.IsNullOrEmpty(glossRequest.text))
  329 + {
  330 + PlayerLogger.Log("PM", "t", "Empty answer.");
  331 + }
  332 + else
  333 + {
  334 + PlayerLogger.Log("PM", "t", "Answer: " + glossRequest.text);
  335 +
  336 + gloss = glossRequest.text;
  337 +
  338 + base.gloss = gloss;
  339 + base.playNow(base.gloss);
  340 +
  341 + yield break;
  342 + }
  343 +
  344 + base.gloss = gloss.ToUpper();
  345 + }
  346 + finally
  347 + {
  348 + this.screenManager.setLoadingSnippetState(false);
  349 + base.randomAnimations.unlockFor("translate");
  350 + }
  351 + }
325 352  
326 353 }
... ...
Assets/Scripts/Trie.meta 0 → 100644
... ... @@ -0,0 +1,9 @@
  1 +fileFormatVersion: 2
  2 +guid: 74962ddb2af5e5043bab96b791977d1c
  3 +folderAsset: yes
  4 +timeCreated: 1476578842
  5 +licenseType: Pro
  6 +DefaultImporter:
  7 + userData:
  8 + assetBundleName:
  9 + assetBundleVariant:
... ...
Assets/Scripts/Trie/JSONParser.cs 0 → 100644
... ... @@ -0,0 +1,302 @@
  1 +using LAViD.VLibras.Utils;
  2 +using System;
  3 +using System.Collections.Generic;
  4 +using System.Linq;
  5 +using System.Text;
  6 +
  7 +namespace LAViD.Utils
  8 +{
  9 + class JSONParser
  10 + {
  11 + private static readonly string True = "true";
  12 + private static readonly string False = "false";
  13 +
  14 + public static int ParseStringLengthLimit = 1024;
  15 +
  16 + private string json;
  17 + private int index;
  18 +
  19 + public JSONParser(string json)
  20 + {
  21 + this.json = json;
  22 + this.index = 0;
  23 + }
  24 +
  25 + public delegate T Casting<T>(string value);
  26 + public delegate T Parser<T>(JSONParser json);
  27 +
  28 + private static string defaultCasting(string value)
  29 + {
  30 + return value;
  31 + }
  32 +
  33 + public static int IntParseCallback(JSONParser json)
  34 + {
  35 + StringBuilder str = new StringBuilder();
  36 +
  37 + if (json.Current('-'))
  38 + {
  39 + str.Append(json.Current());
  40 + json.Next();
  41 + }
  42 +
  43 + while (char.IsDigit(json.Current()))
  44 + {
  45 + str.Append(json.Current());
  46 + json.Next();
  47 + }
  48 +
  49 + // PlayerLogger.Log("JP", "IPC", "Result: '" + str.ToString() + "', at " + json.Current());
  50 +
  51 + if (str.Length == 0)
  52 + throw new FormatException("No digit found.");
  53 + else
  54 + return int.Parse(str.ToString());
  55 + }
  56 +
  57 + public char Current()
  58 + {
  59 + return this.json[this.index];
  60 + }
  61 +
  62 + public bool Current(char value)
  63 + {
  64 + return this.json[this.index].Equals(value);
  65 + }
  66 +
  67 + public char Next()
  68 + {
  69 + return this.json[++this.index];
  70 + }
  71 +
  72 + public bool Next(char value)
  73 + {
  74 + return Jump().Current(value);
  75 + }
  76 +
  77 + public bool End()
  78 + {
  79 + return this.index >= this.json.Length;
  80 + }
  81 +
  82 + public JSONParser Find(char value)
  83 + {
  84 + if (!Current(value))
  85 + while (!End() && !Next(value)) ;
  86 +
  87 + return this;
  88 + }
  89 +
  90 + public JSONParser FindString()
  91 + {
  92 + return Find('"');
  93 + }
  94 +
  95 + public JSONParser FindList()
  96 + {
  97 + return Find('[');
  98 + }
  99 +
  100 + public JSONParser FindDictionary()
  101 + {
  102 + return Find('{');
  103 + }
  104 +
  105 + public JSONParser Jump(int num)
  106 + {
  107 + this.index += num;
  108 + // PlayerLogger.Log("JP", "J", num + " (" + this.index + ", " + Current() + ")");
  109 + return this;
  110 + }
  111 +
  112 + public JSONParser Jump()
  113 + {
  114 + return Jump(1);
  115 + }
  116 +
  117 + public string ParseString()
  118 + {
  119 + if (!Current().Equals('"')) return null;
  120 +
  121 + StringBuilder str = new StringBuilder();
  122 +
  123 + while (!Next('"'))
  124 + {
  125 + str.Append(Current());
  126 +
  127 + if (str.Length > ParseStringLengthLimit)
  128 + throw new FormatException("String exceeded length limit " + ParseStringLengthLimit + ".");
  129 + }
  130 +
  131 + // PlayerLogger.Log("JP", "PS", "Result: '" + str.ToString() + "', at " + Current());
  132 +
  133 + Jump();
  134 + return str.ToString();
  135 + }
  136 +
  137 + public bool Contains(string value)
  138 + {
  139 + StringBuilder s = new StringBuilder();
  140 + for (int i = 0; i < value.Length; i++)
  141 + if (!value[i].Equals(this.json[this.index + i]))
  142 + return false;
  143 + else
  144 + s.Append(this.json[this.index + i]);
  145 +
  146 + Jump(value.Length);
  147 + return true;
  148 + }
  149 +
  150 + public bool ParseBoolean()
  151 + {
  152 + if (Contains(True)) return true;
  153 + else if (Contains(False)) return false;
  154 + else throw new FormatException("Boolean not found.");
  155 + }
  156 +
  157 + public List<T> ParseList<T>(Casting<T> casting)
  158 + {
  159 + if (!Current().Equals('[')) return null;
  160 +
  161 + // PlayerLogger.Log("JP", "PL", "Parsing at '" + Current() + "'.");
  162 +
  163 + List<T> list = new List<T>();
  164 +
  165 + while (!Current().Equals(']'))
  166 + if (Current().Equals('"'))
  167 + list.Add(casting(ParseString()));
  168 + else
  169 + Jump();
  170 +
  171 + Jump();
  172 + return list;
  173 + }
  174 +
  175 + public List<string> ParseList()
  176 + {
  177 + return ParseList<string>(defaultCasting);
  178 + }
  179 +
  180 + public List<T> ParseList<T>(Parser<T> callback)
  181 + {
  182 + if (!Current().Equals('[')) return null;
  183 +
  184 + // PlayerLogger.Log("JP", "PL", "Parsing at '" + Current() + "'.");
  185 +
  186 + List<T> list = new List<T>();
  187 +
  188 + Jump();
  189 + while (!Current().Equals(']'))
  190 + {
  191 + if (Current(' ') || Current(','))
  192 + Jump();
  193 + else
  194 + list.Add(callback(this));
  195 + }
  196 +
  197 + Jump();
  198 + return list;
  199 + }
  200 +
  201 + public Dictionary<A, B> ParseDictionary<A, B>(Casting<A> keyCasting, Parser<B> valueCallback)
  202 + {
  203 + if (!Current().Equals('{')) return null;
  204 +
  205 + // PlayerLogger.Log("JP", "PD", "Parsing at '" + Current() + "'.");
  206 +
  207 + Dictionary<A, B> dict = new Dictionary<A, B>();
  208 +
  209 + while (!Current().Equals('}'))
  210 + {
  211 + if (Current().Equals('"'))
  212 + {
  213 + A key = keyCasting(ParseString());
  214 + B value = valueCallback(Jump(2));
  215 +
  216 + // PlayerLogger.Log("JP", "PD", "Adding '" + key + "', '" + value + "'");
  217 +
  218 + dict.Add(key, value);
  219 + }
  220 + else Jump();
  221 + }
  222 +
  223 + // PlayerLogger.Log("JP", "PD", "Finish at '" + Current() + "'");
  224 +
  225 + Jump();
  226 + return dict;
  227 + }
  228 +
  229 + public Dictionary<A, B> ParseDictionary<A, B>(Casting<A> keyCasting, Casting<B> valueCasting)
  230 + {
  231 + if (!Current().Equals('{')) return null;
  232 +
  233 + // PlayerLogger.Log("JP", "PD", "Parsing at '" + Current() + "'");
  234 +
  235 + Dictionary<A, B> dict = new Dictionary<A, B>();
  236 +
  237 + while (!Current().Equals('}'))
  238 + if (Current().Equals('"'))
  239 + dict.Add(keyCasting(ParseString()), valueCasting(Jump(2).ParseString()));
  240 + else
  241 + Jump();
  242 +
  243 + Jump();
  244 + return dict;
  245 + }
  246 +
  247 + public Dictionary<string, string> ParseDictionary()
  248 + {
  249 + return ParseDictionary<string, string>(defaultCasting, defaultCasting);
  250 + }
  251 + }
  252 +
  253 + class JSONObject<T>
  254 + {
  255 + public delegate T Creator();
  256 + public delegate void Assigner(JSONParser json, T obj);
  257 +
  258 + private Creator create;
  259 + private Dictionary<string, Assigner> fields = new Dictionary<string, Assigner>();
  260 +
  261 + public JSONObject() { }
  262 +
  263 + public JSONObject(Creator creator) {
  264 + this.create = creator;
  265 + }
  266 +
  267 + public JSONObject<T> Add(string field, Assigner assigner)
  268 + {
  269 + this.fields.Add(field, assigner);
  270 + return this;
  271 + }
  272 +
  273 + public T Parse(JSONParser json) {
  274 + return Parse(json, this.create);
  275 + }
  276 +
  277 + public T Parse(JSONParser json, Creator create)
  278 + {
  279 + if (!json.Current('{')) throw new FormatException("JSONParser is not at an object position.");
  280 +
  281 + T obj = create();
  282 +
  283 + while (!json.Current('}')) {
  284 + if (json.Current('"'))
  285 + {
  286 + //PlayerLogger.Log("JO", "P", "Found a field.");
  287 +
  288 + string field = json.ParseString();
  289 +
  290 + //PlayerLogger.Log("JO", "P", "Found: '" + field + "'.");
  291 +
  292 + if (this.fields.ContainsKey(field))
  293 + this.fields[field](json.Jump(2), obj);
  294 + }
  295 + else json.Jump();
  296 + }
  297 +
  298 + json.Jump();
  299 + return obj;
  300 + }
  301 + }
  302 +}
... ...
Assets/Scripts/Trie/JSONParser.cs.meta 0 → 100644
... ... @@ -0,0 +1,12 @@
  1 +fileFormatVersion: 2
  2 +guid: a31b557b2c4f66b4b8ced30ae19f4d8f
  3 +timeCreated: 1476578842
  4 +licenseType: Pro
  5 +MonoImporter:
  6 + serializedVersion: 2
  7 + defaultReferences: []
  8 + executionOrder: 0
  9 + icon: {instanceID: 0}
  10 + userData:
  11 + assetBundleName:
  12 + assetBundleVariant:
... ...
Assets/Scripts/Trie/Trie.cs 0 → 100644
... ... @@ -0,0 +1,123 @@
  1 +using LAViD.Utils;
  2 +using LAViD.VLibras.Utils;
  3 +using System;
  4 +using System.Collections.Generic;
  5 +using System.Diagnostics;
  6 +using System.Linq;
  7 +using System.Text;
  8 +using System.Text.RegularExpressions;
  9 +
  10 +namespace LAViD.Structures
  11 +{
  12 + class Trie
  13 + {
  14 + private char[] characters;
  15 + private Dictionary<char, int> keys;
  16 + private Node root;
  17 +
  18 + private readonly static JSONObject<Trie> Parser = new JSONObject<Trie>(delegate () { return new Trie(); })
  19 + .Add("keys", delegate (JSONParser jsonParser, Trie obj)
  20 + {
  21 + PlayerLogger.Log("T", "FJ", "Checking 'keys'.");
  22 + obj.keys = jsonParser.ParseDictionary<char, int>(char.Parse, JSONParser.IntParseCallback);
  23 + })
  24 + .Add("trie", delegate (JSONParser jsonParser, Trie obj)
  25 + {
  26 + PlayerLogger.Log("T", "FJ", "Checking 'trie'.");
  27 + obj.root = Node.FromJSON(jsonParser, obj.keys.Count);
  28 + })
  29 + .Add("characters", delegate (JSONParser jsonParser, Trie obj)
  30 + {
  31 + PlayerLogger.Log("T", "FJ", "Checking 'characters'.");
  32 + obj.characters = jsonParser.ParseList<char>(char.Parse).ToArray();
  33 + });
  34 +
  35 + public static Trie FromJSON(JSONParser json)
  36 + {
  37 + PlayerLogger.Log("T", "FJ", "Starting trie parsing.");
  38 +
  39 + Trie trie = Trie.Parser.Parse(json);
  40 +
  41 + return trie;
  42 + }
  43 +
  44 + public bool Contains(string word)
  45 + {
  46 + Node node = this.root;
  47 +
  48 + foreach (char c in word)
  49 + {
  50 + node = node.children[this.keys[c]];
  51 + if (node == null) break;
  52 + }
  53 +
  54 + if (node == null) return false;
  55 + else return node.end;
  56 + }
  57 +
  58 + public List<string> StartsWith(string word)
  59 + {
  60 + List<string> list = new List<string>();
  61 + Node node = this.root;
  62 +
  63 + foreach (char c in word)
  64 + {
  65 + node = node.children[this.keys[c]];
  66 + if (node == null) break;
  67 + }
  68 +
  69 + if (node != null) feed(list, "", node);
  70 +
  71 + return list;
  72 + }
  73 +
  74 + private void feed(List<string> list, string word, Node node)
  75 + {
  76 + if (node.end) list.Add(word);
  77 +
  78 + for (int i = 0; i < node.children.Length; i++)
  79 + if (node.children[i] != null)
  80 + feed(list, word + this.characters[i], node.children[i]);
  81 + }
  82 +
  83 +
  84 + private class Node
  85 + {
  86 + public bool end = false;
  87 + public Node[] children = null;
  88 + public int maxChildren;
  89 +
  90 + public Node(int maxChildren) {
  91 + this.maxChildren = maxChildren;
  92 + }
  93 +
  94 + private readonly static JSONObject<Node> Parser = new JSONObject<Node>()
  95 + .Add("keys", delegate (JSONParser jsonParser, Node obj)
  96 + {
  97 + jsonParser.ParseList<int>(JSONParser.IntParseCallback);
  98 + })
  99 + .Add("end", delegate (JSONParser jsonParser, Node obj)
  100 + {
  101 + obj.end = jsonParser.ParseBoolean();
  102 + })
  103 + .Add("children", delegate (JSONParser jsonParser, Node obj)
  104 + {
  105 + Dictionary<int, Node> children = jsonParser.ParseDictionary<int, Node>(
  106 + int.Parse,
  107 + delegate (JSONParser innerJSONParser) {
  108 + return Node.FromJSON(innerJSONParser, obj.maxChildren);
  109 + }
  110 + );
  111 +
  112 + obj.children = new Node[obj.maxChildren];
  113 +
  114 + foreach (KeyValuePair<int, Node> pair in children)
  115 + obj.children[pair.Key] = pair.Value;
  116 + });
  117 +
  118 + public static Node FromJSON(JSONParser json, int maxChildren) {
  119 + return Node.Parser.Parse(json, delegate () { return new Node(maxChildren); });
  120 + }
  121 + }
  122 + }
  123 +}
... ...
Assets/Scripts/Trie/Trie.cs.meta 0 → 100644
... ... @@ -0,0 +1,12 @@
  1 +fileFormatVersion: 2
  2 +guid: 3238f46fe9379b2469349a4bce058b65
  3 +timeCreated: 1476557067
  4 +licenseType: Pro
  5 +MonoImporter:
  6 + serializedVersion: 2
  7 + defaultReferences: []
  8 + executionOrder: 0
  9 + icon: {instanceID: 0}
  10 + userData:
  11 + assetBundleName:
  12 + assetBundleVariant:
... ...