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. NSColor *pageBackgroundColor = NSColor.whiteColor;
  96. if (viewMode < mutableArray.count) {
  97. pageBackgroundColor = mutableArray[viewMode];
  98. }
  99. if (viewMode == KMPDFViewModeOther &&
  100. [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"]) {
  101. CGFloat red,green,blue,alpha;
  102. NSArray *colors = [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"];
  103. red = colors.count>0 ? [colors[0] floatValue] : 0;
  104. green = colors.count>1 ? [colors[1] floatValue] : 0;
  105. blue = colors.count>2 ? [colors[2] floatValue] : 0;
  106. alpha = colors.count>3 ? [colors[3] floatValue] : 0;
  107. pageBackgroundColor = [NSColor colorWithDeviceRed:red green:green blue:blue alpha:alpha];
  108. }
  109. self.viewMode = viewMode;
  110. [self setPageBackgroundColorWithColor:pageBackgroundColor viewMode:viewMode];
  111. self.activeAnnotations = [NSMutableArray array];
  112. self.selectAnnotations = [NSMutableArray array];
  113. self.dragHoverPoints = [NSMutableArray array];
  114. self.aCopyAnnotations = [NSMutableArray array];
  115. [self registerAsObserver];
  116. [self addTrackingArea];
  117. //Table
  118. self.tableTextField = [[NSTextField alloc] initWithFrame:NSRectFromCGRect(CGRectMake(0, 0, 120, 18))];
  119. [self.tableTextField setBordered:NO];
  120. [self.tableTextField setBackgroundColor:[NSColor colorWithDeviceRed:244.0/255.0 green:239/255.0 blue:158/255.0 alpha:1]];
  121. [self.tableTextField setEditable:NO];
  122. [self.tableTextField setAlignment:NSTextAlignmentCenter];
  123. [self.tableTextField setStringValue:@"Column:0 Row:0"];
  124. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChangeNotification:) name:NSViewBoundsDidChangeNotification object:nil];
  125. // [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]];
  126. [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
  127. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
  128. name:CPDFViewPageChangedNotification object:self];
  129. }
  130. - (void)addTrackingArea {
  131. self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingInVisibleRect owner:self userInfo:nil];
  132. [self addTrackingArea:self.trackingArea];
  133. }
  134. - (void)resetPDFToolTipRects {
  135. [self removePDFToolTipRects];
  136. if ([self document] && [self window]) {
  137. NSRect visibleRect = [self visibleContentRect];
  138. NSView *docView = [self documentView];
  139. BOOL hasLinkToolTips = (self.toolMode == CTextToolMode || self.toolMode == CMoveToolMode || self.toolMode == CNoteToolMode);
  140. for (CPDFPage *page in [self visiblePages]) {
  141. for (CPDFAnnotation *annotation in [page annotations]) {
  142. if ([annotation isNote] || (hasLinkToolTips && [annotation linkDestination])) {
  143. // NSLog(@"%@",NSStringFromRect([annotation bounds]));
  144. NSRect rect = NSIntersectionRect([self convertRect:[annotation bounds] fromPage:page], visibleRect);
  145. if (NSIsEmptyRect(rect) == NO) {
  146. rect = [self convertRect:rect toView:docView];
  147. // NSLog(@"%@",NSStringFromRect(rect));
  148. NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:annotation, SKAnnotationKey, nil];
  149. NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:rect options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp owner:self userInfo:userInfo];
  150. [docView addTrackingArea:area];
  151. }
  152. }
  153. }
  154. }
  155. }
  156. }
  157. - (void)removePDFToolTipRects {
  158. NSView *docView = [self documentView];
  159. NSArray *trackingAreas = [[docView trackingAreas] copy];
  160. for (NSTrackingArea *area in trackingAreas) {
  161. if ([area owner] == self && [[area userInfo] objectForKey:SKAnnotationKey])
  162. [docView removeTrackingArea:area];
  163. }
  164. }
  165. - (void)goToPageIndex:(NSInteger)pageIndex animated:(BOOL)animated {
  166. if (self.currentPageIndex != pageIndex) {
  167. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  168. }
  169. [super goToPageIndex:pageIndex animated:animated];
  170. }
  171. - (void)goToSelection:(CPDFSelection *)selection animated:(BOOL)animated {
  172. if (self.currentPageIndex != selection.page.pageIndex) {
  173. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  174. }
  175. [super goToSelection:selection animated:animated];
  176. }
  177. - (void)goToDestination:(CPDFDestination *)destination {
  178. [super goToDestination:destination];
  179. }
  180. - (void)goToRect:(CGRect)rect onPage:(CPDFPage *)page animated:(BOOL)animated {
  181. if (self.currentPageIndex != page.pageIndex) {
  182. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  183. }
  184. [super goToRect:rect onPage:page animated:animated];
  185. }
  186. - (void)goToTargetPoint:(NSPoint)point onPage:(CPDFPage *)page atScrollPosition:(CScrollPosition)scrollPosition {
  187. if (self.currentPageIndex != page.pageIndex) {
  188. [self recordForwardBackWithPageIndex:self.currentPageIndex];
  189. }
  190. [super goToTargetPoint:point onPage:page atScrollPosition:scrollPosition];
  191. }
  192. #pragma mark - Setter & Get
  193. - (KMDrawView *)presentationDrawView {
  194. // if(!_presentationDrawView) {
  195. // float scale = 6;//放大比例,越大可能会卡顿
  196. // _presentationDrawView = [[KMDrawView alloc] initWithFrame:CGRectMake(0, 0,
  197. // scale * self.bounds.size.width,
  198. // scale * self.bounds.size.height)];
  199. // _presentationDrawView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  200. // _presentationDrawView.autoMark = YES;
  201. // [_presentationDrawView resetUndoManager];
  202. // [self addSubview:_presentationDrawView];
  203. // _presentationDrawView.frame = self.bounds;
  204. //
  205. // _presentationDrawView.renderColor = [NSColor blackColor];
  206. // _presentationDrawView.radius = 100;
  207. // _presentationDrawView.hidden = YES;
  208. //
  209. // }
  210. return _presentationDrawView;
  211. }
  212. - (KMDrawView *)CreatePresentationDrawView {
  213. if(!_presentationDrawView) {
  214. float scale = 2.0;//放大比例,越大可能会卡顿
  215. _presentationDrawView = [[KMDrawView alloc] initWithFrame:CGRectMake(0, 0,
  216. scale * self.bounds.size.width,
  217. scale * self.bounds.size.height)];
  218. _presentationDrawView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  219. _presentationDrawView.autoMark = YES;
  220. [_presentationDrawView resetUndoManager];
  221. [self addSubview:_presentationDrawView];
  222. _presentationDrawView.frame = self.bounds;
  223. _presentationDrawView.renderColor = [NSColor blackColor];
  224. _presentationDrawView.radius = 50;
  225. _presentationDrawView.hidden = YES;
  226. }
  227. return _presentationDrawView;
  228. }
  229. - (void)setDocument:(CPDFDocument *)document {
  230. @synchronized (self) {
  231. self.selectionRect = NSZeroRect;
  232. self.selectionPageIndex = NSNotFound;
  233. }
  234. // self.toolMode = CFormToolMode;
  235. // self.annotationType = CAnnotationTypeRadioButton;
  236. // CStampSignatureObject *objc = [[CStampSignatureObject alloc] initImageStampWithFilePath:[[NSBundle mainBundle] pathForResource:@"Quick Start Guide" ofType:@"pdf"]];
  237. // [self setAddStampObject:objc keepToolModel:YES];
  238. //
  239. [super setDocument:document];
  240. [self resetPDFToolTipRectsForAfterDelay];
  241. for(NSInteger i = 0;i<self.document.pageCount;i++) {
  242. CPDFPage *page = [self.document pageAtIndex:i];
  243. for (CPDFAnnotation *annotation in page.annotations) {
  244. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFPageDidLoadAnnotationNotification object:annotation];
  245. }
  246. }
  247. [self.window makeFirstResponder:self];
  248. }
  249. - (void)setToolMode:(CToolMode)newToolMode {
  250. if(newToolMode != _toolMode) {
  251. BOOL isDisplayAnnotationView = NO;
  252. if(self.isSetLinkDestinationArea)
  253. self.isSetLinkDestinationArea = NO;
  254. if ((CTextToolMode == _toolMode || CNoteToolMode == _toolMode) && CTextToolMode != newToolMode) {
  255. if (newToolMode != CNoteToolMode && self.activeAnnotation) {
  256. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  257. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  258. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  259. [self commitEditAnnotationFreeText:freeTextAn];
  260. }
  261. }
  262. [self updateActiveAnnotations:@[]];
  263. }
  264. if ([self currentSelection])
  265. [self setCurrentSelection:nil];
  266. } else if (_toolMode == CSelectToolMode && NSEqualRects(self.selectionRect, NSZeroRect) == NO) {
  267. self.selectionRect = NSZeroRect;
  268. self.selectionPageIndex = NSNotFound;
  269. dispatch_async(dispatch_get_main_queue(), ^{
  270. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFViewSelectionChangedNotification object:self];
  271. });
  272. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedSelectionOrMagnification:)])
  273. [self.pdfListViewDelegate PDFListViewChangedSelectionOrMagnification:self];
  274. isDisplayAnnotationView = YES;
  275. }
  276. BOOL highlightFormFiled = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightFormFiledKey"];
  277. if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewHighlightFormFiledKey"] == nil) {
  278. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kPDFViewHighlightFormFiledKey"];
  279. highlightFormFiled = YES;
  280. }
  281. if (CFormToolMode == _toolMode && !highlightFormFiled) {
  282. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:highlightFormFiled];
  283. isDisplayAnnotationView = YES;
  284. } else if (CFormToolMode == newToolMode && !highlightFormFiled) {
  285. [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:YES];
  286. isDisplayAnnotationView = YES;
  287. }
  288. if (CEditPDFToolMode == newToolMode)
  289. [self beginEditingLoadType:CEditingLoadTypeText|CEditingLoadTypeImage];
  290. if (_toolMode == CEditPDFToolMode) {
  291. if(self.isEdited) {
  292. [self commitEditing];
  293. }
  294. [self endOfEditing];
  295. }
  296. _toolMode = newToolMode;
  297. self.selectZoomToolModeZoomOut = NO;
  298. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedToolMode:forToolMode:)])
  299. [self.pdfListViewDelegate PDFListViewChangedToolMode:self forToolMode:newToolMode];
  300. dispatch_async(dispatch_get_main_queue(), ^{
  301. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewToolModeChangeNotification object:self];
  302. });
  303. [self resetPDFViewAnnotation];
  304. [self resetPDFToolTipRectsForAfterDelay];
  305. if(isDisplayAnnotationView)
  306. [self setNeedsDisplayAnnotationViewForVisiblePages];
  307. }
  308. }
  309. - (void)setShowHopnumber:(BOOL)showHopnumber {
  310. _showHopnumber = showHopnumber;
  311. [self setNeedsDisplayAnnotationViewForVisiblePages];
  312. }
  313. - (void)setAnnotationType:(CAnnotationType)annotationType {
  314. if (_annotationType != annotationType) {
  315. if(CAnnotationTypeLink == annotationType || CAnnotationTypeLink == _annotationType)
  316. [self setNeedsDisplayAnnotationViewForVisiblePages];
  317. if(annotationType == CAnnotationTypeUnkown) {
  318. [self endMeasureModeAddAnnotation];
  319. }
  320. _annotationType = annotationType;
  321. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedAnnotationType:forAnnotationType:)])
  322. [self.pdfListViewDelegate PDFListViewChangedAnnotationType:self forAnnotationType:annotationType];
  323. dispatch_async(dispatch_get_main_queue(), ^{
  324. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewAnnotationTypeChangeNotification object:self];
  325. });
  326. }
  327. if(self.activeAnnotations.count > 0) {
  328. if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  329. CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
  330. if ([self isEditWithCurrentFreeText:freeTextAn]) {
  331. [self commitEditAnnotationFreeText:freeTextAn];
  332. }
  333. }
  334. [self updateActiveAnnotations:@[]];
  335. [self setNeedsDisplayAnnotationViewForVisiblePages];
  336. }
  337. if(self.isSetLinkDestinationArea)
  338. self.isSetLinkDestinationArea = NO;
  339. [self resetPDFViewAnnotation];
  340. }
  341. - (NSRect)currentSelectionRect {
  342. if (CSelectToolMode == self.toolMode)
  343. return self.selectionRect;
  344. return NSZeroRect;
  345. }
  346. - (CPDFAnnotation *)activeAnnotation {
  347. return self.activeAnnotations.lastObject;
  348. }
  349. - (void)setHideNotes:(BOOL)hideNotes {
  350. _hideNotes = hideNotes;
  351. for(NSInteger i = 0;i<self.document.pageCount;i++) {
  352. CPDFPage *page = [self.document pageAtIndex:i];
  353. for (CPDFAnnotation *annotation in page.annotations) {
  354. [annotation setAnnotationShouldDisplay:!self.hideNotes];
  355. [annotation setHidden: self.hideNotes];
  356. [self updateHighLightAnnotation:annotation];
  357. }
  358. }
  359. [self setNeedsDisplayAnnotationViewForVisiblePages];
  360. }
  361. -(void)setIsSetLinkDestinationArea:(BOOL)isSetLinkDestinationArea {
  362. _isSetLinkDestinationArea = isSetLinkDestinationArea;
  363. if (_isSetLinkDestinationArea) {
  364. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationStart:withActiveAnnotation:)]) {
  365. [self.pdfListViewDelegate PDFListViewLinkDestinationStart:self withActiveAnnotation:self.activeAnnotation];
  366. }
  367. } else {
  368. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationEnd:withActiveAnnotation:)]) {
  369. [self.pdfListViewDelegate PDFListViewLinkDestinationEnd:self withActiveAnnotation:self.activeAnnotation];
  370. }
  371. }
  372. }
  373. - (void)setPageBackgroundColorWithColor:(NSColor *)color viewMode:(KMPDFViewMode)viewMode {
  374. if (self.activeAnnotation != nil) {
  375. return;
  376. }
  377. _viewMode = viewMode;
  378. if (viewMode == KMPDFViewModeNormal) {
  379. self.displayMode = CPDFDisplayModeNormal;
  380. } else if (viewMode == KMPDFViewModeSoft) {
  381. self.displayMode = CPDFDisplayModeSoft;
  382. } else if (viewMode == KMPDFViewModeNight) {
  383. self.displayMode = CPDFDisplayModeNight;
  384. } else if (viewMode == KMPDFViewModeGreen) {
  385. self.displayMode = CPDFDisplayModeGreen;
  386. } else {
  387. self.displayMode = CPDFDisplayModeCustom;
  388. self.displayModeCustomColor = color;
  389. }
  390. [self layoutDocumentView];
  391. [self setNeedsDisplayForVisiblePages];
  392. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewMode] forKey:@"kPDFViewModeKey"];
  393. [[NSUserDefaults standardUserDefaults] synchronize];
  394. }
  395. - (void)updateDocumentViewForBackgroundColor{
  396. [self layoutDocumentView];
  397. // [self setNeedsDisplayForVisiblePages];
  398. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_viewMode] forKey:@"kPDFViewModeKey"];
  399. [[NSUserDefaults standardUserDefaults] synchronize];
  400. }
  401. - (void)setViewSplitMode:(KMPDFViewSplitMode)viewSplitMode {
  402. if (_viewSplitMode == viewSplitMode) {
  403. return;
  404. }
  405. _viewSplitMode = viewSplitMode;
  406. [self setNeedsDisplay:YES];
  407. }
  408. - (void)setCurrentSelection:(CPDFSelection *)currentSelection {
  409. if (self.toolMode == CNoteToolMode && self.annotationType == CAnnotationTypeHighlight) {
  410. NSColor *color = [[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey];
  411. CGFloat red = 0, green = 0, blue = 0, alpha = 0.7;
  412. [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red
  413. green:&green
  414. blue:&blue
  415. alpha:nil];
  416. [currentSelection setColor:[NSColor colorWithRed:red green:green blue:blue alpha:alpha]/*[[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey]*/];
  417. }
  418. if (currentSelection == nil) {
  419. // selection = [[[PDFSelection alloc] initWithDocument:[self document]] autorelease];
  420. }
  421. [super setCurrentSelection:currentSelection];
  422. }
  423. #pragma mark - menu add image
  424. - (void)addImageAnnotation:(NSImage *)image center:(NSPoint)center isRemoveBGColor:(BOOL)isRemoveBGColor{
  425. [self setToolMode:CTextToolMode]; //不支持重复添加,重置状态
  426. if (isRemoveBGColor) {
  427. NSData *imageData = [image TIFFRepresentation];
  428. CGImageRef imageRef;
  429. if (imageData) {
  430. CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
  431. imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
  432. } else {
  433. return NSBeep();
  434. }
  435. const int imageWidth = image.size.width;
  436. const int imageHeight = image.size.height;
  437. size_t bytesPerRow = imageWidth * 4;
  438. uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
  439. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  440. CGContextRef context = CGBitmapContextCreate(rgbImageBuf,
  441. imageWidth,
  442. imageHeight,
  443. 8,
  444. bytesPerRow,
  445. colorSpace,
  446. kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
  447. CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), imageRef);
  448. int pixelNum = imageWidth * imageHeight;
  449. uint32_t* pCurPtr = rgbImageBuf;
  450. for (int i = 0; i < pixelNum; i++, pCurPtr++) {
  451. uint8_t* ptr = (uint8_t*)pCurPtr;
  452. if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
  453. ptr[0] = 0;
  454. }
  455. }
  456. CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
  457. imageRef = CGImageCreate(imageWidth,
  458. imageHeight,
  459. 8,
  460. 32,
  461. bytesPerRow,
  462. colorSpace,
  463. kCGImageAlphaLast |kCGBitmapByteOrder32Little,
  464. dataProvider,
  465. NULL,
  466. true,
  467. kCGRenderingIntentDefault);
  468. CGDataProviderRelease(dataProvider);
  469. NSImage *newImage = nil;
  470. if (imageRef) {
  471. NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
  472. CGContextRef imageContext = nil;
  473. // Get the image dimensions.
  474. imageRect.size.height = CGImageGetHeight(imageRef);
  475. imageRect.size.width = CGImageGetWidth(imageRef);
  476. // Create a new image to receive the Quartz image data.
  477. newImage = [[NSImage alloc] initWithSize:imageRect.size];
  478. [newImage lockFocus];
  479. // Get the Quartz context and draw.
  480. imageContext = (CGContextRef)[[NSGraphicsContext currentContext] CGContext];
  481. CGContextDrawImage(imageContext, *(CGRect*)&imageRect, imageRef);
  482. [newImage unlockFocus];
  483. CGImageRelease(imageRef);
  484. }
  485. if (newImage) {
  486. [self addAnnotationWithImage:newImage center:center];
  487. } else {
  488. [self addAnnotationWithImage:image center:center];
  489. }
  490. } else {
  491. [self addAnnotationWithImage:image center:center];
  492. }
  493. }
  494. - (void)addAnnotationWithImage:(NSImage *)image center:(NSPoint)center {
  495. CPDFPage *page = nil;
  496. NSRect bounds = NSZeroRect;
  497. CPDFSelection *selection = [self currentSelection];
  498. page = [selection safeFirstPage];
  499. // if the mouse was in the toolbar and there is a page below the toolbar, we get a point outside of the visible rect
  500. page = NSMouseInRect(center, [self visibleContentRect], [self isFlipped]) ? [self pageForPoint:center nearest:NO] : nil;
  501. if (page == nil) {
  502. // Get center of the PDFView.
  503. // NSRect viewFrame = [self frame];
  504. // center = [self KMCpdfCenterPoint:viewFrame];//KMCpdfCenterPoint(viewFrame);
  505. page = [self pageForPoint: center nearest: YES];
  506. if (page == nil) {
  507. // Get center of the current page
  508. page = [self currentPage];
  509. NSPoint point = [self KMCpdfCenterPoint:[page boundsForBox:[self displayBox]]];
  510. center = [self convertPoint:point fromPage:page];
  511. }
  512. }
  513. CGFloat defaultWidth = 360;
  514. CGFloat defaultHeight = 90;
  515. CGFloat scaleS = MIN(defaultWidth/image.size.width, defaultHeight/image.size.height);
  516. NSSize defaultSize = CGSizeMake(image.size.width * scaleS, image.size.height * scaleS);
  517. // Convert to "page space".
  518. // center = [self KMCpdfIntegralPoint:[self convertPoint:center toPage:page]];
  519. // bounds = [self KMCpdfRectFromCenterAndSize:center size:defaultSize];
  520. // Make sure it fits in the page
  521. // bounds = [self KMCpdfConstrainRect:bounds boundary:[page boundsForBox:[self displayBox]]];
  522. if (page != nil) {
  523. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  524. NSRect pageBounds = [page boundsForBox:CPDFDisplayMediaBox];
  525. // new note added by note tool mode, don't add actual zero sized notes
  526. if (isInitial)
  527. bounds = [self KMCRectFromCenterAndSquareSizeWith:bounds.origin size:8.0];
  528. if(!CGPointEqualToPoint(self.lastAddAnnotationPoint, CGPointZero)) {
  529. bounds.origin.x = self.lastAddAnnotationPoint.x + 3.0;
  530. bounds.origin.y = self.lastAddAnnotationPoint.y - 3.0;
  531. CGFloat pageWidth = pageBounds.size.width;
  532. if (bounds.origin.x + bounds.size.width >pageWidth) {
  533. bounds.origin.x = pageWidth - bounds.size.width;
  534. }
  535. if (bounds.origin.y - bounds.size.height < 0) {
  536. bounds.origin.y = bounds.size.height;
  537. }
  538. }
  539. self.lastAddAnnotationPoint = bounds.origin;
  540. CPDFStampAnnotation *newAnnotation = [[CPDFStampAnnotation alloc]initWithDocument:self.document image:image];
  541. newAnnotation.bounds = CGRectMake(center.x, center.y, defaultSize.width, defaultSize.height);
  542. [newAnnotation registerUserName];
  543. [self addAnnotation:newAnnotation toPage:page];
  544. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  545. [self.activeAnnotations removeAllObjects];
  546. [self.activeAnnotations addObject:newAnnotation];
  547. }
  548. else NSBeep();
  549. }
  550. - (NSRect)KMCRectFromCenterAndSquareSizeWith: (NSPoint)center size:(CGFloat)size{
  551. NSRect rect = NSZeroRect;
  552. rect.origin.x = center.x - 0.5 * size;
  553. rect.origin.y = center.y - 0.5 * size;
  554. rect.size.width = size;
  555. rect.size.height = size;
  556. return rect;
  557. }
  558. - (NSRect)KMCpdfRectFromCenterAndSize: (NSPoint)center size: (NSSize)size{
  559. NSRect rect = NSZeroRect;
  560. rect.origin.x = center.x - 0.5 * size.width;
  561. rect.origin.y = center.y - 0.5 * size.height;
  562. rect.size = size;
  563. return rect;
  564. }
  565. - (NSPoint)KMCpdfCenterPoint:(NSRect)rect{
  566. return NSMakePoint(NSMidX(rect), NSMidY(rect));
  567. }
  568. - (NSPoint)KMCpdfIntegralPoint:(NSPoint)point{
  569. return NSMakePoint(round(point.x), round(point.y));
  570. }
  571. - (NSRect)KMCpdfConstrainRect:(NSRect)rect boundary: (NSRect)boundary{
  572. NSRect newRect = rect;
  573. if (NSWidth(rect) > NSWidth(boundary)){
  574. newRect.size.width = NSWidth(boundary);
  575. }
  576. if (NSHeight(rect) > NSHeight(boundary)){
  577. newRect.size.height = NSHeight(boundary);
  578. }
  579. if (NSMinX(rect) < NSMinX(boundary)){
  580. newRect.origin.x = NSMinX(boundary);
  581. }else if (NSMaxX(rect) > NSMaxX(boundary)){
  582. newRect.origin.x = NSMaxX(boundary) - NSWidth(rect);
  583. }
  584. if (NSMinY(rect) < NSMinY(boundary)){
  585. newRect.origin.y = NSMinY(boundary);
  586. }else if (NSMaxY(rect) > NSMaxY(boundary)){
  587. newRect.origin.y = NSMaxY(boundary) - NSHeight(rect);
  588. }
  589. return newRect;
  590. }
  591. #pragma mark - Public
  592. - (CPDFAnnotation *)addAnnotationWithType:(CAnnotationType)annotationType selection:(CPDFSelection *)selection page:(CPDFPage *)page bounds:(NSRect)bounds {
  593. CPDFAnnotation *annotation = nil;
  594. NSString *text = [selection PDFListViewCleanedString];
  595. if([CPDFListView isMarkupAnnotationType:annotationType]) {
  596. if(selection){
  597. annotation = [self addPDFSelection:selection annotationTyoe:annotationType];
  598. [annotation setContents:text?:@""];
  599. } else NSBeep();
  600. } else {
  601. BOOL isInitial = NO;
  602. if(selection) {
  603. CGRect noteRect = selection.bounds;
  604. isInitial = NSEqualSizes(noteRect.size, NSZeroSize);
  605. } else {
  606. isInitial = NSEqualSizes(bounds.size, NSZeroSize);
  607. }
  608. CPDFAnnotationModel *annotationModel = [[CPDFAnnotationModel alloc]initWithAnnotationType:annotationType];
  609. CGSize size = CGSizeMake(annotationModel.noteWidth, annotationModel.noteHeight);
  610. if(annotationType == CAnnotationTypeAnchored)
  611. bounds = CGRectMake(bounds.origin.x, bounds.origin.y, size.width, size.height);
  612. if (annotationType == CAnnotationTypeCircle || annotationType == CAnnotationTypeSquare || annotationType == CAnnotationTypeLine || annotationType == CAnnotationTypeArrow || annotationType == CAnnotationTypeAnchored) {
  613. bounds = KMConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  614. }
  615. if (isInitial)
  616. bounds = annotationType == CAnnotationTypeAnchored ? CPDFListViewRectFromCenterAndSize(bounds.origin, size) : CPDFListViewRectFromCenterAndSquareSize(bounds.origin, MIN_NOTE_SIZE);
  617. switch (annotationType) {
  618. case CAnnotationTypeFreeText:
  619. annotation = [[CPDFFreeTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  620. annotation.bounds = bounds;
  621. break;
  622. case CAnnotationTypeAnchored:
  623. annotation = [[CPDFTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  624. annotation.bounds = bounds;
  625. break;
  626. case CAnnotationTypeCircle:
  627. annotation = [[CPDFCircleAnnotation alloc]initWithPDFListViewNoteWith:self.document];
  628. annotation.bounds = bounds;
  629. break;
  630. case CAnnotationTypeSquare:
  631. if (CMeasureToolMode == self.toolMode) {
  632. annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeSquare];
  633. [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
  634. annotation.bounds = bounds;
  635. } else {
  636. annotation = [[CPDFSquareAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  637. annotation.bounds = bounds;
  638. }
  639. break;
  640. case CAnnotationTypeLine:
  641. if (self.toolMode == CMeasureToolMode) {
  642. annotation = [[CPDFLineAnnotation alloc] initWithPDFListViewMeasureWith:self.document];
  643. } else if (self.toolMode == CNoteToolMode) {
  644. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeLine];
  645. [(CPDFLineAnnotation *)annotation setStartLineStyle:CPDFLineStyleNone];
  646. [(CPDFLineAnnotation *)annotation setEndLineStyle:CPDFLineStyleNone];
  647. }
  648. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  649. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  650. break;
  651. case CAnnotationTypeArrow: {
  652. annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeArrow];
  653. [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
  654. [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
  655. }
  656. break;
  657. case CAnnotationTypeLink:
  658. annotation = [[CPDFLinkAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  659. annotation.bounds = bounds;
  660. break;
  661. case CAnnotationTypeTextField:
  662. annotation = [[CPDFTextWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  663. annotation.bounds = bounds;
  664. break;
  665. case CAnnotationTypeCheckBox:
  666. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetCheckBoxControl];
  667. break;
  668. case CAnnotationTypeRadioButton:
  669. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetRadioButtonControl];
  670. break;
  671. case CAnnotationTypeListMenu:
  672. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:YES];
  673. break;
  674. case CAnnotationTypeComboBox:
  675. annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:NO];
  676. break;
  677. case CAnnotationTypeSignature:
  678. annotation = [[CPDFSignatureWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
  679. annotation.bounds = bounds;
  680. break;
  681. case CAnnotationTypeActionButton:
  682. annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetPushButtonControl];
  683. break;
  684. case CAnnotationTypeSignFalse:
  685. case CAnnotationTypeSignTure:
  686. case CAnnotationTypeSignCircle:
  687. case CAnnotationTypeSignLine:
  688. case CAnnotationTypeSignDot:
  689. annotation = [[CSelfSignAnnotation alloc]initPDFListViewNoteWithDocument:self.document type:self.annotationType];
  690. annotation.bounds = bounds;
  691. [(CSelfSignAnnotation *)annotation updateAppearanceStream];
  692. break;
  693. case CAnnotationTypeSignText:
  694. case CAnnotationTypeSignConfig:
  695. case CAnnotationTypeSignDate:
  696. annotation = [[CSelfSignAnnotationFreeText alloc]initPDFListViewNoteWithDocument:self.document subType:self.annotationType string:@"" bounds:bounds];
  697. break;
  698. case CAnnotationTypeRedact:
  699. annotation = [self addRedactPDFSelection:selection];
  700. break;
  701. case CAnnotationTypePolyLine:
  702. annotation = [[CPDFPolylineAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypePolyLine];
  703. annotation.bounds = bounds;
  704. break;
  705. case CAnnotationTypePolyGon:
  706. annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypePolyGon];
  707. [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
  708. annotation.bounds = bounds;
  709. break;
  710. default:
  711. break;
  712. }
  713. }
  714. if (annotation) {
  715. if (annotationType != CAnnotationTypeLine && annotationType != CAnnotationTypeArrow && annotationType != CAnnotationTypeInk && [text length] > 0)
  716. [annotation setString:text];
  717. [self addAnnotation:annotation toPage:page];
  718. if ([annotation isKindOfClass:[CPDFMarkupAnnotation class]]) {
  719. [self updateActiveAnnotations:@[annotation]];
  720. }
  721. }
  722. return annotation;
  723. }
  724. - (void)drawAnnotation:(CPDFAnnotation *)annotation toContext:(CGContextRef)context {
  725. [super drawAnnotation:annotation toContext:context];
  726. if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListView:needDrawAnnotation:)]) {
  727. if ([self.pdfListViewDelegate PDFListView:self needDrawAnnotation:annotation] == false) {
  728. return;
  729. }
  730. }
  731. if (CFormToolMode == _toolMode &&
  732. [annotation isKindOfClass:[CPDFWidgetAnnotation class]] && self.showFormFieldName && !annotation.isHidden) {
  733. CPDFWidgetAnnotation *annotationWidget = (CPDFWidgetAnnotation*)annotation;
  734. NSString *fieldName = annotationWidget.fieldName;
  735. if(self.showHopnumber) {
  736. NSInteger hopNumen = annotationWidget.widgetHopNumber;
  737. if(fieldName) {
  738. fieldName = [NSString stringWithFormat:@"%ld %@",hopNumen,fieldName];
  739. } else {
  740. fieldName = [NSString stringWithFormat:@"%ld",hopNumen];
  741. }
  742. }
  743. if (fieldName.length > 0) {
  744. CGContextSaveGState(context);
  745. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  746. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  747. paragraphStyle.alignment = NSTextAlignmentLeft;
  748. NSColor *backgroundColor = [NSColor blackColor];
  749. if ([self.activeAnnotations containsObject:annotation]) {
  750. backgroundColor = [NSColor colorWithRed:82.0/255.0 green:102.0/255.0 blue:204.0/255.0 alpha:1.0];
  751. }
  752. if([CPDFKitConfig sharedInstance].isShowFormRequiredFlagColor)
  753. backgroundColor = [CPDFKitConfig sharedInstance].formRequiredFlagColor?:[NSColor redColor];
  754. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  755. NSForegroundColorAttributeName : [NSColor whiteColor],
  756. NSBackgroundColorAttributeName : backgroundColor,
  757. NSParagraphStyleAttributeName : paragraphStyle};
  758. NSString* drawString = fieldName;
  759. drawString = [drawString getMaxStringWithBounds:annotationWidget.bounds attributes:attributes];
  760. CGSize size = [drawString sizeWithAttributes:attributes];
  761. CGRect drawRect = annotationWidget.bounds;
  762. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  763. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  764. drawRect.size.height = size.height;
  765. drawRect.size.width = size.width;
  766. [NSGraphicsContext saveGraphicsState];
  767. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
  768. [drawString drawInRect:drawRect withAttributes:attributes];
  769. [NSGraphicsContext restoreGraphicsState];
  770. CGContextRestoreGState(context);
  771. NSRect rect = [self integralRect:[annotationWidget bounds] onPage:[annotationWidget page]];
  772. CGFloat lineWidth = [self unitWidthOnPage:[annotationWidget page]];
  773. CGContextSaveGState(context);
  774. CGColorRef color = [NSColor blackColor].CGColor;
  775. CGContextSetStrokeColorWithColor(context, color);
  776. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  777. }
  778. } else if(CNoteToolMode== _toolMode && _annotationType == CAnnotationTypeLink && [annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  779. CGContextSaveGState(context);
  780. NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
  781. paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
  782. paragraphStyle.alignment = NSTextAlignmentLeft;
  783. NSColor *backgroundColor = [NSColor clearColor];
  784. NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
  785. NSForegroundColorAttributeName : [NSColor whiteColor],
  786. NSBackgroundColorAttributeName : backgroundColor,
  787. NSParagraphStyleAttributeName : paragraphStyle};
  788. NSString *drawString = NSLocalizedString(@"No Destination", nil);
  789. CPDFDestination *destination = [(CPDFLinkAnnotation *)annotation destination];
  790. if(destination) {
  791. CPDFPage *page = destination.page;
  792. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  793. if(destination.page) {
  794. NSUInteger index = [self.document indexForPage:page] + 1;
  795. drawString = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"to Page",nil),@(index)];
  796. } else if(url.length > 0) {
  797. drawString = url;
  798. }
  799. }else{
  800. NSString * url = [(CPDFLinkAnnotation *)annotation URL];
  801. if(url.length > 0) {
  802. drawString = url;
  803. }
  804. }
  805. drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
  806. drawString = @"";
  807. CGSize size = [drawString sizeWithAttributes:attributes];
  808. CGRect drawRect = annotation.bounds;
  809. drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
  810. drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
  811. drawRect.size.height = size.height;
  812. drawRect.size.width = size.width;
  813. CGContextSaveGState(context);
  814. CGContextSetFillColorWithColor(context, [NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:0.5].CGColor);
  815. CGContextFillRect(context,annotation.bounds);
  816. CGContextRestoreGState(context);
  817. [NSGraphicsContext saveGraphicsState];
  818. CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
  819. float fontSize = 9;
  820. NSColor *textColor = [NSColor whiteColor];
  821. CTTextAlignment alignMent = kCTTextAlignmentCenter;
  822. CFStringRef stringRef = (__bridge CFStringRef)drawString;
  823. NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
  824. NSInteger _stringLength=[drawString length];
  825. CTTextAlignment theAlignment = alignMent;
  826. CTParagraphStyleSetting theSettings[1] =
  827. {
  828. { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
  829. }
  830. };
  831. CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
  832. [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
  833. [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
  834. [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
  835. CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
  836. CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
  837. CGMutablePathRef framePath = CGPathCreateMutable();
  838. CGPathAddRect(framePath, NULL, frameRect);
  839. CFRange currentRange = CFRangeMake(0, 0);
  840. CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
  841. CGPathRelease(framePath);
  842. CTFrameDraw(frameRef, context);
  843. CFRelease(frameRef);
  844. CFRelease(framesetter);
  845. [NSGraphicsContext restoreGraphicsState];
  846. CGContextRestoreGState(context);
  847. }
  848. }
  849. - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
  850. if (CAnnotationTypeStamp == self.annotationType ||
  851. CAnnotationTypeSignSignature == self.annotationType) {
  852. self.stampObject = stampObject;
  853. self.isStampModel = isToolModel;
  854. [NSCursor clearStampCursor];
  855. }
  856. }
  857. - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
  858. NSRect bounds = NSZeroRect;
  859. CPDFSelection *selection = [self currentSelection];
  860. CGFloat defaultWidth = 360;
  861. CGFloat defaultHeight = 90;
  862. NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
  863. bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
  864. // Make sure it fits in the page
  865. bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
  866. // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
  867. if (page != nil) {
  868. BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
  869. // new note added by note tool mode, don't add actual zero sized notes
  870. if (isInitial)
  871. bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
  872. CGFloat borderDefaultWidth = image.size.width;
  873. CGFloat borderScale = borderDefaultWidth/image.size.height;
  874. if (bounds.size.width/bounds.size.height > borderScale) {
  875. bounds.size.height = bounds.size.height;
  876. bounds.size.width = bounds.size.height*borderScale;
  877. } else {
  878. bounds.size.width = bounds.size.width;
  879. bounds.size.height = bounds.size.width/borderScale;
  880. }
  881. CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
  882. newAnnotation.bounds = bounds;
  883. [newAnnotation setBorderBoundsWithImage:image];
  884. [self addAnnotation:newAnnotation toPage:page];
  885. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  886. [self updateActiveAnnotations:@[newAnnotation]];
  887. [self setNeedsDisplayAnnotation:newAnnotation];
  888. }
  889. else NSBeep();
  890. }
  891. - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  892. [self refreshActiveAnnotations:activeAnnotations isRight:YES];
  893. }
  894. - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  895. [self refreshActiveAnnotations:activeAnnotations isRight:NO];
  896. }
  897. -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
  898. // for (CPDFAnnotation *annotation in self.activeAnnotations) {
  899. // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
  900. // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
  901. // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
  902. // } else {
  903. // [self removeAnnotation:linkAnnotation];
  904. // }
  905. // }
  906. // }
  907. if(activeAnnotations) {
  908. NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
  909. BOOL isSame = NO;
  910. if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
  911. if(!isSame) {
  912. self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
  913. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  914. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  915. dispatch_async(dispatch_get_main_queue(), ^{
  916. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  917. });
  918. }
  919. } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
  920. [self.activeAnnotations removeAllObjects];
  921. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  922. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
  923. dispatch_async(dispatch_get_main_queue(), ^{
  924. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  925. });
  926. }
  927. }
  928. - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
  929. BOOL isContains = YES;
  930. for (CPDFAnnotation *annotation in activeAnnotations) {
  931. if(![self.activeAnnotations containsObject:annotation]) {
  932. [self.activeAnnotations addObject:annotation];
  933. isContains = NO;
  934. }
  935. }
  936. if(!isContains) {
  937. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  938. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  939. dispatch_async(dispatch_get_main_queue(), ^{
  940. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  941. });
  942. }
  943. }
  944. - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
  945. BOOL isContains = NO;
  946. NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
  947. [tarr removeObjectsInArray:removeAnnotations];
  948. self.activeAnnotations = tarr;
  949. isContains = YES;
  950. if(isContains) {
  951. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
  952. [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
  953. dispatch_async(dispatch_get_main_queue(), ^{
  954. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
  955. });
  956. }
  957. }
  958. - (void)editAnnotation:(CPDFAnnotation *)annotation {
  959. if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
  960. [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
  961. [[self window] makeFirstResponder:self];
  962. [self setNeedsDisplayAnnotation:annotation];
  963. } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] || [annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
  964. [self editFormAnnotation:self.activeAnnotation];
  965. } else {
  966. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
  967. [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
  968. } else {
  969. [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
  970. if (!self.popOver) {
  971. _popOver = [[NSPopover alloc] init];
  972. }
  973. if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
  974. __block typeof(self) blockSelf = self;
  975. _popOver.delegate = self;
  976. CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
  977. vc.pdflistView = self;
  978. _popOver.contentViewController = vc;
  979. vc.closeCallBack = ^{
  980. [blockSelf.popOver close];
  981. };
  982. NSBox *box = (NSBox *)vc.view;
  983. NSView *popoverView = [[[self.popOver contentViewController] view] superview];
  984. [popoverView setWantsLayer:YES];
  985. vc.changeColorCallBack = ^{
  986. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  987. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  988. [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
  989. };
  990. NSColor *borColor = annotation.color?:[NSColor whiteColor];
  991. [[popoverView layer] setBackgroundColor:borColor.CGColor];
  992. _popOver.animates = YES;
  993. _popOver.behavior = NSPopoverBehaviorTransient;
  994. [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
  995. } else if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]){
  996. CPDFListAnnotationNoteWindowController *wc = [CPDFListAnnotationNoteWindowController sharedInstance];
  997. CGRect rect = wc.window.frame;
  998. CGRect anBounds = [self convertRect:annotation.bounds fromPage:annotation.page];
  999. anBounds = [self convertRectToScreen:anBounds];
  1000. rect.origin.x = anBounds.origin.x;
  1001. rect.origin.y = anBounds.origin.y;
  1002. if (@available(macOS 10.13, *))
  1003. [wc.window makeKeyAndOrderFront:nil];
  1004. else
  1005. [wc showWindow:nil];
  1006. [wc updateAnnotation:annotation];
  1007. [wc.window setFrame:rect display:YES animate:NO];
  1008. wc.window.title = @"";
  1009. }
  1010. }
  1011. }
  1012. }
  1013. - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
  1014. if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
  1015. CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
  1016. NSInteger rotation = stampAnnotation.rotation;
  1017. rotation = rotation - angle;
  1018. if (rotation < 0) {
  1019. rotation += 360;
  1020. } else if (rotation >= 360) {
  1021. rotation-=360;
  1022. }
  1023. [annotation setRotation:rotation];
  1024. rotation = [annotation appearanceStreamRotation];
  1025. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  1026. [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
  1027. }
  1028. }
  1029. - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
  1030. if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
  1031. CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
  1032. NSInteger rotation = signatureAnnotation.rotation;
  1033. rotation = rotation - angle;
  1034. if (rotation < 0) {
  1035. rotation += 360;
  1036. } else if (rotation >= 360) {
  1037. rotation-=360;
  1038. }
  1039. [signatureAnnotation setRotation:rotation];
  1040. rotation = [signatureAnnotation appearanceStreamRotation];
  1041. [self setNeedsDisplayAnnotationViewForPage:annotation.page];
  1042. [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
  1043. }
  1044. }
  1045. - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  1046. [self addAnnotation:annotation toPage:page];
  1047. }
  1048. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
  1049. if (annotation == nil) {
  1050. return;
  1051. }
  1052. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  1053. [annotation setModificationDate:[NSDate date]];
  1054. //widget设置作者与fieldName冲突
  1055. if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
  1056. [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
  1057. }
  1058. [page addAnnotation:annotation];
  1059. [self setNeedsDisplayAnnotation:annotation];
  1060. [self updateHighLightAnnotation:annotation];
  1061. [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
  1062. dispatch_async(dispatch_get_main_queue(), ^{
  1063. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
  1064. });
  1065. [self resetPDFToolTipRectsForAfterDelay];
  1066. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
  1067. [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
  1068. }
  1069. - (void)removeAnnotation:(CPDFAnnotation *)annotation {
  1070. if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
  1071. // if (annotation.contents.length <= 0) {
  1072. CPDFAnnotation *wasAnnotation = annotation;
  1073. CPDFPage *page = wasAnnotation.page;
  1074. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  1075. [page removeAnnotation:wasAnnotation];
  1076. [self annotationsChangedOnPage:page];
  1077. [self setNeedsDisplayAnnotation:wasAnnotation];
  1078. dispatch_async(dispatch_get_main_queue(), ^{
  1079. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  1080. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  1081. });
  1082. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1083. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1084. // }
  1085. } else {
  1086. CPDFAnnotation *wasAnnotation = annotation;
  1087. CPDFPage *page = wasAnnotation.page;
  1088. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  1089. if ([wasAnnotation isNote]) {
  1090. [self resetPDFToolTipRectsForAfterDelay];
  1091. }
  1092. [page removeAnnotation:wasAnnotation];
  1093. [self annotationsChangedOnPage:page];
  1094. [self setNeedsDisplayAnnotation:wasAnnotation];
  1095. [self updateHighLightAnnotation:annotation];
  1096. dispatch_async(dispatch_get_main_queue(), ^{
  1097. [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
  1098. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
  1099. });
  1100. if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
  1101. if (annotation) {
  1102. [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
  1103. }
  1104. }
  1105. }
  1106. - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
  1107. [super drawPage:pdfPage toContext:context];
  1108. [self drawSelectionForPage:pdfPage inContext:context];
  1109. BOOL isIncludText = NO;
  1110. NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
  1111. NSMutableArray *currentPageAnnotations = [NSMutableArray array];
  1112. for (CPDFAnnotation *an in self.activeAnnotations) {
  1113. if([an.page isEqual:pdfPage]) {
  1114. if([an isKindOfClass:[CPDFFreeTextAnnotation class]])
  1115. isIncludText = YES;
  1116. //多选注释框去除mark注释与便签注释
  1117. if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
  1118. [currentActiveAnnotations addObject:an];
  1119. }
  1120. [currentPageAnnotations addObject:an];
  1121. }
  1122. }
  1123. if(currentActiveAnnotations.count > 1) {
  1124. NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
  1125. CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
  1126. CGContextSaveGState(context);
  1127. CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
  1128. CGContextSetStrokeColorWithColor(context, color);
  1129. CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
  1130. CGContextRestoreGState(context);
  1131. CGContextSaveGState(context);
  1132. [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
  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)changeAnnotations:(NSArray<CPDFAnnotation *> *)annotations alignmentType:(KMPDFActiveFormsAlignType)type {
  1488. CGRect zeroRect = CGRectNull;
  1489. CGRect highestRect = CGRectZero;
  1490. CGRect widthestRect = CGRectZero;
  1491. CPDFAnnotation *firstAnnotation = annotations.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 annotations) {
  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< annotations.count; i++) {
  1532. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1533. CGRect bounds = annotation.bounds;
  1534. bounds.origin.x = zeroRect.origin.x;
  1535. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1536. }
  1537. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1538. } else if (type == KMPDFActiveFormsAlignType_Right) {
  1539. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1540. for (NSInteger i = 0; i< annotations.count; i++) {
  1541. CPDFAnnotation *annotation = [annotations 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:annotations newBounds:newBoundsArray];
  1547. } else if (type == KMPDFActiveFormsAlignType_Top) {
  1548. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1549. for (NSInteger i = 0; i< annotations.count; i++) {
  1550. CPDFAnnotation *annotation = [annotations 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:annotations newBounds:newBoundsArray];
  1556. } else if (type == KMPDFActiveFormsAlignType_Bottom) {
  1557. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1558. for (NSInteger i = 0; i< annotations.count; i++) {
  1559. CPDFAnnotation *annotation = [annotations objectAtIndex:i];
  1560. CGRect bounds = annotation.bounds;
  1561. bounds.origin.y = CGRectGetMinY(zeroRect);
  1562. [newBoundsArray addObject:NSStringFromRect(bounds)];
  1563. }
  1564. [self changeAnnotationsAlign:annotations newBounds:newBoundsArray];
  1565. } else if (type == KMPDFActiveFormsAlignType_Vertical) {
  1566. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1567. for (NSInteger i = 0; i< annotations.count; i++) {
  1568. CPDFAnnotation *annotation = [annotations 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:annotations newBounds:newBoundsArray];
  1574. } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
  1575. NSMutableArray *newBoundsArray = [NSMutableArray array];
  1576. for (NSInteger i = 0; i< annotations.count; i++) {
  1577. CPDFAnnotation *annotation = [annotations 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:annotations 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)/(annotations.count - 1);
  1587. NSMutableArray *annotationsCopyArray = [annotations 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)/(annotations.count - 1);
  1613. NSMutableArray *annotationsCopyArray = [annotations 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