CPDFListView.m 75 KB

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