CPDFListView.m 91 KB

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