CPDFListView.m 81 KB

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