CPDFListView.m 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  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. }
  659. drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
  660. CGSize size = [drawString sizeWithAttributes:attributes];
  661. CGRect drawRect = annotation.bounds;
  662. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  663. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  664. drawRect.size.height = size.height;
  665. drawRect.size.width = size.width;
  666. CGContextSaveGState(context);
  667. CGContextSetFillColorWithColor(context, [NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:0.5].CGColor);
  668. CGContextFillRect(context,annotation.bounds);
  669. CGContextRestoreGState(context);
  670. [NSGraphicsContext saveGraphicsState];
  671. CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
  672. float fontSize = 9;
  673. NSColor *textColor = [NSColor whiteColor];
  674. CTTextAlignment alignMent = kCTTextAlignmentCenter;
  675. CFStringRef stringRef = (__bridge CFStringRef)drawString;
  676. NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
  677. NSInteger _stringLength=[drawString length];
  678. CTTextAlignment theAlignment = alignMent;
  679. CTParagraphStyleSetting theSettings[1] =
  680. {
  681. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
  682. }
  683. };
  684. CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
  685. [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
  686. [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
  687. [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
  688. CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
  689. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  690. CGMutablePathRef framePath = CGPathCreateMutable();
  691. CGPathAddRect(framePath, NULL, frameRect);
  692. CFRange currentRange = CFRangeMake(0, 0);
  693. CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
  694. CGPathRelease(framePath);
  695. CTFrameDraw(frameRef, context);
  696. CFRelease(frameRef);
  697. CFRelease(framesetter);
  698. [NSGraphicsContext restoreGraphicsState];
  699. CGContextRestoreGState(context);
  700. }
  701. }
  702. - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
  703. if (CAnnotationTypeStamp == self.annotationType ||
  704. CAnnotationTypeSignSignature == self.annotationType) {
  705. self.stampObject = stampObject;
  706. self.isStampModel = isToolModel;
  707. [NSCursor clearStampCursor];
  708. }
  709. }
  710. - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
  711. NSRect bounds = NSZeroRect;
  712. CPDFSelection *selection = [self currentSelection];
  713. CGFloat defaultWidth = 360;
  714. CGFloat defaultHeight = 90;
  715. NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
  716. bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
  717. // Make sure it fits in the page
  718. bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
  719. // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  720. if (page != nil) {
  721. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  722. // new note added by note tool mode, don't add actual zero sized notes
  723. if (isInitial)
  724. bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
  725. CGFloat borderDefaultWidth = image.size.width;
  726. CGFloat borderScale = borderDefaultWidth/image.size.height;
  727. if (bounds.size.width/bounds.size.height > borderScale) {
  728. bounds.size.height = bounds.size.height;
  729. bounds.size.width = bounds.size.height*borderScale;
  730. } else {
  731. bounds.size.width = bounds.size.width;
  732. bounds.size.height = bounds.size.width/borderScale;
  733. }
  734. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  735. newAnnotation.bounds = bounds;
  736. [newAnnotation setBorderBoundsWithImage:image];
  737. [self addAnnotation:newAnnotation toPage:page];
  738. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  739. [self updateActiveAnnotations:@[newAnnotation]];
  740. [self setNeedsDisplayAnnotation:newAnnotation];
  741. }
  742. else NSBeep();
  743. }
  744. - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  745. [self refreshActiveAnnotations:activeAnnotations isRight:YES];
  746. }
  747. - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  748. [self refreshActiveAnnotations:activeAnnotations isRight:NO];
  749. }
  750. -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
  751. // for (CPDFAnnotation *annotation in self.activeAnnotations) {
  752. // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  753. // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
  754. // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
  755. // } else {
  756. // [self removeAnnotation:linkAnnotation];
  757. // }
  758. // }
  759. // }
  760. if(activeAnnotations) {
  761. NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
  762. BOOL isSame = NO;
  763. if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
  764. if(!isSame) {
  765. self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
  766. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  767. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  768. dispatch_async(dispatch_get_main_queue(), ^{
  769. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  770. });
  771. }
  772. } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
  773. [self.activeAnnotations removeAllObjects];
  774. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  775. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  776. dispatch_async(dispatch_get_main_queue(), ^{
  777. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  778. });
  779. }
  780. }
  781. - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  782. BOOL isContains = YES;
  783. for (CPDFAnnotation *annotation in activeAnnotations) {
  784. if(![self.activeAnnotations containsObject:annotation]) {
  785. [self.activeAnnotations addObject:annotation];
  786. isContains = NO;
  787. }
  788. }
  789. if(!isContains) {
  790. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  791. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  792. dispatch_async(dispatch_get_main_queue(), ^{
  793. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  794. });
  795. }
  796. }
  797. - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
  798. BOOL isContains = NO;
  799. NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
  800. [tarr removeObjectsInArray:removeAnnotations];
  801. self.activeAnnotations = tarr;
  802. isContains = YES;
  803. if(isContains) {
  804. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  805. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  806. dispatch_async(dispatch_get_main_queue(), ^{
  807. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  808. });
  809. }
  810. }
  811. - (void)editAnnotation:(CPDFAnnotation *)annotation {
  812. if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  813. [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
  814. [[self window] makeFirstResponder:self];
  815. [self setNeedsDisplayAnnotation:annotation];
  816. } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] || [annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  817. [self editFormAnnotation:self.activeAnnotation];
  818. } else {
  819. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
  820. [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
  821. } else {
  822. [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
  823. if (!self.popOver) {
  824. _popOver = [[NSPopover alloc] init];
  825. }
  826. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  827. __block typeof(self) blockSelf = self;
  828. _popOver.delegate = self;
  829. CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
  830. vc.pdflistView = self;
  831. _popOver.contentViewController = vc;
  832. vc.closeCallBack = ^{
  833. [blockSelf.popOver close];
  834. };
  835. NSBox *box = (NSBox *)vc.view;
  836. NSView *popoverView = [[[self.popOver contentViewController] view] superview];
  837. [popoverView setWantsLayer:YES];
  838. vc.changeColorCallBack = ^{
  839. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  840. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  841. [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
  842. };
  843. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  844. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  845. _popOver.animates = YES;
  846. _popOver.behavior = NSPopoverBehaviorTransient;
  847. [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
  848. } else if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]){
  849. CPDFListAnnotationNoteWindowController *wc = [CPDFListAnnotationNoteWindowController sharedInstance];
  850. CGRect rect = wc.window.frame;
  851. CGRect anBounds = [self convertRect:annotation.bounds fromPage:annotation.page];
  852. anBounds = [self convertRectToScreen:anBounds];
  853. rect.origin.x = anBounds.origin.x;
  854. rect.origin.y = anBounds.origin.y;
  855. if (@available(macOS 10.13, *))
  856. [wc.window makeKeyAndOrderFront:nil];
  857. else
  858. [wc showWindow:nil];
  859. [wc updateAnnotation:annotation];
  860. [wc.window setFrame:rect display:YES animate:NO];
  861. wc.window.title = @"";
  862. }
  863. }
  864. }
  865. }
  866. - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
  867. if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
  868. CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
  869. NSInteger rotation = stampAnnotation.rotation;
  870. rotation = rotation - angle;
  871. if (rotation < 0) {
  872. rotation += 360;
  873. } else if (rotation >= 360) {
  874. rotation-=360;
  875. }
  876. [annotation setRotation:rotation];
  877. rotation = [annotation appearanceStreamRotation];
  878. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  879. [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
  880. }
  881. }
  882. - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
  883. if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
  884. CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
  885. NSInteger rotation = signatureAnnotation.rotation;
  886. rotation = rotation - angle;
  887. if (rotation < 0) {
  888. rotation += 360;
  889. } else if (rotation >= 360) {
  890. rotation-=360;
  891. }
  892. [signatureAnnotation setRotation:rotation];
  893. rotation = [signatureAnnotation appearanceStreamRotation];
  894. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  895. [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
  896. }
  897. }
  898. - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  899. [self addAnnotation:annotation toPage:page];
  900. }
  901. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  902. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  903. [annotation setModificationDate:[NSDate date]];
  904. //widget设置作者与fieldName冲突
  905. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
  906. [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
  907. }
  908. [page addAnnotation:annotation];
  909. [self setNeedsDisplayAnnotation:annotation];
  910. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  911. dispatch_async(dispatch_get_main_queue(), ^{
  912. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
  913. });
  914. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
  915. [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
  916. }
  917. - (void)removeAnnotation:(CPDFAnnotation *)annotation {
  918. if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
  919. // if (annotation.contents.length <= 0) {
  920. CPDFAnnotation *wasAnnotation = annotation;
  921. CPDFPage *page = wasAnnotation.page;
  922. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  923. [page removeAnnotation:wasAnnotation];
  924. [self annotationsChangedOnPage:page];
  925. [self setNeedsDisplayAnnotation:wasAnnotation];
  926. dispatch_async(dispatch_get_main_queue(), ^{
  927. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  928. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  929. });
  930. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  931. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  932. // }
  933. } else {
  934. CPDFAnnotation *wasAnnotation = annotation;
  935. CPDFPage *page = wasAnnotation.page;
  936. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  937. [page removeAnnotation:wasAnnotation];
  938. [self annotationsChangedOnPage:page];
  939. [self setNeedsDisplayAnnotation:wasAnnotation];
  940. dispatch_async(dispatch_get_main_queue(), ^{
  941. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  942. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  943. });
  944. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  945. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  946. }
  947. }
  948. - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
  949. [super drawPage:pdfPage toContext:context];
  950. [self drawSelectionForPage:pdfPage inContext:context];
  951. BOOL isIncludText = NO;
  952. NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
  953. NSMutableArray *currentPageAnnotations = [NSMutableArray array];
  954. for (CPDFAnnotation *an in self.activeAnnotations) {
  955. if([an.page isEqual:pdfPage]) {
  956. if([an isKindOfClass:[CPDFFreeTextAnnotation class]])
  957. isIncludText = YES;
  958. //多选注释框去除mark注释与便签注释
  959. if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
  960. [currentActiveAnnotations addObject:an];
  961. }
  962. [currentPageAnnotations addObject:an];
  963. }
  964. }
  965. if(currentActiveAnnotations.count > 1) {
  966. NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
  967. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  968. CGContextSaveGState(context);
  969. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  970. CGContextSetStrokeColorWithColor(context, color);
  971. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  972. CGContextRestoreGState(context);
  973. CGContextSaveGState(context);
  974. if(isIncludText) {
  975. [CPDFListView DrawFreeTextResizeHandle:context rect:rect radius: 4.0 * lineWidth active:true];
  976. } else {
  977. [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
  978. }
  979. CGContextRestoreGState(context);
  980. }
  981. if(self.multiplAnnotationObject &&
  982. !CGRectIsEmpty(self.multiplAnnotationObject.drawRect) &&
  983. self.multiplAnnotationObject.page == pdfPage) {
  984. CGRect selectAnnotationBounds = self.multiplAnnotationObject.drawRect;
  985. NSRect rect = selectAnnotationBounds;
  986. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  987. CGContextSaveGState(context);
  988. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  989. CGContextSetStrokeColorWithColor(context, color);
  990. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  991. CGContextRestoreGState(context);
  992. }
  993. [currentPageAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  994. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  995. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  996. }
  997. }];
  998. [self.selectAnnotations 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. if (self.hoverAnnotation.page && [self.hoverAnnotation.page isEqual:pdfPage] && ![self.activeAnnotations containsObject:self.hoverAnnotation]) {
  1004. [self.hoverAnnotation drawSelectionHighlightForView:self inContext:context isHover:YES];
  1005. }
  1006. if(!CGRectEqualToRect(self.multiplSelectBounds, CGRectZero) && [self.multiplSelectPage isEqual:pdfPage]) {
  1007. @synchronized (self) {
  1008. CGContextSetLineCap(context, kCGLineCapRound);
  1009. CGContextSetLineWidth(context, 1.0);
  1010. CGContextSetStrokeColorWithColor(context, [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor);
  1011. CGContextBeginPath(context);
  1012. CGContextMoveToPoint(context, self.multiplSelectBounds.origin.x, self.multiplSelectBounds.origin.y);
  1013. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x+ self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y);
  1014. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x + self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  1015. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  1016. CGContextClosePath(context);
  1017. CGFloat lengths[] = {5,5};
  1018. CGContextSetLineDash(context, 0, lengths,2);
  1019. CGContextStrokePath(context);
  1020. }
  1021. }
  1022. }
  1023. - (void)drawSelectionForPage:(CPDFPage *)pdfPage inContext:(CGContextRef)context {
  1024. NSRect rect;
  1025. NSUInteger pageIndex;
  1026. @synchronized (self) {
  1027. pageIndex = self.selectionPageIndex;
  1028. rect = self.selectionRect;
  1029. }
  1030. if (pageIndex != NSNotFound) {
  1031. BOOL isWidget = NO;
  1032. for (CPDFAnnotation * annotation in self.activeAnnotations) {
  1033. if ([annotation isForm]) {
  1034. isWidget = YES;
  1035. break;
  1036. }
  1037. }
  1038. if (isWidget &&
  1039. _toolMode != CFormToolMode) {
  1040. return;
  1041. }
  1042. NSRect bounds = [pdfPage boundsForBox:[self displayBox]];
  1043. CGFloat radius = HANDLE_SIZE * [self unitWidthOnPage:pdfPage];
  1044. CGColorRef color = CGColorCreateGenericGray(0.0, 0.6);
  1045. CGContextSetFillColorWithColor(context, color);
  1046. CGColorRelease(color);
  1047. CGContextBeginPath(context);
  1048. CGContextAddRect(context, NSRectToCGRect(bounds));
  1049. CGContextAddRect(context, NSRectToCGRect(rect));
  1050. CGContextEOFillPath(context);
  1051. if ([pdfPage pageIndex] != pageIndex) {
  1052. color = CGColorCreateGenericGray(0.0, 0.3);
  1053. CGContextSetFillColorWithColor(context, color);
  1054. CGColorRelease(color);
  1055. CGContextFillRect(context, NSRectToCGRect(rect));
  1056. }
  1057. [CPDFListView DrawResizeHandles:context rect:rect radius:radius active:true];
  1058. }
  1059. }
  1060. - (void)removeShapeLayer {
  1061. if (![self.shapeLayerTopH isEqual:nil] && ![self.shapeLayerBottomH isEqual:nil] && ![self.shapeLayerLeftV isEqual:nil] && ![self.shapeLayerRightV isEqual:nil]) {
  1062. [self.shapeLayerTopH removeFromSuperlayer];
  1063. [self.shapeLayerBottomH removeFromSuperlayer];
  1064. [self.shapeLayerLeftV removeFromSuperlayer];
  1065. [self.shapeLayerRightV removeFromSuperlayer];
  1066. self.shapeLayerTopH = nil;
  1067. self.shapeLayerBottomH = nil;
  1068. self.shapeLayerLeftV = nil;
  1069. self.shapeLayerRightV = nil;
  1070. }
  1071. }
  1072. - (BOOL)consistentTypeWithAnnotation:(CPDFAnnotation *)annotation {
  1073. if (self.annotationType == CAnnotationTypeSignSignature) {
  1074. if (![annotation isKindOfClass:[CPDFSignatureAnnotation class]])
  1075. return NO;
  1076. } else if (self.annotationType == CAnnotationTypeStamp) {
  1077. if (![annotation isKindOfClass:[CPDFStampAnnotation class]])
  1078. return NO;
  1079. } else if (self.annotationType == CAnnotationTypeAnchored) {
  1080. if (![annotation isKindOfClass:[CPDFTextAnnotation class]])
  1081. return NO;
  1082. } else if (self.annotationType == CAnnotationTypeLink) {
  1083. if (![annotation isKindOfClass:[CPDFLinkAnnotation class]])
  1084. return NO;
  1085. } else if (self.annotationType == CAnnotationTypeFreeText) {
  1086. if (![annotation isKindOfClass:[CPDFFreeTextAnnotation class]])
  1087. return NO;
  1088. } else if (self.annotationType == CAnnotationTypeLine || self.annotationType == CAnnotationTypeArrow || self.annotationType == CAnnotationTypeSquare || self.annotationType == CAnnotationTypeCircle) {
  1089. if (![annotation isKindOfClass:[CPDFLineAnnotation class]] && ![annotation isKindOfClass:[CPDFSquareAnnotation class]] && ![annotation isKindOfClass:[CPDFCircleAnnotation class]])
  1090. return NO;
  1091. } else if (self.annotationType == CAnnotationTypeHighlight || self.annotationType == CAnnotationTypeUnderline || self.annotationType == CAnnotationTypeStrikeOut) {
  1092. if (![annotation isKindOfClass:[CPDFMarkupAnnotation class]])
  1093. return NO;
  1094. } else if (self.annotationType == CAnnotationTypeInk) {
  1095. if (![annotation isKindOfClass:[CPDFInkAnnotation class]])
  1096. return NO;
  1097. } else if (self.annotationType == CAnnotationTypeRadioButton) {
  1098. } else if (self.annotationType == CAnnotationTypeCheckBox) {
  1099. } else if (self.annotationType == CAnnotationTypeTextField) {
  1100. } else if (self.annotationType == CAnnotationTypeComboBox) {
  1101. } else if (self.annotationType == CAnnotationTypeListMenu) {
  1102. } else if (self.annotationType == CAnnotationTypeActionButton) {
  1103. } else if (self.annotationType == CAnnotationTypeSignature) {
  1104. } else if (self.annotationType == CAnnotationTypeSignText) {
  1105. } else if (self.annotationType == CAnnotationTypeSignFalse) {
  1106. } else if (self.annotationType == CAnnotationTypeSignTure) {
  1107. } else if (self.annotationType == CAnnotationTypeSignCircle) {
  1108. } else if (self.annotationType == CAnnotationTypeSignLine) {
  1109. } else if (self.annotationType == CAnnotationTypeSignDot) {
  1110. } else if (self.annotationType == CAnnotationTypeSignConfig) {
  1111. } else if (self.annotationType == CAnnotationTypeSignDate) {
  1112. }
  1113. return YES;
  1114. }
  1115. #pragma mark Zooming
  1116. - (void)zoomToRect:(NSRect)rect onPage:(CPDFPage *)page {
  1117. if (NSIsEmptyRect(rect) == NO) {
  1118. BOOL isLegacy = [NSScroller respondsToSelector:@selector(preferredScrollerStyle)] == NO || [NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy;
  1119. NSRect bounds = [self bounds];
  1120. CGFloat scale = 1.0;
  1121. if (isLegacy) {
  1122. bounds.size.width -= [NSScroller scrollerWidth];
  1123. bounds.size.height -= [NSScroller scrollerWidth];
  1124. }
  1125. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1126. scale = NSHeight(bounds) / NSHeight(rect);
  1127. else
  1128. scale = NSWidth(bounds) / NSWidth(rect);
  1129. [self setScaleFactor:scale];
  1130. NSScrollView *scrollView = [self scrollView];
  1131. if (isLegacy && ([scrollView hasHorizontalScroller] == NO || [scrollView hasVerticalScroller] == NO)) {
  1132. if ([scrollView hasVerticalScroller])
  1133. bounds.size.width -= [NSScroller scrollerWidth];
  1134. if ([scrollView hasHorizontalScroller])
  1135. bounds.size.height -= [NSScroller scrollerWidth];
  1136. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1137. scale = NSHeight(bounds) / NSHeight(rect);
  1138. else
  1139. scale = NSWidth(bounds) / NSWidth(rect);
  1140. [self setScaleFactor:scale];
  1141. }
  1142. [self goToRect:rect onPage:page];
  1143. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1144. CGPoint tPagePoint = CGPointMake(rect.origin.x, rect.origin.y+rect.size.height);
  1145. [self goToTargetPoint:tPagePoint onPage:page atScrollPosition:CScrollPositionTop];
  1146. });
  1147. }
  1148. }
  1149. #pragma mark - NSPopoverDelegate
  1150. - (void)popoverWillClose:(NSNotification *)notification {
  1151. NSPopover *popover = notification.object;
  1152. if([popover.contentViewController isKindOfClass:[CPDFListEditAnnotationViewController class]]) {
  1153. CPDFListEditAnnotationViewController *listEditAnnotationViewController = (CPDFListEditAnnotationViewController *)popover.contentViewController;
  1154. CPDFAnnotation *annotation = listEditAnnotationViewController.annotation;
  1155. NSString *contensString = listEditAnnotationViewController.contentString;
  1156. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  1157. if(contensString && contensString.length > 0) {
  1158. annotation.contents = listEditAnnotationViewController.contentString;
  1159. [self setNeedsDisplayAnnotation:annotation];
  1160. } else {
  1161. if([self.activeAnnotations containsObject:annotation]) {
  1162. [self.activeAnnotations removeObject:annotation];
  1163. }
  1164. [self removeAnnotation:annotation];
  1165. }
  1166. } else {
  1167. annotation.contents = listEditAnnotationViewController.contentString;
  1168. [self setNeedsDisplayAnnotation:annotation];
  1169. }
  1170. }
  1171. self.popOver = nil;
  1172. }
  1173. - (void)handlePageChangedNotification:(NSNotification *)notification {
  1174. self.copyCount = 0;
  1175. }
  1176. #pragma mark - Form Alignment
  1177. - (KMPDFViewActiveFormsType)formAnnotionsType:(NSArray *)annotationArray {
  1178. NSSet *set = [NSSet setWithArray:[annotationArray valueForKey:@"type"]];
  1179. NSArray *array = [set allObjects];
  1180. if (array.count > 1 || ![array.firstObject isEqualToString:@"Widget"]) {
  1181. return KMPDFViewActiveFormsType_NotAllform;
  1182. }
  1183. PDFAnnotation *referenceAnnotation = annotationArray.firstObject;
  1184. Class referenceAnnotationClass = [referenceAnnotation class];
  1185. if ([referenceAnnotationClass isEqual:[CPDFButtonWidgetAnnotation class]]) {
  1186. referenceAnnotationClass = [CPDFButtonWidgetAnnotation superclass];
  1187. }
  1188. if ([referenceAnnotationClass isEqual:[CPDFTextWidgetAnnotation class]]) {
  1189. referenceAnnotationClass = [CPDFTextWidgetAnnotation superclass];
  1190. }
  1191. if ([referenceAnnotationClass isEqual:[CPDFChoiceWidgetAnnotation class]]) {
  1192. referenceAnnotationClass = [CPDFChoiceWidgetAnnotation superclass];
  1193. }
  1194. if (annotationArray.count == 1) {
  1195. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]) {
  1196. return KMPDFViewActiveFormsType_TextSingle;
  1197. } else {
  1198. return KMPDFViewActiveFormsType_PureSingle;
  1199. }
  1200. }
  1201. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1202. PDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1203. if (![annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFTextWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  1204. return KMPDFViewActiveFormsType_Mix;
  1205. }
  1206. }
  1207. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]){
  1208. return KMPDFViewActiveFormsType_Text;
  1209. }
  1210. return KMPDFViewActiveFormsType_Pure;
  1211. }
  1212. - (void)formsAnnotationAlign:(KMPDFActiveFormsAlignType)type {
  1213. CGRect zeroRect = CGRectNull;
  1214. CGRect highestRect = CGRectZero;
  1215. CGRect widthestRect = CGRectZero;
  1216. CPDFAnnotation *firstAnnotation = self.activeAnnotations.firstObject;
  1217. CGRect leftestRect = firstAnnotation.bounds;
  1218. CGRect rightestRect = firstAnnotation.bounds;
  1219. CGRect topestRect = firstAnnotation.bounds;
  1220. CGRect bottomestRect = firstAnnotation.bounds;
  1221. CPDFAnnotation *leftestAnnotation = firstAnnotation;
  1222. CPDFAnnotation *rightestAnnotation = firstAnnotation;
  1223. CPDFAnnotation *topestAnnotation = firstAnnotation;
  1224. CPDFAnnotation *bottomestAnnotation = firstAnnotation;
  1225. CGFloat totalWidth = 0.;
  1226. CGFloat totalHeight = 0.;
  1227. for (CPDFAnnotation *annotation in self.activeAnnotations) {
  1228. zeroRect = CGRectUnion(zeroRect, annotation.bounds);
  1229. totalWidth += CGRectGetWidth(annotation.bounds);
  1230. totalHeight += CGRectGetHeight(annotation.bounds);
  1231. if (CGRectGetHeight(annotation.bounds) > CGRectGetHeight(highestRect)) {
  1232. highestRect = annotation.bounds;
  1233. }
  1234. if (CGRectGetWidth(annotation.bounds) > CGRectGetWidth(widthestRect)) {
  1235. widthestRect = annotation.bounds;
  1236. }
  1237. if (CGRectGetMinX(leftestRect) > CGRectGetMinX(annotation.bounds)) {
  1238. leftestRect = annotation.bounds;
  1239. leftestAnnotation = annotation;
  1240. }
  1241. if (CGRectGetMaxX(annotation.bounds) > CGRectGetMaxX(rightestRect)) {
  1242. rightestRect = annotation.bounds;
  1243. rightestAnnotation = annotation;
  1244. }
  1245. if (CGRectGetMaxY(annotation.bounds) > CGRectGetMaxY(topestRect)) {
  1246. topestRect = annotation.bounds;
  1247. topestAnnotation = annotation;
  1248. }
  1249. if (CGRectGetMinY(bottomestRect) > CGRectGetMinY(annotation.bounds)) {
  1250. bottomestRect = annotation.bounds;
  1251. bottomestAnnotation = annotation;
  1252. }
  1253. }
  1254. if (type == KMPDFActiveFormsAlignType_Left ) {
  1255. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1256. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1257. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1258. CGRect bounds = annotation.bounds;
  1259. bounds.origin.x = zeroRect.origin.x;
  1260. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1261. }
  1262. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1263. } else if (type == KMPDFActiveFormsAlignType_Right) {
  1264. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1265. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1266. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1267. CGRect bounds = annotation.bounds;
  1268. bounds.origin.x = CGRectGetMaxX(zeroRect) - bounds.size.width;
  1269. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1270. }
  1271. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1272. } else if (type == KMPDFActiveFormsAlignType_Top) {
  1273. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1274. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1275. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1276. CGRect bounds = annotation.bounds;
  1277. bounds.origin.y = CGRectGetMaxY(zeroRect) - bounds.size.height;
  1278. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1279. }
  1280. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1281. } else if (type == KMPDFActiveFormsAlignType_Bottom) {
  1282. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1283. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1284. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1285. CGRect bounds = annotation.bounds;
  1286. bounds.origin.y = CGRectGetMinY(zeroRect);
  1287. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1288. }
  1289. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1290. } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
  1291. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1292. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1293. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1294. CGRect bounds = annotation.bounds;
  1295. bounds.origin.y = CGRectGetMidY(highestRect) - CGRectGetHeight(bounds)/2;
  1296. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1297. }
  1298. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1299. } else if (type == KMPDFActiveFormsAlignType_Vertical) {
  1300. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1301. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1302. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1303. CGRect bounds = annotation.bounds;
  1304. bounds.origin.x = CGRectGetMidX(widthestRect) - CGRectGetWidth(bounds)/2;
  1305. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1306. }
  1307. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1308. } else if (type == KMPDFActiveFormsAlignType_DisHorizontally) {
  1309. CGFloat middleGap = CGRectGetWidth(zeroRect) - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1310. CGFloat otherAnnotationsTotalWidth = totalWidth - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1311. CGFloat gap = (middleGap - otherAnnotationsTotalWidth)/(self.activeAnnotations.count - 1);
  1312. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1313. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1314. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1315. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1316. if (annotation1.bounds.origin.x < annotation2.bounds.origin.x) {
  1317. return NSOrderedAscending;
  1318. } else {
  1319. return NSOrderedDescending;
  1320. }
  1321. }];
  1322. [annotationsCopyArray removeObject:leftestAnnotation];
  1323. [annotationsCopyArray removeObject:rightestAnnotation];
  1324. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1325. CGFloat leftStartX = CGRectGetMaxX(leftestRect) + gap;
  1326. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1327. CPDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1328. CGRect bounds = annotation.bounds;
  1329. bounds.origin.x = leftStartX;
  1330. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1331. leftStartX += CGRectGetWidth(bounds) + gap;
  1332. }
  1333. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1334. } else if (type == KMPDFActiveFormsAlignType_DisVertical) {
  1335. CGFloat middleGap = CGRectGetHeight(zeroRect) - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1336. CGFloat otherAnnotationsTotalHeight = totalHeight - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1337. CGFloat gap = (middleGap - otherAnnotationsTotalHeight)/(self.activeAnnotations.count - 1);
  1338. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1339. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1340. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1341. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1342. if (annotation1.bounds.origin.y < annotation2.bounds.origin.y) {
  1343. return NSOrderedAscending;
  1344. } else {
  1345. return NSOrderedDescending;
  1346. }
  1347. }];
  1348. [annotationsCopyArray removeObject:topestAnnotation];
  1349. [annotationsCopyArray removeObject:bottomestAnnotation];
  1350. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1351. CGFloat bottomStartY = CGRectGetMaxY(bottomestRect) + gap;
  1352. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1353. PDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1354. CGRect bounds = annotation.bounds;
  1355. bounds.origin.y = bottomStartY;
  1356. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1357. bottomStartY += CGRectGetHeight(bounds) + gap;
  1358. }
  1359. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1360. }
  1361. }
  1362. - (void)changeAnnotationsAlign:(NSArray *)annotationArray newBounds:(NSArray *)newBoundsArray {
  1363. NSMutableArray * oldBoundsArray = [NSMutableArray array];
  1364. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1365. CPDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1366. [oldBoundsArray addObject:NSStringFromRect(annotation.bounds)];
  1367. annotation.bounds = NSRectFromString([newBoundsArray objectAtIndex:i]);
  1368. }
  1369. [[[self undoManager] prepareWithInvocationTarget:self] changeAnnotationsAlign:annotationArray newBounds:oldBoundsArray];
  1370. [self setNeedsDisplay:YES];
  1371. }
  1372. #pragma mark Services
  1373. - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types {
  1374. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound) {
  1375. NSMutableArray *writeTypes = [NSMutableArray array];
  1376. NSString *pdfType = nil;
  1377. NSData *pdfData = nil;
  1378. NSString *tiffType = nil;
  1379. NSData *tiffData = nil;
  1380. NSRect selRect = NSIntegralRect(_selectionRect);
  1381. // 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
  1382. if ([[self document] allowsPrinting] && [[self document] isLocked] == NO) {
  1383. if ([types containsObject:NSPasteboardTypePDF])
  1384. pdfType = NSPasteboardTypePDF;
  1385. else if ([types containsObject:NSPasteboardTypePDF])
  1386. pdfType = NSPasteboardTypePDF;
  1387. if (pdfType && (pdfData = [[self currentSelectionPage] pdfDataFor:selRect]))
  1388. [writeTypes addObject:pdfType];
  1389. }
  1390. if ([types containsObject:NSPasteboardTypeTIFF])
  1391. tiffType = NSPasteboardTypeTIFF;
  1392. else if ([types containsObject:NSPasteboardTypeTIFF])
  1393. tiffType = NSPasteboardTypeTIFF;
  1394. if (tiffType && (tiffData = [[self currentSelectionPage] PDFListViewTIFFDataFor:selRect]))
  1395. [writeTypes addObject:tiffType];
  1396. if ([writeTypes count] > 0) {
  1397. [pboard declareTypes:writeTypes owner:nil];
  1398. if (pdfData)
  1399. [pboard setData:pdfData forType:pdfType];
  1400. if (tiffData)
  1401. [pboard setData:tiffData forType:tiffType];
  1402. return YES;
  1403. }
  1404. }
  1405. if ([[self currentSelection] hasCharacters]) {
  1406. if ([types containsObject:NSPasteboardTypeRTF] || [types containsObject:NSPasteboardTypeRTF]) {
  1407. [pboard clearContents];
  1408. [pboard writeObjects:[NSArray arrayWithObjects:[[self currentSelection] attributedString], nil]];
  1409. return YES;
  1410. } else if ([types containsObject:NSPasteboardTypeString] || [types containsObject:NSPasteboardTypeString]) {
  1411. [pboard clearContents];
  1412. [pboard writeObjects:[NSArray arrayWithObjects:[[self currentSelection] string], nil]];
  1413. return YES;
  1414. }
  1415. }
  1416. return [[CPDFListView superclass] instancesRespondToSelector:_cmd];
  1417. }
  1418. - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType {
  1419. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound && returnType == nil &&
  1420. (([[self document] allowsPrinting] && [[self document] isLocked] == NO && [sendType isEqualToString:NSPasteboardTypePDF]) || [sendType isEqualToString:NSPasteboardTypeTIFF])) {
  1421. return self;
  1422. }
  1423. if ([[self currentSelection] hasCharacters] && returnType == nil && ([sendType isEqualToString:NSPasteboardTypeString] || [sendType isEqualToString:NSPasteboardTypeRTF])) {
  1424. return self;
  1425. }
  1426. return [super validRequestorForSendType:sendType returnType:returnType];
  1427. }
  1428. @end