CPDFListView.m 88 KB

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