杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
702
703
704
705
706
/**
 * Tencent is pleased to support the open source community by making QMUI_iOS available.
 * Copyright (C) 2016-2021 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */
//
//  QMUIConsoleViewController.m
//  QMUIKit
//
//  Created by MoLice on 2019/J/11.
//
 
#import "QMUIConsoleViewController.h"
#import "QMUICore.h"
#import "QMUITableView.h"
#import "QMUITableViewCell.h"
#import "UITableView+QMUICellHeightKeyCache.h"
#import "QMUITextView.h"
#import "QMUITextField.h"
#import "QMUIButton.h"
#import "UIScrollView+QMUI.h"
#import "UIViewController+QMUI.h"
#import "UIView+QMUI.h"
#import "UIImage+QMUI.h"
#import "NSObject+QMUI.h"
#import "CAAnimation+QMUI.h"
#import "NSArray+QMUI.h"
#import "QMUIConsole.h"
#import "QMUIPopupMenuView.h"
 
@interface QMUIConsoleLogItem : NSObject
 
@property(nullable, nonatomic, copy) NSString *level;
@property(nullable, nonatomic, copy) NSString *name;
@property(nonatomic, copy) NSAttributedString *timeString;
@property(nonatomic, copy) NSAttributedString *logString;
@property(nonatomic, copy) NSAttributedString *displayString;
 
@property(nonatomic, copy) NSString *searchingString;
@property(nonatomic, copy) NSArray<NSTextCheckingResult *> *searchResults;
- (void)updateDisplayStringWithSearchResults:(NSArray<NSTextCheckingResult *> *)searchResults;
- (void)focusSearchResultAtIndex:(NSInteger)index;
@end
 
@implementation QMUIConsoleLogItem
 
+ (instancetype)logItemWithLevel:(NSString *)level name:(NSString *)name timeString:(NSString *)timeString logString:(id)logString {
    QMUIConsoleLogItem *logItem = [[self alloc] init];
    logItem.level = level ?: @"Normal";
    logItem.name = name ?: @"Default";
    
    NSDictionary<NSAttributedStringKey, id> *timeAttributes = [QMUIConsole appearance].timeAttributes;
    logItem.timeString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", timeString] attributes:timeAttributes];
    
    NSDictionary<NSAttributedStringKey, id> *textAttributes = [QMUIConsole appearance].textAttributes;
    NSAttributedString *string = nil;
    if ([logString isKindOfClass:[NSAttributedString class]]) {
        string = (NSAttributedString *)logString;
    } else if ([logString isKindOfClass:[NSString class]]) {
        string = [[NSAttributedString alloc] initWithString:(NSString *)logString attributes:textAttributes];
    } else {
        string = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", logString] attributes:textAttributes];
    }
    logItem.logString = string;
    
    NSMutableAttributedString *displayString = NSMutableAttributedString.new;
    [displayString appendAttributedString:logItem.timeString];
    [displayString appendAttributedString:logItem.logString];
    logItem.displayString = displayString;
    return logItem;
}
 
- (void)updateDisplayStringWithSearchResults:(NSArray<NSTextCheckingResult *> *)searchResults {
    self.searchResults = searchResults;
    NSMutableAttributedString *displayString = self.displayString.mutableCopy;
    [displayString removeAttribute:NSBackgroundColorAttributeName range:NSMakeRange(0, displayString.length)];
    [searchResults enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [displayString addAttribute:NSBackgroundColorAttributeName value:[[QMUIConsole appearance].searchResultHighlightedBackgroundColor colorWithAlphaComponent:.4] range:NSMakeRange(self.timeString.length + obj.range.location, obj.range.length)];
    }];
    self.displayString = displayString.copy;
}
 
- (void)focusSearchResultAtIndex:(NSInteger)index {
    NSAssert(index < self.searchResults.count, @"尝试聚焦一个超出 searchResults 范围的关键词");
    [self updateDisplayStringWithSearchResults:self.searchResults];// 重置之前的 focus range
    NSRange rangeInLogString = self.searchResults[index].range;
    NSRange range = NSMakeRange(self.timeString.length + rangeInLogString.location, rangeInLogString.length);
    NSMutableAttributedString *displayString = self.displayString.mutableCopy;
    [displayString addAttribute:NSBackgroundColorAttributeName value:[QMUIConsole appearance].searchResultHighlightedBackgroundColor range:range];
    self.displayString = displayString.copy;
}
 
@end
 
@interface QMUIConsoleLogItemCell : QMUITableViewCell
 
@property(nonatomic, strong) QMUITextView *textView;
@end
 
@implementation QMUIConsoleLogItemCell
 
- (void)didInitializeWithStyle:(UITableViewCellStyle)style {
    [super didInitializeWithStyle:style];
    self.backgroundColor = UIColor.clearColor;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.textView = [[QMUITextView alloc] init];
    self.textView.textContainerInset = UIEdgeInsetsMake(2, 0, 2, 0);
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.scrollsToTop = NO;
    self.textView.editable = NO;
    self.textView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.contentView addSubview:self.textView];
}
 
- (CGSize)sizeThatFits:(CGSize)size {
    return [self.textView sizeThatFits:CGSizeMake(size.width, CGFLOAT_MAX)];
}
 
- (void)layoutSubviews {
    [super layoutSubviews];
    self.textView.frame = self.contentView.bounds;
}
 
@end
 
@interface QMUIConsoleViewController ()<QMUITableViewDataSource, QMUITableViewDelegate, QMUITextFieldDelegate>
 
@property(nonatomic, strong) UIView *containerView;
@property(nonatomic, strong) QMUIPopupMenuView *levelMenu;
@property(nonatomic, strong) QMUIPopupMenuView *nameMenu;
@property(nonatomic, strong) NSMutableArray<QMUIConsoleLogItem *> *logItems;
@property(nonatomic, strong) NSArray<QMUIConsoleLogItem *> *showingLogItems;
@property(nonatomic, strong) NSMutableArray<NSString *> *selectedLevels;
@property(nonatomic, strong) NSMutableArray<NSString *> *selectedNames;
@property(nonatomic, strong) NSRegularExpression *searchRegularExpression;
@property(nonatomic, assign) NSInteger searchResultsTotalCount;
@property(nonatomic, assign) NSInteger currentHighlightedResultIndex;
@property(nonatomic, weak) QMUIConsoleLogItem *lastHighlightedItem;
 
@property(nonatomic, strong) UIPanGestureRecognizer *popoverPanGesture;
@property(nonatomic, strong) UILongPressGestureRecognizer *popoverLongPressGesture;
@property(nonatomic, assign) BOOL popoverAnimating;
@end
 
@implementation QMUIConsoleViewController
 
- (void)didInitialize {
    [super didInitialize];
    self.backgroundColor = [QMUIConsole appearance].backgroundColor;
    
    _dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"HH:mm:ss.SSS";
    
    self.logItems = [[NSMutableArray alloc] init];
    self.selectedLevels = [[NSMutableArray alloc] init];
    self.selectedNames = [[NSMutableArray alloc] init];
}
 
- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc] init];
        _containerView.backgroundColor = self.backgroundColor;
        _containerView.hidden = YES;
    }
    return _containerView;
}
 
@synthesize tableView = _tableView;
- (QMUITableView *)tableView {
    if (!_tableView) {
        _tableView = [[QMUITableView alloc] init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedRowHeight = 44;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.qmui_cacheCellHeightByKeyAutomatically = YES;
        _tableView.backgroundColor = nil;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = NO;
        [_tableView registerClass:QMUIConsoleLogItemCell.class forCellReuseIdentifier:@"cell"];
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    return _tableView;
}
 
@synthesize toolbar = _toolbar;
- (QMUIConsoleToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [[QMUIConsoleToolbar alloc] init];
        [_toolbar.levelButton addTarget:self action:@selector(handleLevelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_toolbar.nameButton addTarget:self action:@selector(handleNameButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_toolbar.clearButton addTarget:self action:@selector(handleClearButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        __weak __typeof(self)weakSelf = self;
        _toolbar.searchTextField.qmui_keyboardWillChangeFrameNotificationBlock = ^(QMUIKeyboardUserInfo *keyboardUserInfo) {
            [weakSelf handleKeyboardWillChangeFrame:keyboardUserInfo];
        };
        _toolbar.searchTextField.delegate = self;
        [_toolbar.searchTextField addTarget:self action:@selector(handleSearchTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
        [_toolbar.searchResultPreviousButton addTarget:self action:@selector(handleSearchResultPreviousButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_toolbar.searchResultNextButton addTarget:self action:@selector(handleSearchResultNextButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toolbar;
}
 
@synthesize popoverButton = _popoverButton;
- (QMUIButton *)popoverButton {
    if (!_popoverButton) {
        UIImage *popoverImage = [[QMUIHelper imageWithName:@"QMUI_console_logo"] qmui_imageResizedInLimitedSize:CGSizeMake(24, 24)];
        _popoverButton = [[QMUIButton alloc] qmui_initWithSize:CGSizeMake(32, 32)];
        [_popoverButton setImage:popoverImage forState:UIControlStateNormal];
        _popoverButton.adjustsButtonWhenHighlighted = NO;
        _popoverButton.backgroundColor = [[QMUIConsole appearance].backgroundColor colorWithAlphaComponent:.5];
        _popoverButton.layer.cornerRadius = CGRectGetHeight(_popoverButton.bounds) / 2;
        _popoverButton.clipsToBounds = YES;
        [_popoverButton addTarget:self action:@selector(handlePopoverTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
        
        self.popoverLongPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePopverLongPressGestureRecognizer:)];
        [_popoverButton addGestureRecognizer:self.popoverLongPressGesture];
        
        self.popoverPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePopoverPanGestureRecognizer:)];
        [self.popoverPanGesture requireGestureRecognizerToFail:self.popoverLongPressGesture];
        [_popoverButton addGestureRecognizer:self.popoverPanGesture];
    }
    return _popoverButton;
}
 
- (void)initSubviews {
    [super initSubviews];
    [self.view addSubview:self.containerView];
    [self.containerView addSubview:self.tableView];
    [self.containerView addSubview:self.toolbar];
    
    __weak __typeof(self)weakSelf = self;
    self.levelMenu = [self generatePopupMenuView];
    self.levelMenu.willHideBlock = ^(BOOL hidesByUserTap, BOOL animated) {
        weakSelf.toolbar.levelButton.selected = weakSelf.selectedLevels.count > 0;
    };
    self.levelMenu.sourceView = self.toolbar.levelButton;
    
    self.nameMenu = [self generatePopupMenuView];
    self.nameMenu.willHideBlock = ^(BOOL hidesByUserTap, BOOL animated) {
        weakSelf.toolbar.nameButton.selected = weakSelf.selectedNames.count > 0;
    };
    self.nameMenu.sourceView = self.toolbar.nameButton;
    
    [self updateToolbarButtonState];
    
    [self.view addSubview:self.popoverButton];
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    __weak __typeof(self)weakSelf = self;
    self.view.qmui_hitTestBlock = ^__kindof UIView * _Nullable(CGPoint point, UIEvent * _Nullable event, __kindof UIView * _Nullable originalView) {
        
        QMUIPopupMenuView *menuView = weakSelf.levelMenu.isShowing ? weakSelf.levelMenu : (weakSelf.nameMenu.isShowing ? weakSelf.nameMenu : nil);
        if (menuView && ![originalView isDescendantOfView:menuView]) {
            [menuView hideWithAnimated:YES];
            return weakSelf.view;// 也即不再传递这次事件了,相当于无效点击
        }
        
        if (originalView == weakSelf.view) {
            if (weakSelf.toolbar.searchTextField.isFirstResponder) {
                [weakSelf.view endEditing:YES];
            }
            return nil;
        }
        return originalView;
    };
}
 
- (CGRect)safetyPopoverButtonFrame:(CGRect)popoverButtonFrame {
    CGRect safetyBounds = CGRectInsetEdges(self.view.bounds, self.view.safeAreaInsets);
    if (!CGRectContainsRect(safetyBounds, self.popoverButton.frame)) {
        popoverButtonFrame = CGRectSetX(popoverButtonFrame, MAX(self.view.safeAreaInsets.left, MIN(CGRectGetMaxX(safetyBounds) - CGRectGetWidth(popoverButtonFrame), CGRectGetMinX(popoverButtonFrame))));
        popoverButtonFrame = CGRectSetY(popoverButtonFrame, MAX(self.view.safeAreaInsets.top, MIN(CGRectGetMaxY(safetyBounds) - CGRectGetHeight(popoverButtonFrame), CGRectGetMinY(popoverButtonFrame))));
    }
    return popoverButtonFrame;
}
 
- (void)layoutPopoverButton {
    if (self.popoverPanGesture.enabled) {
        CGPoint popoverButtonOrigin;
        NSValue *bindObject = [self.popoverButton qmui_getBoundObjectForKey:@"origin"];
        if (bindObject) {
            popoverButtonOrigin = ((NSValue *)[self.popoverButton qmui_getBoundObjectForKey:@"origin"]).CGPointValue;
        } else {
            popoverButtonOrigin = CGPointMake(16 + self.view.safeAreaInsets.left, CGRectGetHeight(self.view.bounds) * 3.0 / 4.0);
        }
        self.popoverButton.qmui_frameApplyTransform = [self safetyPopoverButtonFrame:CGRectSetXY(self.popoverButton.frame, popoverButtonOrigin.x, popoverButtonOrigin.y)];
    } else {
        self.popoverButton.qmui_frameApplyTransform = CGRectSetXY(self.popoverButton.frame, CGRectGetMaxX(self.containerView.frame) - 10 - CGRectGetWidth(self.popoverButton.bounds), CGRectGetMinY(self.containerView.frame) + 10);
    }
}
 
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (self.popoverAnimating) return;
    
    [self layoutPopoverButton];
    
    CGSize containerViewSize = CGSizeMake(CGRectGetWidth(self.view.bounds), MAX(100, CGRectGetHeight(self.view.bounds) / 3));
    self.containerView.qmui_frameApplyTransform = CGRectMake(0, CGRectGetHeight(self.view.bounds) - containerViewSize.height, containerViewSize.width, containerViewSize.height);
    
    CGFloat toolbarHeight = 44 + self.containerView.safeAreaInsets.bottom;
    self.toolbar.qmui_height = toolbarHeight;
    self.toolbar.qmui_width = self.containerView.qmui_width;
    self.toolbar.qmui_bottom = self.containerView.qmui_height;
    
    self.tableView.qmui_width = self.containerView.qmui_width;
    self.tableView.qmui_height = self.toolbar.qmui_top;
    self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.safeAreaInsets.top, self.tableView.safeAreaInsets.left, self.tableView.contentInset.bottom, self.tableView.safeAreaInsets.right);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    [@[self.levelMenu, self.nameMenu] enumerateObjectsUsingBlock:^(QMUIPopupMenuView *menuView, NSUInteger idx, BOOL * _Nonnull stop) {
        menuView.safetyMarginsOfSuperview = UIEdgeInsetsConcat(UIEdgeInsetsMake(2, 2, 2, 2), self.view.safeAreaInsets);
    }];
}
 
- (BOOL)shouldAutorotate {
    return [QMUIHelper visibleViewController].shouldAutorotate;
}
 
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return [QMUIHelper visibleViewController].supportedInterfaceOrientations;
}
 
- (void)setBackgroundColor:(UIColor *)backgroundColor {
    _backgroundColor = backgroundColor;
    if (self.isViewLoaded) {
        self.containerView.backgroundColor = backgroundColor;
    }
}
 
- (void)logWithLevel:(NSString *)level name:(NSString *)name logString:(id)logString {
    QMUIConsoleLogItem *logItem = [QMUIConsoleLogItem logItemWithLevel:level name:name timeString:[self.dateFormatter stringFromDate:[NSDate new]] logString:logString];
    [self searchInLogItem:logItem];
    [self.logItems addObject:logItem];
    dispatch_async(dispatch_get_main_queue(), ^{// 避免频繁打 log 时卡顿
        [self printLog];
    });
}
 
- (void)log:(id)logString {
    [self logWithLevel:nil name:nil logString:logString];
}
 
- (void)printLog {
    self.showingLogItems = [self.logItems qmui_filterWithBlock:^BOOL(QMUIConsoleLogItem * _Nonnull logItem) {
        BOOL shouldPrintLevel = !self.selectedLevels.count || [self.selectedLevels containsObject:logItem.level];
        BOOL shouldPrintName = !self.selectedNames.count || [self.selectedNames containsObject:logItem.name];
        return shouldPrintLevel && shouldPrintName;
    }];
    if (_tableView) {
        [self updateToolbarButtonState];
        
        [self.tableView reloadData];
        [self.tableView performBatchUpdates:^{
        } completion:^(BOOL finished) {
            NSArray<QMUIConsoleLogItem *> *matchedItems = [self.showingLogItems qmui_filterWithBlock:^BOOL(QMUIConsoleLogItem * _Nonnull item) {
                return item.searchResults.count > 0;
            }];
            NSArray<NSArray<NSTextCheckingResult *> *> *matchedResults = [matchedItems qmui_mapWithBlock:^id _Nonnull(QMUIConsoleLogItem * _Nonnull item) {
                return item.searchResults;
            }];
            self.searchResultsTotalCount = 0;
            [matchedResults enumerateObjectsUsingBlock:^(NSArray<NSTextCheckingResult *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                self.searchResultsTotalCount += obj.count;
            }];
            
            BOOL shouldShowCountLabel = self.toolbar.searchTextField.text.length > 0;// 不管有没有结果,只要有搜索文本,就显示结果计数
            if (shouldShowCountLabel) {
                self.toolbar.searchTextField.rightViewMode = UITextFieldViewModeAlways;
                self.toolbar.searchResultPreviousButton.enabled = self.searchResultsTotalCount > 1;
                self.toolbar.searchResultNextButton.enabled = self.searchResultsTotalCount > 1;
            } else {
                self.toolbar.searchTextField.rightViewMode = UITextFieldViewModeNever;
            }
            if (self.searchResultsTotalCount == 0) {
                self.currentHighlightedResultIndex = -1;// < 0 时不会自动滚动,所以需要手动再滚到列表末尾
                if ([self.tableView numberOfRowsInSection:0] > 0) {
                    NSIndexPath *lastRow = [NSIndexPath indexPathForRow:[self.tableView numberOfRowsInSection:0] - 1 inSection:0];
                    [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                }
            } else {
                self.currentHighlightedResultIndex = 0;// >= 0 时内部会自动滚动
            }
        }];
    }
}
 
- (void)clear {
    [self.selectedLevels removeAllObjects];
    [self.selectedNames removeAllObjects];
    [self.logItems removeAllObjects];
    self.toolbar.levelButton.enabled = NO;
    self.toolbar.levelButton.selected = NO;
    self.toolbar.nameButton.enabled = NO;
    self.toolbar.nameButton.selected = NO;
    [self printLog];
}
 
#pragma mark - <QMUITableViewDataSource, QMUITableViewDelegate>
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.showingLogItems.count;
}
 
- (id<NSCopying>)qmui_tableView:(UITableView *)tableView cacheKeyForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.showingLogItems[indexPath.row].logString.string;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QMUIConsoleLogItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    QMUIConsoleLogItem *logItem = self.showingLogItems[indexPath.row];
    cell.textView.attributedText = logItem.displayString.copy;
    [cell updateCellAppearanceWithIndexPath:indexPath];
    return cell;
}
 
#pragma mark - Popover Button
 
- (void)handlePopoverTouchEvent:(QMUIButton *)button {
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    self.popoverAnimating = YES;
    CGAffineTransform scale = CGAffineTransformMakeScale(CGRectGetWidth(self.popoverButton.frame) / CGRectGetWidth(self.containerView.frame), CGRectGetHeight(self.popoverButton.frame) / CGRectGetHeight(self.containerView.frame));
    CGAffineTransform translation = CGAffineTransformMakeTranslation(self.popoverButton.center.x - self.containerView.center.x, self.popoverButton.center.y - self.containerView.center.y);
    CGAffineTransform transform = CGAffineTransformConcat(scale, translation);
    CGFloat cornerRadius = MIN(CGRectGetWidth(self.containerView.bounds), CGRectGetHeight(self.containerView.bounds));
    
    if (self.containerView.hidden) {
        self.popoverPanGesture.enabled = NO;
        self.popoverLongPressGesture.enabled = NO;
        [UIView animateWithDuration:.1 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.popoverButton.alpha = 0;
        } completion:nil];
        
        self.containerView.alpha = 0;
        self.containerView.hidden = NO;
        self.containerView.layer.cornerRadius = cornerRadius / 2;
        self.containerView.transform = transform;
        [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.containerView.alpha = 1;
            self.containerView.transform = CGAffineTransformIdentity;
            self.containerView.layer.cornerRadius = 0;
        } completion:^(BOOL finished) {
            [self layoutPopoverButton];
            self.popoverButton.transform = CGAffineTransformMakeScale(0, 0);
            [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.popoverButton.alpha = .3;
                self.popoverButton.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                self.popoverAnimating = NO;
            }];
        }];
    } else {
        self.popoverPanGesture.enabled = YES;
        self.popoverLongPressGesture.enabled = YES;
        [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.popoverButton.alpha = 1;
            self.containerView.alpha = 0;
            self.containerView.transform = transform;
            self.containerView.layer.cornerRadius = cornerRadius / 2;
            [self.view endEditing:YES];
        } completion:^(BOOL finished) {
            self.containerView.hidden = YES;
            self.containerView.transform = CGAffineTransformIdentity;
            self.containerView.layer.cornerRadius = 0;
            
            [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:0.69 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                [self layoutPopoverButton];
                self.popoverButton.alpha = 1;
            } completion:^(BOOL finished) {
                self.popoverAnimating = NO;
            }];
        }];
    }
}
 
- (void)handlePopoverPanGestureRecognizer:(UIPanGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            self.popoverAnimating = YES;
            [self.popoverButton qmui_bindObject:[NSValue valueWithCGPoint:self.popoverButton.frame.origin] forKey:@"origin"];
            break;
        case UIGestureRecognizerStateChanged: {
            CGPoint translation = [gesture translationInView:self.view];
            self.popoverButton.transform = CGAffineTransformMakeTranslation(translation.x, translation.y);
        }
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed: {
            CGRect popoverButtonFrame = [self safetyPopoverButtonFrame:self.popoverButton.frame];
            BOOL animated = CGRectEqualToRect(popoverButtonFrame, self.popoverButton.frame);
            [UIView qmui_animateWithAnimated:animated duration:.25 delay:0 options:QMUIViewAnimationOptionsCurveOut animations:^{
                self.popoverButton.transform = CGAffineTransformIdentity;
                self.popoverButton.frame = popoverButtonFrame;
            } completion:^(BOOL finished) {
                [self.popoverButton qmui_bindObject:[NSValue valueWithCGPoint:popoverButtonFrame.origin] forKey:@"origin"];
                self.popoverAnimating = NO;
            }];
        }
            break;
        default:
            break;
    }
}
 
- (void)handlePopverLongPressGestureRecognizer:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        CFTimeInterval duration = 0.5;
        CAKeyframeAnimation *scale = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
        scale.values = @[@1.0, @1.2, @0.2];
        scale.keyTimes = @[@0.0, @(.2 / duration), @1];
        scale.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        scale.duration = duration;
        scale.fillMode = kCAFillModeForwards;
        scale.removedOnCompletion = NO;
        __weak __typeof(self)weakSelf = self;
        scale.qmui_animationDidStopBlock = ^(__kindof CAAnimation *aAnimation, BOOL finished) {
            [QMUIConsole hide];
            [weakSelf.popoverButton.layer removeAnimationForKey:@"scale"];
            [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred];
        };
        [self.popoverButton.layer addAnimation:scale forKey:@"scale"];
    }
}
 
#pragma mark - Toolbar Buttons
 
- (void)updateToolbarButtonState {
    self.toolbar.levelButton.enabled = self.logItems.count > 0;
    self.toolbar.nameButton.enabled = self.logItems.count > 0;
}
 
- (QMUIPopupMenuView *)generatePopupMenuView {
    QMUIPopupMenuView *menuView = [[QMUIPopupMenuView alloc] init];
    menuView.padding = UIEdgeInsetsMake(3, 6, 3, 6);
    menuView.cornerRadius = 3;
    menuView.arrowSize = CGSizeMake(8, 4);
    menuView.borderWidth = 0;
    menuView.itemHeight = 28;
    menuView.itemTitleFont = UIFontMake(12);
    menuView.itemTitleColor = UIColorMake(53, 60, 70);
    menuView.maskViewBackgroundColor = nil;
    menuView.backgroundColor = UIColorWhite;
    menuView.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
        aItem.highlightedBackgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.15];
        QMUIButton *button = aItem.button;
        button.imagePosition = QMUIButtonImagePositionRight;
        button.spacingBetweenImageAndTitle = 10;
        UIImage *selectedImage = [UIImage qmui_imageWithShape:QMUIImageShapeCheckmark size:CGSizeMake(12, 9) lineWidth:1 tintColor:aMenuView.itemTitleColor];
        UIImage *normalImage = [UIImage qmui_imageWithColor:UIColorClear size:selectedImage.size cornerRadius:0];
        [button setImage:normalImage forState:UIControlStateNormal];// 无图像也弄一张空白图,以保证 state 变化时布局不跳动
        [button setImage:selectedImage forState:UIControlStateSelected];
        [button setImage:selectedImage forState:UIControlStateSelected|UIControlStateHighlighted];
    };
    menuView.hidden = YES;
    [self.view addSubview:menuView];
    return menuView;
}
 
- (NSArray<QMUIPopupMenuButtonItem *> *)popupMenuItemsByTitleBlock:(nullable NSString * (^)(QMUIConsoleLogItem *logItem))titleBlock selectedArray:(NSMutableArray<NSString *> *)selectedArray {
    __weak __typeof(self)weakSelf = self;
    NSMutableArray<QMUIPopupMenuButtonItem *> *items = [[NSMutableArray alloc] init];
    NSMutableSet<NSString *> *itemTitles = [[NSMutableSet alloc] init];
    [self.logItems enumerateObjectsUsingBlock:^(QMUIConsoleLogItem * _Nonnull logItem, NSUInteger idx, BOOL * _Nonnull stop) {
        [itemTitles addObject:titleBlock(logItem)];
    }];
    [[itemTitles sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:NSStringFromSelector(@selector(description)) ascending:YES]]] enumerateObjectsUsingBlock:^(NSString * _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIPopupMenuButtonItem *item = [QMUIPopupMenuButtonItem itemWithImage:nil title:title handler:^(QMUIPopupMenuButtonItem *aItem) {
            aItem.button.selected = !aItem.button.selected;
            if (aItem.button.selected) {
                [selectedArray addObject:title];
            } else {
                [selectedArray removeObject:title];
            }
            [weakSelf printLog];
        }];
        item.button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        item.button.selected = [selectedArray containsObject:title];
        [items addObject:item];
    }];
    return items.copy;
}
 
- (void)handleLevelButtonEvent:(UIButton *)button {
    self.levelMenu.items = [self popupMenuItemsByTitleBlock:^NSString *(QMUIConsoleLogItem *logItem) {
        return logItem.level;
    } selectedArray:self.selectedLevels];
    [self.levelMenu showWithAnimated:YES];
    button.selected = YES;
}
 
- (void)handleNameButtonEvent:(UIButton *)button {
    self.nameMenu.items = [self popupMenuItemsByTitleBlock:^NSString *(QMUIConsoleLogItem *logItem) {
        return logItem.name;
    } selectedArray:self.selectedNames];
    [self.nameMenu showWithAnimated:YES];
    button.selected = YES;
}
 
- (void)handleClearButtonEvent:(UIButton *)button {
    [self clear];
}
 
#pragma mark - Search
 
- (void)searchInLogItem:(QMUIConsoleLogItem *)logItem {
    NSString *searchingText = self.toolbar.searchTextField.text ?: @"";
    BOOL valueChanged = ![searchingText isEqualToString:logItem.searchingString ?: @""];// UITextField.text 不会为 nil,至少是 @"",为了保证 isEqualToString: 的正确性,这里对 searchingString 也做了 nil -> @"" 的转换
    if (!valueChanged) return;
    logItem.searchingString = searchingText;
    NSArray<NSTextCheckingResult *> *matches = [self.searchRegularExpression matchesInString:logItem.logString.string options:NSMatchingReportCompletion range:NSMakeRange(0, logItem.logString.string.length)];
    [logItem updateDisplayStringWithSearchResults:matches];
}
 
- (void)handleSearchTextFieldChanged:(QMUITextField *)searchTextField {
    
    if (self.levelMenu.isShowing) [self.levelMenu hideWithAnimated:YES];
    if (self.nameMenu.isShowing) [self.nameMenu hideWithAnimated:YES];
    
    self.searchRegularExpression = [NSRegularExpression regularExpressionWithPattern:searchTextField.text options:NSRegularExpressionCaseInsensitive error:nil];
    [self.logItems enumerateObjectsUsingBlock:^(QMUIConsoleLogItem * _Nonnull logItem, NSUInteger idx, BOOL * _Nonnull stop) {
        [self searchInLogItem:logItem];
    }];
    [self printLog];
}
 
- (void)handleSearchResultPreviousButtonEvent:(QMUIButton *)button {
    if (self.currentHighlightedResultIndex == 0) {
        self.currentHighlightedResultIndex = self.searchResultsTotalCount - 1;
    } else {
        self.currentHighlightedResultIndex --;
    }
}
 
- (void)handleSearchResultNextButtonEvent:(QMUIButton *)button {
    if (self.currentHighlightedResultIndex == self.searchResultsTotalCount - 1) {
        self.currentHighlightedResultIndex = 0;
    } else {
        self.currentHighlightedResultIndex ++;
    }
}
 
- (void)setCurrentHighlightedResultIndex:(NSInteger)currentHighlightedResultIndex {
    _currentHighlightedResultIndex = currentHighlightedResultIndex;
    [self.lastHighlightedItem updateDisplayStringWithSearchResults:self.lastHighlightedItem.searchResults];// clear focus
    self.toolbar.searchResultCountLabel.text = currentHighlightedResultIndex >= 0 ? [NSString stringWithFormat:@"%@/%@", @(currentHighlightedResultIndex + 1), @(self.searchResultsTotalCount)] : @"0";
    [self.toolbar setNeedsLayoutSearchResultViews];
    if (currentHighlightedResultIndex >= 0) {
        
        NSInteger row = NSNotFound;
        NSInteger indexInItem = NSNotFound;
        for (NSInteger i = 0, j = 0; i < self.showingLogItems.count; i++) {
            if (self.currentHighlightedResultIndex < j + self.showingLogItems[i].searchResults.count) {
                row = i;
                indexInItem = self.currentHighlightedResultIndex - j;
                break;
            }
            j += self.showingLogItems[i].searchResults.count;
        }
        if (row != NSNotFound) {
            [self.showingLogItems[row] focusSearchResultAtIndex:indexInItem];
            [self.tableView reloadData];
            self.lastHighlightedItem = self.showingLogItems[row];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            BOOL shouldScrollToVisible = ![self.tableView qmui_cellVisibleAtIndexPath:indexPath];
            if (!shouldScrollToVisible) {
                // 本来就可视的,可能 cell 比较高,只露出屏幕一半,高亮的那个地方没露出来,这种要手动计算
                CGRect rect = [self.tableView rectForRowAtIndexPath:indexPath];
                if (!CGRectContainsRect(self.tableView.bounds, rect)) {
                    shouldScrollToVisible = YES;
                }
            }
            if (shouldScrollToVisible) {
                [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            }
        }
    }
}
 
- (void)handleKeyboardWillChangeFrame:(QMUIKeyboardUserInfo *)userInfo {
    CGFloat height = [userInfo heightInView:self.view];
    self.containerView.transform = CGAffineTransformMakeTranslation(0, -height);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.levelMenu.isShowing) [self.levelMenu updateLayout];
        if (self.nameMenu.isShowing) [self.nameMenu updateLayout];
    });
}
 
#pragma mark - <QMUITextFieldDelegate>
 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return YES;
}
 
@end