CPDFListView.m 98 KB

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