CPDFListView.m 88 KB

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