CPDFListView.m 103 KB

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