CPDFListView.m 75 KB

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