CPDFListView.m 98 KB

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