CPDFListView.m 91 KB

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