CPDFListView.m 74 KB

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