CPDFListView.m 91 KB

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