CPDFListView.m 93 KB

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