CPDFListView.m 78 KB

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