CPDFListView.m 90 KB

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