CPDFListView.m 103 KB

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