CPDFListView.m 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. //
  2. // CPDFListView.m
  3. // ComPDFKit
  4. //
  5. // Copyright © 2014-2022 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 "CPDFListView.h"
  13. #import "CPDFAnnotationModel.h"
  14. #import "CSelfSignAnnotation.h"
  15. #import "CSelfSignAnnotationFreeText.h"
  16. #import "CPDFListView+Private.h"
  17. #import "CPDFListView+Event.h"
  18. #import "CPDFListView+Tool.h"
  19. #import "CPDFListView+Extension.h"
  20. #import "CPDFListView+UndoManager.h"
  21. #import "NSImage+PDFListView.h"
  22. #import "NSCursor+PDFListView.h"
  23. #import "CPDFListView+Extension.h"
  24. #import <PDF_Master-Swift.h>
  25. NSNotificationName const CPDFListViewSelectionChangedNotification = @"CPDFListViewSelectionChangedNotification";
  26. NSNotificationName const CPDFListViewToolModeChangeNotification = @"CPDFListViewToolModeChangeNotification";
  27. NSNotificationName const CPDFListViewAnnotationTypeChangeNotification = @"CPDFListViewAnnotationTypeChangeNotification";
  28. NSNotificationName const CPDFListViewMagnificationChangedNotification = @"CPDFListViewMagnificationChangedNotification";
  29. NSNotificationName const CPDFListViewDidAddAnnotationNotification = @"CPDFListViewDidAddAnnotationNotification";
  30. NSNotificationName const CPDFListViewDidRemoveAnnotationNotification = @"CPDFListViewDidRemoveAnnotationNotification";
  31. NSNotificationName const CPDFListViewActiveAnnotationsChangeNotification = @"CPDFListViewActiveAnnotationsChangeNotification";
  32. NSNotificationName const CPDFListViewAnnotationsAttributeHasChangeNotification = @"CPDFListViewAnnotationsAttributeHasChangeNotification";
  33. @interface CPDFListView ()
  34. @property (nonatomic,retain) NSColor *pageBackgroundColor;
  35. @end
  36. @implementation CPDFListView
  37. #pragma mark - Init
  38. - (id)init {
  39. self = [super init];
  40. if (self) {
  41. [self commonInitialization];
  42. }
  43. return self;
  44. }
  45. - (id)initWithFrame:(NSRect)frameRect {
  46. self = [super initWithFrame:frameRect];
  47. if (self) {
  48. [self commonInitialization];
  49. }
  50. return self;
  51. }
  52. - (id)initWithCoder:(NSCoder *)decoder {
  53. self = [super initWithCoder:decoder];
  54. if (self) {
  55. [self commonInitialization];
  56. }
  57. return self;
  58. }
  59. - (void)updateLayer {
  60. [super updateLayer];
  61. if (@available(macOS 10.14, *)) {
  62. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewBackgroundColor)]) {
  63. NSColor *color = [self.pdfListViewDelegate PDFListViewBackgroundColor];
  64. self.backgroundColor = color;
  65. }
  66. }
  67. }
  68. - (void)commonInitialization {
  69. self.selectionPageIndex = NSNotFound;
  70. self.clickLineAnnotation = nil;
  71. self.isClickDoubleCreatLine = NO;
  72. self.activeAnnotations = [NSMutableArray array];
  73. self.selectAnnotations = [NSMutableArray array];
  74. self.dragHoverPoints = [NSMutableArray array];
  75. self.aCopyAnnotations = [NSMutableArray array];
  76. [self registerAsObserver];
  77. [self addTrackingArea];
  78. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
  79. name:CPDFViewPageChangedNotification object:self];
  80. }
  81. - (void)addTrackingArea {
  82. NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect | NSTrackingActiveInKeyWindow | NSTrackingMouseMoved owner:self userInfo:nil];
  83. [self addTrackingArea:trackingArea];
  84. }
  85. - (void)goToPageIndex:(NSInteger)pageIndex animated:(BOOL)animated {
  86. if (self.currentPageIndex != pageIndex) {
  87. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  88. }
  89. [super goToPageIndex:pageIndex animated:animated];
  90. }
  91. - (void)goToSelection:(CPDFSelection *)selection animated:(BOOL)animated {
  92. if (self.currentPageIndex != selection.page.pageIndex) {
  93. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  94. }
  95. [super goToSelection:selection animated:animated];
  96. }
  97. - (void)goToDestination:(CPDFDestination *)destination {
  98. [super goToDestination:destination];
  99. }
  100. - (void)goToRect:(CGRect)rect onPage:(CPDFPage *)page animated:(BOOL)animated {
  101. if (self.currentPageIndex != page.pageIndex) {
  102. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  103. }
  104. [super goToRect:rect onPage:page animated:animated];
  105. }
  106. - (void)goToTargetPoint:(NSPoint)point onPage:(CPDFPage *)page atScrollPosition:(CScrollPosition)scrollPosition {
  107. if (self.currentPageIndex != page.pageIndex) {
  108. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  109. }
  110. [super goToTargetPoint:point onPage:page atScrollPosition:scrollPosition];
  111. }
  112. #pragma mark - Setter & Get
  113. - (void)setDocument:(CPDFDocument *)document {
  114. @synchronized (self) {
  115. self.selectionRect = NSZeroRect;
  116. self.selectionPageIndex = NSNotFound;
  117. }
  118. // self.toolMode = CFormToolMode;
  119. // self.annotationType = CAnnotationTypeRadioButton;
  120. // CStampSignatureObject *objc = [[CStampSignatureObject alloc] initImageStampWithFilePath:[[NSBundle mainBundle] pathForResource:@"Quick Start Guide" ofType:@"pdf"]];
  121. // [self setAddStampObject:objc keepToolModel:YES];
  122. //
  123. [super setDocument:document];
  124. [self.window makeFirstResponder:self];
  125. }
  126. -(void)setToolMode:(CToolMode)newToolMode {
  127. if(newToolMode != _toolMode) {
  128. BOOL isDisplayAnnotationView = NO;
  129. if(self.isSetLinkDestinationArea)
  130. self.isSetLinkDestinationArea = NO;
  131. if ((CTextToolMode == _toolMode || CNoteToolMode == _toolMode) && CTextToolMode != newToolMode) {
  132. if (newToolMode != CNoteToolMode && self.activeAnnotation) {
  133. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  134. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  135. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  136. [self commitEditAnnotationFreeText:freeTextAn];
  137. }
  138. }
  139. [self updateActiveAnnotations:@[]];
  140. }
  141. if ([self currentSelection])
  142. [self setCurrentSelection:nil];
  143. } else if (_toolMode == CSelectToolMode && NSEqualRects(self.selectionRect, NSZeroRect) == NO) {
  144. self.selectionRect = NSZeroRect;
  145. self.selectionPageIndex = NSNotFound;
  146. dispatch_async(dispatch_get_main_queue(), ^{
  147. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFViewSelectionChangedNotification object:self];
  148. });
  149. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedSelectionOrMagnification:)])
  150. [self.pdfListViewDelegate PDFListViewChangedSelectionOrMagnification:self];
  151. isDisplayAnnotationView = YES;
  152. }
  153. BOOL highlightFormFiled = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightFormFiledKey"];
  154. if (CFormToolMode == _toolMode && !highlightFormFiled) {
  155. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:highlightFormFiled];
  156. isDisplayAnnotationView = YES;
  157. } else if (CFormToolMode == newToolMode && !highlightFormFiled) {
  158. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:YES];
  159. isDisplayAnnotationView = YES;
  160. }
  161. if(CEditPDFToolMode == newToolMode)
  162. [self beginEditingLoadType:CEditingLoadTypeText|CEditingLoadTypeImage];
  163. if(_toolMode == CEditPDFToolMode) {
  164. if(self.isEdited) {
  165. [self commitEditing];
  166. }
  167. [self endOfEditing];
  168. }
  169. _toolMode = newToolMode;
  170. self.selectZoomToolModeZoomOut = NO;
  171. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedToolMode:forToolMode:)])
  172. [self.pdfListViewDelegate PDFListViewChangedToolMode:self forToolMode:newToolMode];
  173. dispatch_async(dispatch_get_main_queue(), ^{
  174. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewToolModeChangeNotification object:self];
  175. });
  176. [self resetPDFViewAnnotation];
  177. if(isDisplayAnnotationView)
  178. [self setNeedsDisplayAnnotationViewForVisiblePages];
  179. }
  180. }
  181. -(void)setShowHopnumber:(BOOL)showHopnumber {
  182. _showHopnumber = showHopnumber;
  183. [self setNeedsDisplayAnnotationViewForVisiblePages];
  184. }
  185. - (void)setAnnotationType:(CAnnotationType)annotationType {
  186. if (_annotationType != annotationType) {
  187. if(CAnnotationTypeLink == annotationType || CAnnotationTypeLink == _annotationType)
  188. [self setNeedsDisplayAnnotationViewForVisiblePages];
  189. _annotationType = annotationType;
  190. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedAnnotationType:forAnnotationType:)])
  191. [self.pdfListViewDelegate PDFListViewChangedAnnotationType:self forAnnotationType:annotationType];
  192. dispatch_async(dispatch_get_main_queue(), ^{
  193. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewAnnotationTypeChangeNotification object:self];
  194. });
  195. }
  196. if(self.activeAnnotations.count > 0) {
  197. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  198. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  199. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  200. [self commitEditAnnotationFreeText:freeTextAn];
  201. }
  202. }
  203. [self updateActiveAnnotations:@[]];
  204. [self setNeedsDisplayAnnotationViewForVisiblePages];
  205. }
  206. if(self.isSetLinkDestinationArea)
  207. self.isSetLinkDestinationArea = NO;
  208. [self resetPDFViewAnnotation];
  209. }
  210. - (NSRect)currentSelectionRect {
  211. if (CSelectToolMode == self.toolMode)
  212. return self.selectionRect;
  213. return NSZeroRect;
  214. }
  215. - (CPDFAnnotation *)activeAnnotation {
  216. return self.activeAnnotations.lastObject;
  217. }
  218. - (void)setHideNotes:(BOOL)hideNotes {
  219. _hideNotes = hideNotes;
  220. for(NSInteger i = 0;i<self.document.pageCount;i++) {
  221. CPDFPage *page = [self.document pageAtIndex:i];
  222. for (CPDFAnnotation *annotation in page.annotations) {
  223. [annotation setAnnotationShouldDisplay:!self.hideNotes];
  224. [annotation setHidden: self.hideNotes];
  225. }
  226. }
  227. [self setNeedsDisplayAnnotationViewForVisiblePages];
  228. }
  229. -(void)setIsSetLinkDestinationArea:(BOOL)isSetLinkDestinationArea {
  230. _isSetLinkDestinationArea = isSetLinkDestinationArea;
  231. if (_isSetLinkDestinationArea) {
  232. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationStart:withActiveAnnotation:)]) {
  233. [self.pdfListViewDelegate PDFListViewLinkDestinationStart:self withActiveAnnotation:self.activeAnnotation];
  234. }
  235. } else {
  236. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationEnd:withActiveAnnotation:)]) {
  237. [self.pdfListViewDelegate PDFListViewLinkDestinationEnd:self withActiveAnnotation:self.activeAnnotation];
  238. }
  239. }
  240. }
  241. - (void)setPageBackgroundColorWithColor:(NSColor *)color viewMode:(KMPDFViewMode)viewMode {
  242. if (self.activeAnnotation != nil) {
  243. return;
  244. }
  245. _viewMode = viewMode;
  246. self.pageBackgroundColor = color;
  247. [self setNeedsDisplay:YES];
  248. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewMode] forKey:@"kPDFViewModeKey"];
  249. [[NSUserDefaults standardUserDefaults] synchronize];
  250. }
  251. - (void)setViewSplitMode:(KMPDFViewSplitMode)viewSplitMode {
  252. if (_viewSplitMode == viewSplitMode) {
  253. return;
  254. }
  255. _viewSplitMode = viewSplitMode;
  256. [self setNeedsDisplay:YES];
  257. }
  258. #pragma mark - menu add image
  259. - (void)addImageAnnotation:(NSImage *)image center:(NSPoint)center isRemoveBGColor:(BOOL)isRemoveBGColor{
  260. [self setToolMode:CTextToolMode]; //不支持重复添加,重置状态
  261. if (isRemoveBGColor) {
  262. NSData *imageData = [image TIFFRepresentation];
  263. CGImageRef imageRef;
  264. if (imageData) {
  265. CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
  266. imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
  267. } else {
  268. return NSBeep();
  269. }
  270. const int imageWidth = image.size.width;
  271. const int imageHeight = image.size.height;
  272. size_t bytesPerRow = imageWidth * 4;
  273. uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
  274. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  275. CGContextRef context = CGBitmapContextCreate(rgbImageBuf,
  276. imageWidth,
  277. imageHeight,
  278. 8,
  279. bytesPerRow,
  280. colorSpace,
  281. kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  282. CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), imageRef);
  283. int pixelNum = imageWidth * imageHeight;
  284. uint32_t* pCurPtr = rgbImageBuf;
  285. for (int i = 0; i < pixelNum; i++, pCurPtr++) {
  286. uint8_t* ptr = (uint8_t*)pCurPtr;
  287. if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
  288. ptr[0] = 0;
  289. }
  290. }
  291. CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
  292. imageRef = CGImageCreate(imageWidth,
  293. imageHeight,
  294. 8,
  295. 32,
  296. bytesPerRow,
  297. colorSpace,
  298. kCGImageAlphaLast |kCGBitmapByteOrder32Little,
  299. dataProvider,
  300. NULL,
  301. true,
  302. kCGRenderingIntentDefault);
  303. CGDataProviderRelease(dataProvider);
  304. NSImage *newImage = nil;
  305. if (imageRef) {
  306. NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
  307. CGContextRef imageContext = nil;
  308. // Get the image dimensions.
  309. imageRect.size.height = CGImageGetHeight(imageRef);
  310. imageRect.size.width = CGImageGetWidth(imageRef);
  311. // Create a new image to receive the Quartz image data.
  312. newImage = [[NSImage alloc] initWithSize:imageRect.size];
  313. [newImage lockFocus];
  314. // Get the Quartz context and draw.
  315. imageContext = (CGContextRef)[[NSGraphicsContext currentContext] CGContext];
  316. CGContextDrawImage(imageContext, *(CGRect*)&imageRect, imageRef);
  317. [newImage unlockFocus];
  318. CGImageRelease(imageRef);
  319. }
  320. if (newImage) {
  321. [self addAnnotationWithImage:newImage center:center];
  322. } else {
  323. [self addAnnotationWithImage:image center:center];
  324. }
  325. } else {
  326. [self addAnnotationWithImage:image center:center];
  327. }
  328. }
  329. - (void)addAnnotationWithImage:(NSImage *)image center:(NSPoint)center {
  330. CPDFPage *page = nil;
  331. NSRect bounds = NSZeroRect;
  332. CPDFSelection *selection = [self currentSelection];
  333. page = [selection safeFirstPage];
  334. // if the mouse was in the toolbar and there is a page below the toolbar, we get a point outside of the visible rect
  335. page = NSMouseInRect(center, [self visibleContentRect], [self isFlipped]) ? [self pageForPoint:center nearest:NO] : nil;
  336. if (page == nil) {
  337. // Get center of the PDFView.
  338. // NSRect viewFrame = [self frame];
  339. // center = [self KMCpdfCenterPoint:viewFrame];//KMCpdfCenterPoint(viewFrame);
  340. page = [self pageForPoint: center nearest: YES];
  341. if (page == nil) {
  342. // Get center of the current page
  343. page = [self currentPage];
  344. NSPoint point = [self KMCpdfCenterPoint:[page boundsForBox:[self displayBox]]];
  345. center = [self convertPoint:point fromPage:page];
  346. }
  347. }
  348. CGFloat defaultWidth = 360;
  349. CGFloat defaultHeight = 90;
  350. CGFloat scaleS = MIN(defaultWidth/image.size.width, defaultHeight/image.size.height);
  351. NSSize defaultSize = CGSizeMake(image.size.width * scaleS, image.size.height * scaleS);
  352. // Convert to "page space".
  353. // center = [self KMCpdfIntegralPoint:[self convertPoint:center toPage:page]];
  354. // bounds = [self KMCpdfRectFromCenterAndSize:center size:defaultSize];
  355. // Make sure it fits in the page
  356. // bounds = [self KMCpdfConstrainRect:bounds boundary:[page boundsForBox:[self displayBox]]];
  357. if (page != nil) {
  358. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  359. NSRect pageBounds = [page boundsForBox:CPDFDisplayMediaBox];
  360. // new note added by note tool mode, don't add actual zero sized notes
  361. if (isInitial)
  362. bounds = [self KMCRectFromCenterAndSquareSizeWith:bounds.origin size:8.0];
  363. if(!CGPointEqualToPoint(self.lastAddAnnotationPoint, CGPointZero)) {
  364. bounds.origin.x = self.lastAddAnnotationPoint.x + 3.0;
  365. bounds.origin.y = self.lastAddAnnotationPoint.y - 3.0;
  366. CGFloat pageWidth = pageBounds.size.width;
  367. if (bounds.origin.x + bounds.size.width >pageWidth) {
  368. bounds.origin.x = pageWidth - bounds.size.width;
  369. }
  370. if (bounds.origin.y - bounds.size.height < 0) {
  371. bounds.origin.y = bounds.size.height;
  372. }
  373. }
  374. self.lastAddAnnotationPoint = bounds.origin;
  375. CPDFStampAnnotation *newAnnotation = [[CPDFStampAnnotation alloc]initWithDocument:self.document image:image];
  376. newAnnotation.bounds = CGRectMake(center.x, center.y, defaultSize.width, defaultSize.height);
  377. [newAnnotation registerUserName];
  378. [self addAnnotation:newAnnotation toPage:page];
  379. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  380. [self.activeAnnotations removeAllObjects];
  381. [self.activeAnnotations addObject:newAnnotation];
  382. }
  383. else NSBeep();
  384. }
  385. - (NSRect)KMCRectFromCenterAndSquareSizeWith: (NSPoint)center size:(CGFloat)size{
  386. NSRect rect = NSZeroRect;
  387. rect.origin.x = center.x - 0.5 * size;
  388. rect.origin.y = center.y - 0.5 * size;
  389. rect.size.width = size;
  390. rect.size.height = size;
  391. return rect;
  392. }
  393. - (NSRect)KMCpdfRectFromCenterAndSize: (NSPoint)center size: (NSSize)size{
  394. NSRect rect = NSZeroRect;
  395. rect.origin.x = center.x - 0.5 * size.width;
  396. rect.origin.y = center.y - 0.5 * size.height;
  397. rect.size = size;
  398. return rect;
  399. }
  400. - (NSPoint)KMCpdfCenterPoint:(NSRect)rect{
  401. return NSMakePoint(NSMidX(rect), NSMidY(rect));
  402. }
  403. - (NSPoint)KMCpdfIntegralPoint:(NSPoint)point{
  404. return NSMakePoint(round(point.x), round(point.y));
  405. }
  406. - (NSRect)KMCpdfConstrainRect:(NSRect)rect boundary: (NSRect)boundary{
  407. NSRect newRect = rect;
  408. if (NSWidth(rect) > NSWidth(boundary)){
  409. newRect.size.width = NSWidth(boundary);
  410. }
  411. if (NSHeight(rect) > NSHeight(boundary)){
  412. newRect.size.height = NSHeight(boundary);
  413. }
  414. if (NSMinX(rect) < NSMinX(boundary)){
  415. newRect.origin.x = NSMinX(boundary);
  416. }else if (NSMaxX(rect) > NSMaxX(boundary)){
  417. newRect.origin.x = NSMaxX(boundary) - NSWidth(rect);
  418. }
  419. if (NSMinY(rect) < NSMinY(boundary)){
  420. newRect.origin.y = NSMinY(boundary);
  421. }else if (NSMaxY(rect) > NSMaxY(boundary)){
  422. newRect.origin.y = NSMaxY(boundary) - NSHeight(rect);
  423. }
  424. return newRect;
  425. }
  426. #pragma mark - Public
  427. - (CPDFAnnotation *)addAnnotationWithType:(CAnnotationType)annotationType selection:(CPDFSelection *)selection page:(CPDFPage *)page bounds:(NSRect)bounds {
  428. CPDFAnnotation *annotation = nil;
  429. NSString *text = [selection PDFListViewCleanedString];
  430. if([CPDFListView isMarkupAnnotationType:annotationType]) {
  431. if(selection){
  432. annotation = [self addPDFSelection:selection annotationTyoe:annotationType];
  433. [annotation setContents:text?:@""];
  434. } else NSBeep();
  435. } else {
  436. BOOL isInitial = NO;
  437. if(selection) {
  438. CGRect noteRect = selection.bounds;
  439. isInitial = NSEqualSizes(noteRect.size, NSZeroSize);
  440. } else {
  441. isInitial = NSEqualSizes(bounds.size, NSZeroSize);
  442. }
  443. CPDFAnnotationModel *annotationModel = [[CPDFAnnotationModel alloc]initWithAnnotationType:annotationType];
  444. CGSize size = CGSizeMake(annotationModel.noteWidth, annotationModel.noteHeight);
  445. if(annotationType == CAnnotationTypeAnchored)
  446. bounds = CGRectMake(bounds.origin.x, bounds.origin.y, size.width, size.height);
  447. if (annotationType == CAnnotationTypeCircle || annotationType == CAnnotationTypeSquare || annotationType == CAnnotationTypeLine || annotationType == CAnnotationTypeArrow || annotationType == CAnnotationTypeAnchored) {
  448. bounds = KMConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  449. }
  450. if (isInitial)
  451. bounds = annotationType == CAnnotationTypeAnchored ? CPDFListViewRectFromCenterAndSize(bounds.origin, size) : CPDFListViewRectFromCenterAndSquareSize(bounds.origin, MIN_NOTE_SIZE);
  452. switch (annotationType) {
  453. case CAnnotationTypeFreeText:
  454. annotation = [[CPDFFreeTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  455. annotation.bounds = bounds;
  456. break;
  457. case CAnnotationTypeAnchored:
  458. annotation = [[CPDFTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  459. annotation.bounds = bounds;
  460. break;
  461. case CAnnotationTypeCircle:
  462. annotation = [[CPDFCircleAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  463. annotation.bounds = bounds;
  464. break;
  465. case CAnnotationTypeSquare:
  466. annotation = [[CPDFSquareAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  467. annotation.bounds = bounds;
  468. break;
  469. case CAnnotationTypeLine:
  470. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeLine];
  471. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  472. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  473. [(CPDFLineAnnotation *)annotation setStartLineStyle:CPDFLineStyleNone];
  474. [(CPDFLineAnnotation *)annotation setEndLineStyle:CPDFLineStyleNone];
  475. break;
  476. case CAnnotationTypeArrow: {
  477. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeArrow];
  478. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  479. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  480. }
  481. break;
  482. case CAnnotationTypeLink:
  483. annotation = [[CPDFLinkAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  484. annotation.bounds = bounds;
  485. break;
  486. case CAnnotationTypeTextField:
  487. annotation = [[CPDFTextWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  488. annotation.bounds = bounds;
  489. break;
  490. case CAnnotationTypeCheckBox:
  491. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document controlType:CPDFWidgetCheckBoxControl];
  492. annotation.bounds = bounds;
  493. break;
  494. case CAnnotationTypeRadioButton:
  495. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document controlType:CPDFWidgetRadioButtonControl];
  496. annotation.bounds = bounds;
  497. break;
  498. case CAnnotationTypeListMenu:
  499. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document listChoice:YES];
  500. annotation.bounds = bounds;
  501. break;
  502. case CAnnotationTypeComboBox:
  503. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document listChoice:NO];
  504. annotation.bounds = bounds;
  505. break;
  506. case CAnnotationTypeSignature:
  507. annotation = [[CPDFSignatureWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  508. annotation.bounds = bounds;
  509. break;
  510. case CAnnotationTypeActionButton:
  511. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document controlType:CPDFWidgetPushButtonControl];
  512. annotation.bounds = bounds;
  513. break;
  514. case CAnnotationTypeSignFalse:
  515. case CAnnotationTypeSignTure:
  516. case CAnnotationTypeSignCircle:
  517. case CAnnotationTypeSignLine:
  518. case CAnnotationTypeSignDot:
  519. annotation = [[CSelfSignAnnotation alloc]initPDFListViewNoteWithDocument:self.document type:self.annotationType];
  520. annotation.bounds = bounds;
  521. [(CSelfSignAnnotation *)annotation updateAppearanceStream];
  522. break;
  523. case CAnnotationTypeSignText:
  524. case CAnnotationTypeSignConfig:
  525. case CAnnotationTypeSignDate:
  526. annotation = [[CSelfSignAnnotationFreeText alloc]initPDFListViewNoteWithDocument:self.document subType:self.annotationType string:@"" bounds:bounds];
  527. break;
  528. case CAnnotationTypeRedact:
  529. annotation = [self addRedactPDFSelection:selection];
  530. break;
  531. default:
  532. break;
  533. }
  534. }
  535. if (annotation) {
  536. if (annotationType != CAnnotationTypeLine && annotationType != CAnnotationTypeArrow && annotationType != CAnnotationTypeInk && [text length] > 0)
  537. [annotation setString:text];
  538. [self addAnnotation:annotation toPage:page];
  539. }
  540. return annotation;
  541. }
  542. - (void)drawAnnotation:(CPDFAnnotation *)annotation toContext:(CGContextRef)context {
  543. [super drawAnnotation:annotation toContext:context];
  544. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListView:needDrawAnnotation:)]) {
  545. if ([self.pdfListViewDelegate PDFListView:self needDrawAnnotation:annotation] == false) {
  546. return;
  547. }
  548. }
  549. if (CFormToolMode == _toolMode &&
  550. [annotation isKindOfClass:[CPDFWidgetAnnotation class]] && self.showFormFieldName && !annotation.isHidden) {
  551. CPDFWidgetAnnotation *annotationWidget = (CPDFWidgetAnnotation*)annotation;
  552. NSString *fieldName = annotationWidget.fieldName;
  553. if(self.showHopnumber) {
  554. NSInteger hopNumen = annotationWidget.widgetHopNumber;
  555. if(fieldName) {
  556. fieldName = [NSString stringWithFormat:@"%ld %@",hopNumen,fieldName];
  557. } else {
  558. fieldName = [NSString stringWithFormat:@"%ld",hopNumen];
  559. }
  560. }
  561. if (fieldName.length > 0) {
  562. CGContextSaveGState(context);
  563. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  564. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  565. paragraphStyle.alignment = NSTextAlignmentLeft;
  566. NSColor *backgroundColor = [NSColor blackColor];
  567. if ([self.activeAnnotations containsObject:annotation]) {
  568. backgroundColor = [NSColor colorWithRed:82.0/255.0 green:102.0/255.0 blue:204.0/255.0 alpha:1.0];
  569. }
  570. if([CPDFKitConfig sharedInstance].isShowFormRequiredFlagColor)
  571. backgroundColor = [CPDFKitConfig sharedInstance].formRequiredFlagColor?:[NSColor redColor];
  572. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  573. NSForegroundColorAttributeName : [NSColor whiteColor],
  574. NSBackgroundColorAttributeName : backgroundColor,
  575. NSParagraphStyleAttributeName : paragraphStyle};
  576. NSString* drawString = fieldName;
  577. drawString = [drawString getMaxStringWithBounds:annotationWidget.bounds attributes:attributes];
  578. CGSize size = [drawString sizeWithAttributes:attributes];
  579. CGRect drawRect = annotationWidget.bounds;
  580. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  581. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  582. drawRect.size.height = size.height;
  583. drawRect.size.width = size.width;
  584. [NSGraphicsContext saveGraphicsState];
  585. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
  586. [drawString drawInRect:drawRect withAttributes:attributes];
  587. [NSGraphicsContext restoreGraphicsState];
  588. CGContextRestoreGState(context);
  589. NSRect rect = [self integralRect:[annotationWidget bounds] onPage:[annotationWidget page]];
  590. CGFloat lineWidth = [self unitWidthOnPage:[annotationWidget page]];
  591. CGContextSaveGState(context);
  592. CGColorRef color = [NSColor blackColor].CGColor;
  593. CGContextSetStrokeColorWithColor(context, color);
  594. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  595. }
  596. } else if(CNoteToolMode== _toolMode && _annotationType == CAnnotationTypeLink && [annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  597. CGContextSaveGState(context);
  598. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  599. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  600. paragraphStyle.alignment = NSTextAlignmentLeft;
  601. NSColor *backgroundColor = [NSColor clearColor];
  602. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  603. NSForegroundColorAttributeName : [NSColor whiteColor],
  604. NSBackgroundColorAttributeName : backgroundColor,
  605. NSParagraphStyleAttributeName : paragraphStyle};
  606. NSString *drawString = NSLocalizedString(@"No Destination", nil);
  607. CPDFDestination *destination = [(CPDFLinkAnnotation *)annotation destination];
  608. if(destination) {
  609. CPDFPage *page = destination.page;
  610. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  611. if(destination.page) {
  612. NSUInteger index = [self.document indexForPage:page] + 1;
  613. drawString = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"to Page",nil),@(index)];
  614. } else if(url.length > 0) {
  615. drawString = url;
  616. }
  617. }
  618. drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
  619. CGSize size = [drawString sizeWithAttributes:attributes];
  620. CGRect drawRect = annotation.bounds;
  621. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  622. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  623. drawRect.size.height = size.height;
  624. drawRect.size.width = size.width;
  625. CGContextSaveGState(context);
  626. CGContextSetFillColorWithColor(context, [NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:0.5].CGColor);
  627. CGContextFillRect(context,annotation.bounds);
  628. CGContextRestoreGState(context);
  629. [NSGraphicsContext saveGraphicsState];
  630. CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
  631. float fontSize = 9;
  632. NSColor *textColor = [NSColor whiteColor];
  633. CTTextAlignment alignMent = kCTTextAlignmentCenter;
  634. CFStringRef stringRef = (__bridge CFStringRef)drawString;
  635. NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
  636. NSInteger _stringLength=[drawString length];
  637. CTTextAlignment theAlignment = alignMent;
  638. CTParagraphStyleSetting theSettings[1] =
  639. {
  640. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
  641. }
  642. };
  643. CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
  644. [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
  645. [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
  646. [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
  647. CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
  648. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  649. CGMutablePathRef framePath = CGPathCreateMutable();
  650. CGPathAddRect(framePath, NULL, frameRect);
  651. CFRange currentRange = CFRangeMake(0, 0);
  652. CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
  653. CGPathRelease(framePath);
  654. CTFrameDraw(frameRef, context);
  655. CFRelease(frameRef);
  656. CFRelease(framesetter);
  657. [NSGraphicsContext restoreGraphicsState];
  658. CGContextRestoreGState(context);
  659. }
  660. }
  661. - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
  662. if (CAnnotationTypeStamp == self.annotationType ||
  663. CAnnotationTypeSignSignature == self.annotationType) {
  664. self.stampObject = stampObject;
  665. self.isStampModel = isToolModel;
  666. [NSCursor clearStampCursor];
  667. }
  668. }
  669. - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
  670. NSRect bounds = NSZeroRect;
  671. CPDFSelection *selection = [self currentSelection];
  672. CGFloat defaultWidth = 360;
  673. CGFloat defaultHeight = 90;
  674. NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
  675. bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
  676. // Make sure it fits in the page
  677. bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
  678. // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  679. if (page != nil) {
  680. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  681. // new note added by note tool mode, don't add actual zero sized notes
  682. if (isInitial)
  683. bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
  684. CGFloat borderDefaultWidth = image.size.width;
  685. CGFloat borderScale = borderDefaultWidth/image.size.height;
  686. if (bounds.size.width/bounds.size.height > borderScale) {
  687. bounds.size.height = bounds.size.height;
  688. bounds.size.width = bounds.size.height*borderScale;
  689. } else {
  690. bounds.size.width = bounds.size.width;
  691. bounds.size.height = bounds.size.width/borderScale;
  692. }
  693. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  694. newAnnotation.bounds = bounds;
  695. [newAnnotation setBorderBoundsWithImage:image];
  696. [self addAnnotation:newAnnotation toPage:page];
  697. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  698. [self updateActiveAnnotations:@[newAnnotation]];
  699. [self setNeedsDisplayAnnotation:newAnnotation];
  700. }
  701. else NSBeep();
  702. }
  703. - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  704. [self refreshActiveAnnotations:activeAnnotations isRight:YES];
  705. }
  706. - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  707. [self refreshActiveAnnotations:activeAnnotations isRight:NO];
  708. }
  709. -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
  710. // for (CPDFAnnotation *annotation in self.activeAnnotations) {
  711. // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  712. // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
  713. // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
  714. // } else {
  715. // [self removeAnnotation:linkAnnotation];
  716. // }
  717. // }
  718. // }
  719. if(activeAnnotations) {
  720. NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
  721. BOOL isSame = NO;
  722. if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
  723. if(!isSame) {
  724. self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
  725. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  726. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  727. dispatch_async(dispatch_get_main_queue(), ^{
  728. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  729. });
  730. }
  731. } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
  732. [self.activeAnnotations removeAllObjects];
  733. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  734. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  735. dispatch_async(dispatch_get_main_queue(), ^{
  736. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  737. });
  738. }
  739. }
  740. - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  741. BOOL isContains = YES;
  742. for (CPDFAnnotation *annotation in activeAnnotations) {
  743. if(![self.activeAnnotations containsObject:annotation]) {
  744. [self.activeAnnotations addObject:annotation];
  745. isContains = NO;
  746. }
  747. }
  748. if(!isContains) {
  749. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  750. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  751. dispatch_async(dispatch_get_main_queue(), ^{
  752. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  753. });
  754. }
  755. }
  756. - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
  757. BOOL isContains = NO;
  758. NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
  759. [tarr removeObjectsInArray:removeAnnotations];
  760. self.activeAnnotations = tarr;
  761. isContains = YES;
  762. if(isContains) {
  763. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  764. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  765. dispatch_async(dispatch_get_main_queue(), ^{
  766. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  767. });
  768. }
  769. }
  770. - (void)editAnnotation:(CPDFAnnotation *)annotation {
  771. if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  772. [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
  773. [[self window] makeFirstResponder:self];
  774. [self setNeedsDisplayAnnotation:annotation];
  775. } else {
  776. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
  777. [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
  778. } else {
  779. [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
  780. if (!self.popOver) {
  781. _popOver = [[NSPopover alloc] init];
  782. }
  783. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  784. __block typeof(self) blockSelf = self;
  785. _popOver.delegate = self;
  786. CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
  787. vc.pdflistView = self;
  788. _popOver.contentViewController = vc;
  789. vc.closeCallBack = ^{
  790. [blockSelf.popOver close];
  791. };
  792. NSBox *box = (NSBox *)vc.view;
  793. NSView *popoverView = [[[self.popOver contentViewController] view] superview];
  794. [popoverView setWantsLayer:YES];
  795. vc.changeColorCallBack = ^{
  796. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  797. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  798. [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
  799. };
  800. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  801. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  802. _popOver.animates = YES;
  803. _popOver.behavior = NSPopoverBehaviorTransient;
  804. [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
  805. } else if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]){
  806. CPDFListAnnotationNoteWindowController *wc = [CPDFListAnnotationNoteWindowController sharedInstance];
  807. CGRect rect = wc.window.frame;
  808. CGRect anBounds = [self convertRect:annotation.bounds fromPage:annotation.page];
  809. anBounds = [self convertRectToScreen:anBounds];
  810. rect.origin.x = anBounds.origin.x;
  811. rect.origin.y = anBounds.origin.y;
  812. if (@available(macOS 10.13, *))
  813. [wc.window makeKeyAndOrderFront:nil];
  814. else
  815. [wc showWindow:nil];
  816. [wc updateAnnotation:annotation];
  817. [wc.window setFrame:rect display:YES animate:NO];
  818. wc.window.title = @"";
  819. }
  820. }
  821. }
  822. }
  823. - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
  824. if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
  825. CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
  826. NSInteger rotation = stampAnnotation.rotation;
  827. rotation = rotation - angle;
  828. if (rotation < 0) {
  829. rotation += 360;
  830. } else if (rotation >= 360) {
  831. rotation-=360;
  832. }
  833. [annotation setRotation:rotation];
  834. rotation = [annotation appearanceStreamRotation];
  835. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  836. [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
  837. }
  838. }
  839. - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
  840. if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
  841. CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
  842. NSInteger rotation = signatureAnnotation.rotation;
  843. rotation = rotation - angle;
  844. if (rotation < 0) {
  845. rotation += 360;
  846. } else if (rotation >= 360) {
  847. rotation-=360;
  848. }
  849. [signatureAnnotation setRotation:rotation];
  850. rotation = [signatureAnnotation appearanceStreamRotation];
  851. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  852. [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
  853. }
  854. }
  855. - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  856. [self addAnnotation:annotation toPage:page];
  857. }
  858. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  859. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  860. [annotation setModificationDate:[NSDate date]];
  861. //widget设置作者与fieldName冲突
  862. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
  863. [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
  864. }
  865. [page addAnnotation:annotation];
  866. [self setNeedsDisplayAnnotation:annotation];
  867. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  868. dispatch_async(dispatch_get_main_queue(), ^{
  869. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
  870. });
  871. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
  872. [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
  873. }
  874. - (void)removeAnnotation:(CPDFAnnotation *)annotation {
  875. if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
  876. // if (annotation.contents.length <= 0) {
  877. CPDFAnnotation *wasAnnotation = annotation;
  878. CPDFPage *page = wasAnnotation.page;
  879. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  880. [page removeAnnotation:wasAnnotation];
  881. [self annotationsChangedOnPage:page];
  882. [self setNeedsDisplayAnnotation:wasAnnotation];
  883. dispatch_async(dispatch_get_main_queue(), ^{
  884. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  885. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  886. });
  887. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  888. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  889. // }
  890. } else {
  891. CPDFAnnotation *wasAnnotation = annotation;
  892. CPDFPage *page = wasAnnotation.page;
  893. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  894. [page removeAnnotation:wasAnnotation];
  895. [self annotationsChangedOnPage:page];
  896. [self setNeedsDisplayAnnotation:wasAnnotation];
  897. dispatch_async(dispatch_get_main_queue(), ^{
  898. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  899. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  900. });
  901. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  902. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  903. }
  904. }
  905. - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
  906. [super drawPage:pdfPage toContext:context];
  907. [self drawSelectionForPage:pdfPage inContext:context];
  908. BOOL isIncludText = NO;
  909. NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
  910. NSMutableArray *currentPageAnnotations = [NSMutableArray array];
  911. for (CPDFAnnotation *an in self.activeAnnotations) {
  912. if([an.page isEqual:pdfPage]) {
  913. if([an isKindOfClass:[CPDFFreeTextAnnotation class]])
  914. isIncludText = YES;
  915. //多选注释框去除mark注释与便签注释
  916. if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
  917. [currentActiveAnnotations addObject:an];
  918. }
  919. [currentPageAnnotations addObject:an];
  920. }
  921. }
  922. if(currentActiveAnnotations.count > 1) {
  923. NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
  924. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  925. CGContextSaveGState(context);
  926. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  927. CGContextSetStrokeColorWithColor(context, color);
  928. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  929. CGContextRestoreGState(context);
  930. CGContextSaveGState(context);
  931. if(isIncludText) {
  932. [CPDFListView DrawFreeTextResizeHandle:context rect:rect radius: 4.0 * lineWidth active:true];
  933. } else {
  934. [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
  935. }
  936. CGContextRestoreGState(context);
  937. }
  938. if(self.multiplAnnotationObject &&
  939. !CGRectIsEmpty(self.multiplAnnotationObject.drawRect) &&
  940. self.multiplAnnotationObject.page == pdfPage) {
  941. CGRect selectAnnotationBounds = self.multiplAnnotationObject.drawRect;
  942. NSRect rect = selectAnnotationBounds;
  943. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  944. CGContextSaveGState(context);
  945. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  946. CGContextSetStrokeColorWithColor(context, color);
  947. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  948. CGContextRestoreGState(context);
  949. }
  950. [currentPageAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  951. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  952. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  953. }
  954. }];
  955. [self.selectAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  956. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  957. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  958. }
  959. }];
  960. if (self.hoverAnnotation.page && [self.hoverAnnotation.page isEqual:pdfPage] && ![self.activeAnnotations containsObject:self.hoverAnnotation]) {
  961. [self.hoverAnnotation drawSelectionHighlightForView:self inContext:context isHover:YES];
  962. }
  963. if(!CGRectEqualToRect(self.multiplSelectBounds, CGRectZero) && [self.multiplSelectPage isEqual:pdfPage]) {
  964. @synchronized (self) {
  965. CGContextSetLineCap(context, kCGLineCapRound);
  966. CGContextSetLineWidth(context, 1.0);
  967. CGContextSetStrokeColorWithColor(context, [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor);
  968. CGContextBeginPath(context);
  969. CGContextMoveToPoint(context, self.multiplSelectBounds.origin.x, self.multiplSelectBounds.origin.y);
  970. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x+ self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y);
  971. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x + self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  972. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  973. CGContextClosePath(context);
  974. CGFloat lengths[] = {5,5};
  975. CGContextSetLineDash(context, 0, lengths,2);
  976. CGContextStrokePath(context);
  977. }
  978. }
  979. }
  980. - (void)drawSelectionForPage:(CPDFPage *)pdfPage inContext:(CGContextRef)context {
  981. NSRect rect;
  982. NSUInteger pageIndex;
  983. @synchronized (self) {
  984. pageIndex = self.selectionPageIndex;
  985. rect = self.selectionRect;
  986. }
  987. if (pageIndex != NSNotFound) {
  988. BOOL isWidget = NO;
  989. for (CPDFAnnotation * annotation in self.activeAnnotations) {
  990. if ([annotation isForm]) {
  991. isWidget = YES;
  992. break;
  993. }
  994. }
  995. if (isWidget &&
  996. _toolMode != CFormToolMode) {
  997. return;
  998. }
  999. NSRect bounds = [pdfPage boundsForBox:[self displayBox]];
  1000. CGFloat radius = HANDLE_SIZE * [self unitWidthOnPage:pdfPage];
  1001. CGColorRef color = CGColorCreateGenericGray(0.0, 0.6);
  1002. CGContextSetFillColorWithColor(context, color);
  1003. CGColorRelease(color);
  1004. CGContextBeginPath(context);
  1005. CGContextAddRect(context, NSRectToCGRect(bounds));
  1006. CGContextAddRect(context, NSRectToCGRect(rect));
  1007. CGContextEOFillPath(context);
  1008. if ([pdfPage pageIndex] != pageIndex) {
  1009. color = CGColorCreateGenericGray(0.0, 0.3);
  1010. CGContextSetFillColorWithColor(context, color);
  1011. CGColorRelease(color);
  1012. CGContextFillRect(context, NSRectToCGRect(rect));
  1013. }
  1014. [CPDFListView DrawResizeHandles:context rect:rect radius:radius active:true];
  1015. }
  1016. }
  1017. - (void)removeShapeLayer {
  1018. if (![self.shapeLayerTopH isEqual:nil] && ![self.shapeLayerBottomH isEqual:nil] && ![self.shapeLayerLeftV isEqual:nil] && ![self.shapeLayerRightV isEqual:nil]) {
  1019. [self.shapeLayerTopH removeFromSuperlayer];
  1020. [self.shapeLayerBottomH removeFromSuperlayer];
  1021. [self.shapeLayerLeftV removeFromSuperlayer];
  1022. [self.shapeLayerRightV removeFromSuperlayer];
  1023. self.shapeLayerTopH = nil;
  1024. self.shapeLayerBottomH = nil;
  1025. self.shapeLayerLeftV = nil;
  1026. self.shapeLayerRightV = nil;
  1027. }
  1028. }
  1029. - (BOOL)consistentTypeWithAnnotation:(CPDFAnnotation *)annotation {
  1030. if (self.annotationType == CAnnotationTypeSignSignature) {
  1031. if (![annotation isKindOfClass:[CPDFSignatureAnnotation class]])
  1032. return NO;
  1033. } else if (self.annotationType == CAnnotationTypeStamp) {
  1034. if (![annotation isKindOfClass:[CPDFStampAnnotation class]])
  1035. return NO;
  1036. } else if (self.annotationType == CAnnotationTypeAnchored) {
  1037. if (![annotation isKindOfClass:[CPDFTextAnnotation class]])
  1038. return NO;
  1039. } else if (self.annotationType == CAnnotationTypeLink) {
  1040. if (![annotation isKindOfClass:[CPDFLinkAnnotation class]])
  1041. return NO;
  1042. } else if (self.annotationType == CAnnotationTypeFreeText) {
  1043. if (![annotation isKindOfClass:[CPDFFreeTextAnnotation class]])
  1044. return NO;
  1045. } else if (self.annotationType == CAnnotationTypeLine || self.annotationType == CAnnotationTypeArrow || self.annotationType == CAnnotationTypeSquare || self.annotationType == CAnnotationTypeCircle) {
  1046. if (![annotation isKindOfClass:[CPDFLineAnnotation class]] && ![annotation isKindOfClass:[CPDFSquareAnnotation class]] && ![annotation isKindOfClass:[CPDFCircleAnnotation class]])
  1047. return NO;
  1048. } else if (self.annotationType == CAnnotationTypeHighlight || self.annotationType == CAnnotationTypeUnderline || self.annotationType == CAnnotationTypeStrikeOut) {
  1049. if (![annotation isKindOfClass:[CPDFMarkupAnnotation class]])
  1050. return NO;
  1051. } else if (self.annotationType == CAnnotationTypeInk) {
  1052. if (![annotation isKindOfClass:[CPDFInkAnnotation class]])
  1053. return NO;
  1054. } else if (self.annotationType == CAnnotationTypeRadioButton) {
  1055. } else if (self.annotationType == CAnnotationTypeCheckBox) {
  1056. } else if (self.annotationType == CAnnotationTypeTextField) {
  1057. } else if (self.annotationType == CAnnotationTypeComboBox) {
  1058. } else if (self.annotationType == CAnnotationTypeListMenu) {
  1059. } else if (self.annotationType == CAnnotationTypeActionButton) {
  1060. } else if (self.annotationType == CAnnotationTypeSignature) {
  1061. } else if (self.annotationType == CAnnotationTypeSignText) {
  1062. } else if (self.annotationType == CAnnotationTypeSignFalse) {
  1063. } else if (self.annotationType == CAnnotationTypeSignTure) {
  1064. } else if (self.annotationType == CAnnotationTypeSignCircle) {
  1065. } else if (self.annotationType == CAnnotationTypeSignLine) {
  1066. } else if (self.annotationType == CAnnotationTypeSignDot) {
  1067. } else if (self.annotationType == CAnnotationTypeSignConfig) {
  1068. } else if (self.annotationType == CAnnotationTypeSignDate) {
  1069. }
  1070. return YES;
  1071. }
  1072. #pragma mark Zooming
  1073. - (void)zoomToRect:(NSRect)rect onPage:(CPDFPage *)page {
  1074. if (NSIsEmptyRect(rect) == NO) {
  1075. BOOL isLegacy = [NSScroller respondsToSelector:@selector(preferredScrollerStyle)] == NO || [NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy;
  1076. NSRect bounds = [self bounds];
  1077. CGFloat scale = 1.0;
  1078. if (isLegacy) {
  1079. bounds.size.width -= [NSScroller scrollerWidth];
  1080. bounds.size.height -= [NSScroller scrollerWidth];
  1081. }
  1082. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1083. scale = NSHeight(bounds) / NSHeight(rect);
  1084. else
  1085. scale = NSWidth(bounds) / NSWidth(rect);
  1086. [self setScaleFactor:scale];
  1087. NSScrollView *scrollView = [self scrollView];
  1088. if (isLegacy && ([scrollView hasHorizontalScroller] == NO || [scrollView hasVerticalScroller] == NO)) {
  1089. if ([scrollView hasVerticalScroller])
  1090. bounds.size.width -= [NSScroller scrollerWidth];
  1091. if ([scrollView hasHorizontalScroller])
  1092. bounds.size.height -= [NSScroller scrollerWidth];
  1093. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1094. scale = NSHeight(bounds) / NSHeight(rect);
  1095. else
  1096. scale = NSWidth(bounds) / NSWidth(rect);
  1097. [self setScaleFactor:scale];
  1098. }
  1099. [self goToRect:rect onPage:page];
  1100. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1101. CGPoint tPagePoint = CGPointMake(rect.origin.x, rect.origin.y+rect.size.height);
  1102. [self goToTargetPoint:tPagePoint onPage:page atScrollPosition:CScrollPositionTop];
  1103. });
  1104. }
  1105. }
  1106. #pragma mark - NSPopoverDelegate
  1107. - (void)popoverWillClose:(NSNotification *)notification {
  1108. NSPopover *popover = notification.object;
  1109. if([popover.contentViewController isKindOfClass:[CPDFListEditAnnotationViewController class]]) {
  1110. CPDFListEditAnnotationViewController *listEditAnnotationViewController = (CPDFListEditAnnotationViewController *)popover.contentViewController;
  1111. CPDFAnnotation *annotation = listEditAnnotationViewController.annotation;
  1112. NSString *contensString = listEditAnnotationViewController.contentString;
  1113. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  1114. if(contensString && contensString.length > 0) {
  1115. annotation.contents = listEditAnnotationViewController.contentString;
  1116. [self setNeedsDisplayAnnotation:annotation];
  1117. } else {
  1118. if([self.activeAnnotations containsObject:annotation]) {
  1119. [self.activeAnnotations removeObject:annotation];
  1120. }
  1121. [self removeAnnotation:annotation];
  1122. }
  1123. } else {
  1124. annotation.contents = listEditAnnotationViewController.contentString;
  1125. [self setNeedsDisplayAnnotation:annotation];
  1126. }
  1127. }
  1128. self.popOver = nil;
  1129. }
  1130. - (void)handlePageChangedNotification:(NSNotification *)notification {
  1131. self.copyCount = 0;
  1132. }
  1133. #pragma mark - Form Alignment
  1134. - (KMPDFViewActiveFormsType)formAnnotionsType:(NSArray *)annotationArray {
  1135. NSSet *set = [NSSet setWithArray:[annotationArray valueForKey:@"type"]];
  1136. NSArray *array = [set allObjects];
  1137. if (array.count > 1 || ![array.firstObject isEqualToString:@"Widget"]) {
  1138. return KMPDFViewActiveFormsType_NotAllform;
  1139. }
  1140. PDFAnnotation *referenceAnnotation = annotationArray.firstObject;
  1141. Class referenceAnnotationClass = [referenceAnnotation class];
  1142. if ([referenceAnnotationClass isEqual:[CPDFButtonWidgetAnnotation class]]) {
  1143. referenceAnnotationClass = [CPDFButtonWidgetAnnotation superclass];
  1144. }
  1145. if ([referenceAnnotationClass isEqual:[CPDFTextWidgetAnnotation class]]) {
  1146. referenceAnnotationClass = [CPDFTextWidgetAnnotation superclass];
  1147. }
  1148. if ([referenceAnnotationClass isEqual:[CPDFChoiceWidgetAnnotation class]]) {
  1149. referenceAnnotationClass = [CPDFChoiceWidgetAnnotation superclass];
  1150. }
  1151. if (annotationArray.count == 1) {
  1152. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]) {
  1153. return KMPDFViewActiveFormsType_TextSingle;
  1154. } else {
  1155. return KMPDFViewActiveFormsType_PureSingle;
  1156. }
  1157. }
  1158. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1159. PDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1160. if (![annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFTextWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  1161. return KMPDFViewActiveFormsType_Mix;
  1162. }
  1163. }
  1164. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]){
  1165. return KMPDFViewActiveFormsType_Text;
  1166. }
  1167. return KMPDFViewActiveFormsType_Pure;
  1168. }
  1169. - (void)formsAnnotationAlign:(KMPDFActiveFormsAlignType)type {
  1170. CGRect zeroRect = CGRectNull;
  1171. CGRect highestRect = CGRectZero;
  1172. CGRect widthestRect = CGRectZero;
  1173. CPDFAnnotation *firstAnnotation = self.activeAnnotations.firstObject;
  1174. CGRect leftestRect = firstAnnotation.bounds;
  1175. CGRect rightestRect = firstAnnotation.bounds;
  1176. CGRect topestRect = firstAnnotation.bounds;
  1177. CGRect bottomestRect = firstAnnotation.bounds;
  1178. CPDFAnnotation *leftestAnnotation = firstAnnotation;
  1179. CPDFAnnotation *rightestAnnotation = firstAnnotation;
  1180. CPDFAnnotation *topestAnnotation = firstAnnotation;
  1181. CPDFAnnotation *bottomestAnnotation = firstAnnotation;
  1182. CGFloat totalWidth = 0.;
  1183. CGFloat totalHeight = 0.;
  1184. for (CPDFAnnotation *annotation in self.activeAnnotations) {
  1185. zeroRect = CGRectUnion(zeroRect, annotation.bounds);
  1186. totalWidth += CGRectGetWidth(annotation.bounds);
  1187. totalHeight += CGRectGetHeight(annotation.bounds);
  1188. if (CGRectGetHeight(annotation.bounds) > CGRectGetHeight(highestRect)) {
  1189. highestRect = annotation.bounds;
  1190. }
  1191. if (CGRectGetWidth(annotation.bounds) > CGRectGetWidth(widthestRect)) {
  1192. widthestRect = annotation.bounds;
  1193. }
  1194. if (CGRectGetMinX(leftestRect) > CGRectGetMinX(annotation.bounds)) {
  1195. leftestRect = annotation.bounds;
  1196. leftestAnnotation = annotation;
  1197. }
  1198. if (CGRectGetMaxX(annotation.bounds) > CGRectGetMaxX(rightestRect)) {
  1199. rightestRect = annotation.bounds;
  1200. rightestAnnotation = annotation;
  1201. }
  1202. if (CGRectGetMaxY(annotation.bounds) > CGRectGetMaxY(topestRect)) {
  1203. topestRect = annotation.bounds;
  1204. topestAnnotation = annotation;
  1205. }
  1206. if (CGRectGetMinY(bottomestRect) > CGRectGetMinY(annotation.bounds)) {
  1207. bottomestRect = annotation.bounds;
  1208. bottomestAnnotation = annotation;
  1209. }
  1210. }
  1211. if (type == KMPDFActiveFormsAlignType_Left ) {
  1212. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1213. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1214. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1215. CGRect bounds = annotation.bounds;
  1216. bounds.origin.x = zeroRect.origin.x;
  1217. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1218. }
  1219. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1220. } else if (type == KMPDFActiveFormsAlignType_Right) {
  1221. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1222. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1223. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1224. CGRect bounds = annotation.bounds;
  1225. bounds.origin.x = CGRectGetMaxX(zeroRect) - bounds.size.width;
  1226. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1227. }
  1228. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1229. } else if (type == KMPDFActiveFormsAlignType_Top) {
  1230. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1231. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1232. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1233. CGRect bounds = annotation.bounds;
  1234. bounds.origin.y = CGRectGetMaxY(zeroRect) - bounds.size.height;
  1235. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1236. }
  1237. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1238. } else if (type == KMPDFActiveFormsAlignType_Bottom) {
  1239. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1240. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1241. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1242. CGRect bounds = annotation.bounds;
  1243. bounds.origin.y = CGRectGetMinY(zeroRect);
  1244. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1245. }
  1246. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1247. } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
  1248. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1249. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1250. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1251. CGRect bounds = annotation.bounds;
  1252. bounds.origin.y = CGRectGetMidY(highestRect) - CGRectGetHeight(bounds)/2;
  1253. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1254. }
  1255. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1256. } else if (type == KMPDFActiveFormsAlignType_Vertical) {
  1257. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1258. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1259. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1260. CGRect bounds = annotation.bounds;
  1261. bounds.origin.x = CGRectGetMidX(widthestRect) - CGRectGetWidth(bounds)/2;
  1262. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1263. }
  1264. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1265. } else if (type == KMPDFActiveFormsAlignType_DisHorizontally) {
  1266. CGFloat middleGap = CGRectGetWidth(zeroRect) - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1267. CGFloat otherAnnotationsTotalWidth = totalWidth - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1268. CGFloat gap = (middleGap - otherAnnotationsTotalWidth)/(self.activeAnnotations.count - 1);
  1269. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1270. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1271. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1272. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1273. if (annotation1.bounds.origin.x < annotation2.bounds.origin.x) {
  1274. return NSOrderedAscending;
  1275. } else {
  1276. return NSOrderedDescending;
  1277. }
  1278. }];
  1279. [annotationsCopyArray removeObject:leftestAnnotation];
  1280. [annotationsCopyArray removeObject:rightestAnnotation];
  1281. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1282. CGFloat leftStartX = CGRectGetMaxX(leftestRect) + gap;
  1283. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1284. CPDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1285. CGRect bounds = annotation.bounds;
  1286. bounds.origin.x = leftStartX;
  1287. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1288. leftStartX += CGRectGetWidth(bounds) + gap;
  1289. }
  1290. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1291. } else if (type == KMPDFActiveFormsAlignType_DisVertical) {
  1292. CGFloat middleGap = CGRectGetHeight(zeroRect) - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1293. CGFloat otherAnnotationsTotalHeight = totalHeight - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1294. CGFloat gap = (middleGap - otherAnnotationsTotalHeight)/(self.activeAnnotations.count - 1);
  1295. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1296. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1297. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1298. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1299. if (annotation1.bounds.origin.y < annotation2.bounds.origin.y) {
  1300. return NSOrderedAscending;
  1301. } else {
  1302. return NSOrderedDescending;
  1303. }
  1304. }];
  1305. [annotationsCopyArray removeObject:topestAnnotation];
  1306. [annotationsCopyArray removeObject:bottomestAnnotation];
  1307. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1308. CGFloat bottomStartY = CGRectGetMaxY(bottomestRect) + gap;
  1309. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1310. PDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1311. CGRect bounds = annotation.bounds;
  1312. bounds.origin.y = bottomStartY;
  1313. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1314. bottomStartY += CGRectGetHeight(bounds) + gap;
  1315. }
  1316. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1317. }
  1318. }
  1319. - (void)changeAnnotationsAlign:(NSArray *)annotationArray newBounds:(NSArray *)newBoundsArray {
  1320. NSMutableArray * oldBoundsArray = [NSMutableArray array];
  1321. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1322. CPDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1323. [oldBoundsArray addObject:NSStringFromRect(annotation.bounds)];
  1324. annotation.bounds = NSRectFromString([newBoundsArray objectAtIndex:i]);
  1325. }
  1326. [[[self undoManager] prepareWithInvocationTarget:self] changeAnnotationsAlign:annotationArray newBounds:oldBoundsArray];
  1327. [self setNeedsDisplay:YES];
  1328. }
  1329. @end