CPDFListView.m 89 KB

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