CPDFListView.m 95 KB

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