CPDFListView.m 93 KB

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