-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
WXComponentManager.m
701 lines (562 loc) · 19.5 KB
/
WXComponentManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/**
* Created by Weex.
* Copyright (c) 2016, Alibaba, Inc. All rights reserved.
*
* This source code is licensed under the Apache Licence 2.0.
* For the full copyright and license information,please view the LICENSE file in the root directory of this source tree.
*/
#import "WXComponentManager.h"
#import "WXComponent.h"
#import "WXComponent_internal.h"
#import "WXComponentFactory.h"
#import "WXDefine.h"
#import "NSArray+Weex.h"
#import "WXSDKInstance.h"
#import "WXAssert.h"
#import "WXUtility.h"
#import "WXMonitor.h"
#import "WXScrollerProtocol.h"
#import "WXSDKManager.h"
#import "WXSDKError.h"
#import "WXInvocationConfig.h"
static NSThread *WXComponentThread;
#define WXAssertComponentExist(component) WXAssert(component, @"component not exists")
@implementation WXComponentManager
{
__weak WXSDKInstance *_weexInstance;
BOOL _isValid;
BOOL _stopRunning;
NSUInteger _noTaskTickCount;
// access only on component thread
NSMapTable<NSString *, WXComponent *> *_indexDict;
NSMutableArray<dispatch_block_t> *_uiTaskQueue;
WXComponent *_rootComponent;
NSMutableArray *_fixedComponents;
css_node_t *_rootCSSNode;
CADisplayLink *_displayLink;
}
+ (instancetype)sharedManager
{
static id _sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (instancetype)initWithWeexInstance:(id)weexInstance
{
if (self = [self init]) {
_weexInstance = weexInstance;
_indexDict = [NSMapTable strongToWeakObjectsMapTable];
_fixedComponents = [NSMutableArray wx_mutableArrayUsingWeakReferences];
_uiTaskQueue = [NSMutableArray array];
_isValid = YES;
[self _startDisplayLink];
}
return self;
}
- (void)dealloc
{
free_css_node(_rootCSSNode);
[NSMutableArray wx_releaseArray:_fixedComponents];
}
#pragma mark Thread Management
+ (NSThread *)componentThread
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
WXComponentThread = [[NSThread alloc] initWithTarget:[self sharedManager] selector:@selector(_runLoopThread) object:nil];
[WXComponentThread setName:WX_COMPONENT_THREAD_NAME];
if(WX_SYS_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
[WXComponentThread setQualityOfService:[[NSThread mainThread] qualityOfService]];
} else {
[WXComponentThread setThreadPriority:[[NSThread mainThread] threadPriority]];
}
[WXComponentThread start];
});
return WXComponentThread;
}
- (void)_runLoopThread
{
[[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
while (!_stopRunning) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
+ (void)_performBlockOnComponentThread:(void (^)())block
{
if([NSThread currentThread] == [self componentThread]){
block();
} else {
[self performSelector:@selector(_performBlockOnComponentThread:)
onThread:WXComponentThread
withObject:[block copy]
waitUntilDone:NO];
}
}
- (void)startComponentTasks
{
[self _awakeDisplayLink];
}
- (void)rootViewFrameDidChange:(CGRect)frame
{
WXAssertComponentThread();
if (_rootCSSNode) {
[self _applyRootFrame:frame toRootCSSNode:_rootCSSNode];
if (!_rootComponent.styles[@"width"]) {
_rootComponent.cssNode->style.dimensions[CSS_WIDTH] = frame.size.width;
}
if (!_rootComponent.styles[@"height"]) {
_rootComponent.cssNode->style.dimensions[CSS_HEIGHT] = frame.size.height;
}
[_rootComponent setNeedsLayout];
[self startComponentTasks];
}
}
- (void)_applyRootFrame:(CGRect)rootFrame toRootCSSNode:(css_node_t *)rootCSSNode
{
_rootCSSNode->style.position[CSS_LEFT] = self.weexInstance.frame.origin.x;
_rootCSSNode->style.position[CSS_TOP] = self.weexInstance.frame.origin.y;
// if no instance width/height, use layout width/height, as Android's wrap_content
_rootCSSNode->style.dimensions[CSS_WIDTH] = self.weexInstance.frame.size.width ?: CSS_UNDEFINED;
_rootCSSNode->style.dimensions[CSS_HEIGHT] = self.weexInstance.frame.size.height ?: CSS_UNDEFINED;
}
- (void)_addUITask:(void (^)())block
{
[_uiTaskQueue addObject:block];
}
#pragma mark Component Tree Building
- (void)createRoot:(NSDictionary *)data
{
WXAssertComponentThread();
WXAssertParam(data);
_rootComponent = [self _buildComponentForData:data];
[self _initRootCSSNode];
__weak typeof(self) weakSelf = self;
[self _addUITask:^{
__strong typeof(self) strongSelf = weakSelf;
strongSelf.weexInstance.rootView.wx_component = strongSelf->_rootComponent;
[strongSelf.weexInstance.rootView addSubview:strongSelf->_rootComponent.view];
}];
}
static bool rootNodeIsDirty(void *context)
{
WXComponentManager *mananger = (__bridge WXComponentManager *)(context);
return [mananger->_rootComponent needsLayout];
}
static css_node_t * rootNodeGetChild(void *context, int i)
{
WXComponentManager *mananger = (__bridge WXComponentManager *)(context);
if (i == 0) {
return mananger->_rootComponent.cssNode;
} else if(mananger->_fixedComponents.count > 0) {
return ((WXComponent *)((mananger->_fixedComponents)[i-1])).cssNode;
}
return NULL;
}
- (void)addComponent:(NSDictionary *)componentData toSupercomponent:(NSString *)superRef atIndex:(NSInteger)index appendingInTree:(BOOL)appendingInTree
{
WXAssertComponentThread();
WXAssertParam(componentData);
WXAssertParam(superRef);
WXComponent *supercomponent = [_indexDict objectForKey:superRef];
WXAssertComponentExist(supercomponent);
[self _recursivelyAddComponent:componentData toSupercomponent:supercomponent atIndex:index appendingInTree:appendingInTree];
}
- (void)_recursivelyAddComponent:(NSDictionary *)componentData toSupercomponent:(WXComponent *)supercomponent atIndex:(NSInteger)index appendingInTree:(BOOL)appendingInTree
{
WXComponent *component = [self _buildComponentForData:componentData];
index = (index == -1 ? supercomponent->_subcomponents.count : index);
[supercomponent _insertSubcomponent:component atIndex:index];
// use _lazyCreateView to forbid component like cell's view creating
if(supercomponent && component && supercomponent->_lazyCreateView) {
component->_lazyCreateView = YES;
}
[self _addUITask:^{
[supercomponent insertSubview:component atIndex:index];
}];
NSArray *subcomponentsData = [componentData valueForKey:@"children"];
BOOL appendTree = !appendingInTree && [component.attributes[@"append"] isEqualToString:@"tree"];
// if ancestor is appending tree, child should not be laid out again even it is appending tree.
for(NSDictionary *subcomponentData in subcomponentsData){
[self _recursivelyAddComponent:subcomponentData toSupercomponent:component atIndex:-1 appendingInTree:appendTree || appendingInTree];
}
if (appendTree) {
// If appending tree,force layout in case of too much tasks piling up in syncQueue
[self _layoutAndSyncUI];
}
}
- (void)moveComponent:(NSString *)ref toSuper:(NSString *)superRef atIndex:(NSInteger)index
{
WXAssertComponentThread();
WXAssertParam(ref);
WXAssertParam(superRef);
WXComponent *component = [_indexDict objectForKey:ref];
WXComponent *newSupercomponent = [_indexDict objectForKey:superRef];
WXAssertComponentExist(component);
WXAssertComponentExist(newSupercomponent);
if (component.supercomponent == newSupercomponent && [newSupercomponent.subcomponents indexOfObject:component] < index) {
// if the supercomponent moved to is the same as original supercomponent,
// unify it into the index after removing.
index--;
}
[component _moveToSupercomponent:newSupercomponent atIndex:index];
[self _addUITask:^{
[component moveToSuperview:newSupercomponent atIndex:index];
}];
}
- (void)removeComponent:(NSString *)ref
{
WXAssertComponentThread();
WXAssertParam(ref);
WXComponent *component = [_indexDict objectForKey:ref];
WXAssertComponentExist(component);
[component _removeFromSupercomponent];
[_indexDict removeObjectForKey:ref];
[self _addUITask:^{
if (component.supercomponent) {
[component.supercomponent willRemoveSubview:component];
}
[component removeFromSuperview];
}];
}
- (WXComponent *)componentForRef:(NSString *)ref
{
WXAssertComponentThread();
return [_indexDict objectForKey:ref];
}
- (WXComponent *)componentForRoot
{
return _rootComponent;
}
- (NSUInteger)numberOfComponents
{
WXAssertComponentThread();
return _indexDict.count;
}
- (WXComponent *)_buildComponentForData:(NSDictionary *)data
{
NSString *ref = data[@"ref"];
NSString *type = data[@"type"];
NSDictionary *styles = data[@"style"];
NSDictionary *attributes = data[@"attr"];
NSArray *events = data[@"event"];
Class clazz = [WXComponentFactory classWithComponentName:type];
WXComponent *component = [[clazz alloc] initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:self.weexInstance];
WXAssert(component, @"Component build failed for data:%@", data);
[_indexDict setObject:component forKey:component.ref];
return component;
}
#pragma mark Updating
#pragma mark Reset
-(BOOL)isShouldReset:(id )value
{
if([value isKindOfClass:[NSString class]]) {
if(!value || [@"" isEqualToString:value]) {
return YES;
}
}
return NO;
}
-(NSDictionary *)fetchResetStyles:(NSDictionary *)styles
{
NSMutableDictionary *resetStyles = [@{} mutableCopy];
for (NSString *key in styles) {
id value = [styles objectForKey:key];
if([self isShouldReset:value]) {
[resetStyles setValue:styles[key] forKey:key];
}
}
return resetStyles;
}
-(NSDictionary *)fetchStyles:(NSDictionary *)styles
{
NSMutableDictionary *normalStyles = [@{} mutableCopy];
for (NSString *key in styles) {
id value = [styles objectForKey:key];
if(![self isShouldReset:value]) {
[normalStyles setValue:styles[key] forKey:key];
}
}
return normalStyles;
}
- (void)updateStyles:(NSDictionary *)styles forComponent:(NSString *)ref
{
WXAssertParam(styles);
WXAssertParam(ref);
WXComponent *component = [_indexDict objectForKey:ref];
WXAssertComponentExist(component);
NSDictionary *normalStyles = [self fetchStyles:styles];
NSDictionary *resetStyles = [self fetchResetStyles:styles];
[component _updateStylesOnComponentThread:normalStyles resetStyles:resetStyles];
[self _addUITask:^{
[component _updateStylesOnMainThread:normalStyles resetStyles:resetStyles];
}];
}
- (void)updateAttributes:(NSDictionary *)attributes forComponent:(NSString *)ref
{
WXAssertParam(attributes);
WXAssertParam(ref);
WXComponent *component = [_indexDict objectForKey:ref];
WXAssertComponentExist(component);
[component _updateAttributesOnComponentThread:attributes];
[self _addUITask:^{
[component _updateAttributesOnMainThread:attributes];
}];
}
- (void)addEvent:(NSString *)eventName toComponent:(NSString *)ref
{
WXAssertComponentThread();
WXAssertParam(eventName);
WXAssertParam(ref);
WXComponent *component = [_indexDict objectForKey:ref];
WXAssertComponentExist(component);
[component _addEventOnComponentThread:eventName];
[self _addUITask:^{
[component _addEventOnMainThread:eventName];
}];
}
- (void)removeEvent:(NSString *)eventName fromComponent:(NSString *)ref
{
WXAssertComponentThread();
WXAssertParam(eventName);
WXAssertParam(ref);
WXComponent *component = [_indexDict objectForKey:ref];
WXAssertComponentExist(component);
[component _removeEventOnComponentThread:eventName];
[self _addUITask:^{
[component _removeEventOnMainThread:eventName];
}];
}
- (void)scrollToComponent:(NSString *)ref options:(NSDictionary *)options
{
WXAssertComponentThread();
WXAssertParam(ref);
WXComponent *toComponent = [_indexDict objectForKey:ref];
WXAssertComponentExist(toComponent);
id<WXScrollerProtocol> scrollerComponent = toComponent.ancestorScroller;
if (!scrollerComponent) {
return;
}
CGFloat offset = [[options objectForKey:@"offset"] floatValue];
[self _addUITask:^{
[scrollerComponent scrollToComponent:toComponent withOffset:offset];
}];
}
- (void)dispatchComponentMethod:(WXBridgeMethod *)method
{
if (!method) {
return;
}
Class componentClazz = [WXComponentFactory classWithComponentName:method.targets[@"component"]];
if (!componentClazz) {
NSString *errorMessage = [NSString stringWithFormat:@"Module:%@ doesn't exist!", method.module];
WX_MONITOR_FAIL(WXMTJSBridge, WX_ERR_INVOKE_NATIVE, errorMessage);
return;
}
WXPerformBlockOnComponentThread(^{
WXSDKInstance *weexInstance = [WXSDKManager instanceForID:method.instance];
WXComponent *componentInstance = [weexInstance componentForRef:method.targets[@"ref"]];
[self _executeComponentMethod:componentInstance withMethod:method];
});
}
- (void)_executeComponentMethod:(id)target withMethod:(WXBridgeMethod*)method
{
NSInvocation * invocation = [[WXInvocationConfig sharedInstance] invocationWithTargetMethod:target method:method];
WXPerformBlockOnMainThread(^{
[invocation invoke];
});
}
#pragma mark Life Cycle
- (void)createFinish
{
WXAssertComponentThread();
WXSDKInstance *instance = self.weexInstance;
[self _addUITask:^{
UIView *rootView = instance.rootView;
WX_MONITOR_INSTANCE_PERF_END(WXPTFirstScreenRender, instance);
WX_MONITOR_INSTANCE_PERF_END(WXPTAllRender, instance);
WX_MONITOR_SUCCESS(WXMTJSBridge);
WX_MONITOR_SUCCESS(WXMTNativeRender);
if(instance.renderFinish){
instance.renderFinish(rootView);
}
}];
}
- (void)updateFinish
{
WXAssertComponentThread();
WXSDKInstance *instance = self.weexInstance;
WXComponent *root = [_indexDict objectForKey:WX_SDK_ROOT_REF];
[self _addUITask:^{
if(instance.updateFinish){
instance.updateFinish(root.view);
}
}];
}
- (void)refreshFinish
{
WXAssertComponentThread();
WXSDKInstance *instance = self.weexInstance;
WXComponent *root = [_indexDict objectForKey:WX_SDK_ROOT_REF];
[self _addUITask:^{
if(instance.refreshFinish){
instance.refreshFinish(root.view);
}
}];
}
- (void)unload
{
WXAssertComponentThread();
NSEnumerator *enumerator = [_indexDict objectEnumerator];
WXComponent *component;
while ((component = [enumerator nextObject])) {
dispatch_async(dispatch_get_main_queue(), ^{
[component _unloadViewWithReusing:NO];
});
}
[_indexDict removeAllObjects];
[_uiTaskQueue removeAllObjects];
dispatch_async(dispatch_get_main_queue(), ^{
_rootComponent = nil;
});
[self _stopDisplayLink];
_isValid = NO;
}
- (BOOL)isValid
{
return _isValid;
}
#pragma mark Layout Batch
- (void)_startDisplayLink
{
WXAssertComponentThread();
if(!_displayLink){
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(_handleDisplayLink)];
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
}
- (void)_stopDisplayLink
{
WXAssertComponentThread();
if(_displayLink){
[_displayLink invalidate];
_displayLink = nil;
}
}
- (void)_suspendDisplayLink
{
WXAssertComponentThread();
if(_displayLink && !_displayLink.paused) {
_displayLink.paused = YES;
}
}
- (void)_awakeDisplayLink
{
WXAssertComponentThread();
if(_displayLink && _displayLink.paused) {
_displayLink.paused = NO;
}
}
- (void)_handleDisplayLink
{
WXAssertComponentThread();
[self _layoutAndSyncUI];
}
- (void)_layoutAndSyncUI
{
[self _layout];
if(_uiTaskQueue.count > 0){
[self _syncUITasks];
_noTaskTickCount = 0;
} else {
// suspend display link when there's no task for 1 second, in order to save CPU time.
_noTaskTickCount ++;
if (_noTaskTickCount > 60) {
[self _suspendDisplayLink];
}
}
}
- (void)_layout
{
BOOL needsLayout = NO;
NSEnumerator *enumerator = [_indexDict objectEnumerator];
WXComponent *component;
while ((component = [enumerator nextObject])) {
if ([component needsLayout]) {
needsLayout = YES;
break;
}
}
if (!needsLayout) {
return;
}
layoutNode(_rootCSSNode, _rootCSSNode->style.dimensions[CSS_WIDTH], _rootCSSNode->style.dimensions[CSS_HEIGHT], CSS_DIRECTION_INHERIT);
if ([_rootComponent needsLayout]) {
if ([WXLog logLevel] >= WXLogLevelDebug) {
print_css_node(_rootCSSNode, CSS_PRINT_LAYOUT | CSS_PRINT_STYLE | CSS_PRINT_CHILDREN);
}
}
NSMutableSet<WXComponent *> *dirtyComponents = [NSMutableSet set];
[_rootComponent _calculateFrameWithSuperAbsolutePosition:CGPointZero gatherDirtyComponents:dirtyComponents];
[self _calculateRootFrame];
for (WXComponent *dirtyComponent in dirtyComponents) {
[self _addUITask:^{
[dirtyComponent _layoutDidFinish];
}];
}
}
- (void)_syncUITasks
{
NSArray<dispatch_block_t> *blocks = _uiTaskQueue;
_uiTaskQueue = [NSMutableArray array];
dispatch_async(dispatch_get_main_queue(), ^{
for(dispatch_block_t block in blocks) {
block();
}
});
}
- (void)_initRootCSSNode
{
_rootCSSNode = new_css_node();
[self _applyRootFrame:self.weexInstance.frame toRootCSSNode:_rootCSSNode];
_rootCSSNode->style.flex_wrap = CSS_NOWRAP;
_rootCSSNode->is_dirty = rootNodeIsDirty;
_rootCSSNode->get_child = rootNodeGetChild;
_rootCSSNode->context = (__bridge void *)(self);
_rootCSSNode->children_count = 1;
}
- (void)_calculateRootFrame
{
if (!_rootCSSNode->layout.should_update) {
return;
}
_rootCSSNode->layout.should_update = false;
CGRect frame = CGRectMake(WXRoundPixelValue(_rootCSSNode->layout.position[CSS_LEFT]),
WXRoundPixelValue(_rootCSSNode->layout.position[CSS_TOP]),
WXRoundPixelValue(_rootCSSNode->layout.dimensions[CSS_WIDTH]),
WXRoundPixelValue(_rootCSSNode->layout.dimensions[CSS_HEIGHT]));
WXPerformBlockOnMainThread(^{
if(!self.weexInstance.isRootViewFrozen) {
self.weexInstance.rootView.frame = frame;
}
});
resetNodeLayout(_rootCSSNode);
}
#pragma mark Fixed
- (void)addFixedComponent:(WXComponent *)fixComponent
{
[_fixedComponents addObject:fixComponent];
_rootCSSNode->children_count = (int)[_fixedComponents count] + 1;
}
- (void)removeFixedComponent:(WXComponent *)fixComponent
{
[_fixedComponents removeObject:fixComponent];
_rootCSSNode->children_count = (int)[_fixedComponents count] + 1;
}
@end
void WXPerformBlockOnComponentThread(void (^block)())
{
[WXComponentManager _performBlockOnComponentThread:block];
}