CPDFListView.m 103 KB

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