icloud.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*************************************************************************/
  2. /* icloud.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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 <Foundation/Foundation.h>
  36. #import "app_delegate.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. }
  117. } else if ([object isKindOfClass:[NSDate class]]) {
  118. //this is a type that icloud supports...but how did you submit it in the first place?
  119. //I guess this is a type that *might* show up, if you were, say, trying to make your game
  120. //compatible with existing cloud data written by another engine's version of your game
  121. WARN_PRINT("NSDate unsupported, returning null Variant")
  122. return Variant();
  123. } else if ([object isKindOfClass:[NSNull class]] or object == nil) {
  124. return Variant();
  125. } else {
  126. WARN_PRINT("Trying to convert unknown NSObject type to Variant");
  127. return Variant();
  128. }
  129. }
  130. NSObject* variant_to_nsobject(Variant v) {
  131. if (v.get_type() == Variant::STRING) {
  132. return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease];
  133. } else if (v.get_type() == Variant::REAL) {
  134. return [NSNumber numberWithDouble:(double)v];
  135. } else if (v.get_type() == Variant::INT) {
  136. return [NSNumber numberWithLongLong:(long)(int)v];
  137. } else if (v.get_type() == Variant::BOOL) {
  138. return [NSNumber numberWithBool:BOOL((bool)v)];
  139. } else if (v.get_type() == Variant::DICTIONARY) {
  140. NSMutableDictionary* result = [[[NSMutableDictionary alloc] init] autorelease];
  141. Dictionary dic = v;
  142. Array keys = dic.keys();
  143. for (unsigned int i = 0; i < keys.size(); ++i) {
  144. NSString* key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease];
  145. NSObject* value = variant_to_nsobject(dic[keys[i]]);
  146. if (key == NULL || value == NULL) {
  147. return NULL;
  148. }
  149. [result setObject:value forKey:key];
  150. }
  151. return result;
  152. } else if (v.get_type() == Variant::ARRAY) {
  153. NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease];
  154. Array arr = v;
  155. for (unsigned int i = 0; i < arr.size(); ++i) {
  156. NSObject* value = variant_to_nsobject(arr[i]);
  157. if (value == NULL) {
  158. //trying to add something unsupported to the array. cancel the whole array
  159. return NULL;
  160. }
  161. [result addObject:value];
  162. }
  163. return result;
  164. } else if (v.get_type() == Variant::POOL_BYTE_ARRAY) {
  165. PoolByteArray arr = v;
  166. PoolByteArray::Read r = arr.read();
  167. NSData* result = [NSData dataWithBytes:r.ptr() length:arr.size()];
  168. return result;
  169. }
  170. WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type())+"'").utf8().get_data());
  171. return NULL;
  172. }
  173. Error ICloud::remove_key(Variant p_param) {
  174. String param = p_param;
  175. NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  176. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  177. if (![[store dictionaryRepresentation] objectForKey:key]) {
  178. return ERR_INVALID_PARAMETER;
  179. }
  180. [store removeObjectForKey:key];
  181. return OK;
  182. }
  183. //return an array of the keys that could not be set
  184. Variant ICloud::set_key_values(Variant p_params) {
  185. Dictionary params = p_params;
  186. Array keys = params.keys();
  187. Array error_keys;
  188. for (unsigned int i = 0; i < keys.size(); ++i) {
  189. String variant_key = keys[i];
  190. Variant variant_value = params[variant_key];
  191. NSString* key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease];
  192. if (key == NULL) {
  193. error_keys.push_back(variant_key);
  194. continue;
  195. }
  196. NSObject* value = variant_to_nsobject(variant_value);
  197. if (value == NULL) {
  198. error_keys.push_back(variant_key);
  199. continue;
  200. }
  201. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  202. [store setObject:value forKey:key];
  203. }
  204. return error_keys;
  205. }
  206. Variant ICloud::get_key_value(Variant p_param) {
  207. String param = p_param;
  208. NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
  209. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  210. if (![[store dictionaryRepresentation] objectForKey:key]) {
  211. return Variant();
  212. }
  213. Variant result = nsobject_to_variant([[store dictionaryRepresentation] objectForKey:key]);
  214. return result;
  215. }
  216. Variant ICloud::get_all_key_values() {
  217. Dictionary result;
  218. NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
  219. NSDictionary* store_dictionary = [store dictionaryRepresentation];
  220. NSArray* keys = [store_dictionary allKeys];
  221. int count = [keys count];
  222. for (int i=0; i < count; ++i) {
  223. NSString* k = [ keys objectAtIndex:i];
  224. NSObject* v = [store_dictionary objectForKey:k];
  225. const char* str = [k UTF8String];
  226. if (str != NULL) {
  227. result[String::utf8(str)] = nsobject_to_variant(v);
  228. }
  229. }
  230. return result;
  231. }
  232. Error ICloud::synchronize_key_values() {
  233. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  234. BOOL result = [store synchronize];
  235. if (result == YES) {
  236. return OK;
  237. } else {
  238. return FAILED;
  239. }
  240. }
  241. /*
  242. Error ICloud::initial_sync() {
  243. //you sometimes have to write something to the store to get it to download new data. go apple!
  244. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  245. if ([store boolForKey:@"isb"])
  246. {
  247. [store setBool:NO forKey:@"isb"];
  248. }
  249. else
  250. {
  251. [store setBool:YES forKey:@"isb"];
  252. }
  253. return synchronize();
  254. }
  255. */
  256. ICloud::ICloud() {
  257. ERR_FAIL_COND(instance != NULL);
  258. instance = this;
  259. //connected = false;
  260. [
  261. //[NSNotificationCenter defaultCenter] addObserverForName: @"notify"
  262. [NSNotificationCenter defaultCenter] addObserverForName: NSUbiquitousKeyValueStoreDidChangeExternallyNotification
  263. object: [NSUbiquitousKeyValueStore defaultStore]
  264. queue: nil
  265. usingBlock: ^ (NSNotification * notification) {
  266. NSDictionary* userInfo = [notification userInfo];
  267. NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
  268. Dictionary ret;
  269. ret["type"] = "key_value_changed";
  270. //PoolStringArray result_keys;
  271. //Array result_values;
  272. Dictionary keyValues;
  273. String reason = "";
  274. if (change == NSUbiquitousKeyValueStoreServerChange) {
  275. reason = "server";
  276. } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
  277. reason = "initial_sync";
  278. } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
  279. reason = "quota_violation";
  280. } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
  281. reason = "account";
  282. }
  283. ret["reason"] = reason;
  284. NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
  285. NSArray * keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
  286. for (NSString* key in keys) {
  287. const char* str = [key UTF8String];
  288. if (str == NULL) {
  289. continue;
  290. }
  291. NSObject* object = [store objectForKey:key];
  292. //figure out what kind of object it is
  293. Variant value = nsobject_to_variant(object);
  294. keyValues[String::utf8(str)] = value;
  295. }
  296. ret["changed_values"] = keyValues;
  297. pending_events.push_back(ret);
  298. }
  299. ];
  300. }
  301. ICloud::~ICloud() {
  302. };
  303. #endif