icloud.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*************************************************************************/
  2. /* icloud.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #import "app_delegate.h"
  33. #import <Foundation/Foundation.h>
  34. ICloud *ICloud::instance = NULL;
  35. void ICloud::_bind_methods() {
  36. ClassDB::bind_method(D_METHOD("remove_key"), &ICloud::remove_key);
  37. ClassDB::bind_method(D_METHOD("set_key_values"), &ICloud::set_key_values);
  38. ClassDB::bind_method(D_METHOD("get_key_value"), &ICloud::get_key_value);
  39. ClassDB::bind_method(D_METHOD("synchronize_key_values"), &ICloud::synchronize_key_values);
  40. ClassDB::bind_method(D_METHOD("get_all_key_values"), &ICloud::get_all_key_values);
  41. ClassDB::bind_method(D_METHOD("get_pending_event_count"), &ICloud::get_pending_event_count);
  42. ClassDB::bind_method(D_METHOD("pop_pending_event"), &ICloud::pop_pending_event);
  43. };
  44. int ICloud::get_pending_event_count() {
  45. return pending_events.size();
  46. };
  47. Variant ICloud::pop_pending_event() {
  48. Variant front = pending_events.front()->get();
  49. pending_events.pop_front();
  50. return front;
  51. };
  52. ICloud *ICloud::get_singleton() {
  53. return instance;
  54. };
  55. //convert from apple's abstract type to godot's abstract type....
  56. Variant nsobject_to_variant(NSObject *object) {
  57. if ([object isKindOfClass:[NSString class]]) {
  58. const char *str = [(NSString *)object UTF8String];
  59. return String::utf8(str != NULL ? str : "");
  60. } else if ([object isKindOfClass:[NSData class]]) {
  61. PoolByteArray ret;
  62. NSData *data = (NSData *)object;
  63. if ([data length] > 0) {
  64. ret.resize([data length]);
  65. {
  66. PoolByteArray::Write w = ret.write();
  67. copymem(w.ptr(), [data bytes], [data length]);
  68. }
  69. }
  70. return ret;
  71. } else if ([object isKindOfClass:[NSArray class]]) {
  72. Array result;
  73. NSArray *array = (NSArray *)object;
  74. for (unsigned int i = 0; i < [array count]; ++i) {
  75. NSObject *value = [array objectAtIndex:i];
  76. result.push_back(nsobject_to_variant(value));
  77. }
  78. return result;
  79. } else if ([object isKindOfClass:[NSDictionary class]]) {
  80. Dictionary result;
  81. NSDictionary *dic = (NSDictionary *)object;
  82. NSArray *keys = [dic allKeys];
  83. int count = [keys count];
  84. for (int i = 0; i < count; ++i) {
  85. NSObject *k = [keys objectAtIndex:i];
  86. NSObject *v = [dic objectForKey:k];
  87. result[nsobject_to_variant(k)] = nsobject_to_variant(v);
  88. }
  89. return result;
  90. } else if ([object isKindOfClass:[NSNumber class]]) {
  91. //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)
  92. //To avoid errors, we'll cast as broadly as possible, and only return int or float.
  93. //bool, char, int, uint, longlong -> int
  94. //float, double -> float
  95. NSNumber *num = (NSNumber *)object;
  96. if (strcmp([num objCType], @encode(BOOL)) == 0) {
  97. return Variant((int)[num boolValue]);
  98. } else if (strcmp([num objCType], @encode(char)) == 0) {
  99. return Variant((int)[num charValue]);
  100. } else if (strcmp([num objCType], @encode(int)) == 0) {
  101. return Variant([num intValue]);
  102. } else if (strcmp([num objCType], @encode(unsigned int)) == 0) {
  103. return Variant((int)[num unsignedIntValue]);
  104. } else if (strcmp([num objCType], @encode(long long)) == 0) {
  105. return Variant((int)[num longValue]);
  106. } else if (strcmp([num objCType], @encode(float)) == 0) {
  107. return Variant([num floatValue]);
  108. } else if (strcmp([num objCType], @encode(double)) == 0) {
  109. return Variant((float)[num doubleValue]);
  110. } else {
  111. return Variant();
  112. }
  113. } else if ([object isKindOfClass:[NSDate class]]) {
  114. //this is a type that icloud supports...but how did you submit it in the first place?
  115. //I guess this is a type that *might* show up, if you were, say, trying to make your game
  116. //compatible with existing cloud data written by another engine's version of your game
  117. WARN_PRINT("NSDate unsupported, returning null Variant");
  118. return Variant();
  119. } else if ([object isKindOfClass:[NSNull class]] or object == nil) {
  120. return Variant();
  121. } else {
  122. WARN_PRINT("Trying to convert unknown NSObject type to Variant");
  123. return Variant();
  124. }
  125. }
  126. NSObject *variant_to_nsobject(Variant v) {
  127. if (v.get_type() == Variant::STRING) {
  128. return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease];
  129. } else if (v.get_type() == Variant::REAL) {
  130. return [NSNumber numberWithDouble:(double)v];
  131. } else if (v.get_type() == Variant::INT) {
  132. return [NSNumber numberWithLongLong:(long)(int)v];
  133. } else if (v.get_type() == Variant::BOOL) {
  134. return [NSNumber numberWithBool:BOOL((bool)v)];
  135. } else if (v.get_type() == Variant::DICTIONARY) {
  136. NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
  137. Dictionary dic = v;
  138. Array keys = dic.keys();
  139. for (unsigned int i = 0; i < keys.size(); ++i) {
  140. NSString *key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease];
  141. NSObject *value = variant_to_nsobject(dic[keys[i]]);
  142. if (key == NULL || value == NULL) {
  143. return NULL;
  144. }
  145. [result setObject:value forKey:key];
  146. }
  147. return result;
  148. } else if (v.get_type() == Variant::ARRAY) {
  149. NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease];
  150. Array arr = v;
  151. for (unsigned int i = 0; i < arr.size(); ++i) {
  152. NSObject *value = variant_to_nsobject(arr[i]);
  153. if (value == NULL) {
  154. //trying to add something unsupported to the array. cancel the whole array
  155. return NULL;
  156. }
  157. [result addObject:value];
  158. }
  159. return result;
  160. } else if (v.get_type() == Variant::POOL_BYTE_ARRAY) {
  161. PoolByteArray arr = v;
  162. PoolByteArray::Read r = arr.read();
  163. NSData *result = [NSData dataWithBytes:r.ptr() length:arr.size()];
  164. return result;
  165. }
  166. WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type()) + "'").utf8().get_data());
  167. return NULL;
  168. }
  169. Error ICloud::remove_key(Variant p_param) {
  170. String param = p_param;
  171. NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  172. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  173. if (![[store dictionaryRepresentation] objectForKey:key]) {
  174. return ERR_INVALID_PARAMETER;
  175. }
  176. [store removeObjectForKey:key];
  177. return OK;
  178. }
  179. //return an array of the keys that could not be set
  180. Variant ICloud::set_key_values(Variant p_params) {
  181. Dictionary params = p_params;
  182. Array keys = params.keys();
  183. Array error_keys;
  184. for (unsigned int i = 0; i < keys.size(); ++i) {
  185. String variant_key = keys[i];
  186. Variant variant_value = params[variant_key];
  187. NSString *key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease];
  188. if (key == NULL) {
  189. error_keys.push_back(variant_key);
  190. continue;
  191. }
  192. NSObject *value = variant_to_nsobject(variant_value);
  193. if (value == NULL) {
  194. error_keys.push_back(variant_key);
  195. continue;
  196. }
  197. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  198. [store setObject:value forKey:key];
  199. }
  200. return error_keys;
  201. }
  202. Variant ICloud::get_key_value(Variant p_param) {
  203. String param = p_param;
  204. NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  205. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  206. if (![[store dictionaryRepresentation] objectForKey:key]) {
  207. return Variant();
  208. }
  209. Variant result = nsobject_to_variant([[store dictionaryRepresentation] objectForKey:key]);
  210. return result;
  211. }
  212. Variant ICloud::get_all_key_values() {
  213. Dictionary result;
  214. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  215. NSDictionary *store_dictionary = [store dictionaryRepresentation];
  216. NSArray *keys = [store_dictionary allKeys];
  217. int count = [keys count];
  218. for (int i = 0; i < count; ++i) {
  219. NSString *k = [keys objectAtIndex:i];
  220. NSObject *v = [store_dictionary objectForKey:k];
  221. const char *str = [k UTF8String];
  222. if (str != NULL) {
  223. result[String::utf8(str)] = nsobject_to_variant(v);
  224. }
  225. }
  226. return result;
  227. }
  228. Error ICloud::synchronize_key_values() {
  229. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  230. BOOL result = [store synchronize];
  231. if (result == YES) {
  232. return OK;
  233. } else {
  234. return FAILED;
  235. }
  236. }
  237. /*
  238. Error ICloud::initial_sync() {
  239. //you sometimes have to write something to the store to get it to download new data. go apple!
  240. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  241. if ([store boolForKey:@"isb"])
  242. {
  243. [store setBool:NO forKey:@"isb"];
  244. }
  245. else
  246. {
  247. [store setBool:YES forKey:@"isb"];
  248. }
  249. return synchronize();
  250. }
  251. */
  252. ICloud::ICloud() {
  253. ERR_FAIL_COND(instance != NULL);
  254. instance = this;
  255. //connected = false;
  256. [[NSNotificationCenter defaultCenter]
  257. addObserverForName:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
  258. object:[NSUbiquitousKeyValueStore defaultStore]
  259. queue:nil
  260. usingBlock:^(NSNotification *notification) {
  261. NSDictionary *userInfo = [notification userInfo];
  262. NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
  263. Dictionary ret;
  264. ret["type"] = "key_value_changed";
  265. //PoolStringArray result_keys;
  266. //Array result_values;
  267. Dictionary keyValues;
  268. String reason = "";
  269. if (change == NSUbiquitousKeyValueStoreServerChange) {
  270. reason = "server";
  271. } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
  272. reason = "initial_sync";
  273. } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
  274. reason = "quota_violation";
  275. } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
  276. reason = "account";
  277. }
  278. ret["reason"] = reason;
  279. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  280. NSArray *keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
  281. for (NSString *key in keys) {
  282. const char *str = [key UTF8String];
  283. if (str == NULL) {
  284. continue;
  285. }
  286. NSObject *object = [store objectForKey:key];
  287. //figure out what kind of object it is
  288. Variant value = nsobject_to_variant(object);
  289. keyValues[String::utf8(str)] = value;
  290. }
  291. ret["changed_values"] = keyValues;
  292. pending_events.push_back(ret);
  293. }];
  294. }
  295. ICloud::~ICloud(){};
  296. #endif