CPDFListView.m 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  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 | NSTrackingInVisibleRect | NSTrackingActiveInKeyWindow | NSTrackingMouseMoved 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 controlType:CPDFWidgetCheckBoxControl];
  593. annotation.bounds = bounds;
  594. break;
  595. case CAnnotationTypeRadioButton:
  596. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document controlType:CPDFWidgetRadioButtonControl];
  597. annotation.bounds = bounds;
  598. break;
  599. case CAnnotationTypeListMenu:
  600. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document listChoice:YES];
  601. annotation.bounds = bounds;
  602. break;
  603. case CAnnotationTypeComboBox:
  604. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document listChoice:NO];
  605. annotation.bounds = bounds;
  606. break;
  607. case CAnnotationTypeSignature:
  608. annotation = [[CPDFSignatureWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  609. annotation.bounds = bounds;
  610. break;
  611. case CAnnotationTypeActionButton:
  612. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document controlType:CPDFWidgetPushButtonControl];
  613. annotation.bounds = bounds;
  614. break;
  615. case CAnnotationTypeSignFalse:
  616. case CAnnotationTypeSignTure:
  617. case CAnnotationTypeSignCircle:
  618. case CAnnotationTypeSignLine:
  619. case CAnnotationTypeSignDot:
  620. annotation = [[CSelfSignAnnotation alloc]initPDFListViewNoteWithDocument:self.document type:self.annotationType];
  621. annotation.bounds = bounds;
  622. [(CSelfSignAnnotation *)annotation updateAppearanceStream];
  623. break;
  624. case CAnnotationTypeSignText:
  625. case CAnnotationTypeSignConfig:
  626. case CAnnotationTypeSignDate:
  627. annotation = [[CSelfSignAnnotationFreeText alloc]initPDFListViewNoteWithDocument:self.document subType:self.annotationType string:@"" bounds:bounds];
  628. break;
  629. case CAnnotationTypeRedact:
  630. annotation = [self addRedactPDFSelection:selection];
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. if (annotation) {
  637. if (annotationType != CAnnotationTypeLine && annotationType != CAnnotationTypeArrow && annotationType != CAnnotationTypeInk && [text length] > 0)
  638. [annotation setString:text];
  639. [self addAnnotation:annotation toPage:page];
  640. if ([annotation isKindOfClass:[CPDFMarkupAnnotation class]]) {
  641. [self updateActiveAnnotations:@[annotation]];
  642. }
  643. }
  644. return annotation;
  645. }
  646. - (void)drawAnnotation:(CPDFAnnotation *)annotation toContext:(CGContextRef)context {
  647. [super drawAnnotation:annotation toContext:context];
  648. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListView:needDrawAnnotation:)]) {
  649. if ([self.pdfListViewDelegate PDFListView:self needDrawAnnotation:annotation] == false) {
  650. return;
  651. }
  652. }
  653. if (CFormToolMode == _toolMode &&
  654. [annotation isKindOfClass:[CPDFWidgetAnnotation class]] && self.showFormFieldName && !annotation.isHidden) {
  655. CPDFWidgetAnnotation *annotationWidget = (CPDFWidgetAnnotation*)annotation;
  656. NSString *fieldName = annotationWidget.fieldName;
  657. if(self.showHopnumber) {
  658. NSInteger hopNumen = annotationWidget.widgetHopNumber;
  659. if(fieldName) {
  660. fieldName = [NSString stringWithFormat:@"%ld %@",hopNumen,fieldName];
  661. } else {
  662. fieldName = [NSString stringWithFormat:@"%ld",hopNumen];
  663. }
  664. }
  665. if (fieldName.length > 0) {
  666. CGContextSaveGState(context);
  667. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  668. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  669. paragraphStyle.alignment = NSTextAlignmentLeft;
  670. NSColor *backgroundColor = [NSColor blackColor];
  671. if ([self.activeAnnotations containsObject:annotation]) {
  672. backgroundColor = [NSColor colorWithRed:82.0/255.0 green:102.0/255.0 blue:204.0/255.0 alpha:1.0];
  673. }
  674. if([CPDFKitConfig sharedInstance].isShowFormRequiredFlagColor)
  675. backgroundColor = [CPDFKitConfig sharedInstance].formRequiredFlagColor?:[NSColor redColor];
  676. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  677. NSForegroundColorAttributeName : [NSColor whiteColor],
  678. NSBackgroundColorAttributeName : backgroundColor,
  679. NSParagraphStyleAttributeName : paragraphStyle};
  680. NSString* drawString = fieldName;
  681. drawString = [drawString getMaxStringWithBounds:annotationWidget.bounds attributes:attributes];
  682. CGSize size = [drawString sizeWithAttributes:attributes];
  683. CGRect drawRect = annotationWidget.bounds;
  684. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  685. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  686. drawRect.size.height = size.height;
  687. drawRect.size.width = size.width;
  688. [NSGraphicsContext saveGraphicsState];
  689. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
  690. [drawString drawInRect:drawRect withAttributes:attributes];
  691. [NSGraphicsContext restoreGraphicsState];
  692. CGContextRestoreGState(context);
  693. NSRect rect = [self integralRect:[annotationWidget bounds] onPage:[annotationWidget page]];
  694. CGFloat lineWidth = [self unitWidthOnPage:[annotationWidget page]];
  695. CGContextSaveGState(context);
  696. CGColorRef color = [NSColor blackColor].CGColor;
  697. CGContextSetStrokeColorWithColor(context, color);
  698. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  699. }
  700. } else if(CNoteToolMode== _toolMode && _annotationType == CAnnotationTypeLink && [annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  701. CGContextSaveGState(context);
  702. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  703. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  704. paragraphStyle.alignment = NSTextAlignmentLeft;
  705. NSColor *backgroundColor = [NSColor clearColor];
  706. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  707. NSForegroundColorAttributeName : [NSColor whiteColor],
  708. NSBackgroundColorAttributeName : backgroundColor,
  709. NSParagraphStyleAttributeName : paragraphStyle};
  710. NSString *drawString = NSLocalizedString(@"No Destination", nil);
  711. CPDFDestination *destination = [(CPDFLinkAnnotation *)annotation destination];
  712. if(destination) {
  713. CPDFPage *page = destination.page;
  714. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  715. if(destination.page) {
  716. NSUInteger index = [self.document indexForPage:page] + 1;
  717. drawString = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"to Page",nil),@(index)];
  718. } else if(url.length > 0) {
  719. drawString = url;
  720. }
  721. }else{
  722. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  723. if(url.length > 0) {
  724. drawString = url;
  725. }
  726. }
  727. drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
  728. drawString = @"";
  729. CGSize size = [drawString sizeWithAttributes:attributes];
  730. CGRect drawRect = annotation.bounds;
  731. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  732. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  733. drawRect.size.height = size.height;
  734. drawRect.size.width = size.width;
  735. CGContextSaveGState(context);
  736. CGContextSetFillColorWithColor(context, [NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:0.5].CGColor);
  737. CGContextFillRect(context,annotation.bounds);
  738. CGContextRestoreGState(context);
  739. [NSGraphicsContext saveGraphicsState];
  740. CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
  741. float fontSize = 9;
  742. NSColor *textColor = [NSColor whiteColor];
  743. CTTextAlignment alignMent = kCTTextAlignmentCenter;
  744. CFStringRef stringRef = (__bridge CFStringRef)drawString;
  745. NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
  746. NSInteger _stringLength=[drawString length];
  747. CTTextAlignment theAlignment = alignMent;
  748. CTParagraphStyleSetting theSettings[1] =
  749. {
  750. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
  751. }
  752. };
  753. CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
  754. [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
  755. [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
  756. [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
  757. CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
  758. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  759. CGMutablePathRef framePath = CGPathCreateMutable();
  760. CGPathAddRect(framePath, NULL, frameRect);
  761. CFRange currentRange = CFRangeMake(0, 0);
  762. CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
  763. CGPathRelease(framePath);
  764. CTFrameDraw(frameRef, context);
  765. CFRelease(frameRef);
  766. CFRelease(framesetter);
  767. [NSGraphicsContext restoreGraphicsState];
  768. CGContextRestoreGState(context);
  769. }
  770. }
  771. - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
  772. if (CAnnotationTypeStamp == self.annotationType ||
  773. CAnnotationTypeSignSignature == self.annotationType) {
  774. self.stampObject = stampObject;
  775. self.isStampModel = isToolModel;
  776. [NSCursor clearStampCursor];
  777. }
  778. }
  779. - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
  780. NSRect bounds = NSZeroRect;
  781. CPDFSelection *selection = [self currentSelection];
  782. CGFloat defaultWidth = 360;
  783. CGFloat defaultHeight = 90;
  784. NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
  785. bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
  786. // Make sure it fits in the page
  787. bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
  788. // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  789. if (page != nil) {
  790. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  791. // new note added by note tool mode, don't add actual zero sized notes
  792. if (isInitial)
  793. bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
  794. CGFloat borderDefaultWidth = image.size.width;
  795. CGFloat borderScale = borderDefaultWidth/image.size.height;
  796. if (bounds.size.width/bounds.size.height > borderScale) {
  797. bounds.size.height = bounds.size.height;
  798. bounds.size.width = bounds.size.height*borderScale;
  799. } else {
  800. bounds.size.width = bounds.size.width;
  801. bounds.size.height = bounds.size.width/borderScale;
  802. }
  803. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  804. newAnnotation.bounds = bounds;
  805. [newAnnotation setBorderBoundsWithImage:image];
  806. [self addAnnotation:newAnnotation toPage:page];
  807. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  808. [self updateActiveAnnotations:@[newAnnotation]];
  809. [self setNeedsDisplayAnnotation:newAnnotation];
  810. }
  811. else NSBeep();
  812. }
  813. - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  814. [self refreshActiveAnnotations:activeAnnotations isRight:YES];
  815. }
  816. - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  817. [self refreshActiveAnnotations:activeAnnotations isRight:NO];
  818. }
  819. -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
  820. // for (CPDFAnnotation *annotation in self.activeAnnotations) {
  821. // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  822. // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
  823. // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
  824. // } else {
  825. // [self removeAnnotation:linkAnnotation];
  826. // }
  827. // }
  828. // }
  829. if(activeAnnotations) {
  830. NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
  831. BOOL isSame = NO;
  832. if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
  833. if(!isSame) {
  834. self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
  835. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  836. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  837. dispatch_async(dispatch_get_main_queue(), ^{
  838. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  839. });
  840. }
  841. } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
  842. [self.activeAnnotations removeAllObjects];
  843. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  844. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  845. dispatch_async(dispatch_get_main_queue(), ^{
  846. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  847. });
  848. }
  849. }
  850. - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  851. BOOL isContains = YES;
  852. for (CPDFAnnotation *annotation in activeAnnotations) {
  853. if(![self.activeAnnotations containsObject:annotation]) {
  854. [self.activeAnnotations addObject:annotation];
  855. isContains = NO;
  856. }
  857. }
  858. if(!isContains) {
  859. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  860. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  861. dispatch_async(dispatch_get_main_queue(), ^{
  862. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  863. });
  864. }
  865. }
  866. - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
  867. BOOL isContains = NO;
  868. NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
  869. [tarr removeObjectsInArray:removeAnnotations];
  870. self.activeAnnotations = tarr;
  871. isContains = YES;
  872. if(isContains) {
  873. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  874. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  875. dispatch_async(dispatch_get_main_queue(), ^{
  876. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  877. });
  878. }
  879. }
  880. - (void)editAnnotation:(CPDFAnnotation *)annotation {
  881. if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  882. [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
  883. [[self window] makeFirstResponder:self];
  884. [self setNeedsDisplayAnnotation:annotation];
  885. } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] || [annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  886. [self editFormAnnotation:self.activeAnnotation];
  887. } else {
  888. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
  889. [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
  890. } else {
  891. [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
  892. if (!self.popOver) {
  893. _popOver = [[NSPopover alloc] init];
  894. }
  895. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  896. __block typeof(self) blockSelf = self;
  897. _popOver.delegate = self;
  898. CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
  899. vc.pdflistView = self;
  900. _popOver.contentViewController = vc;
  901. vc.closeCallBack = ^{
  902. [blockSelf.popOver close];
  903. };
  904. NSBox *box = (NSBox *)vc.view;
  905. NSView *popoverView = [[[self.popOver contentViewController] view] superview];
  906. [popoverView setWantsLayer:YES];
  907. vc.changeColorCallBack = ^{
  908. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  909. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  910. [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
  911. };
  912. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  913. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  914. _popOver.animates = YES;
  915. _popOver.behavior = NSPopoverBehaviorTransient;
  916. [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
  917. } else if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]){
  918. CPDFListAnnotationNoteWindowController *wc = [CPDFListAnnotationNoteWindowController sharedInstance];
  919. CGRect rect = wc.window.frame;
  920. CGRect anBounds = [self convertRect:annotation.bounds fromPage:annotation.page];
  921. anBounds = [self convertRectToScreen:anBounds];
  922. rect.origin.x = anBounds.origin.x;
  923. rect.origin.y = anBounds.origin.y;
  924. if (@available(macOS 10.13, *))
  925. [wc.window makeKeyAndOrderFront:nil];
  926. else
  927. [wc showWindow:nil];
  928. [wc updateAnnotation:annotation];
  929. [wc.window setFrame:rect display:YES animate:NO];
  930. wc.window.title = @"";
  931. }
  932. }
  933. }
  934. }
  935. - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
  936. if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
  937. CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
  938. NSInteger rotation = stampAnnotation.rotation;
  939. rotation = rotation - angle;
  940. if (rotation < 0) {
  941. rotation += 360;
  942. } else if (rotation >= 360) {
  943. rotation-=360;
  944. }
  945. [annotation setRotation:rotation];
  946. rotation = [annotation appearanceStreamRotation];
  947. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  948. [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
  949. }
  950. }
  951. - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
  952. if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
  953. CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
  954. NSInteger rotation = signatureAnnotation.rotation;
  955. rotation = rotation - angle;
  956. if (rotation < 0) {
  957. rotation += 360;
  958. } else if (rotation >= 360) {
  959. rotation-=360;
  960. }
  961. [signatureAnnotation setRotation:rotation];
  962. rotation = [signatureAnnotation appearanceStreamRotation];
  963. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  964. [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
  965. }
  966. }
  967. - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  968. [self addAnnotation:annotation toPage:page];
  969. }
  970. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  971. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  972. [annotation setModificationDate:[NSDate date]];
  973. //widget设置作者与fieldName冲突
  974. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
  975. [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
  976. }
  977. [page addAnnotation:annotation];
  978. [self setNeedsDisplayAnnotation:annotation];
  979. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  980. dispatch_async(dispatch_get_main_queue(), ^{
  981. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
  982. });
  983. [self resetPDFToolTipRects];
  984. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
  985. [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
  986. }
  987. - (void)removeAnnotation:(CPDFAnnotation *)annotation {
  988. if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
  989. // if (annotation.contents.length <= 0) {
  990. CPDFAnnotation *wasAnnotation = annotation;
  991. CPDFPage *page = wasAnnotation.page;
  992. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  993. [page removeAnnotation:wasAnnotation];
  994. [self annotationsChangedOnPage:page];
  995. [self setNeedsDisplayAnnotation:wasAnnotation];
  996. dispatch_async(dispatch_get_main_queue(), ^{
  997. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  998. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  999. });
  1000. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1001. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1002. // }
  1003. } else {
  1004. CPDFAnnotation *wasAnnotation = annotation;
  1005. CPDFPage *page = wasAnnotation.page;
  1006. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  1007. if ([wasAnnotation isNote]) {
  1008. [self resetPDFToolTipRects];
  1009. }
  1010. [page removeAnnotation:wasAnnotation];
  1011. [self annotationsChangedOnPage:page];
  1012. [self setNeedsDisplayAnnotation:wasAnnotation];
  1013. dispatch_async(dispatch_get_main_queue(), ^{
  1014. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  1015. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  1016. });
  1017. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1018. if (annotation) {
  1019. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1020. }
  1021. }
  1022. }
  1023. - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
  1024. [super drawPage:pdfPage toContext:context];
  1025. [self drawSelectionForPage:pdfPage inContext:context];
  1026. BOOL isIncludText = NO;
  1027. NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
  1028. NSMutableArray *currentPageAnnotations = [NSMutableArray array];
  1029. for (CPDFAnnotation *an in self.activeAnnotations) {
  1030. if([an.page isEqual:pdfPage]) {
  1031. if([an isKindOfClass:[CPDFFreeTextAnnotation class]])
  1032. isIncludText = YES;
  1033. //多选注释框去除mark注释与便签注释
  1034. if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
  1035. [currentActiveAnnotations addObject:an];
  1036. }
  1037. [currentPageAnnotations addObject:an];
  1038. }
  1039. }
  1040. if(currentActiveAnnotations.count > 1) {
  1041. NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
  1042. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  1043. CGContextSaveGState(context);
  1044. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  1045. CGContextSetStrokeColorWithColor(context, color);
  1046. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  1047. CGContextRestoreGState(context);
  1048. CGContextSaveGState(context);
  1049. if(isIncludText) {
  1050. [CPDFListView DrawFreeTextResizeHandle:context rect:rect radius: 4.0 * lineWidth active:true];
  1051. } else {
  1052. [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
  1053. }
  1054. CGContextRestoreGState(context);
  1055. }
  1056. if(self.multiplAnnotationObject &&
  1057. !CGRectIsEmpty(self.multiplAnnotationObject.drawRect) &&
  1058. self.multiplAnnotationObject.page == pdfPage) {
  1059. CGRect selectAnnotationBounds = self.multiplAnnotationObject.drawRect;
  1060. NSRect rect = selectAnnotationBounds;
  1061. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  1062. CGContextSaveGState(context);
  1063. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  1064. CGContextSetStrokeColorWithColor(context, color);
  1065. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  1066. CGContextRestoreGState(context);
  1067. }
  1068. [currentPageAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  1069. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  1070. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  1071. }
  1072. }];
  1073. [self.selectAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  1074. if (annotation.page && [annotation.page isEqual:pdfPage]) {
  1075. [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
  1076. }
  1077. }];
  1078. if (self.hoverAnnotation.page && [self.hoverAnnotation.page isEqual:pdfPage] && ![self.activeAnnotations containsObject:self.hoverAnnotation]) {
  1079. [self.hoverAnnotation drawSelectionHighlightForView:self inContext:context isHover:YES];
  1080. }
  1081. if(!CGRectEqualToRect(self.multiplSelectBounds, CGRectZero) && [self.multiplSelectPage isEqual:pdfPage]) {
  1082. @synchronized (self) {
  1083. CGContextSetLineCap(context, kCGLineCapRound);
  1084. CGContextSetLineWidth(context, 1.0);
  1085. CGContextSetStrokeColorWithColor(context, [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor);
  1086. CGContextBeginPath(context);
  1087. CGContextMoveToPoint(context, self.multiplSelectBounds.origin.x, self.multiplSelectBounds.origin.y);
  1088. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x+ self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y);
  1089. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x + self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  1090. CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
  1091. CGContextClosePath(context);
  1092. CGFloat lengths[] = {5,5};
  1093. CGContextSetLineDash(context, 0, lengths,2);
  1094. CGContextStrokePath(context);
  1095. }
  1096. }
  1097. }
  1098. - (void)drawSelectionForPage:(CPDFPage *)pdfPage inContext:(CGContextRef)context {
  1099. NSRect rect;
  1100. NSUInteger pageIndex;
  1101. @synchronized (self) {
  1102. pageIndex = self.selectionPageIndex;
  1103. rect = self.selectionRect;
  1104. }
  1105. if (pageIndex != NSNotFound) {
  1106. BOOL isWidget = NO;
  1107. for (CPDFAnnotation * annotation in self.activeAnnotations) {
  1108. if ([annotation isForm]) {
  1109. isWidget = YES;
  1110. break;
  1111. }
  1112. }
  1113. if (isWidget &&
  1114. _toolMode != CFormToolMode) {
  1115. return;
  1116. }
  1117. NSRect bounds = [pdfPage boundsForBox:[self displayBox]];
  1118. CGFloat radius = HANDLE_SIZE * [self unitWidthOnPage:pdfPage];
  1119. CGColorRef color = CGColorCreateGenericGray(0.0, 0.6);
  1120. CGContextSetFillColorWithColor(context, color);
  1121. CGColorRelease(color);
  1122. CGContextBeginPath(context);
  1123. CGContextAddRect(context, NSRectToCGRect(bounds));
  1124. CGContextAddRect(context, NSRectToCGRect(rect));
  1125. CGContextEOFillPath(context);
  1126. if ([pdfPage pageIndex] != pageIndex) {
  1127. color = CGColorCreateGenericGray(0.0, 0.3);
  1128. CGContextSetFillColorWithColor(context, color);
  1129. CGColorRelease(color);
  1130. CGContextFillRect(context, NSRectToCGRect(rect));
  1131. }
  1132. [CPDFListView DrawResizeHandles:context rect:rect radius:radius active:true];
  1133. }
  1134. }
  1135. - (void)removeShapeLayer {
  1136. if (![self.shapeLayerTopH isEqual:nil] && ![self.shapeLayerBottomH isEqual:nil] && ![self.shapeLayerLeftV isEqual:nil] && ![self.shapeLayerRightV isEqual:nil]) {
  1137. [self.shapeLayerTopH removeFromSuperlayer];
  1138. [self.shapeLayerBottomH removeFromSuperlayer];
  1139. [self.shapeLayerLeftV removeFromSuperlayer];
  1140. [self.shapeLayerRightV removeFromSuperlayer];
  1141. self.shapeLayerTopH = nil;
  1142. self.shapeLayerBottomH = nil;
  1143. self.shapeLayerLeftV = nil;
  1144. self.shapeLayerRightV = nil;
  1145. }
  1146. }
  1147. - (BOOL)consistentTypeWithAnnotation:(CPDFAnnotation *)annotation {
  1148. if (self.annotationType == CAnnotationTypeSignSignature) {
  1149. if (![annotation isKindOfClass:[CPDFSignatureAnnotation class]])
  1150. return NO;
  1151. } else if (self.annotationType == CAnnotationTypeStamp) {
  1152. if (![annotation isKindOfClass:[CPDFStampAnnotation class]])
  1153. return NO;
  1154. } else if (self.annotationType == CAnnotationTypeAnchored) {
  1155. if (![annotation isKindOfClass:[CPDFTextAnnotation class]])
  1156. return NO;
  1157. } else if (self.annotationType == CAnnotationTypeLink) {
  1158. if (![annotation isKindOfClass:[CPDFLinkAnnotation class]])
  1159. return NO;
  1160. } else if (self.annotationType == CAnnotationTypeFreeText) {
  1161. if (![annotation isKindOfClass:[CPDFFreeTextAnnotation class]])
  1162. return NO;
  1163. } else if (self.annotationType == CAnnotationTypeLine || self.annotationType == CAnnotationTypeArrow || self.annotationType == CAnnotationTypeSquare || self.annotationType == CAnnotationTypeCircle) {
  1164. if (![annotation isKindOfClass:[CPDFLineAnnotation class]] && ![annotation isKindOfClass:[CPDFSquareAnnotation class]] && ![annotation isKindOfClass:[CPDFCircleAnnotation class]])
  1165. return NO;
  1166. } else if (self.annotationType == CAnnotationTypeHighlight || self.annotationType == CAnnotationTypeUnderline || self.annotationType == CAnnotationTypeStrikeOut) {
  1167. if (![annotation isKindOfClass:[CPDFMarkupAnnotation class]])
  1168. return NO;
  1169. } else if (self.annotationType == CAnnotationTypeInk) {
  1170. if (![annotation isKindOfClass:[CPDFInkAnnotation class]])
  1171. return NO;
  1172. } else if (self.annotationType == CAnnotationTypeRadioButton) {
  1173. } else if (self.annotationType == CAnnotationTypeCheckBox) {
  1174. } else if (self.annotationType == CAnnotationTypeTextField) {
  1175. } else if (self.annotationType == CAnnotationTypeComboBox) {
  1176. } else if (self.annotationType == CAnnotationTypeListMenu) {
  1177. } else if (self.annotationType == CAnnotationTypeActionButton) {
  1178. } else if (self.annotationType == CAnnotationTypeSignature) {
  1179. } else if (self.annotationType == CAnnotationTypeSignText) {
  1180. } else if (self.annotationType == CAnnotationTypeSignFalse) {
  1181. } else if (self.annotationType == CAnnotationTypeSignTure) {
  1182. } else if (self.annotationType == CAnnotationTypeSignCircle) {
  1183. } else if (self.annotationType == CAnnotationTypeSignLine) {
  1184. } else if (self.annotationType == CAnnotationTypeSignDot) {
  1185. } else if (self.annotationType == CAnnotationTypeSignConfig) {
  1186. } else if (self.annotationType == CAnnotationTypeSignDate) {
  1187. }
  1188. return YES;
  1189. }
  1190. #pragma mark Zooming
  1191. - (void)zoomToRect:(NSRect)rect onPage:(CPDFPage *)page {
  1192. if (NSIsEmptyRect(rect) == NO) {
  1193. BOOL isLegacy = [NSScroller respondsToSelector:@selector(preferredScrollerStyle)] == NO || [NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy;
  1194. NSRect bounds = [self bounds];
  1195. CGFloat scale = 1.0;
  1196. if (isLegacy) {
  1197. bounds.size.width -= [NSScroller scrollerWidth];
  1198. bounds.size.height -= [NSScroller scrollerWidth];
  1199. }
  1200. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1201. scale = NSHeight(bounds) / NSHeight(rect);
  1202. else
  1203. scale = NSWidth(bounds) / NSWidth(rect);
  1204. [self setScaleFactor:scale];
  1205. NSScrollView *scrollView = [self scrollView];
  1206. if (isLegacy && ([scrollView hasHorizontalScroller] == NO || [scrollView hasVerticalScroller] == NO)) {
  1207. if ([scrollView hasVerticalScroller])
  1208. bounds.size.width -= [NSScroller scrollerWidth];
  1209. if ([scrollView hasHorizontalScroller])
  1210. bounds.size.height -= [NSScroller scrollerWidth];
  1211. if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
  1212. scale = NSHeight(bounds) / NSHeight(rect);
  1213. else
  1214. scale = NSWidth(bounds) / NSWidth(rect);
  1215. [self setScaleFactor:scale];
  1216. }
  1217. [self goToRect:rect onPage:page];
  1218. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1219. CGPoint tPagePoint = CGPointMake(rect.origin.x, rect.origin.y+rect.size.height);
  1220. [self goToTargetPoint:tPagePoint onPage:page atScrollPosition:CScrollPositionTop];
  1221. });
  1222. }
  1223. }
  1224. #pragma mark NSDraggingDestination protocol
  1225. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  1226. 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];
  1227. NSPasteboard *pasteboard = [sender draggingPasteboard];
  1228. if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]) {
  1229. NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  1230. NSString *filePath = fileNames.firstObject;
  1231. if (fileNames.count == 1 && [supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
  1232. return NSDragOperationCopy;
  1233. }
  1234. }
  1235. return NSDragOperationNone;
  1236. }
  1237. - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender {
  1238. NSDragOperation dragOp = NSDragOperationNone;
  1239. NSPasteboard *pboard = [sender draggingPasteboard];
  1240. if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
  1241. NSPoint location = [self convertPoint:[sender draggingLocation] fromView:nil];
  1242. CPDFPage *page = [self pageForPoint:location nearest:NO];
  1243. if (page) {
  1244. NSArray *annotations = [page annotations];
  1245. CPDFAnnotation *annotation = nil;
  1246. NSInteger i = [annotations count];
  1247. location = [self convertPoint:location toPage:page];
  1248. while (i-- > 0) {
  1249. annotation = [annotations objectAtIndex:i];
  1250. if ([self annoHitTest:location Anno:annotation] &&
  1251. ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, nil]] || [annotation hasBorder])) {
  1252. // if ([annotation isEqual:highlightAnnotation] == NO) {
  1253. // if (highlightAnnotation)
  1254. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1255. // [self setHighlightAnnotation:annotation];
  1256. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1257. // }
  1258. dragOp = NSDragOperationGeneric;
  1259. break;
  1260. }
  1261. }
  1262. }
  1263. if (dragOp == NSDragOperationNone /*&& highlightAnnotation*/) {
  1264. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1265. // [self setHighlightAnnotation:nil];
  1266. }
  1267. } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
  1268. dragOp = [super draggingUpdated:sender];
  1269. }
  1270. return dragOp;
  1271. }
  1272. - (BOOL)annoHitTest:(NSPoint)point Anno: (CPDFAnnotation *)anno{
  1273. return [anno shouldDisplay] ? NSPointInRect(point, [self bounds]) : NO;
  1274. }
  1275. - (void)draggingExited:(id <NSDraggingInfo>)sender {
  1276. NSPasteboard *pboard = [sender draggingPasteboard];
  1277. if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
  1278. // if (highlightAnnotation) {
  1279. // [self setNeedsDisplayForAnnotation:highlightAnnotation];
  1280. // [self setHighlightAnnotation:nil];
  1281. // }
  1282. } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
  1283. [super draggingExited:sender];
  1284. }
  1285. }
  1286. - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
  1287. BOOL performedDrag = NO;
  1288. NSPasteboard *pasteboard = [sender draggingPasteboard];
  1289. if ([sender draggingSource] != self) {
  1290. NSArray* filePaths = [pasteboard propertyListForType:NSFilenamesPboardType];
  1291. 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];
  1292. NSString *filePath = filePaths.firstObject;
  1293. if ([supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
  1294. if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  1295. [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1296. return NO;
  1297. }
  1298. if([[filePath.pathExtension lowercaseString] isEqual:@"pdf"]) {
  1299. PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:filePath]];
  1300. if([document isLocked]) {
  1301. return NO;
  1302. }
  1303. }
  1304. NSImage *image = [[NSImage alloc] initWithContentsOfFile:filePath];
  1305. NSPoint point = [sender draggingLocation];
  1306. point = [self convertPoint:point fromView:nil];
  1307. CPDFPage *page = [self pageForPoint:point nearest:YES];
  1308. NSRect rect = NSMakeRect(point.x, point.y - 45, 360, 90);
  1309. NSRect bounds = [self convertRect:rect toPage:page];
  1310. if (page != nil) {
  1311. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  1312. newAnnotation.bounds = bounds;
  1313. [newAnnotation setBorderBoundsWithImage:image];
  1314. [self addAnnotation:newAnnotation toPage:page];
  1315. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  1316. [self updateActiveAnnotations:@[newAnnotation]];
  1317. [self setNeedsDisplayAnnotation:newAnnotation];
  1318. }
  1319. return YES;
  1320. }
  1321. }
  1322. return NO;
  1323. }
  1324. #pragma mark - NSPopoverDelegate
  1325. - (void)popoverWillClose:(NSNotification *)notification {
  1326. NSPopover *popover = notification.object;
  1327. if([popover.contentViewController isKindOfClass:[CPDFListEditAnnotationViewController class]]) {
  1328. CPDFListEditAnnotationViewController *listEditAnnotationViewController = (CPDFListEditAnnotationViewController *)popover.contentViewController;
  1329. CPDFAnnotation *annotation = listEditAnnotationViewController.annotation;
  1330. NSString *contensString = listEditAnnotationViewController.contentString;
  1331. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  1332. if(contensString && contensString.length > 0) {
  1333. annotation.contents = listEditAnnotationViewController.contentString;
  1334. [self setNeedsDisplayAnnotation:annotation];
  1335. } else {
  1336. if([self.activeAnnotations containsObject:annotation]) {
  1337. [self.activeAnnotations removeObject:annotation];
  1338. }
  1339. [self removeAnnotation:annotation];
  1340. }
  1341. } else {
  1342. annotation.contents = listEditAnnotationViewController.contentString;
  1343. [self setNeedsDisplayAnnotation:annotation];
  1344. }
  1345. }
  1346. self.popOver = nil;
  1347. }
  1348. - (void)handlePageChangedNotification:(NSNotification *)notification {
  1349. if ([self displayMode] == kPDFDisplaySinglePage || [self displayMode] == kPDFDisplayTwoUp) {
  1350. [self resetPDFToolTipRects];
  1351. }
  1352. self.copyCount = 0;
  1353. }
  1354. #pragma mark - Form Alignment
  1355. - (KMPDFViewActiveFormsType)formAnnotionsType:(NSArray *)annotationArray {
  1356. NSSet *set = [NSSet setWithArray:[annotationArray valueForKey:@"type"]];
  1357. NSArray *array = [set allObjects];
  1358. if (array.count > 1 || ![array.firstObject isEqualToString:@"Widget"]) {
  1359. return KMPDFViewActiveFormsType_NotAllform;
  1360. }
  1361. PDFAnnotation *referenceAnnotation = annotationArray.firstObject;
  1362. Class referenceAnnotationClass = [referenceAnnotation class];
  1363. if ([referenceAnnotationClass isEqual:[CPDFButtonWidgetAnnotation class]]) {
  1364. referenceAnnotationClass = [CPDFButtonWidgetAnnotation superclass];
  1365. }
  1366. if ([referenceAnnotationClass isEqual:[CPDFTextWidgetAnnotation class]]) {
  1367. referenceAnnotationClass = [CPDFTextWidgetAnnotation superclass];
  1368. }
  1369. if ([referenceAnnotationClass isEqual:[CPDFChoiceWidgetAnnotation class]]) {
  1370. referenceAnnotationClass = [CPDFChoiceWidgetAnnotation superclass];
  1371. }
  1372. if (annotationArray.count == 1) {
  1373. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]) {
  1374. return KMPDFViewActiveFormsType_TextSingle;
  1375. } else {
  1376. return KMPDFViewActiveFormsType_PureSingle;
  1377. }
  1378. }
  1379. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1380. PDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1381. if (![annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFTextWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  1382. return KMPDFViewActiveFormsType_Mix;
  1383. }
  1384. }
  1385. if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]){
  1386. return KMPDFViewActiveFormsType_Text;
  1387. }
  1388. return KMPDFViewActiveFormsType_Pure;
  1389. }
  1390. - (void)formsAnnotationAlign:(KMPDFActiveFormsAlignType)type {
  1391. CGRect zeroRect = CGRectNull;
  1392. CGRect highestRect = CGRectZero;
  1393. CGRect widthestRect = CGRectZero;
  1394. CPDFAnnotation *firstAnnotation = self.activeAnnotations.firstObject;
  1395. CGRect leftestRect = firstAnnotation.bounds;
  1396. CGRect rightestRect = firstAnnotation.bounds;
  1397. CGRect topestRect = firstAnnotation.bounds;
  1398. CGRect bottomestRect = firstAnnotation.bounds;
  1399. CPDFAnnotation *leftestAnnotation = firstAnnotation;
  1400. CPDFAnnotation *rightestAnnotation = firstAnnotation;
  1401. CPDFAnnotation *topestAnnotation = firstAnnotation;
  1402. CPDFAnnotation *bottomestAnnotation = firstAnnotation;
  1403. CGFloat totalWidth = 0.;
  1404. CGFloat totalHeight = 0.;
  1405. for (CPDFAnnotation *annotation in self.activeAnnotations) {
  1406. zeroRect = CGRectUnion(zeroRect, annotation.bounds);
  1407. totalWidth += CGRectGetWidth(annotation.bounds);
  1408. totalHeight += CGRectGetHeight(annotation.bounds);
  1409. if (CGRectGetHeight(annotation.bounds) > CGRectGetHeight(highestRect)) {
  1410. highestRect = annotation.bounds;
  1411. }
  1412. if (CGRectGetWidth(annotation.bounds) > CGRectGetWidth(widthestRect)) {
  1413. widthestRect = annotation.bounds;
  1414. }
  1415. if (CGRectGetMinX(leftestRect) > CGRectGetMinX(annotation.bounds)) {
  1416. leftestRect = annotation.bounds;
  1417. leftestAnnotation = annotation;
  1418. }
  1419. if (CGRectGetMaxX(annotation.bounds) > CGRectGetMaxX(rightestRect)) {
  1420. rightestRect = annotation.bounds;
  1421. rightestAnnotation = annotation;
  1422. }
  1423. if (CGRectGetMaxY(annotation.bounds) > CGRectGetMaxY(topestRect)) {
  1424. topestRect = annotation.bounds;
  1425. topestAnnotation = annotation;
  1426. }
  1427. if (CGRectGetMinY(bottomestRect) > CGRectGetMinY(annotation.bounds)) {
  1428. bottomestRect = annotation.bounds;
  1429. bottomestAnnotation = annotation;
  1430. }
  1431. }
  1432. if (type == KMPDFActiveFormsAlignType_Left ) {
  1433. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1434. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1435. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1436. CGRect bounds = annotation.bounds;
  1437. bounds.origin.x = zeroRect.origin.x;
  1438. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1439. }
  1440. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1441. } else if (type == KMPDFActiveFormsAlignType_Right) {
  1442. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1443. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1444. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1445. CGRect bounds = annotation.bounds;
  1446. bounds.origin.x = CGRectGetMaxX(zeroRect) - bounds.size.width;
  1447. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1448. }
  1449. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1450. } else if (type == KMPDFActiveFormsAlignType_Top) {
  1451. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1452. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1453. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1454. CGRect bounds = annotation.bounds;
  1455. bounds.origin.y = CGRectGetMaxY(zeroRect) - bounds.size.height;
  1456. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1457. }
  1458. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1459. } else if (type == KMPDFActiveFormsAlignType_Bottom) {
  1460. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1461. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1462. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1463. CGRect bounds = annotation.bounds;
  1464. bounds.origin.y = CGRectGetMinY(zeroRect);
  1465. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1466. }
  1467. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1468. } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
  1469. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1470. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1471. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1472. CGRect bounds = annotation.bounds;
  1473. bounds.origin.y = CGRectGetMidY(highestRect) - CGRectGetHeight(bounds)/2;
  1474. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1475. }
  1476. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1477. } else if (type == KMPDFActiveFormsAlignType_Vertical) {
  1478. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1479. for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
  1480. CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
  1481. CGRect bounds = annotation.bounds;
  1482. bounds.origin.x = CGRectGetMidX(widthestRect) - CGRectGetWidth(bounds)/2;
  1483. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1484. }
  1485. [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
  1486. } else if (type == KMPDFActiveFormsAlignType_DisHorizontally) {
  1487. CGFloat middleGap = CGRectGetWidth(zeroRect) - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1488. CGFloat otherAnnotationsTotalWidth = totalWidth - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
  1489. CGFloat gap = (middleGap - otherAnnotationsTotalWidth)/(self.activeAnnotations.count - 1);
  1490. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1491. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1492. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1493. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1494. if (annotation1.bounds.origin.x < annotation2.bounds.origin.x) {
  1495. return NSOrderedAscending;
  1496. } else {
  1497. return NSOrderedDescending;
  1498. }
  1499. }];
  1500. [annotationsCopyArray removeObject:leftestAnnotation];
  1501. [annotationsCopyArray removeObject:rightestAnnotation];
  1502. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1503. CGFloat leftStartX = CGRectGetMaxX(leftestRect) + gap;
  1504. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1505. CPDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1506. CGRect bounds = annotation.bounds;
  1507. bounds.origin.x = leftStartX;
  1508. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1509. leftStartX += CGRectGetWidth(bounds) + gap;
  1510. }
  1511. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1512. } else if (type == KMPDFActiveFormsAlignType_DisVertical) {
  1513. CGFloat middleGap = CGRectGetHeight(zeroRect) - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1514. CGFloat otherAnnotationsTotalHeight = totalHeight - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
  1515. CGFloat gap = (middleGap - otherAnnotationsTotalHeight)/(self.activeAnnotations.count - 1);
  1516. NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
  1517. [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  1518. CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
  1519. CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
  1520. if (annotation1.bounds.origin.y < annotation2.bounds.origin.y) {
  1521. return NSOrderedAscending;
  1522. } else {
  1523. return NSOrderedDescending;
  1524. }
  1525. }];
  1526. [annotationsCopyArray removeObject:topestAnnotation];
  1527. [annotationsCopyArray removeObject:bottomestAnnotation];
  1528. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1529. CGFloat bottomStartY = CGRectGetMaxY(bottomestRect) + gap;
  1530. for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
  1531. PDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
  1532. CGRect bounds = annotation.bounds;
  1533. bounds.origin.y = bottomStartY;
  1534. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1535. bottomStartY += CGRectGetHeight(bounds) + gap;
  1536. }
  1537. [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
  1538. }
  1539. }
  1540. - (void)changeAnnotationsAlign:(NSArray *)annotationArray newBounds:(NSArray *)newBoundsArray {
  1541. NSMutableArray * oldBoundsArray = [NSMutableArray array];
  1542. for (NSInteger i = 0; i < annotationArray.count; i++) {
  1543. CPDFAnnotation *annotation = [annotationArray objectAtIndex:i];
  1544. [oldBoundsArray addObject:NSStringFromRect(annotation.bounds)];
  1545. annotation.bounds = NSRectFromString([newBoundsArray objectAtIndex:i]);
  1546. }
  1547. [[[self undoManager] prepareWithInvocationTarget:self] changeAnnotationsAlign:annotationArray newBounds:oldBoundsArray];
  1548. [self setNeedsDisplay:YES];
  1549. }
  1550. #pragma mark Services
  1551. - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types {
  1552. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound) {
  1553. NSMutableArray *writeTypes = [NSMutableArray array];
  1554. NSString *pdfType = nil;
  1555. NSData *pdfData = nil;
  1556. NSString *tiffType = nil;
  1557. NSData *tiffData = nil;
  1558. NSRect selRect = NSIntegralRect(_selectionRect);
  1559. // 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
  1560. if ([[self document] allowsPrinting] && [[self document] isLocked] == NO) {
  1561. if ([types containsObject:NSPasteboardTypePDF])
  1562. pdfType = NSPasteboardTypePDF;
  1563. else if ([types containsObject:NSPasteboardTypePDF])
  1564. pdfType = NSPasteboardTypePDF;
  1565. if (pdfType && (pdfData = [[self currentSelectionPage] pdfDataFor:selRect]))
  1566. [writeTypes addObject:pdfType];
  1567. }
  1568. if ([types containsObject:NSPasteboardTypeTIFF])
  1569. tiffType = NSPasteboardTypeTIFF;
  1570. else if ([types containsObject:NSPasteboardTypeTIFF])
  1571. tiffType = NSPasteboardTypeTIFF;
  1572. if (tiffType && (tiffData = [[self currentSelectionPage] PDFListViewTIFFDataFor:selRect]))
  1573. [writeTypes addObject:tiffType];
  1574. if ([writeTypes count] > 0) {
  1575. [pboard declareTypes:writeTypes owner:nil];
  1576. if (pdfData)
  1577. [pboard setData:pdfData forType:pdfType];
  1578. if (tiffData)
  1579. [pboard setData:tiffData forType:tiffType];
  1580. return YES;
  1581. }
  1582. }
  1583. if ([[self currentSelection] hasCharacters]) {
  1584. if ([types containsObject:NSPasteboardTypeRTF] || [types containsObject:NSPasteboardTypeRTF]) {
  1585. [pboard clearContents];
  1586. [pboard writeObjects:[NSArray arrayWithObjects:[[self currentSelection] attributedString], nil]];
  1587. return YES;
  1588. } else if ([types containsObject:NSPasteboardTypeString] || [types containsObject:NSPasteboardTypeString]) {
  1589. [pboard clearContents];
  1590. [pboard writeObjects:[NSArray arrayWithObjects:[[self currentSelection] string], nil]];
  1591. return YES;
  1592. }
  1593. }
  1594. return [[CPDFListView superclass] instancesRespondToSelector:_cmd];
  1595. }
  1596. - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType {
  1597. if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound && returnType == nil &&
  1598. (([[self document] allowsPrinting] && [[self document] isLocked] == NO && [sendType isEqualToString:NSPasteboardTypePDF]) || [sendType isEqualToString:NSPasteboardTypeTIFF])) {
  1599. return self;
  1600. }
  1601. if ([[self currentSelection] hasCharacters] && returnType == nil && ([sendType isEqualToString:NSPasteboardTypeString] || [sendType isEqualToString:NSPasteboardTypeRTF])) {
  1602. return self;
  1603. }
  1604. return [super validRequestorForSendType:sendType returnType:returnType];
  1605. }
  1606. #pragma mark Notification handling
  1607. - (void)boundsDidChangeNotification:(NSNotification*)notification
  1608. {
  1609. id object = notification.object;
  1610. NSClipView *pdfContentView = self.scrollView.contentView;
  1611. if (object == pdfContentView) {
  1612. if ([self.activeAnnotation isKindOfClass:[KMTableAnnotation class]] && [[(KMTableAnnotation*)self.activeAnnotation scrollView] superview]) {
  1613. [(KMTableAnnotation*)self.activeAnnotation completeEditCellText];
  1614. }
  1615. }
  1616. }
  1617. @end