CPDFListView.m 93 KB

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