CPDFSearchResultsViewController.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. //
  2. // CPDFSearchResultsViewController.m
  3. // ComPDFKit_Tools
  4. //
  5. // Copyright © 2014-2024 PDF Technologies, Inc. All Rights Reserved.
  6. //
  7. // THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
  8. // AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
  9. // UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
  10. // This notice may not be removed from this file.
  11. //
  12. #import "CPDFSearchResultsViewController.h"
  13. #import "CPDFSearchViewCell.h"
  14. #import <ComPDFKit/ComPDFKit.h>
  15. #import <CoreText/CoreText.h>
  16. #import "UIViewController+LeftItem.h"
  17. #import "CPDFColorUtils.h"
  18. #import "CPDFListView.h"
  19. #import "CActivityIndicatorView.h"
  20. #define kTextSearch_Content_Length_Max 100
  21. @interface CPDFSearchResultsViewController () <UITableViewDelegate, UITableViewDataSource>
  22. @property (nonatomic, strong) NSArray *resultArray;
  23. @property (nonatomic, strong) NSString *keyword;
  24. @property (nonatomic, strong) CPDFDocument *document;
  25. @property (nonatomic, strong) UITableView *tableView;
  26. @property (nonatomic, strong) UIView * searchResultView;
  27. @property (nonatomic, strong) UILabel * searchResultLabel;
  28. @property (nonatomic, strong) UILabel * pageLabel;
  29. @property (nonatomic, strong) UIButton *backBtn;
  30. @property(nonatomic, strong) CActivityIndicatorView *loadingView;
  31. @end
  32. @implementation CPDFSearchResultsViewController
  33. #pragma mark - Initializers
  34. - (instancetype)initWithResultArray:(NSArray *)resultArray keyword:(NSString *) keyword document:(CPDFDocument *) document {
  35. if (self = [super init]) {
  36. _resultArray = resultArray;
  37. _keyword = keyword;
  38. _document = document;
  39. }
  40. return self;
  41. }
  42. #pragma mark - Accessors
  43. #pragma mark - UIViewController Methods
  44. - (void)viewDidLoad {
  45. [super viewDidLoad];
  46. // Do any additional setup after loading the view.
  47. // [self changeleftItem];
  48. self.title = NSLocalizedString(@"Results", nil);
  49. self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
  50. self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  51. self.tableView.delegate = self;
  52. self.tableView.dataSource = self;
  53. self.view.backgroundColor = [UIColor whiteColor];
  54. self.tableView.rowHeight = UITableViewAutomaticDimension;
  55. self.tableView.estimatedRowHeight = 60;
  56. self.tableView.tableFooterView = [[UIView alloc] init];
  57. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  58. [self.tableView registerClass:[CPDFSearchViewCell class] forCellReuseIdentifier:@"cell"];
  59. [self.view addSubview:self.tableView];
  60. self.searchResultView = [[UIView alloc] init];
  61. self.searchResultLabel = [[UILabel alloc] init];
  62. self.pageLabel = [[UILabel alloc] init];
  63. self.searchResultView.backgroundColor = [CPDFColorUtils CAnnotationSampleBackgoundColor];
  64. self.pageLabel.font = [UIFont systemFontOfSize:14];
  65. self.pageLabel.text = NSLocalizedString(@"Page",nil);
  66. self.pageLabel.textAlignment = NSTextAlignmentRight;
  67. self.pageLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
  68. self.searchResultLabel.font = [UIFont systemFontOfSize:14];
  69. self.searchResultLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
  70. [self.searchResultView addSubview:self.searchResultLabel];
  71. NSMutableArray *datas = [NSMutableArray array];
  72. for (NSArray *results in self.resultArray) {
  73. for (CPDFSelection *selection in results) {
  74. [datas addObject:selection];
  75. }
  76. }
  77. self.searchResultLabel.text = [NSString stringWithFormat:@"%zd %@",datas.count, NSLocalizedString(@"Resultss",nil)];
  78. [self.searchResultLabel sizeToFit];
  79. [self.searchResultView addSubview:self.pageLabel];
  80. [self.view addSubview:self.searchResultView];
  81. [self updatePreferredContentSizeWithTraitCollection:self.traitCollection];
  82. self.backBtn = [[UIButton alloc] init];
  83. [self.backBtn setImage:[UIImage imageNamed:@"CPDFViewImageBack" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
  84. [self.backBtn sizeToFit];
  85. [self.backBtn addTarget:self action:@selector(buttonItemClicked_Back:) forControlEvents:UIControlEventTouchUpInside];
  86. UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
  87. self.navigationItem.leftBarButtonItems = @[backItem];
  88. UIButton *replaceBtn = [[UIButton alloc] init];
  89. replaceBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  90. if (@available(iOS 13.0, *)) {
  91. [replaceBtn setTitleColor:[UIColor labelColor] forState:UIControlStateNormal];
  92. } else {
  93. [replaceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  94. }
  95. [replaceBtn setTitle:NSLocalizedString(@"Replace", nil) forState:UIControlStateNormal];
  96. [replaceBtn addTarget:self action:@selector(buttonItemClicked_Replace:) forControlEvents:UIControlEventTouchUpInside];
  97. [replaceBtn sizeToFit];
  98. UIBarButtonItem* replaceItem = [[UIBarButtonItem alloc] initWithCustomView:replaceBtn];
  99. if (self.pdfListView.toolModel == CToolModelEdit) {
  100. self.navigationItem.rightBarButtonItems = @[replaceItem];
  101. } else {
  102. self.navigationItem.rightBarButtonItems = @[];
  103. }
  104. self.view.backgroundColor = [CPDFColorUtils CPDFViewControllerBackgroundColor];
  105. }
  106. - (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  107. [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator];
  108. [self updatePreferredContentSizeWithTraitCollection:newCollection];
  109. }
  110. - (void)updatePreferredContentSizeWithTraitCollection:(UITraitCollection *)traitCollection
  111. {
  112. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  113. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  114. CGFloat mWidth = fmin(width, height);
  115. CGFloat mHeight = fmax(width, height);
  116. UIDevice *currentDevice = [UIDevice currentDevice];
  117. if (currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
  118. // This is an iPad
  119. self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact ? mWidth*0.9 : mHeight*0.7);
  120. } else {
  121. // This is an iPhone or iPod touch
  122. self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact ? mWidth*0.9 : mHeight*0.9);
  123. }
  124. }
  125. - (void)viewWillLayoutSubviews {
  126. [super viewWillLayoutSubviews];
  127. if (@available(iOS 11.0, *)) {
  128. self.tableView.frame = CGRectMake(self.view.safeAreaInsets.left, self.view.safeAreaInsets.top + 28, self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right, self.view.frame.size.height - self.view.safeAreaInsets.bottom- self.view.safeAreaInsets.top - 28);
  129. self.searchResultView.frame = CGRectMake(self.view.safeAreaInsets.left, self.view.safeAreaInsets.top, self.view.frame.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right, 28);
  130. self.searchResultLabel.frame = CGRectMake(20, 4, 200, 20);
  131. self.pageLabel.frame = CGRectMake(self.view.frame.size.width - 50, 4, 40, 20);
  132. } else {
  133. self.searchResultView.frame = CGRectMake(10, CGRectGetMaxY(self.navigationController.navigationBar.frame), self.view.frame.size.width-20, 28);
  134. self.searchResultLabel.frame = CGRectMake(20, 4, 200, 20);
  135. self.pageLabel.frame = CGRectMake(self.view.frame.size.width - 50, 4, 40, 20);
  136. self.tableView.frame = CGRectMake(self.view.bounds.origin.x, 28, self.view.bounds.size.width, self.view.bounds.size.height-28);
  137. }
  138. }
  139. - (CActivityIndicatorView *)loadingView {
  140. if (!_loadingView) {
  141. if (@available(iOS 13.0, *)) {
  142. _loadingView = [[CActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge];
  143. } else {
  144. _loadingView = [[CActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
  145. }
  146. _loadingView.center = self.view.center;
  147. _loadingView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
  148. }
  149. return _loadingView;
  150. }
  151. #pragma mark - Button Actions
  152. - (void)buttonItemClicked_Back:(id)sender {
  153. if([self.delegate respondsToSelector:@selector(searchResultsViewControllerDismiss:)])
  154. [self.delegate searchResultsViewControllerDismiss:self];
  155. }
  156. - (void)buttonItemClicked_Replace:(UIButton *)sender {
  157. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:NSLocalizedString(@"Please enter Replace text!", nil) preferredStyle:UIAlertControllerStyleAlert];
  158. __weak typeof(self) weakSelf = self;
  159. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  160. }]];
  161. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Replace", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  162. UITextField *pageTextField = alertController.textFields.firstObject;
  163. NSString *replaceString = pageTextField.text;
  164. if (![self.loadingView superview]) {
  165. [self.view addSubview:self.loadingView];
  166. }
  167. [self.loadingView startAnimating];
  168. [self.navigationController.view setUserInteractionEnabled:NO];
  169. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  170. [weakSelf.document replaceAllEditTextWithString:weakSelf.searchString toReplaceString:replaceString];
  171. dispatch_async(dispatch_get_main_queue(), ^{
  172. [self.navigationController.view setUserInteractionEnabled:YES];
  173. [self.loadingView removeFromSuperview];
  174. self.pdfListView.superview.userInteractionEnabled = YES;
  175. if([self.delegate respondsToSelector:@selector(searchResultsViewControllerReplace:)]) {
  176. [self.delegate searchResultsViewControllerReplace:self];
  177. }
  178. });
  179. });
  180. }]];
  181. [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  182. textField.clearButtonMode = UITextFieldViewModeWhileEditing;
  183. [textField addTarget:weakSelf action:@selector(textField_ShouldReturn:) forControlEvents:UIControlEventEditingDidEnd];
  184. }];
  185. if (UIUserInterfaceIdiomPad == UI_USER_INTERFACE_IDIOM()) {
  186. alertController.popoverPresentationController.sourceView = sender;
  187. alertController.popoverPresentationController.sourceRect = sender.bounds;
  188. }
  189. [self presentViewController:alertController animated:YES completion:nil];
  190. }
  191. - (void)textField_ShouldReturn:(UITextField *)textField {
  192. [self resignFirstResponder];
  193. }
  194. #pragma mark - Private Methods
  195. - (NSMutableAttributedString *)getAttributedStringWithSelection:(CPDFSelection *)selection {
  196. CPDFPage * currentPage = selection.page;
  197. NSRange range = selection.range;
  198. NSUInteger startLocation = 0;
  199. NSUInteger maxLocation = 20;
  200. NSInteger keyLocation = 0;
  201. NSUInteger maxEndLocation = 80;
  202. if (range.location > maxLocation) {
  203. startLocation = range.location - maxLocation;
  204. keyLocation = maxLocation;
  205. } else {
  206. startLocation = 0;
  207. keyLocation = range.location;
  208. }
  209. NSUInteger endLocation = 0;
  210. if (range.location + maxEndLocation > currentPage.numberOfCharacters) {
  211. endLocation = currentPage.numberOfCharacters;
  212. } else {
  213. endLocation = range.location + maxEndLocation;
  214. }
  215. NSMutableAttributedString * attributed = nil;
  216. if (endLocation> startLocation) {
  217. NSString * currentString = [currentPage stringForRange:NSMakeRange(startLocation, endLocation - startLocation)];
  218. NSRange tRange = NSMakeRange(keyLocation, self.keyword.length);
  219. if (tRange.location != NSNotFound) {
  220. attributed = [[NSMutableAttributedString alloc] initWithString:currentString];
  221. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
  222. paragraphStyle.firstLineHeadIndent = 10.0;
  223. paragraphStyle.headIndent = 10.0;
  224. paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
  225. NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue-Medium" size:13.0],NSFontAttributeName,paragraphStyle,NSParagraphStyleAttributeName,nil];
  226. NSRange range = [[attributed string] rangeOfString:[attributed string]];
  227. [attributed setAttributes:dic range:range];
  228. dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:102./255. green:102/255. blue:102/255. alpha:1.],NSForegroundColorAttributeName,nil];
  229. [attributed addAttributes:dic range:NSMakeRange(0, currentString.length)];
  230. //hightlight string
  231. dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:1.0 green:220.0/255.0 blue:27.0/255.0 alpha:1.0],NSBackgroundColorAttributeName,nil];
  232. if (attributed.length > tRange.length + tRange.location) {
  233. [attributed addAttributes:dic range:tRange];
  234. }
  235. }
  236. }
  237. return attributed;
  238. }
  239. #pragma mark - UITableViewDatasource
  240. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  241. return [self.resultArray count];
  242. }
  243. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  244. NSArray *array = [self.resultArray objectAtIndex:section];
  245. return [array count];
  246. }
  247. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  248. CPDFSearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  249. if (!cell) {
  250. cell = [[CPDFSearchViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
  251. }
  252. CPDFSelection *selection = self.resultArray[indexPath.section][indexPath.row];
  253. cell.contentLabel.attributedText = [self getAttributedStringWithSelection:selection];
  254. return cell;
  255. }
  256. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  257. CPDFSelection *selection = self.resultArray[indexPath.section][indexPath.row];
  258. NSAttributedString *attributeText = [self getAttributedStringWithSelection:selection];
  259. CGFloat cellWidth = tableView.frame.size.width;
  260. UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
  261. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributeText);
  262. CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(cellWidth - padding.left - padding.right, CGFLOAT_MAX), NULL);
  263. CGFloat cellHeight = suggestedSize.height + padding.top + padding.bottom;
  264. CFRelease(framesetter);
  265. return cellHeight;
  266. }
  267. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  268. return 30;
  269. }
  270. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  271. NSArray *array = [self.resultArray objectAtIndex:section];
  272. CPDFSelection *selection = array.firstObject;
  273. NSInteger pageIndex = [self.document indexForPage:selection.page];
  274. NSString *countStr = [NSString stringWithFormat:NSLocalizedString(@"%ld",nil), (long)(pageIndex+1)];
  275. UITableViewHeaderFooterView *view = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
  276. view.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  277. view.backgroundColor = [UIColor colorWithRed:250./255. green:252/255. blue:255/255. alpha:1];
  278. UILabel *sublabel = [[UILabel alloc] init];
  279. sublabel.font = [UIFont systemFontOfSize:14];
  280. sublabel.text = countStr;
  281. sublabel.textColor = [UIColor colorWithRed:67./255. green:71.0/255.0 blue:77./255.0 alpha:1.0];
  282. [sublabel sizeToFit];
  283. sublabel.frame = CGRectMake(view.bounds.size.width-sublabel.bounds.size.width-10, 0,
  284. sublabel.bounds.size.width, view.bounds.size.height);
  285. sublabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
  286. [view.contentView addSubview:sublabel];
  287. return view;
  288. }
  289. #pragma mark - UITableViewDelegate
  290. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  291. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  292. [self dismissViewControllerAnimated:YES completion:^{
  293. CPDFSelection *selection = self.resultArray[indexPath.section][indexPath.row];
  294. if([self.delegate respondsToSelector:@selector(searchResultsView:forSelection:indexPath:)]) {
  295. [self.delegate searchResultsView:self forSelection:selection indexPath:indexPath];
  296. }
  297. }];
  298. }
  299. @end