CPDFListView.m 103 KB

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