CPDFListView.m 91 KB

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