CPDFListView.m 72 KB

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