CPDFListView.m 99 KB

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