icloud.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*************************************************************************/
  2. /* icloud.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef ICLOUD_ENABLED
  31. #include "icloud.h"
  32. #ifndef __IPHONE_9_0
  33. extern "C" {
  34. #endif
  35. #import "app_delegate.h"
  36. #import <Foundation/Foundation.h>
  37. #ifndef __IPHONE_9_0
  38. };
  39. #endif
  40. ICloud *ICloud::instance = NULL;
  41. void ICloud::_bind_methods() {
  42. ClassDB::bind_method(D_METHOD("remove_key"), &ICloud::remove_key);
  43. ClassDB::bind_method(D_METHOD("set_key_values"), &ICloud::set_key_values);
  44. ClassDB::bind_method(D_METHOD("get_key_value"), &ICloud::get_key_value);
  45. ClassDB::bind_method(D_METHOD("synchronize_key_values"), &ICloud::synchronize_key_values);
  46. ClassDB::bind_method(D_METHOD("get_all_key_values"), &ICloud::get_all_key_values);
  47. ClassDB::bind_method(D_METHOD("get_pending_event_count"), &ICloud::get_pending_event_count);
  48. ClassDB::bind_method(D_METHOD("pop_pending_event"), &ICloud::pop_pending_event);
  49. };
  50. int ICloud::get_pending_event_count() {
  51. return pending_events.size();
  52. };
  53. Variant ICloud::pop_pending_event() {
  54. Variant front = pending_events.front()->get();
  55. pending_events.pop_front();
  56. return front;
  57. };
  58. ICloud *ICloud::get_singleton() {
  59. return instance;
  60. };
  61. //convert from apple's abstract type to godot's abstract type....
  62. Variant nsobject_to_variant(NSObject *object) {
  63. if ([object isKindOfClass:[NSString class]]) {
  64. const char *str = [(NSString *)object UTF8String];
  65. return String::utf8(str != NULL ? str : "");
  66. } else if ([object isKindOfClass:[NSData class]]) {
  67. PoolByteArray ret;
  68. NSData *data = (NSData *)object;
  69. if ([data length] > 0) {
  70. ret.resize([data length]);
  71. {
  72. PoolByteArray::Write w = ret.write();
  73. copymem(w.ptr(), [data bytes], [data length]);
  74. }
  75. }
  76. return ret;
  77. } else if ([object isKindOfClass:[NSArray class]]) {
  78. Array result;
  79. NSArray *array = (NSArray *)object;
  80. for (unsigned int i = 0; i < [array count]; ++i) {
  81. NSObject *value = [array objectAtIndex:i];
  82. result.push_back(nsobject_to_variant(value));
  83. }
  84. return result;
  85. } else if ([object isKindOfClass:[NSDictionary class]]) {
  86. Dictionary result;
  87. NSDictionary *dic = (NSDictionary *)object;
  88. NSArray *keys = [dic allKeys];
  89. int count = [keys count];
  90. for (int i = 0; i < count; ++i) {
  91. NSObject *k = [keys objectAtIndex:i];
  92. NSObject *v = [dic objectForKey:k];
  93. result[nsobject_to_variant(k)] = nsobject_to_variant(v);
  94. }
  95. return result;
  96. } else if ([object isKindOfClass:[NSNumber class]]) {
  97. //Every type except numbers can reliably identify its type. The following is comparing to the *internal* representation, which isn't guaranteed to match the type that was used to create it, and is not advised, particularly when dealing with potential platform differences (ie, 32/64 bit)
  98. //To avoid errors, we'll cast as broadly as possible, and only return int or float.
  99. //bool, char, int, uint, longlong -> int
  100. //float, double -> float
  101. NSNumber *num = (NSNumber *)object;
  102. if (strcmp([num objCType], @encode(BOOL)) == 0) {
  103. return Variant((int)[num boolValue]);
  104. } else if (strcmp([num objCType], @encode(char)) == 0) {
  105. return Variant((int)[num charValue]);
  106. } else if (strcmp([num objCType], @encode(int)) == 0) {
  107. return Variant([num intValue]);
  108. } else if (strcmp([num objCType], @encode(unsigned int)) == 0) {
  109. return Variant((int)[num unsignedIntValue]);
  110. } else if (strcmp([num objCType], @encode(long long)) == 0) {
  111. return Variant((int)[num longValue]);
  112. } else if (strcmp([num objCType], @encode(float)) == 0) {
  113. return Variant([num floatValue]);
  114. } else if (strcmp([num objCType], @encode(double)) == 0) {
  115. return Variant((float)[num doubleValue]);
  116. } else {
  117. return Variant();
  118. }
  119. } else if ([object isKindOfClass:[NSDate class]]) {
  120. //this is a type that icloud supports...but how did you submit it in the first place?
  121. //I guess this is a type that *might* show up, if you were, say, trying to make your game
  122. //compatible with existing cloud data written by another engine's version of your game
  123. WARN_PRINT("NSDate unsupported, returning null Variant")
  124. return Variant();
  125. } else if ([object isKindOfClass:[NSNull class]] or object == nil) {
  126. return Variant();
  127. } else {
  128. WARN_PRINT("Trying to convert unknown NSObject type to Variant");
  129. return Variant();
  130. }
  131. }
  132. NSObject *variant_to_nsobject(Variant v) {
  133. if (v.get_type() == Variant::STRING) {
  134. return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease];
  135. } else if (v.get_type() == Variant::REAL) {
  136. return [NSNumber numberWithDouble:(double)v];
  137. } else if (v.get_type() == Variant::INT) {
  138. return [NSNumber numberWithLongLong:(long)(int)v];
  139. } else if (v.get_type() == Variant::BOOL) {
  140. return [NSNumber numberWithBool:BOOL((bool)v)];
  141. } else if (v.get_type() == Variant::DICTIONARY) {
  142. NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
  143. Dictionary dic = v;
  144. Array keys = dic.keys();
  145. for (unsigned int i = 0; i < keys.size(); ++i) {
  146. NSString *key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease];
  147. NSObject *value = variant_to_nsobject(dic[keys[i]]);
  148. if (key == NULL || value == NULL) {
  149. return NULL;
  150. }
  151. [result setObject:value forKey:key];
  152. }
  153. return result;
  154. } else if (v.get_type() == Variant::ARRAY) {
  155. NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease];
  156. Array arr = v;
  157. for (unsigned int i = 0; i < arr.size(); ++i) {
  158. NSObject *value = variant_to_nsobject(arr[i]);
  159. if (value == NULL) {
  160. //trying to add something unsupported to the array. cancel the whole array
  161. return NULL;
  162. }
  163. [result addObject:value];
  164. }
  165. return result;
  166. } else if (v.get_type() == Variant::POOL_BYTE_ARRAY) {
  167. PoolByteArray arr = v;
  168. PoolByteArray::Read r = arr.read();
  169. NSData *result = [NSData dataWithBytes:r.ptr() length:arr.size()];
  170. return result;
  171. }
  172. WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type()) + "'").utf8().get_data());
  173. return NULL;
  174. }
  175. Error ICloud::remove_key(Variant p_param) {
  176. String param = p_param;
  177. NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  178. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  179. if (![[store dictionaryRepresentation] objectForKey:key]) {
  180. return ERR_INVALID_PARAMETER;
  181. }
  182. [store removeObjectForKey:key];
  183. return OK;
  184. }
  185. //return an array of the keys that could not be set
  186. Variant ICloud::set_key_values(Variant p_params) {
  187. Dictionary params = p_params;
  188. Array keys = params.keys();
  189. Array error_keys;
  190. for (unsigned int i = 0; i < keys.size(); ++i) {
  191. String variant_key = keys[i];
  192. Variant variant_value = params[variant_key];
  193. NSString *key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease];
  194. if (key == NULL) {
  195. error_keys.push_back(variant_key);
  196. continue;
  197. }
  198. NSObject *value = variant_to_nsobject(variant_value);
  199. if (value == NULL) {
  200. error_keys.push_back(variant_key);
  201. continue;
  202. }
  203. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  204. [store setObject:value forKey:key];
  205. }
  206. return error_keys;
  207. }
  208. Variant ICloud::get_key_value(Variant p_param) {
  209. String param = p_param;
  210. NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  211. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  212. if (![[store dictionaryRepresentation] objectForKey:key]) {
  213. return Variant();
  214. }
  215. Variant result = nsobject_to_variant([[store dictionaryRepresentation] objectForKey:key]);
  216. return result;
  217. }
  218. Variant ICloud::get_all_key_values() {
  219. Dictionary result;
  220. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  221. NSDictionary *store_dictionary = [store dictionaryRepresentation];
  222. NSArray *keys = [store_dictionary allKeys];
  223. int count = [keys count];
  224. for (int i = 0; i < count; ++i) {
  225. NSString *k = [keys objectAtIndex:i];
  226. NSObject *v = [store_dictionary objectForKey:k];
  227. const char *str = [k UTF8String];
  228. if (str != NULL) {
  229. result[String::utf8(str)] = nsobject_to_variant(v);
  230. }
  231. }
  232. return result;
  233. }
  234. Error ICloud::synchronize_key_values() {
  235. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  236. BOOL result = [store synchronize];
  237. if (result == YES) {
  238. return OK;
  239. } else {
  240. return FAILED;
  241. }
  242. }
  243. /*
  244. Error ICloud::initial_sync() {
  245. //you sometimes have to write something to the store to get it to download new data. go apple!
  246. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  247. if ([store boolForKey:@"isb"])
  248. {
  249. [store setBool:NO forKey:@"isb"];
  250. }
  251. else
  252. {
  253. [store setBool:YES forKey:@"isb"];
  254. }
  255. return synchronize();
  256. }
  257. */
  258. ICloud::ICloud() {
  259. ERR_FAIL_COND(instance != NULL);
  260. instance = this;
  261. //connected = false;
  262. [[NSNotificationCenter defaultCenter]
  263. addObserverForName:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
  264. object:[NSUbiquitousKeyValueStore defaultStore]
  265. queue:nil
  266. usingBlock:^(NSNotification *notification) {
  267. NSDictionary *userInfo = [notification userInfo];
  268. NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
  269. Dictionary ret;
  270. ret["type"] = "key_value_changed";
  271. //PoolStringArray result_keys;
  272. //Array result_values;
  273. Dictionary keyValues;
  274. String reason = "";
  275. if (change == NSUbiquitousKeyValueStoreServerChange) {
  276. reason = "server";
  277. } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
  278. reason = "initial_sync";
  279. } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
  280. reason = "quota_violation";
  281. } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
  282. reason = "account";
  283. }
  284. ret["reason"] = reason;
  285. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  286. NSArray *keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
  287. for (NSString *key in keys) {
  288. const char *str = [key UTF8String];
  289. if (str == NULL) {
  290. continue;
  291. }
  292. NSObject *object = [store objectForKey:key];
  293. //figure out what kind of object it is
  294. Variant value = nsobject_to_variant(object);
  295. keyValues[String::utf8(str)] = value;
  296. }
  297. ret["changed_values"] = keyValues;
  298. pending_events.push_back(ret);
  299. }];
  300. }
  301. ICloud::~ICloud(){};
  302. #endif