CPDFListView.m 93 KB

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