CPDFListView.m 94 KB

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