CPDFListView.m 88 KB

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