CPDFListView.m 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  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. NSString *SKPasteboardTypeLineStyle = @"net.sourceforge.skim-app.pasteboard.line-style";
  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. NSNotificationName const CPDFListViewDisplayModeChangeNotification = @"CPDFListViewDisplayModeChangeNotification";
  35. @implementation CPDFListView
  36. void CPDFListViewOCDrawLineHandles(CGContextRef context, CGRect rect, CGFloat radius) {
  37. CGPoint startPoint0 = CGPointMake(rect.origin.x + radius, rect.origin.y);
  38. CGPoint endPoint0 = CGPointMake(CGRectGetMidX(rect) - radius, rect.origin.y);
  39. CGContextMoveToPoint(context, startPoint0.x, startPoint0.y);
  40. CGContextAddLineToPoint(context, endPoint0.x, endPoint0.y);
  41. CGPoint startPoint1 = CGPointMake(CGRectGetMidX(rect) + radius, rect.origin.y);
  42. CGPoint endPoint1 = CGPointMake(CGRectGetMaxX(rect) - radius, rect.origin.y);
  43. CGContextMoveToPoint(context, startPoint1.x, startPoint1.y);
  44. CGContextAddLineToPoint(context, endPoint1.x, endPoint1.y);
  45. CGPoint startPoint2 = CGPointMake(CGRectGetMaxX(rect), rect.origin.y + radius);
  46. CGPoint endPoint2 = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect) - radius);
  47. CGContextMoveToPoint(context, startPoint2.x, startPoint2.y);
  48. CGContextAddLineToPoint(context, endPoint2.x, endPoint2.y);
  49. CGPoint startPoint3 = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect) + radius);
  50. CGPoint endPoint3 = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect) - radius);
  51. CGContextMoveToPoint(context, startPoint3.x, startPoint3.y);
  52. CGContextAddLineToPoint(context, endPoint3.x, endPoint3.y);
  53. CGPoint startPoint4 = CGPointMake(CGRectGetMaxX(rect) - radius, CGRectGetMaxY(rect));
  54. CGPoint endPoint4 = CGPointMake(CGRectGetMidX(rect) + radius, CGRectGetMaxY(rect));
  55. CGContextMoveToPoint(context, startPoint4.x, startPoint4.y);
  56. CGContextAddLineToPoint(context, endPoint4.x, endPoint4.y);
  57. CGPoint startPoint5 = CGPointMake(CGRectGetMidX(rect) - radius, CGRectGetMaxY(rect));
  58. CGPoint endPoint5 = CGPointMake(rect.origin.x + radius, CGRectGetMaxY(rect));
  59. CGContextMoveToPoint(context, startPoint5.x, startPoint5.y);
  60. CGContextAddLineToPoint(context, endPoint5.x, endPoint5.y);
  61. CGPoint startPoint6 = CGPointMake(rect.origin.x, CGRectGetMaxY(rect) - radius);
  62. CGPoint endPoint6 = CGPointMake(rect.origin.x, CGRectGetMidY(rect) + radius);
  63. CGContextMoveToPoint(context, startPoint6.x, startPoint6.y);
  64. CGContextAddLineToPoint(context, endPoint6.x, endPoint6.y);
  65. CGPoint startPoint7 = CGPointMake(rect.origin.x, CGRectGetMidY(rect) - radius);
  66. CGPoint endPoint7 = CGPointMake(rect.origin.x, rect.origin.y + radius);
  67. CGContextMoveToPoint(context, startPoint7.x, startPoint7.y);
  68. CGContextAddLineToPoint(context, endPoint7.x, endPoint7.y);
  69. }
  70. #pragma mark - Init
  71. - (id)init {
  72. self = [super init];
  73. if (self) {
  74. [self commonInitialization];
  75. }
  76. return self;
  77. }
  78. - (id)initWithFrame:(NSRect)frameRect {
  79. self = [super initWithFrame:frameRect];
  80. if (self) {
  81. [self commonInitialization];
  82. }
  83. return self;
  84. }
  85. - (id)initWithCoder:(NSCoder *)decoder {
  86. self = [super initWithCoder:decoder];
  87. if (self) {
  88. [self commonInitialization];
  89. }
  90. return self;
  91. }
  92. - (BOOL)mouseDownIsClickAnnotationWithPoint:(CGPoint)point forPage:(CPDFPage *)page {
  93. if (_annotationType != CAnnotationTypeUnkown) {
  94. return NO;
  95. }
  96. return YES;
  97. }
  98. - (void)updateLayer {
  99. [super updateLayer];
  100. if (@available(macOS 10.14, *)) {
  101. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewBackgroundColor)]) {
  102. NSColor *color = [self.pdfListViewDelegate PDFListViewBackgroundColor];
  103. self.backgroundColor = color;
  104. }
  105. }
  106. }
  107. - (void)commonInitialization {
  108. self.selectionPageIndex = NSNotFound;
  109. self.clickLineAnnotation = nil;
  110. self.isClickDoubleCreatLine = NO;
  111. self.perimeterMeasureInfo = [[CPDFPerimeterMeasureInfo alloc] init];
  112. self.polygonAreaMeasureInfo = [[CPDFAreaMeasureInfo alloc] init];
  113. self.squareAreaMeasureInfo = [[CPDFAreaMeasureInfo alloc] init];
  114. self.distanceMeasureInfo = [[CPDFDistanceMeasureInfo alloc] init];
  115. NSArray *sendTypes = [NSArray arrayWithObjects:NSPasteboardTypePDF, NSPasteboardTypeTIFF, nil];
  116. [NSApp registerServicesMenuSendTypes:sendTypes returnTypes:[NSArray array]];
  117. KMPDFViewMode viewMode = KMPDFViewModeNormal;
  118. if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeKey"]) {
  119. viewMode = (KMPDFViewMode)[[[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeKey"] integerValue];
  120. }
  121. NSData * data = nil;
  122. if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kKMPDFViewModeThemesArray"]) {
  123. data = [[NSUserDefaults standardUserDefaults] objectForKey:@"kKMPDFViewModeThemesArray"];
  124. }
  125. NSArray * appArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  126. NSMutableArray * mutableArray = [NSMutableArray arrayWithArray:appArray];
  127. if (mutableArray.count == 0) {
  128. NSColor *normalColor = [NSColor whiteColor];
  129. NSColor *softColor = [NSColor colorWithDeviceRed:238.0/255.0 green:232.0/255.0 blue:216.0/255.0 alpha:1.0];
  130. NSColor *nightColor = [NSColor blackColor];
  131. NSColor *greenColor = [NSColor colorWithDeviceRed:153.0/255.0 green:207.0/255.0 blue:161.0/255.0 alpha:1.0];
  132. mutableArray = [NSMutableArray arrayWithArray:@[normalColor, softColor,nightColor, greenColor]];
  133. }
  134. // NSColor *pageBackgroundColor = mutableArray[viewMode];
  135. NSColor *pageBackgroundColor = NSColor.whiteColor;
  136. if (viewMode < mutableArray.count) {
  137. pageBackgroundColor = mutableArray[viewMode];
  138. }
  139. if (viewMode == KMPDFViewModeOther &&
  140. [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"]) {
  141. CGFloat red,green,blue,alpha;
  142. NSArray *colors = [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"];
  143. red = colors.count>0 ? [colors[0] floatValue] : 0;
  144. green = colors.count>1 ? [colors[1] floatValue] : 0;
  145. blue = colors.count>2 ? [colors[2] floatValue] : 0;
  146. alpha = colors.count>3 ? [colors[3] floatValue] : 0;
  147. pageBackgroundColor = [NSColor colorWithDeviceRed:red green:green blue:blue alpha:alpha];
  148. }
  149. self.viewMode = viewMode;
  150. [self setPageBackgroundColorWithColor:pageBackgroundColor viewMode:viewMode];
  151. self.activeAnnotations = [NSMutableArray array];
  152. self.selectAnnotations = [NSMutableArray array];
  153. self.dragHoverPoints = [NSMutableArray array];
  154. self.aCopyAnnotations = [NSMutableArray array];
  155. [self registerAsObserver];
  156. [self addTrackingArea];
  157. //Table
  158. self.tableTextField = [[NSTextField alloc] initWithFrame:NSRectFromCGRect(CGRectMake(0, 0, 120, 18))];
  159. [self.tableTextField setBordered:NO];
  160. [self.tableTextField setBackgroundColor:[NSColor colorWithDeviceRed:244.0/255.0 green:239/255.0 blue:158/255.0 alpha:1]];
  161. [self.tableTextField setEditable:NO];
  162. [self.tableTextField setAlignment:NSTextAlignmentCenter];
  163. [self.tableTextField setStringValue:@"Column:0 Row:0"];
  164. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChangeNotification:) name:NSViewBoundsDidChangeNotification object:nil];
  165. // [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]];
  166. [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
  167. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
  168. name:CPDFViewPageChangedNotification object:self];
  169. }
  170. - (void)addTrackingArea {
  171. self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingInVisibleRect owner:self userInfo:nil];
  172. [self addTrackingArea:self.trackingArea];
  173. }
  174. - (void)resetPDFToolTipRects {
  175. [self removePDFToolTipRects];
  176. if ([self document] && [self window]) {
  177. NSRect visibleRect = [self visibleContentRect];
  178. NSView *docView = [self documentView];
  179. BOOL hasLinkToolTips = (self.toolMode == CTextToolMode || self.toolMode == CMoveToolMode || self.toolMode == CNoteToolMode);
  180. for (CPDFPage *page in [self visiblePages]) {
  181. for (CPDFAnnotation *annotation in [page annotations]) {
  182. if ([annotation isNote] || (hasLinkToolTips && [annotation linkDestination])) {
  183. // NSLog(@"%@",NSStringFromRect([annotation bounds]));
  184. NSRect rect = NSIntersectionRect([self convertRect:[annotation bounds] fromPage:page], visibleRect);
  185. if (NSIsEmptyRect(rect) == NO) {
  186. rect = [self convertRect:rect toView:docView];
  187. // NSLog(@"%@",NSStringFromRect(rect));
  188. NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:annotation, SKAnnotationKey, nil];
  189. NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:rect options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp owner:self userInfo:userInfo];
  190. [docView addTrackingArea:area];
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. - (void)removePDFToolTipRects {
  198. NSView *docView = [self documentView];
  199. NSArray *trackingAreas = [[docView trackingAreas] copy];
  200. for (NSTrackingArea *area in trackingAreas) {
  201. if ([area owner] == self && [[area userInfo] objectForKey:SKAnnotationKey])
  202. [docView removeTrackingArea:area];
  203. }
  204. }
  205. - (void)goToPageIndex:(NSInteger)pageIndex animated:(BOOL)animated {
  206. if (self.currentPageIndex != pageIndex) {
  207. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  208. }
  209. [super goToPageIndex:pageIndex animated:animated];
  210. }
  211. - (void)goToSelection:(CPDFSelection *)selection animated:(BOOL)animated {
  212. if (self.currentPageIndex != selection.page.pageIndex) {
  213. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  214. }
  215. [super goToSelection:selection animated:animated];
  216. }
  217. - (void)goToDestination:(CPDFDestination *)destination {
  218. [super goToDestination:destination];
  219. }
  220. - (void)goToRect:(CGRect)rect onPage:(CPDFPage *)page animated:(BOOL)animated {
  221. if (self.currentPageIndex != page.pageIndex) {
  222. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  223. }
  224. [super goToRect:rect onPage:page animated:animated];
  225. }
  226. - (void)goToTargetPoint:(NSPoint)point onPage:(CPDFPage *)page atScrollPosition:(CScrollPosition)scrollPosition {
  227. if (self.currentPageIndex != page.pageIndex) {
  228. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  229. }
  230. [super goToTargetPoint:point onPage:page atScrollPosition:scrollPosition];
  231. }
  232. #pragma mark - Setter & Get
  233. - (KMDrawView *)presentationDrawView {
  234. // if(!_presentationDrawView) {
  235. // float scale = 6;//放大比例,越大可能会卡顿
  236. // _presentationDrawView = [[KMDrawView alloc] initWithFrame:CGRectMake(0, 0,
  237. // scale * self.bounds.size.width,
  238. // scale * self.bounds.size.height)];
  239. // _presentationDrawView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  240. // _presentationDrawView.autoMark = YES;
  241. // [_presentationDrawView resetUndoManager];
  242. // [self addSubview:_presentationDrawView];
  243. // _presentationDrawView.frame = self.bounds;
  244. //
  245. // _presentationDrawView.renderColor = [NSColor blackColor];
  246. // _presentationDrawView.radius = 100;
  247. // _presentationDrawView.hidden = YES;
  248. //
  249. // }
  250. return _presentationDrawView;
  251. }
  252. - (KMDrawView *)CreatePresentationDrawView {
  253. if(!_presentationDrawView) {
  254. float scale = 2.0;//放大比例,越大可能会卡顿
  255. _presentationDrawView = [[KMDrawView alloc] initWithFrame:CGRectMake(0, 0,
  256. scale * self.bounds.size.width,
  257. scale * self.bounds.size.height)];
  258. _presentationDrawView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  259. _presentationDrawView.autoMark = YES;
  260. [_presentationDrawView resetUndoManager];
  261. [self addSubview:_presentationDrawView];
  262. _presentationDrawView.frame = self.bounds;
  263. _presentationDrawView.renderColor = [NSColor blackColor];
  264. _presentationDrawView.radius = 50;
  265. _presentationDrawView.hidden = YES;
  266. }
  267. return _presentationDrawView;
  268. }
  269. - (void)setDocument:(CPDFDocument *)document {
  270. @synchronized (self) {
  271. self.selectionRect = NSZeroRect;
  272. self.selectionPageIndex = NSNotFound;
  273. }
  274. // self.toolMode = CFormToolMode;
  275. // self.annotationType = CAnnotationTypeRadioButton;
  276. // CStampSignatureObject *objc = [[CStampSignatureObject alloc] initImageStampWithFilePath:[[NSBundle mainBundle] pathForResource:@"Quick Start Guide" ofType:@"pdf"]];
  277. // [self setAddStampObject:objc keepToolModel:YES];
  278. //
  279. [super setDocument:document];
  280. [self resetPDFToolTipRectsForAfterDelay];
  281. for(NSInteger i = 0;i<self.document.pageCount;i++) {
  282. CPDFPage *page = [self.document pageAtIndex:i];
  283. for (CPDFAnnotation *annotation in page.annotations) {
  284. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFPageDidLoadAnnotationNotification object:annotation];
  285. }
  286. }
  287. [self.window makeFirstResponder:self];
  288. }
  289. - (void)setToolMode:(CToolMode)newToolMode {
  290. if(newToolMode != _toolMode) {
  291. BOOL isDisplayAnnotationView = NO;
  292. if(self.isSetLinkDestinationArea)
  293. self.isSetLinkDestinationArea = NO;
  294. if ((CTextToolMode == _toolMode || CNoteToolMode == _toolMode) && CTextToolMode != newToolMode) {
  295. if (newToolMode != CNoteToolMode && self.activeAnnotation) {
  296. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  297. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  298. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  299. [self commitEditAnnotationFreeText:freeTextAn];
  300. }
  301. }
  302. [self updateActiveAnnotations:@[]];
  303. }
  304. if ([self currentSelection])
  305. [self setCurrentSelection:nil];
  306. } else if ((_toolMode == CSelectToolMode || _toolMode == CCropToolMode) && NSEqualRects(self.selectionRect, NSZeroRect) == NO) {
  307. self.selectionRect = NSZeroRect;
  308. self.selectionPageIndex = NSNotFound;
  309. dispatch_async(dispatch_get_main_queue(), ^{
  310. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFViewSelectionChangedNotification object:self];
  311. });
  312. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedSelectionOrMagnification:)])
  313. [self.pdfListViewDelegate PDFListViewChangedSelectionOrMagnification:self];
  314. isDisplayAnnotationView = YES;
  315. }
  316. BOOL highlightFormFiled = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightFormFiledKey"];
  317. if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewHighlightFormFiledKey"] == nil) {
  318. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kPDFViewHighlightFormFiledKey"];
  319. highlightFormFiled = YES;
  320. }
  321. if (CFormToolMode == _toolMode && !highlightFormFiled) {
  322. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:highlightFormFiled];
  323. isDisplayAnnotationView = YES;
  324. } else if (CFormToolMode == newToolMode && !highlightFormFiled) {
  325. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:YES];
  326. isDisplayAnnotationView = YES;
  327. }
  328. if (CEditPDFToolMode == newToolMode)
  329. [self beginEditingLoadType:CEditingLoadTypeText|CEditingLoadTypeImage];
  330. if (_toolMode == CEditPDFToolMode) {
  331. if(self.isEdited) {
  332. [self commitEditing];
  333. }
  334. [self endOfEditing];
  335. }
  336. _toolMode = newToolMode;
  337. self.selectZoomToolModeZoomOut = NO;
  338. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedToolMode:forToolMode:)])
  339. [self.pdfListViewDelegate PDFListViewChangedToolMode:self forToolMode:newToolMode];
  340. dispatch_async(dispatch_get_main_queue(), ^{
  341. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewToolModeChangeNotification object:self];
  342. });
  343. [self resetPDFViewAnnotation];
  344. [self resetPDFToolTipRectsForAfterDelay];
  345. if(isDisplayAnnotationView)
  346. [self setNeedsDisplayAnnotationViewForVisiblePages];
  347. }
  348. }
  349. - (void)setShowHopnumber:(BOOL)showHopnumber {
  350. _showHopnumber = showHopnumber;
  351. [self setNeedsDisplayAnnotationViewForVisiblePages];
  352. }
  353. - (void)setAnnotationType:(CAnnotationType)annotationType {
  354. if (_annotationType != annotationType) {
  355. if(CAnnotationTypeLink == annotationType || CAnnotationTypeLink == _annotationType)
  356. [self setNeedsDisplayAnnotationViewForVisiblePages];
  357. if(annotationType == CAnnotationTypeUnkown) {
  358. [self endMeasureModeAddAnnotation];
  359. }
  360. _annotationType = annotationType;
  361. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedAnnotationType:forAnnotationType:)])
  362. [self.pdfListViewDelegate PDFListViewChangedAnnotationType:self forAnnotationType:annotationType];
  363. dispatch_async(dispatch_get_main_queue(), ^{
  364. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewAnnotationTypeChangeNotification object:self];
  365. });
  366. }
  367. if(self.activeAnnotations.count > 0) {
  368. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  369. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  370. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  371. [self commitEditAnnotationFreeText:freeTextAn];
  372. }
  373. }
  374. [self updateActiveAnnotations:@[]];
  375. [self setNeedsDisplayAnnotationViewForVisiblePages];
  376. }
  377. if(self.isSetLinkDestinationArea)
  378. self.isSetLinkDestinationArea = NO;
  379. [self resetPDFViewAnnotation];
  380. }
  381. - (NSRect)currentSelectionRect {
  382. if (CSelectToolMode == self.toolMode)
  383. return self.selectionRect;
  384. return NSZeroRect;
  385. }
  386. - (CPDFPage *)currentSelectionPage {
  387. if (self.selectionPageIndex != NSNotFound) {
  388. return [self.document pageAtIndex:self.selectionPageIndex];
  389. }
  390. return nil;
  391. }
  392. - (CPDFAnnotation *)activeAnnotation {
  393. return self.activeAnnotations.lastObject;
  394. }
  395. - (void)setHideNotes:(BOOL)hideNotes {
  396. _hideNotes = hideNotes;
  397. for(NSInteger i = 0;i<self.document.pageCount;i++) {
  398. CPDFPage *page = [self.document pageAtIndex:i];
  399. for (CPDFAnnotation *annotation in page.annotations) {
  400. [annotation setAnnotationShouldDisplay:!self.hideNotes];
  401. [annotation setHidden: self.hideNotes];
  402. [self updateHighLightAnnotation:annotation];
  403. }
  404. }
  405. [self setNeedsDisplayAnnotationViewForVisiblePages];
  406. }
  407. -(void)setIsSetLinkDestinationArea:(BOOL)isSetLinkDestinationArea {
  408. _isSetLinkDestinationArea = isSetLinkDestinationArea;
  409. if (_isSetLinkDestinationArea) {
  410. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationStart:withActiveAnnotation:)]) {
  411. [self.pdfListViewDelegate PDFListViewLinkDestinationStart:self withActiveAnnotation:self.activeAnnotation];
  412. }
  413. } else {
  414. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationEnd:withActiveAnnotation:)]) {
  415. [self.pdfListViewDelegate PDFListViewLinkDestinationEnd:self withActiveAnnotation:self.activeAnnotation];
  416. }
  417. }
  418. }
  419. - (void)setPageBackgroundColorWithColor:(NSColor *)color viewMode:(KMPDFViewMode)viewMode {
  420. if (self.activeAnnotation != nil) {
  421. return;
  422. }
  423. _viewMode = viewMode;
  424. if (viewMode == KMPDFViewModeNormal) {
  425. self.displayMode = CPDFDisplayModeNormal;
  426. } else if (viewMode == KMPDFViewModeSoft) {
  427. self.displayMode = CPDFDisplayModeSoft;
  428. } else if (viewMode == KMPDFViewModeNight) {
  429. self.displayMode = CPDFDisplayModeNight;
  430. } else if (viewMode == KMPDFViewModeGreen) {
  431. self.displayMode = CPDFDisplayModeGreen;
  432. } else {
  433. self.displayMode = CPDFDisplayModeCustom;
  434. self.displayModeCustomColor = color;
  435. }
  436. [self layoutDocumentView];
  437. [self setNeedsDisplayForVisiblePages];
  438. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewMode] forKey:@"kPDFViewModeKey"];
  439. [[NSUserDefaults standardUserDefaults] synchronize];
  440. }
  441. - (void)updateDocumentViewForBackgroundColor{
  442. [self layoutDocumentView];
  443. // [self setNeedsDisplayForVisiblePages];
  444. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_viewMode] forKey:@"kPDFViewModeKey"];
  445. [[NSUserDefaults standardUserDefaults] synchronize];
  446. }
  447. - (void)setViewSplitMode:(KMPDFViewSplitMode)viewSplitMode {
  448. if (_viewSplitMode == viewSplitMode) {
  449. return;
  450. }
  451. _viewSplitMode = viewSplitMode;
  452. [self setNeedsDisplay:YES];
  453. }
  454. - (void)setCurrentSelection:(CPDFSelection *)currentSelection {
  455. if (self.toolMode == CNoteToolMode && self.annotationType == CAnnotationTypeHighlight) {
  456. NSColor *color = [[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey];
  457. CGFloat red = 0, green = 0, blue = 0, alpha = 0.7;
  458. [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red
  459. green:&green
  460. blue:&blue
  461. alpha:nil];
  462. [currentSelection setColor:[NSColor colorWithRed:red green:green blue:blue alpha:alpha]/*[[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey]*/];
  463. }
  464. if (currentSelection == nil) {
  465. // selection = [[[PDFSelection alloc] initWithDocument:[self document]] autorelease];
  466. }
  467. [super setCurrentSelection:currentSelection];
  468. }
  469. #pragma mark - menu add image
  470. - (void)addImageAnnotation:(NSImage *)image center:(NSPoint)center isRemoveBGColor:(BOOL)isRemoveBGColor{
  471. [self setToolMode:CTextToolMode]; //不支持重复添加,重置状态
  472. if (isRemoveBGColor) {
  473. NSData *imageData = [image TIFFRepresentation];
  474. CGImageRef imageRef;
  475. if (imageData) {
  476. CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
  477. imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
  478. } else {
  479. return NSBeep();
  480. }
  481. const int imageWidth = image.size.width;
  482. const int imageHeight = image.size.height;
  483. size_t bytesPerRow = imageWidth * 4;
  484. uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
  485. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  486. CGContextRef context = CGBitmapContextCreate(rgbImageBuf,
  487. imageWidth,
  488. imageHeight,
  489. 8,
  490. bytesPerRow,
  491. colorSpace,
  492. kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  493. CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), imageRef);
  494. int pixelNum = imageWidth * imageHeight;
  495. uint32_t* pCurPtr = rgbImageBuf;
  496. for (int i = 0; i < pixelNum; i++, pCurPtr++) {
  497. uint8_t* ptr = (uint8_t*)pCurPtr;
  498. if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
  499. ptr[0] = 0;
  500. }
  501. }
  502. CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
  503. imageRef = CGImageCreate(imageWidth,
  504. imageHeight,
  505. 8,
  506. 32,
  507. bytesPerRow,
  508. colorSpace,
  509. kCGImageAlphaLast |kCGBitmapByteOrder32Little,
  510. dataProvider,
  511. NULL,
  512. true,
  513. kCGRenderingIntentDefault);
  514. CGDataProviderRelease(dataProvider);
  515. NSImage *newImage = nil;
  516. if (imageRef) {
  517. NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
  518. CGContextRef imageContext = nil;
  519. // Get the image dimensions.
  520. imageRect.size.height = CGImageGetHeight(imageRef);
  521. imageRect.size.width = CGImageGetWidth(imageRef);
  522. // Create a new image to receive the Quartz image data.
  523. newImage = [[NSImage alloc] initWithSize:imageRect.size];
  524. [newImage lockFocus];
  525. // Get the Quartz context and draw.
  526. imageContext = (CGContextRef)[[NSGraphicsContext currentContext] CGContext];
  527. CGContextDrawImage(imageContext, *(CGRect*)&imageRect, imageRef);
  528. [newImage unlockFocus];
  529. CGImageRelease(imageRef);
  530. }
  531. if (newImage) {
  532. [self addAnnotationWithImage:newImage center:center];
  533. } else {
  534. [self addAnnotationWithImage:image center:center];
  535. }
  536. } else {
  537. [self addAnnotationWithImage:image center:center];
  538. }
  539. }
  540. - (void)addAnnotationWithImage:(NSImage *)image center:(NSPoint)center {
  541. CPDFPage *page = nil;
  542. NSRect bounds = NSZeroRect;
  543. CPDFSelection *selection = [self currentSelection];
  544. page = [selection safeFirstPage];
  545. // if the mouse was in the toolbar and there is a page below the toolbar, we get a point outside of the visible rect
  546. page = NSMouseInRect(center, [self visibleContentRect], [self isFlipped]) ? [self pageForPoint:center nearest:NO] : nil;
  547. if (page == nil) {
  548. // Get center of the PDFView.
  549. // NSRect viewFrame = [self frame];
  550. // center = [self KMCpdfCenterPoint:viewFrame];//KMCpdfCenterPoint(viewFrame);
  551. page = [self pageForPoint: center nearest: YES];
  552. if (page == nil) {
  553. // Get center of the current page
  554. page = [self currentPage];
  555. NSPoint point = [self KMCpdfCenterPoint:[page boundsForBox:[self displayBox]]];
  556. center = [self convertPoint:point fromPage:page];
  557. }
  558. }
  559. CGFloat defaultWidth = 360;
  560. CGFloat defaultHeight = 90;
  561. CGFloat scaleS = MIN(defaultWidth/image.size.width, defaultHeight/image.size.height);
  562. NSSize defaultSize = CGSizeMake(image.size.width * scaleS, image.size.height * scaleS);
  563. // Convert to "page space".
  564. // center = [self KMCpdfIntegralPoint:[self convertPoint:center toPage:page]];
  565. // bounds = [self KMCpdfRectFromCenterAndSize:center size:defaultSize];
  566. // Make sure it fits in the page
  567. // bounds = [self KMCpdfConstrainRect:bounds boundary:[page boundsForBox:[self displayBox]]];
  568. if (page != nil) {
  569. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  570. NSRect pageBounds = [page boundsForBox:CPDFDisplayMediaBox];
  571. // new note added by note tool mode, don't add actual zero sized notes
  572. if (isInitial)
  573. bounds = [self KMCRectFromCenterAndSquareSizeWith:bounds.origin size:8.0];
  574. if(!CGPointEqualToPoint(self.lastAddAnnotationPoint, CGPointZero)) {
  575. bounds.origin.x = self.lastAddAnnotationPoint.x + 3.0;
  576. bounds.origin.y = self.lastAddAnnotationPoint.y - 3.0;
  577. CGFloat pageWidth = pageBounds.size.width;
  578. if (bounds.origin.x + bounds.size.width >pageWidth) {
  579. bounds.origin.x = pageWidth - bounds.size.width;
  580. }
  581. if (bounds.origin.y - bounds.size.height < 0) {
  582. bounds.origin.y = bounds.size.height;
  583. }
  584. }
  585. self.lastAddAnnotationPoint = bounds.origin;
  586. CPDFStampAnnotation *newAnnotation = [[CPDFStampAnnotation alloc]initWithDocument:self.document image:image];
  587. newAnnotation.bounds = CGRectMake(center.x, center.y, defaultSize.width, defaultSize.height);
  588. [newAnnotation registerUserName];
  589. [self addAnnotation:newAnnotation toPage:page];
  590. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  591. [self.activeAnnotations removeAllObjects];
  592. [self.activeAnnotations addObject:newAnnotation];
  593. }
  594. else NSBeep();
  595. }
  596. - (NSRect)KMCRectFromCenterAndSquareSizeWith: (NSPoint)center size:(CGFloat)size{
  597. NSRect rect = NSZeroRect;
  598. rect.origin.x = center.x - 0.5 * size;
  599. rect.origin.y = center.y - 0.5 * size;
  600. rect.size.width = size;
  601. rect.size.height = size;
  602. return rect;
  603. }
  604. - (NSRect)KMCpdfRectFromCenterAndSize: (NSPoint)center size: (NSSize)size{
  605. NSRect rect = NSZeroRect;
  606. rect.origin.x = center.x - 0.5 * size.width;
  607. rect.origin.y = center.y - 0.5 * size.height;
  608. rect.size = size;
  609. return rect;
  610. }
  611. - (NSPoint)KMCpdfCenterPoint:(NSRect)rect{
  612. return NSMakePoint(NSMidX(rect), NSMidY(rect));
  613. }
  614. - (NSPoint)KMCpdfIntegralPoint:(NSPoint)point{
  615. return NSMakePoint(round(point.x), round(point.y));
  616. }
  617. - (NSRect)KMCpdfConstrainRect:(NSRect)rect boundary: (NSRect)boundary{
  618. NSRect newRect = rect;
  619. if (NSWidth(rect) > NSWidth(boundary)){
  620. newRect.size.width = NSWidth(boundary);
  621. }
  622. if (NSHeight(rect) > NSHeight(boundary)){
  623. newRect.size.height = NSHeight(boundary);
  624. }
  625. if (NSMinX(rect) < NSMinX(boundary)){
  626. newRect.origin.x = NSMinX(boundary);
  627. }else if (NSMaxX(rect) > NSMaxX(boundary)){
  628. newRect.origin.x = NSMaxX(boundary) - NSWidth(rect);
  629. }
  630. if (NSMinY(rect) < NSMinY(boundary)){
  631. newRect.origin.y = NSMinY(boundary);
  632. }else if (NSMaxY(rect) > NSMaxY(boundary)){
  633. newRect.origin.y = NSMaxY(boundary) - NSHeight(rect);
  634. }
  635. return newRect;
  636. }
  637. #pragma mark - Public
  638. - (CPDFAnnotation *)addAnnotationWithType:(CAnnotationType)annotationType selection:(CPDFSelection *)selection page:(CPDFPage *)page bounds:(NSRect)bounds {
  639. CPDFAnnotation *annotation = nil;
  640. NSString *text = [selection PDFListViewCleanedString];
  641. if([CPDFListView isMarkupAnnotationType:annotationType]) {
  642. if(selection){
  643. annotation = [self addPDFSelection:selection annotationTyoe:annotationType];
  644. [annotation setContents:text?:@""];
  645. } else NSBeep();
  646. } else {
  647. BOOL isInitial = NO;
  648. if(selection) {
  649. CGRect noteRect = selection.bounds;
  650. isInitial = NSEqualSizes(noteRect.size, NSZeroSize);
  651. } else {
  652. isInitial = NSEqualSizes(bounds.size, NSZeroSize);
  653. }
  654. CPDFAnnotationModel *annotationModel = [[CPDFAnnotationModel alloc]initWithAnnotationType:annotationType];
  655. CGSize size = CGSizeMake(annotationModel.noteWidth, annotationModel.noteHeight);
  656. if(annotationType == CAnnotationTypeAnchored)
  657. bounds = CGRectMake(bounds.origin.x, bounds.origin.y, size.width, size.height);
  658. if (annotationType == CAnnotationTypeCircle || annotationType == CAnnotationTypeSquare || annotationType == CAnnotationTypeLine || annotationType == CAnnotationTypeArrow || annotationType == CAnnotationTypeAnchored) {
  659. bounds = KMConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  660. }
  661. if (isInitial)
  662. bounds = annotationType == CAnnotationTypeAnchored ? CPDFListViewRectFromCenterAndSize(bounds.origin, size) : CPDFListViewRectFromCenterAndSquareSize(bounds.origin, MIN_NOTE_SIZE);
  663. switch (annotationType) {
  664. case CAnnotationTypeFreeText:
  665. annotation = [[CPDFFreeTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  666. annotation.bounds = bounds;
  667. break;
  668. case CAnnotationTypeAnchored:
  669. annotation = [[CPDFTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  670. annotation.bounds = bounds;
  671. break;
  672. case CAnnotationTypeCircle:
  673. annotation = [[CPDFCircleAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  674. annotation.bounds = bounds;
  675. break;
  676. case CAnnotationTypeSquare:
  677. annotation = [[CPDFSquareAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  678. annotation.bounds = bounds;
  679. break;
  680. case CAnnotationTypeMeasureSquare:
  681. annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeSquare];
  682. [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
  683. annotation.bounds = bounds;
  684. break;
  685. case CAnnotationTypeLine:
  686. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeLine];
  687. [(CPDFLineAnnotation *)annotation setStartLineStyle:CPDFLineStyleNone];
  688. [(CPDFLineAnnotation *)annotation setEndLineStyle:CPDFLineStyleNone];
  689. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  690. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  691. break;
  692. case CAnnotationTypeMeasureLine:
  693. annotation = [[CPDFLineAnnotation alloc] initWithPDFListViewMeasureWith:self.document];
  694. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  695. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  696. case CAnnotationTypeArrow: {
  697. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeArrow];
  698. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  699. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  700. }
  701. break;
  702. case CAnnotationTypeLink:
  703. annotation = [[CPDFLinkAnnotation alloc] initWithPDFListViewNoteWith:self.document page:page];
  704. annotation.bounds = bounds;
  705. break;
  706. case CAnnotationTypeTextField:
  707. annotation = [[CPDFTextWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  708. annotation.bounds = bounds;
  709. break;
  710. case CAnnotationTypeCheckBox:
  711. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetCheckBoxControl];
  712. break;
  713. case CAnnotationTypeRadioButton:
  714. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetRadioButtonControl];
  715. break;
  716. case CAnnotationTypeListMenu:
  717. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:YES];
  718. break;
  719. case CAnnotationTypeComboBox:
  720. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:NO];
  721. break;
  722. case CAnnotationTypeSignature:
  723. annotation = [[CPDFSignatureWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  724. annotation.bounds = bounds;
  725. break;
  726. case CAnnotationTypeActionButton:
  727. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetPushButtonControl];
  728. break;
  729. case CAnnotationTypeSignFalse:
  730. case CAnnotationTypeSignTure:
  731. case CAnnotationTypeSignCircle:
  732. case CAnnotationTypeSignLine:
  733. case CAnnotationTypeSignDot:
  734. annotation = [[CSelfSignAnnotation alloc]initPDFListViewNoteWithDocument:self.document type:self.annotationType];
  735. annotation.bounds = bounds;
  736. [(CSelfSignAnnotation *)annotation updateAppearanceStream];
  737. break;
  738. case CAnnotationTypeSignText:
  739. case CAnnotationTypeSignConfig:
  740. case CAnnotationTypeSignDate:
  741. annotation = [[CSelfSignAnnotationFreeText alloc]initPDFListViewNoteWithDocument:self.document subType:self.annotationType string:@"" bounds:bounds];
  742. break;
  743. case CAnnotationTypeRedact:
  744. annotation = [self addRedactPDFSelection:selection];
  745. break;
  746. case CAnnotationTypeMeasurePolyLine:
  747. annotation = [[CPDFPolylineAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeMeasurePolyLine];
  748. annotation.bounds = bounds;
  749. break;
  750. case CAnnotationTypeMeasurePolyGon:
  751. annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeMeasurePolyGon];
  752. [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
  753. annotation.bounds = bounds;
  754. break;
  755. default:
  756. break;
  757. }
  758. }
  759. if (annotation) {
  760. if (annotationType != CAnnotationTypeLine && annotationType != CAnnotationTypeArrow && annotationType != CAnnotationTypeInk && [text length] > 0)
  761. [annotation setString:text];
  762. [self addAnnotation:annotation toPage:page];
  763. if ([annotation isKindOfClass:[CPDFMarkupAnnotation class]]) {
  764. [self updateActiveAnnotations:@[annotation]];
  765. }
  766. }
  767. return annotation;
  768. }
  769. - (void)drawAnnotation:(CPDFAnnotation *)annotation toContext:(CGContextRef)context {
  770. [super drawAnnotation:annotation toContext:context];
  771. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListView:needDrawAnnotation:)]) {
  772. if ([self.pdfListViewDelegate PDFListView:self needDrawAnnotation:annotation] == false) {
  773. return;
  774. }
  775. }
  776. if (CFormToolMode == _toolMode &&
  777. [annotation isKindOfClass:[CPDFWidgetAnnotation class]] && self.showFormFieldName && !annotation.isHidden) {
  778. CPDFWidgetAnnotation *annotationWidget = (CPDFWidgetAnnotation*)annotation;
  779. NSString *fieldName = annotationWidget.fieldName;
  780. if(self.showHopnumber) {
  781. NSInteger hopNumen = annotationWidget.widgetHopNumber;
  782. if(fieldName) {
  783. fieldName = [NSString stringWithFormat:@"%ld %@",hopNumen,fieldName];
  784. } else {
  785. fieldName = [NSString stringWithFormat:@"%ld",hopNumen];
  786. }
  787. }
  788. if (fieldName.length > 0) {
  789. CGContextSaveGState(context);
  790. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  791. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  792. paragraphStyle.alignment = NSTextAlignmentLeft;
  793. NSColor *backgroundColor = [NSColor blackColor];
  794. if ([self.activeAnnotations containsObject:annotation]) {
  795. backgroundColor = [NSColor colorWithRed:82.0/255.0 green:102.0/255.0 blue:204.0/255.0 alpha:1.0];
  796. }
  797. if([CPDFKitConfig sharedInstance].isShowFormRequiredFlagColor)
  798. backgroundColor = [CPDFKitConfig sharedInstance].formRequiredFlagColor?:[NSColor redColor];
  799. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  800. NSForegroundColorAttributeName : [NSColor whiteColor],
  801. NSBackgroundColorAttributeName : backgroundColor,
  802. NSParagraphStyleAttributeName : paragraphStyle};
  803. NSString* drawString = fieldName;
  804. drawString = [drawString getMaxStringWithBounds:annotationWidget.bounds attributes:attributes];
  805. CGSize size = [drawString sizeWithAttributes:attributes];
  806. CGRect drawRect = annotationWidget.bounds;
  807. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  808. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  809. drawRect.size.height = size.height;
  810. drawRect.size.width = size.width;
  811. [NSGraphicsContext saveGraphicsState];
  812. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
  813. [drawString drawInRect:drawRect withAttributes:attributes];
  814. [NSGraphicsContext restoreGraphicsState];
  815. CGContextRestoreGState(context);
  816. NSRect rect = [self integralRect:[annotationWidget bounds] onPage:[annotationWidget page]];
  817. CGFloat lineWidth = [self unitWidthOnPage:[annotationWidget page]];
  818. CGContextSaveGState(context);
  819. CGColorRef color = [NSColor blackColor].CGColor;
  820. CGContextSetStrokeColorWithColor(context, color);
  821. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  822. }
  823. } else if(CNoteToolMode== _toolMode && _annotationType == CAnnotationTypeLink && [annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  824. CGContextSaveGState(context);
  825. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  826. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  827. paragraphStyle.alignment = NSTextAlignmentLeft;
  828. NSColor *backgroundColor = [NSColor clearColor];
  829. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  830. NSForegroundColorAttributeName : [NSColor whiteColor],
  831. NSBackgroundColorAttributeName : backgroundColor,
  832. NSParagraphStyleAttributeName : paragraphStyle};
  833. NSString *drawString = NSLocalizedString(@"No Destination", nil);
  834. CPDFDestination *destination = [(CPDFLinkAnnotation *)annotation destination];
  835. if(destination) {
  836. CPDFPage *page = destination.page;
  837. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  838. if(destination.page) {
  839. NSUInteger index = [self.document indexForPage:page] + 1;
  840. drawString = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"to Page",nil),@(index)];
  841. } else if(url.length > 0) {
  842. drawString = url;
  843. }
  844. }else{
  845. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  846. if(url.length > 0) {
  847. drawString = url;
  848. }
  849. }
  850. drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
  851. drawString = @"";
  852. CGSize size = [drawString sizeWithAttributes:attributes];
  853. CGRect drawRect = annotation.bounds;
  854. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  855. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  856. drawRect.size.height = size.height;
  857. drawRect.size.width = size.width;
  858. CGContextSaveGState(context);
  859. CGContextSetFillColorWithColor(context, [NSColor colorWithRed:48.0/255.0 green:145.0/255.0 blue:255.0/255.0 alpha:0.14].CGColor);
  860. CGContextFillRect(context,annotation.bounds);
  861. CGContextRestoreGState(context);
  862. [NSGraphicsContext saveGraphicsState];
  863. CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
  864. float fontSize = 9;
  865. NSColor *textColor = [NSColor whiteColor];
  866. CTTextAlignment alignMent = kCTTextAlignmentCenter;
  867. CFStringRef stringRef = (__bridge CFStringRef)drawString;
  868. NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
  869. NSInteger _stringLength=[drawString length];
  870. CTTextAlignment theAlignment = alignMent;
  871. CTParagraphStyleSetting theSettings[1] =
  872. {
  873. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
  874. }
  875. };
  876. CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
  877. [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
  878. [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
  879. [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
  880. CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
  881. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  882. CGMutablePathRef framePath = CGPathCreateMutable();
  883. CGPathAddRect(framePath, NULL, frameRect);
  884. CFRange currentRange = CFRangeMake(0, 0);
  885. CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
  886. CGPathRelease(framePath);
  887. CTFrameDraw(frameRef, context);
  888. CFRelease(frameRef);
  889. CFRelease(framesetter);
  890. [NSGraphicsContext restoreGraphicsState];
  891. CGContextRestoreGState(context);
  892. }
  893. }
  894. - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
  895. if (CAnnotationTypeStamp == self.annotationType ||
  896. CAnnotationTypeSignSignature == self.annotationType) {
  897. self.stampObject = stampObject;
  898. self.isStampModel = isToolModel;
  899. [NSCursor clearStampCursor];
  900. }
  901. }
  902. - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
  903. NSRect bounds = NSZeroRect;
  904. CPDFSelection *selection = [self currentSelection];
  905. CGFloat defaultWidth = 360;
  906. CGFloat defaultHeight = 90;
  907. NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
  908. bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
  909. // Make sure it fits in the page
  910. bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
  911. // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  912. if (page != nil) {
  913. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  914. // new note added by note tool mode, don't add actual zero sized notes
  915. if (isInitial)
  916. bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
  917. CGFloat borderDefaultWidth = image.size.width;
  918. CGFloat borderScale = borderDefaultWidth/image.size.height;
  919. if (bounds.size.width/bounds.size.height > borderScale) {
  920. bounds.size.height = bounds.size.height;
  921. bounds.size.width = bounds.size.height*borderScale;
  922. } else {
  923. bounds.size.width = bounds.size.width;
  924. bounds.size.height = bounds.size.width/borderScale;
  925. }
  926. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  927. newAnnotation.bounds = bounds;
  928. [newAnnotation setBorderBoundsWithImage:image];
  929. [self addAnnotation:newAnnotation toPage:page];
  930. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  931. [self updateActiveAnnotations:@[newAnnotation]];
  932. [self setNeedsDisplayAnnotation:newAnnotation];
  933. }
  934. else NSBeep();
  935. }
  936. - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  937. [self refreshActiveAnnotations:activeAnnotations isRight:YES];
  938. }
  939. - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  940. [self refreshActiveAnnotations:activeAnnotations isRight:NO];
  941. }
  942. -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
  943. // for (CPDFAnnotation *annotation in self.activeAnnotations) {
  944. // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  945. // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
  946. // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
  947. // } else {
  948. // [self removeAnnotation:linkAnnotation];
  949. // }
  950. // }
  951. // }
  952. if(activeAnnotations) {
  953. NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
  954. BOOL isSame = NO;
  955. if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
  956. if(!isSame) {
  957. self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
  958. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  959. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  960. dispatch_async(dispatch_get_main_queue(), ^{
  961. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  962. });
  963. }
  964. } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
  965. [self.activeAnnotations removeAllObjects];
  966. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  967. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  968. dispatch_async(dispatch_get_main_queue(), ^{
  969. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  970. });
  971. }
  972. }
  973. - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  974. BOOL isContains = YES;
  975. for (CPDFAnnotation *annotation in activeAnnotations) {
  976. if(![self.activeAnnotations containsObject:annotation]) {
  977. [self.activeAnnotations addObject:annotation];
  978. isContains = NO;
  979. }
  980. }
  981. if(!isContains) {
  982. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  983. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  984. dispatch_async(dispatch_get_main_queue(), ^{
  985. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  986. });
  987. }
  988. }
  989. - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
  990. BOOL isContains = NO;
  991. NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
  992. [tarr removeObjectsInArray:removeAnnotations];
  993. self.activeAnnotations = tarr;
  994. isContains = YES;
  995. if(isContains) {
  996. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  997. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  998. dispatch_async(dispatch_get_main_queue(), ^{
  999. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  1000. });
  1001. }
  1002. }
  1003. - (void)editAnnotation:(CPDFAnnotation *)annotation {
  1004. if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  1005. [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
  1006. [[self window] makeFirstResponder:self];
  1007. [self setNeedsDisplayAnnotation:annotation];
  1008. } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] || [annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  1009. [self editFormAnnotation:self.activeAnnotation];
  1010. } else {
  1011. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
  1012. [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
  1013. } else {
  1014. [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
  1015. if (!self.popOver) {
  1016. _popOver = [[NSPopover alloc] init];
  1017. }
  1018. if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  1019. __block typeof(self) blockSelf = self;
  1020. _popOver.delegate = self;
  1021. CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
  1022. vc.pdflistView = self;
  1023. _popOver.contentViewController = vc;
  1024. vc.closeCallBack = ^{
  1025. [blockSelf.popOver close];
  1026. };
  1027. NSBox *box = (NSBox *)vc.view;
  1028. NSView *popoverView = [[[self.popOver contentViewController] view] superview];
  1029. [popoverView setWantsLayer:YES];
  1030. vc.changeColorCallBack = ^{
  1031. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  1032. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  1033. [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
  1034. };
  1035. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  1036. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  1037. _popOver.animates = YES;
  1038. _popOver.behavior = NSPopoverBehaviorTransient;
  1039. [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
  1040. }
  1041. }
  1042. }
  1043. }
  1044. - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
  1045. if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
  1046. CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
  1047. NSInteger rotation = stampAnnotation.rotation;
  1048. rotation = rotation - angle;
  1049. if (rotation < 0) {
  1050. rotation += 360;
  1051. } else if (rotation >= 360) {
  1052. rotation-=360;
  1053. }
  1054. [annotation setRotation:rotation];
  1055. rotation = [annotation appearanceStreamRotation];
  1056. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  1057. [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
  1058. }
  1059. }
  1060. - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
  1061. if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
  1062. CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
  1063. NSInteger rotation = signatureAnnotation.rotation;
  1064. rotation = rotation - angle;
  1065. if (rotation < 0) {
  1066. rotation += 360;
  1067. } else if (rotation >= 360) {
  1068. rotation-=360;
  1069. }
  1070. [signatureAnnotation setRotation:rotation];
  1071. rotation = [signatureAnnotation appearanceStreamRotation];
  1072. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  1073. [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
  1074. }
  1075. }
  1076. - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  1077. [self addAnnotation:annotation toPage:page];
  1078. }
  1079. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  1080. if (annotation == nil) {
  1081. return;
  1082. }
  1083. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  1084. [annotation setModificationDate:[NSDate date]];
  1085. //widget设置作者与fieldName冲突
  1086. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
  1087. [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
  1088. }
  1089. [page addAnnotation:annotation];
  1090. [self setNeedsDisplayAnnotation:annotation];
  1091. [self updateHighLightAnnotation:annotation];
  1092. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  1093. dispatch_async(dispatch_get_main_queue(), ^{
  1094. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
  1095. });
  1096. [self resetPDFToolTipRectsForAfterDelay];
  1097. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
  1098. [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
  1099. }
  1100. - (void)removeAnnotation:(CPDFAnnotation *)annotation {
  1101. if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
  1102. // if (annotation.contents.length <= 0) {
  1103. CPDFAnnotation *wasAnnotation = annotation;
  1104. CPDFPage *page = wasAnnotation.page;
  1105. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  1106. [page removeAnnotation:wasAnnotation];
  1107. [self annotationsChangedOnPage:page];
  1108. [self setNeedsDisplayAnnotation:wasAnnotation];
  1109. dispatch_async(dispatch_get_main_queue(), ^{
  1110. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  1111. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  1112. });
  1113. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1114. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1115. // }
  1116. } else {
  1117. CPDFAnnotation *wasAnnotation = annotation;
  1118. CPDFPage *page = wasAnnotation.page;
  1119. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  1120. if ([wasAnnotation isNote]) {
  1121. [self resetPDFToolTipRectsForAfterDelay];
  1122. }
  1123. [page removeAnnotation:wasAnnotation];
  1124. [self annotationsChangedOnPage:page];
  1125. [self setNeedsDisplayAnnotation:wasAnnotation];
  1126. [self updateHighLightAnnotation:annotation];
  1127. dispatch_async(dispatch_get_main_queue(), ^{
  1128. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  1129. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  1130. });
  1131. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1132. if (annotation) {
  1133. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1134. }
  1135. }
  1136. }
  1137. - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
  1138. [super drawPage:pdfPage toContext:context];
  1139. [self drawSelectionForPage:pdfPage inContext:context];
  1140. NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
  1141. NSMutableArray *currentPageAnnotations = [NSMutableArray array];
  1142. for (CPDFAnnotation *an in self.activeAnnotations) {
  1143. if([an.page isEqual:pdfPage]) {
  1144. //多选注释框去除mark注释与便签注释
  1145. if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
  1146. [currentActiveAnnotations addObject:an];
  1147. }
  1148. [currentPageAnnotations addObject:an];
  1149. }
  1150. }
  1151. if(currentActiveAnnotations.count > 1) {
  1152. NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
  1153. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  1154. CGContextSaveGState(context);
  1155. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  1156. CGContextSetStrokeColorWithColor(context, color);
  1157. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  1158. CGContextRestoreGState(context);
  1159. CGContextSaveGState(context);
  1160. [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
  1161. CGContextRestoreGState(context);
  1162. }
  1163. if(self.multiplAnnotationObject &&
  1164. !CGRectIsEmpty(self.multiplAnnotationObject.drawRect) &&
  1165. self.multiplAnnotationObject.page == pdfPage) {
  1166. CGRect selectAnnotationBounds = self.multiplAnnotationObject.drawRect;
  1167. NSRect rect = selectAnnotationBounds;
  1168. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  1169. CGContextSaveGState(context);
  1170. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  1171. CGContextSetStrokeColorWithColor(context, color);
  1172. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  1173. CGContextRestoreGState(context);
  1174. }
  1175. [currentPageAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  1176. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  1177. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  1178. }
  1179. }];
  1180. [self.selectAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  1181. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  1182. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  1183. }
  1184. }];
  1185. if (self.hoverAnnotation.page && [self.hoverAnnotation.page isEqual:pdfPage] && ![self.activeAnnotations containsObject:self.hoverAnnotation]) {
  1186. [self.hoverAnnotation drawSelectionHighlightForView:self inContext:context isHover:YES];
  1187. }
  1188. if(!CGRectEqualToRect(self.multiplSelectBounds, CGRectZero) && [self.multiplSelectPage isEqual:pdfPage]) {
  1189. @synchronized (self) {
  1190. CGContextSetLineCap(context, kCGLineCapRound);
  1191. CGContextSetLineWidth(context, 1.0);
  1192. CGContextSetStrokeColorWithColor(context, [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor);
  1193. CGContextBeginPath(context);
  1194. CGContextMoveToPoint(context, self.multiplSelectBounds.origin.x, self.multiplSelectBounds.origin.y);
  1195. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x+ self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y);
  1196. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x + self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y + self.multiplSelectBounds.size.height);
  1197. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x,self.multiplSelectBounds.origin.y + self.multiplSelectBounds.size.height);
  1198. CGContextClosePath(context);
  1199. CGFloat lengths[] = {5,5};
  1200. CGContextSetLineDash(context, 0, lengths,2);
  1201. CGContextStrokePath(context);
  1202. }
  1203. }
  1204. }
  1205. - (void)drawSelectionForPage:(CPDFPage *)pdfPage inContext:(CGContextRef)context {
  1206. NSRect rect;
  1207. NSUInteger pageIndex;
  1208. @synchronized (self) {
  1209. pageIndex = self.selectionPageIndex;
  1210. rect = self.selectionRect;
  1211. }
  1212. if (pageIndex != NSNotFound) {
  1213. BOOL isWidget = NO;
  1214. for (CPDFAnnotation * annotation in self.activeAnnotations) {
  1215. if ([annotation isForm]) {
  1216. isWidget = YES;
  1217. break;
  1218. }
  1219. }
  1220. if (isWidget &&
  1221. _toolMode != CFormToolMode) {
  1222. return;
  1223. }
  1224. NSRect bounds = [pdfPage boundsForBox:[self displayBox]];
  1225. CGFloat radius = HANDLE_SIZE * [self unitWidthOnPage:pdfPage];
  1226. CGColorRef color = CGColorCreateGenericGray(0.0, 0.6);
  1227. CGContextSetFillColorWithColor(context, color);
  1228. CGColorRelease(color);
  1229. CGContextBeginPath(context);
  1230. CGContextAddRect(context, NSRectToCGRect(bounds));
  1231. CGContextAddRect(context, NSRectToCGRect(rect));
  1232. CGContextEOFillPath(context);
  1233. if ([pdfPage pageIndex] != pageIndex) {
  1234. color = CGColorCreateGenericGray(0.0, 0.3);
  1235. CGContextSetFillColorWithColor(context, color);
  1236. CGColorRelease(color);
  1237. CGContextFillRect(context, NSRectToCGRect(rect));
  1238. }
  1239. [CPDFListView DrawResizeHandles:context rect:rect radius:radius active:true];
  1240. CGColorRef borderColor = CGColorCreateGenericRGB(48.0/255.0, 145.0/255.0, 255.0/255.0, 1.0);
  1241. CGContextSetStrokeColorWithColor(context, borderColor);
  1242. CPDFListViewOCDrawLineHandles(context, rect, 4.0 / 2);
  1243. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), 1.0);
  1244. }
  1245. }
  1246. - (void)removeShapeLayer {
  1247. if (![self.shapeLayerTopH isEqual:nil] && ![self.shapeLayerBottomH isEqual:nil] && ![self.shapeLayerLeftV isEqual:nil] && ![self.shapeLayerRightV isEqual:nil]) {
  1248. [self.shapeLayerTopH removeFromSuperlayer];
  1249. [self.shapeLayerBottomH removeFromSuperlayer];
  1250. [self.shapeLayerLeftV removeFromSuperlayer];
  1251. [self.shapeLayerRightV removeFromSuperlayer];
  1252. self.shapeLayerTopH = nil;
  1253. self.shapeLayerBottomH = nil;
  1254. self.shapeLayerLeftV = nil;
  1255. self.shapeLayerRightV = nil;
  1256. }
  1257. }
  1258. - (BOOL)consistentTypeWithAnnotation:(CPDFAnnotation *)annotation {
  1259. if([CPDFListView isMarkupAnnotationType:self.annotationType]) {
  1260. if (![annotation isKindOfClass:[CPDFMarkupAnnotation class]])
  1261. return NO;
  1262. } else if (CAnnotationTypeLink == self.annotationType) {
  1263. if (![annotation isKindOfClass:[CPDFLinkAnnotation class]])
  1264. return NO;
  1265. } else {
  1266. if(CFormToolMode == self.toolMode) {
  1267. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]])
  1268. return NO;
  1269. } else if(CRedactToolMode == self.toolMode) {
  1270. if(![annotation isKindOfClass:[CPDFRedactAnnotation class]])
  1271. return NO;
  1272. }
  1273. if ([annotation isForm]) {
  1274. if (self.toolMode != CFormToolMode)
  1275. return NO;
  1276. }
  1277. }
  1278. return YES;
  1279. }
  1280. - (void)enterPresentationDrawMode {
  1281. self.presentationDrawView.hidden = NO;
  1282. [self.presentationDrawView clear];
  1283. [_presentationDrawView resetUndoManager];
  1284. }
  1285. - (BOOL)isEnterPresentationDrawMode {
  1286. return !self.presentationDrawView.isHidden;
  1287. }
  1288. - (void)changePresentationDrawModelColor:(NSColor *)color {
  1289. _presentationDrawView.renderColor = color;
  1290. }
  1291. - (void)resetPresentationDrawMode {
  1292. [_presentationDrawView clear];
  1293. [_presentationDrawView resetUndoManager];
  1294. }
  1295. - (void)exitPresentationDrawMode {
  1296. self.presentationDrawView.hidden = YES;
  1297. }
  1298. #pragma mark Zooming
  1299. - (void)zoomToRect:(NSRect)rect onPage:(CPDFPage *)page {
  1300. if (NSIsEmptyRect(rect) == NO) {
  1301. BOOL isLegacy = [NSScroller respondsToSelector:@selector(preferredScrollerStyle)] == NO || [NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy;
  1302. NSRect bounds = [self bounds];
  1303. CGFloat scale = 1.0;
  1304. if (isLegacy) {
  1305. bounds.size.width -= [NSScroller scrollerWidth];
  1306. bounds.size.height -= [NSScroller scrollerWidth];
  1307. }
  1308. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1309. scale = NSHeight(bounds) / NSHeight(rect);
  1310. else
  1311. scale = NSWidth(bounds) / NSWidth(rect);
  1312. [self setScaleFactor:scale];
  1313. NSScrollView *scrollView = [self scrollView];
  1314. if (isLegacy && ([scrollView hasHorizontalScroller] == NO || [scrollView hasVerticalScroller] == NO)) {
  1315. if ([scrollView hasVerticalScroller])
  1316. bounds.size.width -= [NSScroller scrollerWidth];
  1317. if ([scrollView hasHorizontalScroller])
  1318. bounds.size.height -= [NSScroller scrollerWidth];
  1319. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1320. scale = NSHeight(bounds) / NSHeight(rect);
  1321. else
  1322. scale = NSWidth(bounds) / NSWidth(rect);
  1323. [self setScaleFactor:scale];
  1324. }
  1325. [self goToRect:rect onPage:page];
  1326. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1327. CGPoint tPagePoint = CGPointMake(rect.origin.x, rect.origin.y+rect.size.height);
  1328. [self goToTargetPoint:tPagePoint onPage:page atScrollPosition:CScrollPositionTop];
  1329. });
  1330. }
  1331. }
  1332. #pragma mark NSDraggingDestination protocol
  1333. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  1334. NSArray *supportArray = [NSArray arrayWithObjects:@"jpg",@"cur",@"bmp",@"jpeg",@"gif",@"png",@"tiff",@"tif",/*@"pic",*/@"ico",@"icns",@"tga",@"psd",@"eps",@"hdr",@"jp2",@"jpc",@"pict",@"sgi",@"pdf", nil];
  1335. NSPasteboard *pasteboard = [sender draggingPasteboard];
  1336. if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]) {
  1337. NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  1338. NSString *filePath = fileNames.firstObject;
  1339. if (fileNames.count == 1 && [supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
  1340. return NSDragOperationCopy;
  1341. }
  1342. }
  1343. return NSDragOperationNone;
  1344. }
  1345. - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender {
  1346. NSDragOperation dragOp = NSDragOperationNone;
  1347. NSPasteboard *pboard = [sender draggingPasteboard];
  1348. if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
  1349. NSPoint location = [self convertPoint:[sender draggingLocation] fromView:nil];
  1350. CPDFPage *page = [self pageForPoint:location nearest:NO];
  1351. if (page) {
  1352. NSArray *annotations = [page annotations];
  1353. CPDFAnnotation *annotation = nil;
  1354. NSInteger i = [annotations count];
  1355. location = [self convertPoint:location toPage:page];
  1356. while (i-- > 0) {
  1357. annotation = [annotations objectAtIndex:i];
  1358. if ([self annoHitTest:location Anno:annotation] &&
  1359. ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, nil]] || [annotation hasBorder])) {
  1360. // if ([annotation isEqual:highlightAnnotation] == NO) {
  1361. // if (highlightAnnotation)
  1362. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1363. // [self setHighlightAnnotation:annotation];
  1364. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1365. // }
  1366. dragOp = NSDragOperationGeneric;
  1367. break;
  1368. }
  1369. }
  1370. }
  1371. if (dragOp == NSDragOperationNone /*&& highlightAnnotation*/) {
  1372. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1373. // [self setHighlightAnnotation:nil];
  1374. }
  1375. } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
  1376. dragOp = [super draggingUpdated:sender];
  1377. }
  1378. return dragOp;
  1379. }
  1380. - (BOOL)annoHitTest:(NSPoint)point Anno: (CPDFAnnotation *)anno{
  1381. return [anno shouldDisplay] ? NSPointInRect(point, [self bounds]) : NO;
  1382. }
  1383. - (void)draggingExited:(id <NSDraggingInfo>)sender {
  1384. NSPasteboard *pboard = [sender draggingPasteboard];
  1385. if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
  1386. // if (highlightAnnotation) {
  1387. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1388. // [self setHighlightAnnotation:nil];
  1389. // }
  1390. } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
  1391. [super draggingExited:sender];
  1392. }
  1393. }
  1394. - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
  1395. BOOL performedDrag = NO;
  1396. NSPasteboard *pasteboard = [sender draggingPasteboard];
  1397. if ([sender draggingSource] != self) {
  1398. NSArray* filePaths = [pasteboard propertyListForType:NSFilenamesPboardType];
  1399. NSArray *supportArray= [NSArray arrayWithObjects:@"jpg",@"cur",@"bmp",@"jpeg",@"gif",@"png",@"tiff",@"tif",/*@"pic",*/@"ico",@"icns",@"tga",@"psd",@"eps",@"hdr",@"jp2",@"jpc",@"pict",@"sgi",@"pdf", nil];
  1400. NSString *filePath = filePaths.firstObject;
  1401. if ([supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
  1402. if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  1403. [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1404. return NO;
  1405. }
  1406. if([[filePath.pathExtension lowercaseString] isEqual:@"pdf"]) {
  1407. PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:filePath]];
  1408. if([document isLocked]) {
  1409. return NO;
  1410. }
  1411. }
  1412. NSImage *image = [[NSImage alloc] initWithContentsOfFile:filePath];
  1413. NSPoint point = [sender draggingLocation];
  1414. point = [self convertPoint:point fromView:nil];
  1415. CPDFPage *page = [self pageForPoint:point nearest:YES];
  1416. NSRect rect = NSMakeRect(point.x, point.y - 45, 360, 90);
  1417. NSRect bounds = [self convertRect:rect toPage:page];
  1418. if (page != nil) {
  1419. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  1420. newAnnotation.bounds = bounds;
  1421. [newAnnotation setBorderBoundsWithImage:image];
  1422. [self addAnnotation:newAnnotation toPage:page];
  1423. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  1424. [self updateActiveAnnotations:@[newAnnotation]];
  1425. [self setNeedsDisplayAnnotation:newAnnotation];
  1426. }
  1427. return YES;
  1428. }
  1429. }
  1430. return NO;
  1431. }
  1432. #pragma mark - NSPopoverDelegate
  1433. - (void)popoverWillClose:(NSNotification *)notification {
  1434. NSPopover *popover = notification.object;
  1435. if([popover.contentViewController isKindOfClass:[CPDFListEditAnnotationViewController class]]) {
  1436. CPDFListEditAnnotationViewController *listEditAnnotationViewController = (CPDFListEditAnnotationViewController *)popover.contentViewController;
  1437. CPDFAnnotation *annotation = listEditAnnotationViewController.annotation;
  1438. NSString *contensString = listEditAnnotationViewController.contentString;
  1439. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  1440. if(contensString && contensString.length > 0) {
  1441. annotation.contents = listEditAnnotationViewController.contentString;
  1442. [self setNeedsDisplayAnnotation:annotation];
  1443. } else {
  1444. if([self.activeAnnotations containsObject:annotation]) {
  1445. [self.activeAnnotations removeObject:annotation];
  1446. }
  1447. [self removeAnnotation:annotation];
  1448. }
  1449. } else {
  1450. annotation.contents = listEditAnnotationViewController.contentString;
  1451. [self setNeedsDisplayAnnotation:annotation];
  1452. }
  1453. }
  1454. self.popOver = nil;
  1455. }
  1456. - (void)handlePageChangedNotification:(NSNotification *)notification {
  1457. if (self.isSinglePageMode || self.isTwoPageMode) {
  1458. [self resetPDFToolTipRectsForAfterDelay];
  1459. }
  1460. self.copyCount = 0;
  1461. }
  1462. #pragma mark - Form Alignment
  1463. - (void)changeAnnotations:(NSArray<CPDFAnnotation *> *)annotations alignmentType:(KMPDFActiveFormsAlignType)type {
  1464. CGRect zeroRect = CGRectNull;
  1465. CGRect highestRect = CGRectZero;
  1466. CGRect widthestRect = CGRectZero;
  1467. CPDFAnnotation *firstAnnotation = annotations.firstObject;
  1468. CGRect leftestRect = firstAnnotation.bounds;
  1469. CGRect rightestRect = firstAnnotation.bounds;
  1470. CGRect topestRect = firstAnnotation.bounds;
  1471. CGRect bottomestRect = firstAnnotation.bounds;
  1472. CPDFAnnotation *leftestAnnotation = firstAnnotation;
  1473. CPDFAnnotation *rightestAnnotation = firstAnnotation;
  1474. CPDFAnnotation *topestAnnotation = firstAnnotation;
  1475. CPDFAnnotation *bottomestAnnotation = firstAnnotation;
  1476. CGFloat totalWidth = 0.;
  1477. CGFloat totalHeight = 0.;
  1478. for (CPDFAnnotation *annotation in annotations) {
  1479. zeroRect = CGRectUnion(zeroRect, annotation.bounds);
  1480. totalWidth += CGRectGetWidth(annotation.bounds);
  1481. totalHeight += CGRectGetHeight(annotation.bounds);
  1482. if (CGRectGetHeight(annotation.bounds) > CGRectGetHeight(highestRect)) {
  1483. highestRect = annotation.bounds;
  1484. }
  1485. if (CGRectGetWidth(annotation.bounds) > CGRectGetWidth(widthestRect)) {
  1486. widthestRect = annotation.bounds;
  1487. }
  1488. if (CGRectGetMinX(leftestRect) > CGRectGetMinX(annotation.bounds)) {
  1489. leftestRect = annotation.bounds;
  1490. leftestAnnotation = annotation;
  1491. }
  1492. if (CGRectGetMaxX(annotation.bounds) > CGRectGetMaxX(rightestRect)) {
  1493. rightestRect = annotation.bounds;
  1494. rightestAnnotation = annotation;
  1495. }
  1496. if (CGRectGetMaxY(annotation.bounds) > CGRectGetMaxY(topestRect)) {
  1497. topestRect = annotation.bounds;
  1498. topestAnnotation = annotation;
  1499. }
  1500. if (CGRectGetMinY(bottomestRect) > CGRectGetMinY(annotation.bounds)) {
  1501. bottomestRect = annotation.bounds;
  1502. bottomestAnnotation = annotation;
  1503. }
  1504. }
  1505. if (type == KMPDFActiveFormsAlignType_Left ) {
  1506. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1507. for (NSInteger i = 0; i< annotations.count; i++) {
  1508. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1509. CGRect bounds = annotation.bounds;
  1510. bounds.origin.x = zeroRect.origin.x;
  1511. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1512. }
  1513. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1514. } else if (type == KMPDFActiveFormsAlignType_Right) {
  1515. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1516. for (NSInteger i = 0; i< annotations.count; i++) {
  1517. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1518. CGRect bounds = annotation.bounds;
  1519. bounds.origin.x = CGRectGetMaxX(zeroRect) - bounds.size.width;
  1520. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1521. }
  1522. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1523. } else if (type == KMPDFActiveFormsAlignType_Top) {
  1524. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1525. for (NSInteger i = 0; i< annotations.count; i++) {
  1526. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1527. CGRect bounds = annotation.bounds;
  1528. bounds.origin.y = CGRectGetMaxY(zeroRect) - bounds.size.height;
  1529. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1530. }
  1531. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1532. } else if (type == KMPDFActiveFormsAlignType_Bottom) {
  1533. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1534. for (NSInteger i = 0; i< annotations.count; i++) {
  1535. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1536. CGRect bounds = annotation.bounds;
  1537. bounds.origin.y = CGRectGetMinY(zeroRect);
  1538. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1539. }
  1540. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1541. } else if (type == KMPDFActiveFormsAlignType_Vertical) {
  1542. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1543. for (NSInteger i = 0; i< annotations.count; i++) {
  1544. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1545. CGRect bounds = annotation.bounds;
  1546. bounds.origin.y = CGRectGetMidY(highestRect) - CGRectGetHeight(bounds)/2;
  1547. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1548. }
  1549. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1550. } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
  1551. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1552. for (NSInteger i = 0; i< annotations.count; i++) {
  1553. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1554. CGRect bounds = annotation.bounds;
  1555. bounds.origin.x = CGRectGetMidX(widthestRect) - CGRectGetWidth(bounds)/2;
  1556. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1557. }
  1558. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1559. } else if (type == KMPDFActiveFormsAlignType_DisHorizontally) {
  1560. CGFloat middleGap = CGRectGetWidth(zeroRect) - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1561. CGFloat otherAnnotationsTotalWidth = totalWidth - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1562. CGFloat gap = (middleGap - otherAnnotationsTotalWidth)/(annotations.count - 1);
  1563. NSMutableArray *annotationsCopyArray = [annotations mutableCopy];
  1564. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1565. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1566. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1567. if (annotation1.bounds.origin.x < annotation2.bounds.origin.x) {
  1568. return NSOrderedAscending;
  1569. } else {
  1570. return NSOrderedDescending;
  1571. }
  1572. }];
  1573. [annotationsCopyArray removeObject:leftestAnnotation];
  1574. [annotationsCopyArray removeObject:rightestAnnotation];
  1575. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1576. CGFloat leftStartX = CGRectGetMaxX(leftestRect) + gap;
  1577. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1578. CPDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1579. CGRect bounds = annotation.bounds;
  1580. bounds.origin.x = leftStartX;
  1581. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1582. leftStartX += CGRectGetWidth(bounds) + gap;
  1583. }
  1584. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1585. } else if (type == KMPDFActiveFormsAlignType_DisVertical) {
  1586. CGFloat middleGap = CGRectGetHeight(zeroRect) - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1587. CGFloat otherAnnotationsTotalHeight = totalHeight - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1588. CGFloat gap = (middleGap - otherAnnotationsTotalHeight)/(annotations.count - 1);
  1589. NSMutableArray *annotationsCopyArray = [annotations mutableCopy];
  1590. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1591. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1592. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1593. if (annotation1.bounds.origin.y < annotation2.bounds.origin.y) {
  1594. return NSOrderedAscending;
  1595. } else {
  1596. return NSOrderedDescending;
  1597. }
  1598. }];
  1599. [annotationsCopyArray removeObject:topestAnnotation];
  1600. [annotationsCopyArray removeObject:bottomestAnnotation];
  1601. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1602. CGFloat bottomStartY = CGRectGetMaxY(bottomestRect) + gap;
  1603. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1604. PDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1605. CGRect bounds = annotation.bounds;
  1606. bounds.origin.y = bottomStartY;
  1607. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1608. bottomStartY += CGRectGetHeight(bounds) + gap;
  1609. }
  1610. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1611. }
  1612. }
  1613. - (void)changeAnnotationsAlign:(NSArray *)annotationArray newBounds:(NSArray *)newBoundsArray {
  1614. NSMutableArray * oldBoundsArray = [NSMutableArray array];
  1615. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1616. CPDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1617. [oldBoundsArray addObject:NSStringFromRect(annotation.bounds)];
  1618. annotation.bounds = NSRectFromString([newBoundsArray objectAtIndex:i]);
  1619. }
  1620. [[[self undoManager] prepareWithInvocationTarget:self] changeAnnotationsAlign:annotationArray newBounds:oldBoundsArray];
  1621. [self setNeedsDisplay:YES];
  1622. }
  1623. #pragma mark Services
  1624. - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types {
  1625. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound) {
  1626. NSMutableArray *writeTypes = [NSMutableArray array];
  1627. NSString *pdfType = nil;
  1628. NSData *pdfData = nil;
  1629. NSString *tiffType = nil;
  1630. NSData *tiffData = nil;
  1631. NSRect selRect = NSIntegralRect(_selectionRect);
  1632. // 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
  1633. if ([[self document] allowsPrinting] && [[self document] isLocked] == NO) {
  1634. if ([types containsObject:NSPasteboardTypePDF])
  1635. pdfType = NSPasteboardTypePDF;
  1636. else if ([types containsObject:NSPasteboardTypePDF])
  1637. pdfType = NSPasteboardTypePDF;
  1638. if (pdfType && (pdfData = [[self currentSelectionPage] pdfDataFor:selRect]))
  1639. [writeTypes addObject:pdfType];
  1640. }
  1641. if ([types containsObject:NSPasteboardTypeTIFF])
  1642. tiffType = NSPasteboardTypeTIFF;
  1643. else if ([types containsObject:NSPasteboardTypeTIFF])
  1644. tiffType = NSPasteboardTypeTIFF;
  1645. if (tiffType && (tiffData = [[self currentSelectionPage] PDFListViewTIFFDataFor:selRect]))
  1646. [writeTypes addObject:tiffType];
  1647. if ([writeTypes count] > 0) {
  1648. [pboard declareTypes:writeTypes owner:nil];
  1649. if (pdfData)
  1650. [pboard setData:pdfData forType:pdfType];
  1651. if (tiffData)
  1652. [pboard setData:tiffData forType:tiffType];
  1653. return YES;
  1654. }
  1655. }
  1656. if ([[self currentSelection] hasCharacters]) {
  1657. if ([types containsObject:NSPasteboardTypeRTF] || [types containsObject:NSPasteboardTypeRTF]) {
  1658. [pboard clearContents];
  1659. NSAttributedString *attri = [[self currentSelection] attributedString];
  1660. if (attri != nil) {
  1661. [pboard writeObjects:[NSArray arrayWithObjects:attri, nil]];
  1662. }
  1663. return YES;
  1664. } else if ([types containsObject:NSPasteboardTypeString] || [types containsObject:NSPasteboardTypeString]) {
  1665. [pboard clearContents];
  1666. NSString *str = [[self currentSelection] string];
  1667. if (str != nil) {
  1668. [pboard writeObjects:[NSArray arrayWithObjects:str, nil]];
  1669. }
  1670. return YES;
  1671. }
  1672. }
  1673. return [[CPDFListView superclass] instancesRespondToSelector:_cmd];
  1674. }
  1675. - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType {
  1676. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound && returnType == nil &&
  1677. (([[self document] allowsPrinting] && [[self document] isLocked] == NO && [sendType isEqualToString:NSPasteboardTypePDF]) || [sendType isEqualToString:NSPasteboardTypeTIFF])) {
  1678. return self;
  1679. }
  1680. if ([[self currentSelection] hasCharacters] && returnType == nil && ([sendType isEqualToString:NSPasteboardTypeString] || [sendType isEqualToString:NSPasteboardTypeRTF])) {
  1681. return self;
  1682. }
  1683. return [super validRequestorForSendType:sendType returnType:returnType];
  1684. }
  1685. #pragma mark Notification handling
  1686. - (void)boundsDidChangeNotification:(NSNotification*)notification
  1687. {
  1688. id object = notification.object;
  1689. NSClipView *pdfContentView = self.scrollView.contentView;
  1690. if (object == pdfContentView) {
  1691. if ([self.activeAnnotation isKindOfClass:[KMTableAnnotation class]] && [[(KMTableAnnotation*)self.activeAnnotation scrollView] superview]) {
  1692. [(KMTableAnnotation*)self.activeAnnotation completeEditCellText];
  1693. }
  1694. }
  1695. }
  1696. @end