CPDFListView.m 88 KB

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