CPDFListView.m 81 KB

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