CPDFListView.m 87 KB

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