CPDFListView.m 91 KB

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