CPDFListView.m 98 KB

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