CPDFListView.m 89 KB

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