Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

CDVCommandQueue.m 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. #include <objc/message.h>
  18. #import "CDVCommandQueue.h"
  19. #import "CDVViewController.h"
  20. #import "CDVCommandDelegateImpl.h"
  21. #import "CDVJSON_private.h"
  22. #import "CDVDebug.h"
  23. // Parse JS on the main thread if it's shorter than this.
  24. static const NSInteger JSON_SIZE_FOR_MAIN_THREAD = 4 * 1024; // Chosen arbitrarily.
  25. // Execute multiple commands in one go until this many seconds have passed.
  26. static const double MAX_EXECUTION_TIME = .008; // Half of a 60fps frame.
  27. @interface CDVCommandQueue () {
  28. NSInteger _lastCommandQueueFlushRequestId;
  29. __weak CDVViewController* _viewController;
  30. NSMutableArray* _queue;
  31. NSTimeInterval _startExecutionTime;
  32. }
  33. @end
  34. @implementation CDVCommandQueue
  35. - (BOOL)currentlyExecuting
  36. {
  37. return _startExecutionTime > 0;
  38. }
  39. - (id)initWithViewController:(CDVViewController*)viewController
  40. {
  41. self = [super init];
  42. if (self != nil) {
  43. _viewController = viewController;
  44. _queue = [[NSMutableArray alloc] init];
  45. }
  46. return self;
  47. }
  48. - (void)dispose
  49. {
  50. // TODO(agrieve): Make this a zeroing weak ref once we drop support for 4.3.
  51. _viewController = nil;
  52. }
  53. - (void)resetRequestId
  54. {
  55. _lastCommandQueueFlushRequestId = 0;
  56. }
  57. - (void)enqueueCommandBatch:(NSString*)batchJSON
  58. {
  59. if ([batchJSON length] > 0) {
  60. NSMutableArray* commandBatchHolder = [[NSMutableArray alloc] init];
  61. [_queue addObject:commandBatchHolder];
  62. if ([batchJSON length] < JSON_SIZE_FOR_MAIN_THREAD) {
  63. [commandBatchHolder addObject:[batchJSON cdv_JSONObject]];
  64. } else {
  65. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {
  66. NSMutableArray* result = [batchJSON cdv_JSONObject];
  67. @synchronized(commandBatchHolder) {
  68. [commandBatchHolder addObject:result];
  69. }
  70. [self performSelectorOnMainThread:@selector(executePending) withObject:nil waitUntilDone:NO];
  71. });
  72. }
  73. }
  74. }
  75. - (void)fetchCommandsFromJs
  76. {
  77. __weak CDVCommandQueue* weakSelf = self;
  78. NSString* js = @"cordova.require('cordova/exec').nativeFetchMessages()";
  79. [_viewController.webViewEngine evaluateJavaScript:js
  80. completionHandler:^(id obj, NSError* error) {
  81. if ((error == nil) && [obj isKindOfClass:[NSString class]]) {
  82. NSString* queuedCommandsJSON = (NSString*)obj;
  83. CDV_EXEC_LOG(@"Exec: Flushed JS->native queue (hadCommands=%d).", [queuedCommandsJSON length] > 0);
  84. [weakSelf enqueueCommandBatch:queuedCommandsJSON];
  85. // this has to be called here now, because fetchCommandsFromJs is now async (previously: synchronous)
  86. [self executePending];
  87. }
  88. }];
  89. }
  90. - (void)executePending
  91. {
  92. // Make us re-entrant-safe.
  93. if (_startExecutionTime > 0) {
  94. return;
  95. }
  96. @try {
  97. _startExecutionTime = [NSDate timeIntervalSinceReferenceDate];
  98. while ([_queue count] > 0) {
  99. NSMutableArray* commandBatchHolder = _queue[0];
  100. NSMutableArray* commandBatch = nil;
  101. @synchronized(commandBatchHolder) {
  102. // If the next-up command is still being decoded, wait for it.
  103. if ([commandBatchHolder count] == 0) {
  104. break;
  105. }
  106. commandBatch = commandBatchHolder[0];
  107. }
  108. while ([commandBatch count] > 0) {
  109. @autoreleasepool {
  110. // Execute the commands one-at-a-time.
  111. NSArray* jsonEntry = [commandBatch cdv_dequeue];
  112. if ([commandBatch count] == 0) {
  113. [_queue removeObjectAtIndex:0];
  114. }
  115. CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];
  116. CDV_EXEC_LOG(@"Exec(%@): Calling %@.%@", command.callbackId, command.className, command.methodName);
  117. if (![self execute:command]) {
  118. #ifdef DEBUG
  119. NSString* commandJson = [jsonEntry cdv_JSONString];
  120. static NSUInteger maxLogLength = 1024;
  121. NSString* commandString = ([commandJson length] > maxLogLength) ?
  122. [NSString stringWithFormat : @"%@[...]", [commandJson substringToIndex:maxLogLength]] :
  123. commandJson;
  124. DLog(@"FAILED pluginJSON = %@", commandString);
  125. #endif
  126. }
  127. }
  128. // Yield if we're taking too long.
  129. if (([_queue count] > 0) && ([NSDate timeIntervalSinceReferenceDate] - _startExecutionTime > MAX_EXECUTION_TIME)) {
  130. [self performSelector:@selector(executePending) withObject:nil afterDelay:0];
  131. return;
  132. }
  133. }
  134. }
  135. } @finally
  136. {
  137. _startExecutionTime = 0;
  138. }
  139. }
  140. - (BOOL)execute:(CDVInvokedUrlCommand*)command
  141. {
  142. if ((command.className == nil) || (command.methodName == nil)) {
  143. NSLog(@"ERROR: Classname and/or methodName not found for command.");
  144. return NO;
  145. }
  146. // Fetch an instance of this class
  147. CDVPlugin* obj = [_viewController.commandDelegate getCommandInstance:command.className];
  148. if (!([obj isKindOfClass:[CDVPlugin class]])) {
  149. NSLog(@"ERROR: Plugin '%@' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.", command.className);
  150. return NO;
  151. }
  152. BOOL retVal = YES;
  153. double started = [[NSDate date] timeIntervalSince1970] * 1000.0;
  154. // Find the proper selector to call.
  155. NSString* methodName = [NSString stringWithFormat:@"%@:", command.methodName];
  156. SEL normalSelector = NSSelectorFromString(methodName);
  157. if ([obj respondsToSelector:normalSelector]) {
  158. // [obj performSelector:normalSelector withObject:command];
  159. ((void (*)(id, SEL, id))objc_msgSend)(obj, normalSelector, command);
  160. } else {
  161. // There's no method to call, so throw an error.
  162. NSLog(@"ERROR: Method '%@' not defined in Plugin '%@'", methodName, command.className);
  163. retVal = NO;
  164. }
  165. double elapsed = [[NSDate date] timeIntervalSince1970] * 1000.0 - started;
  166. if (elapsed > 10) {
  167. NSLog(@"THREAD WARNING: ['%@'] took '%f' ms. Plugin should use a background thread.", command.className, elapsed);
  168. }
  169. return retVal;
  170. }
  171. @end