1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969 |
- //
- // CPDFListView.m
- // ComPDFKit
- //
- // Copyright © 2014-2022 PDF Technologies, Inc. All Rights Reserved.
- //
- // THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
- // AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
- // UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
- // This notice may not be removed from this file.
- //
- #import "CPDFListView.h"
- #import "CPDFAnnotationModel.h"
- #import "CSelfSignAnnotation.h"
- #import "CSelfSignAnnotationFreeText.h"
- #import "CPDFListView+Private.h"
- #import "CPDFListView+Event.h"
- #import "CPDFListView+Tool.h"
- #import "CPDFListView+Extension.h"
- #import "CPDFListView+UndoManager.h"
- #import "NSImage+PDFListView.h"
- #import "NSCursor+PDFListView.h"
- #import <PDF_Reader_Pro-Swift.h>
- NSString *SKPasteboardTypeLineStyle = @"net.sourceforge.skim-app.pasteboard.line-style";
- NSNotificationName const CPDFListViewSelectionChangedNotification = @"CPDFListViewSelectionChangedNotification";
- NSNotificationName const CPDFListViewToolModeChangeNotification = @"CPDFListViewToolModeChangeNotification";
- NSNotificationName const CPDFListViewAnnotationTypeChangeNotification = @"CPDFListViewAnnotationTypeChangeNotification";
- NSNotificationName const CPDFListViewMagnificationChangedNotification = @"CPDFListViewMagnificationChangedNotification";
- NSNotificationName const CPDFListViewDidAddAnnotationNotification = @"CPDFListViewDidAddAnnotationNotification";
- NSNotificationName const CPDFListViewDidRemoveAnnotationNotification = @"CPDFListViewDidRemoveAnnotationNotification";
- NSNotificationName const CPDFListViewActiveAnnotationsChangeNotification = @"CPDFListViewActiveAnnotationsChangeNotification";
- NSNotificationName const CPDFListViewAnnotationsAttributeHasChangeNotification = @"CPDFListViewAnnotationsAttributeHasChangeNotification";
- NSNotificationName const KMPDFViewTableAnnotationDidChangeNotification = @"KMPDFViewTableAnnotationDidChangeNotification";
- NSNotificationName const CPDFListViewDisplayModeChangeNotification = @"CPDFListViewDisplayModeChangeNotification";
- @implementation CPDFListView
- #pragma mark - Init
- - (id)init {
- self = [super init];
- if (self) {
- [self commonInitialization];
- }
- return self;
- }
- - (id)initWithFrame:(NSRect)frameRect {
- self = [super initWithFrame:frameRect];
- if (self) {
- [self commonInitialization];
- }
- return self;
- }
- - (id)initWithCoder:(NSCoder *)decoder {
- self = [super initWithCoder:decoder];
- if (self) {
- [self commonInitialization];
- }
- return self;
- }
- - (void)updateLayer {
- [super updateLayer];
- if (@available(macOS 10.14, *)) {
- if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewBackgroundColor)]) {
- NSColor *color = [self.pdfListViewDelegate PDFListViewBackgroundColor];
- self.backgroundColor = color;
- }
- }
- }
- - (void)commonInitialization {
- self.selectionPageIndex = NSNotFound;
- self.clickLineAnnotation = nil;
- self.isClickDoubleCreatLine = NO;
-
- self.perimeterMeasureInfo = [[CPDFPerimeterMeasureInfo alloc] init];
- self.polygonAreaMeasureInfo = [[CPDFAreaMeasureInfo alloc] init];
- self.squareAreaMeasureInfo = [[CPDFAreaMeasureInfo alloc] init];
- self.distanceMeasureInfo = [[CPDFDistanceMeasureInfo alloc] init];
-
- NSArray *sendTypes = [NSArray arrayWithObjects:NSPasteboardTypePDF, NSPasteboardTypeTIFF, nil];
- [NSApp registerServicesMenuSendTypes:sendTypes returnTypes:[NSArray array]];
-
- KMPDFViewMode viewMode = KMPDFViewModeNormal;
- if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeKey"]) {
- viewMode = (KMPDFViewMode)[[[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeKey"] integerValue];
- }
- NSData * data = nil;
- if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kKMPDFViewModeThemesArray"]) {
- data = [[NSUserDefaults standardUserDefaults] objectForKey:@"kKMPDFViewModeThemesArray"];
- }
- NSArray * appArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
- NSMutableArray * mutableArray = [NSMutableArray arrayWithArray:appArray];
- if (mutableArray.count == 0) {
- NSColor *normalColor = [NSColor whiteColor];
- NSColor *softColor = [NSColor colorWithDeviceRed:238.0/255.0 green:232.0/255.0 blue:216.0/255.0 alpha:1.0];
- NSColor *nightColor = [NSColor blackColor];
- NSColor *greenColor = [NSColor colorWithDeviceRed:153.0/255.0 green:207.0/255.0 blue:161.0/255.0 alpha:1.0];
- mutableArray = [NSMutableArray arrayWithArray:@[normalColor, softColor,nightColor, greenColor]];
- }
- NSColor *pageBackgroundColor = mutableArray[viewMode];
- if (viewMode == KMPDFViewModeOther &&
- [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"]) {
- CGFloat red,green,blue,alpha;
- NSArray *colors = [[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewModeColorKey"];
- red = colors.count>0 ? [colors[0] floatValue] : 0;
- green = colors.count>1 ? [colors[1] floatValue] : 0;
- blue = colors.count>2 ? [colors[2] floatValue] : 0;
- alpha = colors.count>3 ? [colors[3] floatValue] : 0;
- pageBackgroundColor = [NSColor colorWithDeviceRed:red green:green blue:blue alpha:alpha];
- }
- self.viewMode = viewMode;
- [self setPageBackgroundColorWithColor:pageBackgroundColor viewMode:viewMode];
-
- self.activeAnnotations = [NSMutableArray array];
- self.selectAnnotations = [NSMutableArray array];
- self.dragHoverPoints = [NSMutableArray array];
- self.aCopyAnnotations = [NSMutableArray array];
-
- [self registerAsObserver];
-
- [self addTrackingArea];
-
- //Table
- self.tableTextField = [[NSTextField alloc] initWithFrame:NSRectFromCGRect(CGRectMake(0, 0, 120, 18))];
- [self.tableTextField setBordered:NO];
- [self.tableTextField setBackgroundColor:[NSColor colorWithDeviceRed:244.0/255.0 green:239/255.0 blue:158/255.0 alpha:1]];
- [self.tableTextField setEditable:NO];
- [self.tableTextField setAlignment:NSTextAlignmentCenter];
- [self.tableTextField setStringValue:@"Column:0 Row:0"];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundsDidChangeNotification:) name:NSViewBoundsDidChangeNotification object:nil];
-
- // [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]];
- [self registerForDraggedTypes:[NSArray arrayWithObjects:NSPasteboardTypeFileURL, nil]];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePageChangedNotification:)
- name:CPDFViewPageChangedNotification object:self];
- }
- - (void)addTrackingArea {
- self.trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingInVisibleRect owner:self userInfo:nil];
- [self addTrackingArea:self.trackingArea];
- }
- - (void)resetPDFToolTipRects {
- [self removePDFToolTipRects];
-
- if ([self document] && [self window]) {
- NSRect visibleRect = [self visibleContentRect];
- NSView *docView = [self documentView];
- BOOL hasLinkToolTips = (self.toolMode == CTextToolMode || self.toolMode == CMoveToolMode || self.toolMode == CNoteToolMode);
-
- for (CPDFPage *page in [self visiblePages]) {
- for (CPDFAnnotation *annotation in [page annotations]) {
- if ([annotation isNote] || (hasLinkToolTips && [annotation linkDestination])) {
- // NSLog(@"%@",NSStringFromRect([annotation bounds]));
- NSRect rect = NSIntersectionRect([self convertRect:[annotation bounds] fromPage:page], visibleRect);
- if (NSIsEmptyRect(rect) == NO) {
- rect = [self convertRect:rect toView:docView];
- // NSLog(@"%@",NSStringFromRect(rect));
-
- NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:annotation, SKAnnotationKey, nil];
- NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:rect options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp owner:self userInfo:userInfo];
- [docView addTrackingArea:area];
- }
- }
- }
- }
- }
- }
- - (void)removePDFToolTipRects {
- NSView *docView = [self documentView];
- NSArray *trackingAreas = [[docView trackingAreas] copy];
- for (NSTrackingArea *area in trackingAreas) {
- if ([area owner] == self && [[area userInfo] objectForKey:SKAnnotationKey])
- [docView removeTrackingArea:area];
- }
- }
- - (void)goToPageIndex:(NSInteger)pageIndex animated:(BOOL)animated {
- if (self.currentPageIndex != pageIndex) {
- [self recordForwardBackWithPageIndex:self.currentPageIndex];
- }
-
- [super goToPageIndex:pageIndex animated:animated];
- }
- - (void)goToSelection:(CPDFSelection *)selection animated:(BOOL)animated {
- if (self.currentPageIndex != selection.page.pageIndex) {
- [self recordForwardBackWithPageIndex:self.currentPageIndex];
- }
-
- [super goToSelection:selection animated:animated];
- }
- - (void)goToDestination:(CPDFDestination *)destination {
- [super goToDestination:destination];
- }
- - (void)goToRect:(CGRect)rect onPage:(CPDFPage *)page animated:(BOOL)animated {
- if (self.currentPageIndex != page.pageIndex) {
- [self recordForwardBackWithPageIndex:self.currentPageIndex];
- }
-
- [super goToRect:rect onPage:page animated:animated];
- }
- - (void)goToTargetPoint:(NSPoint)point onPage:(CPDFPage *)page atScrollPosition:(CScrollPosition)scrollPosition {
- if (self.currentPageIndex != page.pageIndex) {
- [self recordForwardBackWithPageIndex:self.currentPageIndex];
- }
-
- [super goToTargetPoint:point onPage:page atScrollPosition:scrollPosition];
- }
- #pragma mark - Setter & Get
- - (void)setDocument:(CPDFDocument *)document {
- @synchronized (self) {
- self.selectionRect = NSZeroRect;
- self.selectionPageIndex = NSNotFound;
- }
- // self.toolMode = CFormToolMode;
- // self.annotationType = CAnnotationTypeRadioButton;
- // CStampSignatureObject *objc = [[CStampSignatureObject alloc] initImageStampWithFilePath:[[NSBundle mainBundle] pathForResource:@"Quick Start Guide" ofType:@"pdf"]];
- // [self setAddStampObject:objc keepToolModel:YES];
- //
- [super setDocument:document];
-
- [self resetPDFToolTipRectsForAfterDelay];
-
- for(NSInteger i = 0;i<self.document.pageCount;i++) {
- CPDFPage *page = [self.document pageAtIndex:i];
- for (CPDFAnnotation *annotation in page.annotations) {
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFPageDidLoadAnnotationNotification object:annotation];
- }
- }
-
- [self.window makeFirstResponder:self];
-
- }
- -(void)setToolMode:(CToolMode)newToolMode {
- if(newToolMode != _toolMode) {
- BOOL isDisplayAnnotationView = NO;
-
- if(self.isSetLinkDestinationArea)
- self.isSetLinkDestinationArea = NO;
-
- if ((CTextToolMode == _toolMode || CNoteToolMode == _toolMode) && CTextToolMode != newToolMode) {
- if (newToolMode != CNoteToolMode && self.activeAnnotation) {
- if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
- CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
- if ([self isEditWithCurrentFreeText:freeTextAn]) {
- [self commitEditAnnotationFreeText:freeTextAn];
- }
- }
- [self updateActiveAnnotations:@[]];
- }
- if ([self currentSelection])
- [self setCurrentSelection:nil];
- } else if (_toolMode == CSelectToolMode && NSEqualRects(self.selectionRect, NSZeroRect) == NO) {
- self.selectionRect = NSZeroRect;
- self.selectionPageIndex = NSNotFound;
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFViewSelectionChangedNotification object:self];
- });
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedSelectionOrMagnification:)])
- [self.pdfListViewDelegate PDFListViewChangedSelectionOrMagnification:self];
-
- isDisplayAnnotationView = YES;
- }
-
- BOOL highlightFormFiled = [[NSUserDefaults standardUserDefaults] boolForKey:@"kPDFViewHighlightFormFiledKey"];
- if ([[NSUserDefaults standardUserDefaults] objectForKey:@"kPDFViewHighlightFormFiledKey"] == nil) {
- [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kPDFViewHighlightFormFiledKey"];
- highlightFormFiled = YES;
- }
- if (CFormToolMode == _toolMode && !highlightFormFiled) {
- [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:highlightFormFiled];
- isDisplayAnnotationView = YES;
- } else if (CFormToolMode == newToolMode && !highlightFormFiled) {
- [[CPDFKitConfig sharedInstance] setEnableFormFieldHighlight:YES];
- isDisplayAnnotationView = YES;
- }
-
- if(CEditPDFToolMode == newToolMode)
- [self beginEditingLoadType:CEditingLoadTypeText|CEditingLoadTypeImage];
-
- if(_toolMode == CEditPDFToolMode) {
- if(self.isEdited) {
- [self commitEditing];
- }
- [self endOfEditing];
- }
-
- _toolMode = newToolMode;
-
- self.selectZoomToolModeZoomOut = NO;
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedToolMode:forToolMode:)])
- [self.pdfListViewDelegate PDFListViewChangedToolMode:self forToolMode:newToolMode];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewToolModeChangeNotification object:self];
- });
- [self resetPDFViewAnnotation];
- [self resetPDFToolTipRectsForAfterDelay];
-
- if(isDisplayAnnotationView)
- [self setNeedsDisplayAnnotationViewForVisiblePages];
- }
- }
- -(void)setShowHopnumber:(BOOL)showHopnumber {
- _showHopnumber = showHopnumber;
- [self setNeedsDisplayAnnotationViewForVisiblePages];
- }
- - (void)setAnnotationType:(CAnnotationType)annotationType {
- if (_annotationType != annotationType) {
- if(CAnnotationTypeLink == annotationType || CAnnotationTypeLink == _annotationType)
- [self setNeedsDisplayAnnotationViewForVisiblePages];
-
- if(annotationType == CAnnotationTypeUnkown) {
- [self endMeasureModeAddAnnotation];
- }
- _annotationType = annotationType;
-
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangedAnnotationType:forAnnotationType:)])
- [self.pdfListViewDelegate PDFListViewChangedAnnotationType:self forAnnotationType:annotationType];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewAnnotationTypeChangeNotification object:self];
- });
- }
- if(self.activeAnnotations.count > 0) {
- if([self.activeAnnotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
- CPDFFreeTextAnnotation *freeTextAn = (CPDFFreeTextAnnotation *)self.activeAnnotation;
- if ([self isEditWithCurrentFreeText:freeTextAn]) {
- [self commitEditAnnotationFreeText:freeTextAn];
- }
- }
- [self updateActiveAnnotations:@[]];
- [self setNeedsDisplayAnnotationViewForVisiblePages];
- }
-
- if(self.isSetLinkDestinationArea)
- self.isSetLinkDestinationArea = NO;
- [self resetPDFViewAnnotation];
- }
- - (NSRect)currentSelectionRect {
- if (CSelectToolMode == self.toolMode)
- return self.selectionRect;
- return NSZeroRect;
- }
- - (CPDFAnnotation *)activeAnnotation {
- return self.activeAnnotations.lastObject;
- }
- - (void)setHideNotes:(BOOL)hideNotes {
- _hideNotes = hideNotes;
-
- for(NSInteger i = 0;i<self.document.pageCount;i++) {
- CPDFPage *page = [self.document pageAtIndex:i];
- for (CPDFAnnotation *annotation in page.annotations) {
- [annotation setAnnotationShouldDisplay:!self.hideNotes];
- [annotation setHidden: self.hideNotes];
- [self updateHighLightAnnotation:annotation];
- }
- }
- [self setNeedsDisplayAnnotationViewForVisiblePages];
- }
- -(void)setIsSetLinkDestinationArea:(BOOL)isSetLinkDestinationArea {
- _isSetLinkDestinationArea = isSetLinkDestinationArea;
- if (_isSetLinkDestinationArea) {
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationStart:withActiveAnnotation:)]) {
- [self.pdfListViewDelegate PDFListViewLinkDestinationStart:self withActiveAnnotation:self.activeAnnotation];
- }
- } else {
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewLinkDestinationEnd:withActiveAnnotation:)]) {
- [self.pdfListViewDelegate PDFListViewLinkDestinationEnd:self withActiveAnnotation:self.activeAnnotation];
- }
- }
- }
- - (void)setPageBackgroundColorWithColor:(NSColor *)color viewMode:(KMPDFViewMode)viewMode {
- if (self.activeAnnotation != nil) {
- return;
- }
- _viewMode = viewMode;
- if (viewMode == KMPDFViewModeNormal) {
- self.displayMode = CPDFDisplayModeNormal;
- } else if (viewMode == KMPDFViewModeSoft) {
- self.displayMode = CPDFDisplayModeSoft;
- } else if (viewMode == KMPDFViewModeNight) {
- self.displayMode = CPDFDisplayModeNight;
- } else if (viewMode == KMPDFViewModeGreen) {
- self.displayMode = CPDFDisplayModeGreen;
- } else {
- self.displayMode = CPDFDisplayModeCustom;
- self.displayModeCustomColor = color;
- }
-
- [self layoutDocumentView];
- [self setNeedsDisplayForVisiblePages];
- [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:viewMode] forKey:@"kPDFViewModeKey"];
- [[NSUserDefaults standardUserDefaults] synchronize];
- }
- - (void)updateDocumentViewForBackgroundColor{
-
- [self layoutDocumentView];
- // [self setNeedsDisplayForVisiblePages];
- [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_viewMode] forKey:@"kPDFViewModeKey"];
- [[NSUserDefaults standardUserDefaults] synchronize];
- }
- - (void)setViewSplitMode:(KMPDFViewSplitMode)viewSplitMode {
- if (_viewSplitMode == viewSplitMode) {
- return;
- }
- _viewSplitMode = viewSplitMode;
- [self setNeedsDisplay:YES];
- }
- - (void)setCurrentSelection:(CPDFSelection *)currentSelection {
- if (self.toolMode == CNoteToolMode && self.annotationType == CAnnotationTypeHighlight) {
- NSColor *color = [[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey];
- CGFloat red = 0, green = 0, blue = 0, alpha = 0.7;
- [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red
- green:&green
- blue:&blue
- alpha:nil];
-
- [currentSelection setColor:[NSColor colorWithRed:red green:green blue:blue alpha:alpha]/*[[NSUserDefaults standardUserDefaults] colorForKey:CHighlightNoteColorKey]*/];
- }
- if (currentSelection == nil) {
- // selection = [[[PDFSelection alloc] initWithDocument:[self document]] autorelease];
- }
- [super setCurrentSelection:currentSelection];
- }
- #pragma mark - menu add image
- - (void)addImageAnnotation:(NSImage *)image center:(NSPoint)center isRemoveBGColor:(BOOL)isRemoveBGColor{
- [self setToolMode:CTextToolMode]; //不支持重复添加,重置状态
- if (isRemoveBGColor) {
- NSData *imageData = [image TIFFRepresentation];
- CGImageRef imageRef;
- if (imageData) {
- CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
- imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
- } else {
- return NSBeep();
- }
-
- const int imageWidth = image.size.width;
- const int imageHeight = image.size.height;
- size_t bytesPerRow = imageWidth * 4;
- uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
-
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef context = CGBitmapContextCreate(rgbImageBuf,
- imageWidth,
- imageHeight,
- 8,
- bytesPerRow,
- colorSpace,
- kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
- CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), imageRef);
-
- int pixelNum = imageWidth * imageHeight;
- uint32_t* pCurPtr = rgbImageBuf;
- for (int i = 0; i < pixelNum; i++, pCurPtr++) {
- uint8_t* ptr = (uint8_t*)pCurPtr;
- if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
- ptr[0] = 0;
- }
- }
-
- CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
- imageRef = CGImageCreate(imageWidth,
- imageHeight,
- 8,
- 32,
- bytesPerRow,
- colorSpace,
- kCGImageAlphaLast |kCGBitmapByteOrder32Little,
- dataProvider,
- NULL,
- true,
- kCGRenderingIntentDefault);
- CGDataProviderRelease(dataProvider);
-
- NSImage *newImage = nil;
- if (imageRef) {
- NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
- CGContextRef imageContext = nil;
-
- // Get the image dimensions.
- imageRect.size.height = CGImageGetHeight(imageRef);
- imageRect.size.width = CGImageGetWidth(imageRef);
-
- // Create a new image to receive the Quartz image data.
- newImage = [[NSImage alloc] initWithSize:imageRect.size];
- [newImage lockFocus];
-
- // Get the Quartz context and draw.
- imageContext = (CGContextRef)[[NSGraphicsContext currentContext] CGContext];
- CGContextDrawImage(imageContext, *(CGRect*)&imageRect, imageRef);
- [newImage unlockFocus];
- CGImageRelease(imageRef);
- }
-
- if (newImage) {
- [self addAnnotationWithImage:newImage center:center];
- } else {
- [self addAnnotationWithImage:image center:center];
- }
- } else {
- [self addAnnotationWithImage:image center:center];
- }
- }
- - (void)addAnnotationWithImage:(NSImage *)image center:(NSPoint)center {
- CPDFPage *page = nil;
- NSRect bounds = NSZeroRect;
- CPDFSelection *selection = [self currentSelection];
- page = [selection safeFirstPage];
-
- // if the mouse was in the toolbar and there is a page below the toolbar, we get a point outside of the visible rect
- page = NSMouseInRect(center, [self visibleContentRect], [self isFlipped]) ? [self pageForPoint:center nearest:NO] : nil;
-
- if (page == nil) {
- // Get center of the PDFView.
- // NSRect viewFrame = [self frame];
- // center = [self KMCpdfCenterPoint:viewFrame];//KMCpdfCenterPoint(viewFrame);
- page = [self pageForPoint: center nearest: YES];
- if (page == nil) {
- // Get center of the current page
- page = [self currentPage];
- NSPoint point = [self KMCpdfCenterPoint:[page boundsForBox:[self displayBox]]];
- center = [self convertPoint:point fromPage:page];
- }
- }
- CGFloat defaultWidth = 360;
- CGFloat defaultHeight = 90;
- CGFloat scaleS = MIN(defaultWidth/image.size.width, defaultHeight/image.size.height);
- NSSize defaultSize = CGSizeMake(image.size.width * scaleS, image.size.height * scaleS);
-
- // Convert to "page space".
- // center = [self KMCpdfIntegralPoint:[self convertPoint:center toPage:page]];
- // bounds = [self KMCpdfRectFromCenterAndSize:center size:defaultSize];
-
- // Make sure it fits in the page
- // bounds = [self KMCpdfConstrainRect:bounds boundary:[page boundsForBox:[self displayBox]]];
-
- if (page != nil) {
- BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
- NSRect pageBounds = [page boundsForBox:CPDFDisplayMediaBox];
-
- // new note added by note tool mode, don't add actual zero sized notes
- if (isInitial)
- bounds = [self KMCRectFromCenterAndSquareSizeWith:bounds.origin size:8.0];
-
-
- if(!CGPointEqualToPoint(self.lastAddAnnotationPoint, CGPointZero)) {
- bounds.origin.x = self.lastAddAnnotationPoint.x + 3.0;
- bounds.origin.y = self.lastAddAnnotationPoint.y - 3.0;
- CGFloat pageWidth = pageBounds.size.width;
-
- if (bounds.origin.x + bounds.size.width >pageWidth) {
- bounds.origin.x = pageWidth - bounds.size.width;
- }
- if (bounds.origin.y - bounds.size.height < 0) {
- bounds.origin.y = bounds.size.height;
- }
- }
- self.lastAddAnnotationPoint = bounds.origin;
-
- CPDFStampAnnotation *newAnnotation = [[CPDFStampAnnotation alloc]initWithDocument:self.document image:image];
- newAnnotation.bounds = CGRectMake(center.x, center.y, defaultSize.width, defaultSize.height);
- [newAnnotation registerUserName];
- [self addAnnotation:newAnnotation toPage:page];
- [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
-
- [self.activeAnnotations removeAllObjects];
- [self.activeAnnotations addObject:newAnnotation];
- }
- else NSBeep();
- }
- - (NSRect)KMCRectFromCenterAndSquareSizeWith: (NSPoint)center size:(CGFloat)size{
- NSRect rect = NSZeroRect;
- rect.origin.x = center.x - 0.5 * size;
- rect.origin.y = center.y - 0.5 * size;
- rect.size.width = size;
- rect.size.height = size;
- return rect;
- }
- - (NSRect)KMCpdfRectFromCenterAndSize: (NSPoint)center size: (NSSize)size{
- NSRect rect = NSZeroRect;
- rect.origin.x = center.x - 0.5 * size.width;
- rect.origin.y = center.y - 0.5 * size.height;
- rect.size = size;
- return rect;
- }
- - (NSPoint)KMCpdfCenterPoint:(NSRect)rect{
- return NSMakePoint(NSMidX(rect), NSMidY(rect));
- }
- - (NSPoint)KMCpdfIntegralPoint:(NSPoint)point{
- return NSMakePoint(round(point.x), round(point.y));
- }
- - (NSRect)KMCpdfConstrainRect:(NSRect)rect boundary: (NSRect)boundary{
- NSRect newRect = rect;
- if (NSWidth(rect) > NSWidth(boundary)){
- newRect.size.width = NSWidth(boundary);
- }
- if (NSHeight(rect) > NSHeight(boundary)){
- newRect.size.height = NSHeight(boundary);
- }
- if (NSMinX(rect) < NSMinX(boundary)){
- newRect.origin.x = NSMinX(boundary);
- }else if (NSMaxX(rect) > NSMaxX(boundary)){
- newRect.origin.x = NSMaxX(boundary) - NSWidth(rect);
- }
- if (NSMinY(rect) < NSMinY(boundary)){
- newRect.origin.y = NSMinY(boundary);
- }else if (NSMaxY(rect) > NSMaxY(boundary)){
- newRect.origin.y = NSMaxY(boundary) - NSHeight(rect);
- }
- return newRect;
- }
- #pragma mark - Public
- - (CPDFAnnotation *)addAnnotationWithType:(CAnnotationType)annotationType selection:(CPDFSelection *)selection page:(CPDFPage *)page bounds:(NSRect)bounds {
- CPDFAnnotation *annotation = nil;
-
- NSString *text = [selection PDFListViewCleanedString];
-
- if([CPDFListView isMarkupAnnotationType:annotationType]) {
- if(selection){
- annotation = [self addPDFSelection:selection annotationTyoe:annotationType];
- [annotation setContents:text?:@""];
- } else NSBeep();
- } else {
- BOOL isInitial = NO;
- if(selection) {
- CGRect noteRect = selection.bounds;
- isInitial = NSEqualSizes(noteRect.size, NSZeroSize);
- } else {
- isInitial = NSEqualSizes(bounds.size, NSZeroSize);
- }
- CPDFAnnotationModel *annotationModel = [[CPDFAnnotationModel alloc]initWithAnnotationType:annotationType];
- CGSize size = CGSizeMake(annotationModel.noteWidth, annotationModel.noteHeight);
- if(annotationType == CAnnotationTypeAnchored)
- bounds = CGRectMake(bounds.origin.x, bounds.origin.y, size.width, size.height);
- if (annotationType == CAnnotationTypeCircle || annotationType == CAnnotationTypeSquare || annotationType == CAnnotationTypeLine || annotationType == CAnnotationTypeArrow || annotationType == CAnnotationTypeAnchored) {
- bounds = KMConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
- }
-
- if (isInitial)
- bounds = annotationType == CAnnotationTypeAnchored ? CPDFListViewRectFromCenterAndSize(bounds.origin, size) : CPDFListViewRectFromCenterAndSquareSize(bounds.origin, MIN_NOTE_SIZE);
- switch (annotationType) {
- case CAnnotationTypeFreeText:
- annotation = [[CPDFFreeTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeAnchored:
- annotation = [[CPDFTextAnnotation alloc]initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeCircle:
- annotation = [[CPDFCircleAnnotation alloc]initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeSquare:
- if (CMeasureToolMode == self.toolMode) {
- annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeSquare];
- [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
- annotation.bounds = bounds;
- } else {
- annotation = [[CPDFSquareAnnotation alloc] initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- }
- break;
- case CAnnotationTypeLine:
- if (self.toolMode == CMeasureToolMode) {
- annotation = [[CPDFLineAnnotation alloc] initWithPDFListViewMeasureWith:self.document];
- } else if (self.toolMode == CNoteToolMode) {
- annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeLine];
- [(CPDFLineAnnotation *)annotation setStartLineStyle:CPDFLineStyleNone];
- [(CPDFLineAnnotation *)annotation setEndLineStyle:CPDFLineStyleNone];
- }
- [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
- [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
- break;
- case CAnnotationTypeArrow: {
- annotation = [[CPDFLineAnnotation alloc]initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypeArrow];
- [(CPDFLineAnnotation *)annotation setObservedStartPoint:CGPointMake(bounds.origin.x, bounds.origin.y)];
- [(CPDFLineAnnotation *)annotation setObservedEndPoint:CGPointMake(bounds.origin.x + bounds.size.width,bounds.origin.y+ bounds.size.height)];
- }
- break;
- case CAnnotationTypeLink:
- annotation = [[CPDFLinkAnnotation alloc] initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeTextField:
- annotation = [[CPDFTextWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeCheckBox:
- annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetCheckBoxControl];
- break;
- case CAnnotationTypeRadioButton:
- annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetRadioButtonControl];
- break;
- case CAnnotationTypeListMenu:
- annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:YES];
- break;
- case CAnnotationTypeComboBox:
- annotation = [[CPDFChoiceWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds listChoice:NO];
- break;
- case CAnnotationTypeSignature:
- annotation = [[CPDFSignatureWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypeActionButton:
- annotation = [[CPDFButtonWidgetAnnotation alloc] initWithPDFListViewNoteWith:self.document bounds:bounds controlType:CPDFWidgetPushButtonControl];
- break;
- case CAnnotationTypeSignFalse:
- case CAnnotationTypeSignTure:
- case CAnnotationTypeSignCircle:
- case CAnnotationTypeSignLine:
- case CAnnotationTypeSignDot:
- annotation = [[CSelfSignAnnotation alloc]initPDFListViewNoteWithDocument:self.document type:self.annotationType];
- annotation.bounds = bounds;
- [(CSelfSignAnnotation *)annotation updateAppearanceStream];
- break;
- case CAnnotationTypeSignText:
- case CAnnotationTypeSignConfig:
- case CAnnotationTypeSignDate:
- annotation = [[CSelfSignAnnotationFreeText alloc]initPDFListViewNoteWithDocument:self.document subType:self.annotationType string:@"" bounds:bounds];
- break;
- case CAnnotationTypeRedact:
- annotation = [self addRedactPDFSelection:selection];
- break;
- case CAnnotationTypePolyLine:
- annotation = [[CPDFPolylineAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypePolyLine];
- annotation.bounds = bounds;
- break;
- case CAnnotationTypePolyGon:
- annotation = [[CPDFPolygonAnnotation alloc] initWithPDFListViewNoteWith:self.document annotationType:CAnnotationTypePolyGon];
- [CPDFListViewConfig defaultManager].isSquareFromPolygon = NO;
- annotation.bounds = bounds;
- break;
- default:
- break;
- }
- }
-
- if (annotation) {
- if (annotationType != CAnnotationTypeLine && annotationType != CAnnotationTypeArrow && annotationType != CAnnotationTypeInk && [text length] > 0)
- [annotation setString:text];
-
- [self addAnnotation:annotation toPage:page];
-
- if ([annotation isKindOfClass:[CPDFMarkupAnnotation class]]) {
- [self updateActiveAnnotations:@[annotation]];
- }
- }
-
- return annotation;
- }
- - (void)drawAnnotation:(CPDFAnnotation *)annotation toContext:(CGContextRef)context {
- [super drawAnnotation:annotation toContext:context];
-
- if ([self.pdfListViewDelegate respondsToSelector:@selector(PDFListView:needDrawAnnotation:)]) {
- if ([self.pdfListViewDelegate PDFListView:self needDrawAnnotation:annotation] == false) {
- return;
- }
- }
-
- if (CFormToolMode == _toolMode &&
- [annotation isKindOfClass:[CPDFWidgetAnnotation class]] && self.showFormFieldName && !annotation.isHidden) {
-
- CPDFWidgetAnnotation *annotationWidget = (CPDFWidgetAnnotation*)annotation;
- NSString *fieldName = annotationWidget.fieldName;
- if(self.showHopnumber) {
- NSInteger hopNumen = annotationWidget.widgetHopNumber;
- if(fieldName) {
- fieldName = [NSString stringWithFormat:@"%ld %@",hopNumen,fieldName];
- } else {
- fieldName = [NSString stringWithFormat:@"%ld",hopNumen];
- }
-
- }
- if (fieldName.length > 0) {
- CGContextSaveGState(context);
- NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
- paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
- paragraphStyle.alignment = NSTextAlignmentLeft;
- NSColor *backgroundColor = [NSColor blackColor];
- if ([self.activeAnnotations containsObject:annotation]) {
- backgroundColor = [NSColor colorWithRed:82.0/255.0 green:102.0/255.0 blue:204.0/255.0 alpha:1.0];
- }
-
- if([CPDFKitConfig sharedInstance].isShowFormRequiredFlagColor)
- backgroundColor = [CPDFKitConfig sharedInstance].formRequiredFlagColor?:[NSColor redColor];
-
- NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
- NSForegroundColorAttributeName : [NSColor whiteColor],
- NSBackgroundColorAttributeName : backgroundColor,
- NSParagraphStyleAttributeName : paragraphStyle};
- NSString* drawString = fieldName;
- drawString = [drawString getMaxStringWithBounds:annotationWidget.bounds attributes:attributes];
-
- CGSize size = [drawString sizeWithAttributes:attributes];
- CGRect drawRect = annotationWidget.bounds;
- drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
- drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
- drawRect.size.height = size.height;
- drawRect.size.width = size.width;
-
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
- [drawString drawInRect:drawRect withAttributes:attributes];
- [NSGraphicsContext restoreGraphicsState];
- CGContextRestoreGState(context);
-
- NSRect rect = [self integralRect:[annotationWidget bounds] onPage:[annotationWidget page]];
- CGFloat lineWidth = [self unitWidthOnPage:[annotationWidget page]];
- CGContextSaveGState(context);
- CGColorRef color = [NSColor blackColor].CGColor;
- CGContextSetStrokeColorWithColor(context, color);
- CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
- }
- } else if(CNoteToolMode== _toolMode && _annotationType == CAnnotationTypeLink && [annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
- CGContextSaveGState(context);
- NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
- paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
- paragraphStyle.alignment = NSTextAlignmentLeft;
- NSColor *backgroundColor = [NSColor clearColor];
-
- NSDictionary *attributes = @{NSFontAttributeName : [NSFont systemFontOfSize:12],
- NSForegroundColorAttributeName : [NSColor whiteColor],
- NSBackgroundColorAttributeName : backgroundColor,
- NSParagraphStyleAttributeName : paragraphStyle};
-
- NSString *drawString = NSLocalizedString(@"No Destination", nil);
- CPDFDestination *destination = [(CPDFLinkAnnotation *)annotation destination];
- if(destination) {
- CPDFPage *page = destination.page;
- NSString * url = [(CPDFLinkAnnotation *)annotation URL];
-
- if(destination.page) {
- NSUInteger index = [self.document indexForPage:page] + 1;
- drawString = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"to Page",nil),@(index)];
- } else if(url.length > 0) {
- drawString = url;
- }
- }else{
- NSString * url = [(CPDFLinkAnnotation *)annotation URL];
- if(url.length > 0) {
- drawString = url;
- }
- }
- drawString = [drawString getMaxStringWithBounds:annotation.bounds attributes:attributes];
- drawString = @"";
- CGSize size = [drawString sizeWithAttributes:attributes];
- CGRect drawRect = annotation.bounds;
- drawRect.origin.y += (drawRect.size.height - size.height)/2.0;
- drawRect.origin.x += (drawRect.size.width - size.width)/2.0;
- drawRect.size.height = size.height;
- drawRect.size.width = size.width;
-
- CGContextSaveGState(context);
- CGContextSetFillColorWithColor(context, [NSColor colorWithRed:23.0/255.0 green:112.0/255.0 blue:244.0/255.0 alpha:0.5].CGColor);
- CGContextFillRect(context,annotation.bounds);
- CGContextRestoreGState(context);
-
- [NSGraphicsContext saveGraphicsState];
- CGRect frameRect=CGRectMake(annotation.bounds.origin.x, annotation.bounds.origin.y + (annotation.bounds.size.height - 20)/2, annotation.bounds.size.width, 20);
- float fontSize = 9;
- NSColor *textColor = [NSColor whiteColor];
- CTTextAlignment alignMent = kCTTextAlignmentCenter;
- CFStringRef stringRef = (__bridge CFStringRef)drawString;
- NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:drawString];
- NSInteger _stringLength=[drawString length];
- CTTextAlignment theAlignment = alignMent;
- CTParagraphStyleSetting theSettings[1] =
- {
- { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),&theAlignment
- }
-
- };
-
- CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate(theSettings, 1);
- [attString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)paragraphStyleRef range:NSMakeRange(0, _stringLength)];
- [attString addAttribute:(id)kCTForegroundColorAttributeName value:(id)textColor.CGColor range:NSMakeRange(0, _stringLength)];
- [attString addAttribute:(id)kCTFontNameAttribute value:@"Courier" range:NSMakeRange(0, _stringLength)];
- CFAttributedStringRef attrString =(__bridge CFAttributedStringRef) attString;
- CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
- CGMutablePathRef framePath = CGPathCreateMutable();
- CGPathAddRect(framePath, NULL, frameRect);
- CFRange currentRange = CFRangeMake(0, 0);
- CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
- CGPathRelease(framePath);
- CTFrameDraw(frameRef, context);
- CFRelease(frameRef);
- CFRelease(framesetter);
- [NSGraphicsContext restoreGraphicsState];
- CGContextRestoreGState(context);
- }
- }
- - (void)setAddStampObject:(CStampSignatureObject *)stampObject keepToolModel:(BOOL)isToolModel {
- if (CAnnotationTypeStamp == self.annotationType ||
- CAnnotationTypeSignSignature == self.annotationType) {
- self.stampObject = stampObject;
- self.isStampModel = isToolModel;
- [NSCursor clearStampCursor];
- }
- }
- - (void)addAnnotationWithImage:(NSImage *)image page:(CPDFPage *)page point:(NSPoint)point {
- NSRect bounds = NSZeroRect;
- CPDFSelection *selection = [self currentSelection];
-
- CGFloat defaultWidth = 360;
- CGFloat defaultHeight = 90;
- NSSize defaultSize = ([page rotation] % 180 == 0) ? NSMakeSize(defaultWidth, defaultHeight) : NSMakeSize(defaultHeight, defaultWidth);
- bounds = CPDFListViewRectFromCenterAndSize(point, defaultSize);
-
- // Make sure it fits in the page
- bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]],[CPDFListViewConfig defaultManager].annotationBorderOffset.floatValue);
- // bounds = CPDFListViewConstrainRect(bounds, [page boundsForBox:[self displayBox]]);
- if (page != nil) {
- BOOL isInitial = NSEqualSizes(bounds.size, NSZeroSize) && selection == nil;
- // new note added by note tool mode, don't add actual zero sized notes
- if (isInitial)
- bounds = CPDFListViewRectFromCenterAndSquareSize(bounds.origin, 8.0);
-
- CGFloat borderDefaultWidth = image.size.width;
- CGFloat borderScale = borderDefaultWidth/image.size.height;
- if (bounds.size.width/bounds.size.height > borderScale) {
- bounds.size.height = bounds.size.height;
- bounds.size.width = bounds.size.height*borderScale;
- } else {
- bounds.size.width = bounds.size.width;
- bounds.size.height = bounds.size.width/borderScale;
- }
-
- CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
- newAnnotation.bounds = bounds;
- [newAnnotation setBorderBoundsWithImage:image];
- [self addAnnotation:newAnnotation toPage:page];
- [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
-
- [self updateActiveAnnotations:@[newAnnotation]];
- [self setNeedsDisplayAnnotation:newAnnotation];
- }
- else NSBeep();
- }
- - (void)updateIsRightActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
- [self refreshActiveAnnotations:activeAnnotations isRight:YES];
- }
- - (void)updateActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
- [self refreshActiveAnnotations:activeAnnotations isRight:NO];
- }
- -(void)refreshActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations isRight:(BOOL)isRight {
- // for (CPDFAnnotation *annotation in self.activeAnnotations) {
- // if([annotation isKindOfClass:[CPDFLinkAnnotation class]]) {
- // CPDFLinkAnnotation *linkAnnotation = (CPDFLinkAnnotation *)annotation;
- // if((linkAnnotation.destination || linkAnnotation.URL.length > 0)) {
- // } else {
- // [self removeAnnotation:linkAnnotation];
- // }
- // }
- // }
-
- if(activeAnnotations) {
- NSArray *selectTure = [activeAnnotations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in %@", self.activeAnnotations]];
-
- BOOL isSame = NO;
- if(self.activeAnnotations.count == activeAnnotations.count && self.activeAnnotations.count == selectTure.count) isSame = YES;
-
- if(!isSame) {
- self.activeAnnotations = [NSMutableArray arrayWithArray:activeAnnotations];
-
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
- [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
- });
- }
- } else if (!activeAnnotations && self.activeAnnotations.count > 0) {
- [self.activeAnnotations removeAllObjects];
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
- [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:isRight];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
- });
- }
- }
- - (void)addActiveAnnotations:(NSArray<CPDFAnnotation *> *)activeAnnotations {
- BOOL isContains = YES;
- for (CPDFAnnotation *annotation in activeAnnotations) {
- if(![self.activeAnnotations containsObject:annotation]) {
- [self.activeAnnotations addObject:annotation];
- isContains = NO;
- }
- }
-
- if(!isContains) {
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
- [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
- });
- }
- }
- - (void)removeActiveAnnotations:(NSArray<CPDFAnnotation *> *)removeAnnotations {
- BOOL isContains = NO;
- NSMutableArray *tarr = [NSMutableArray arrayWithArray:self.activeAnnotations];
- [tarr removeObjectsInArray:removeAnnotations];
- self.activeAnnotations = tarr;
- isContains = YES;
- if(isContains) {
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewChangeatioActiveAnnotations:forActiveAnnotations:isRightMenu:)])
- [self.pdfListViewDelegate PDFListViewChangeatioActiveAnnotations:self forActiveAnnotations:self.activeAnnotations isRightMenu:NO];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewActiveAnnotationsChangeNotification object:self];
- });
- }
- }
- - (void)editAnnotation:(CPDFAnnotation *)annotation {
- if ([annotation isKindOfClass:[CPDFFreeTextAnnotation class]]) {
- [self editAnnotationFreeText:(CPDFFreeTextAnnotation *)annotation];
- [[self window] makeFirstResponder:self];
-
- [self setNeedsDisplayAnnotation:annotation];
- } else if ([annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] || [annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
- [self editFormAnnotation:self.activeAnnotation];
- } else {
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewEditAnnotation:forAnnotation:)]) {
- [self.pdfListViewDelegate PDFListViewEditAnnotation:self forAnnotation:annotation];
- } else {
- [CPDFListView cancelPreviousPerformRequestsWithTarget:self selector:@selector(showHUDHint:) object:self.hoverAnnotation];
- if (!self.popOver) {
- _popOver = [[NSPopover alloc] init];
- }
-
- if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
- __block typeof(self) blockSelf = self;
- _popOver.delegate = self;
- CPDFListEditAnnotationViewController *vc = [[CPDFListEditAnnotationViewController alloc] initWithNibName:@"CPDFListEditAnnotationViewController" bundle:[NSBundle mainBundle] annotation:annotation];
- vc.pdflistView = self;
- _popOver.contentViewController = vc;
- vc.closeCallBack = ^{
- [blockSelf.popOver close];
- };
- NSBox *box = (NSBox *)vc.view;
- NSView *popoverView = [[[self.popOver contentViewController] view] superview];
- [popoverView setWantsLayer:YES];
-
- vc.changeColorCallBack = ^{
- NSColor *borColor = annotation.color?:[NSColor whiteColor];
- [[popoverView layer] setBackgroundColor:borColor.CGColor];
- [blockSelf setNeedsDisplayAnnotationViewForPage:annotation.page];
- };
- NSColor *borColor = annotation.color?:[NSColor whiteColor];
- [[popoverView layer] setBackgroundColor:borColor.CGColor];
- _popOver.animates = YES;
- _popOver.behavior = NSPopoverBehaviorTransient;
- [_popOver showRelativeToRect:[self convertRect:annotation.bounds fromPage:annotation.page] ofView:self preferredEdge:NSMaxXEdge];
- } else if(![annotation isKindOfClass:[CPDFLinkAnnotation class]]){
- CPDFListAnnotationNoteWindowController *wc = [CPDFListAnnotationNoteWindowController sharedInstance];
- CGRect rect = wc.window.frame;
- CGRect anBounds = [self convertRect:annotation.bounds fromPage:annotation.page];
-
- anBounds = [self convertRectToScreen:anBounds];
- rect.origin.x = anBounds.origin.x;
- rect.origin.y = anBounds.origin.y;
- if (@available(macOS 10.13, *))
- [wc.window makeKeyAndOrderFront:nil];
- else
- [wc showWindow:nil];
- [wc updateAnnotation:annotation];
- [wc.window setFrame:rect display:YES animate:NO];
- wc.window.title = @"";
- }
-
- }
- }
- }
- - (void)rotateStampAnnotation:(CPDFListStampAnnotation *)annotation rotateAngle:(NSInteger)angle {
- if([annotation isKindOfClass:[CPDFListStampAnnotation class]]) {
- CPDFListStampAnnotation *stampAnnotation = (CPDFListStampAnnotation *)annotation;
- NSInteger rotation = stampAnnotation.rotation;
- rotation = rotation - angle;
-
- if (rotation < 0) {
- rotation += 360;
- } else if (rotation >= 360) {
- rotation-=360;
- }
- [annotation setRotation:rotation];
- rotation = [annotation appearanceStreamRotation];
-
- [self setNeedsDisplayAnnotationViewForPage:annotation.page];
-
- [[[self undoManager] prepareWithInvocationTarget:self] rotateStampAnnotation:annotation rotateAngle:-angle];
- }
- }
- - (void)rotateSignatureAnnotation:(CPDFListSignatureAnnotation *)annotation rotateAngle:(NSInteger)angle {
- if([annotation isKindOfClass:[CPDFListSignatureAnnotation class]]) {
- CPDFListSignatureAnnotation *signatureAnnotation = (CPDFListSignatureAnnotation *)annotation;
- NSInteger rotation = signatureAnnotation.rotation;
- rotation = rotation - angle;
-
- if (rotation < 0) {
- rotation += 360;
- } else if (rotation >= 360) {
- rotation-=360;
- }
- [signatureAnnotation setRotation:rotation];
- rotation = [signatureAnnotation appearanceStreamRotation];
-
- [self setNeedsDisplayAnnotationViewForPage:annotation.page];
-
- [[[self undoManager] prepareWithInvocationTarget:self] rotateSignatureAnnotation:annotation rotateAngle:-angle];
- }
- }
- - (void)addAnnotationWithAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
- [self addAnnotation:annotation toPage:page];
- }
- - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page {
- if (annotation == nil) {
- return;
- }
-
- [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
-
- [annotation setModificationDate:[NSDate date]];
- //widget设置作者与fieldName冲突
- if (![annotation isKindOfClass:[CPDFWidgetAnnotation class]]) {
- [annotation setUserName:CPDFKitShareConfig.annotationAuthor?:NSFullUserName()];
- }
- [page addAnnotation:annotation];
- [self setNeedsDisplayAnnotation:annotation];
- [self updateHighLightAnnotation:annotation];
- [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidAddAnnotationNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:page, CPDFListViewPageKey, annotation, CPDFListViewAnnotationKey, nil]];
- });
-
- [self resetPDFToolTipRectsForAfterDelay];
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewAddAnnotations:forAddAnnotations:inPage:)])
- [self.pdfListViewDelegate PDFListViewAddAnnotations:self forAddAnnotations:@[annotation] inPage:page];
- }
- - (void)removeAnnotation:(CPDFAnnotation *)annotation {
- if ([annotation isKindOfClass:[CPDFTextAnnotation class]] && self.popOver.isShown) {
- // if (annotation.contents.length <= 0) {
- CPDFAnnotation *wasAnnotation = annotation;
- CPDFPage *page = wasAnnotation.page;
-
- [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
-
- [page removeAnnotation:wasAnnotation];
- [self annotationsChangedOnPage:page];
- [self setNeedsDisplayAnnotation:wasAnnotation];
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
- userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
- });
-
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
- [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
- // }
- } else {
- CPDFAnnotation *wasAnnotation = annotation;
- CPDFPage *page = wasAnnotation.page;
-
- [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
- if ([wasAnnotation isNote]) {
- [self resetPDFToolTipRectsForAfterDelay];
- }
- [page removeAnnotation:wasAnnotation];
- [self annotationsChangedOnPage:page];
- [self setNeedsDisplayAnnotation:wasAnnotation];
- [self updateHighLightAnnotation:annotation];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:CPDFListViewDidRemoveAnnotationNotification object:self
- userInfo:[NSDictionary dictionaryWithObjectsAndKeys:wasAnnotation, CPDFListViewAnnotationKey, page, CPDFListViewPageKey, nil]];
- });
-
- if([self.pdfListViewDelegate respondsToSelector:@selector(PDFListViewRemoveAnnotations:forRemoveAnnotations:inPage:)])
- if (annotation) {
- [self.pdfListViewDelegate PDFListViewRemoveAnnotations:self forRemoveAnnotations:@[annotation] inPage:page];
- }
- }
- }
- - (void)drawPage:(CPDFPage *)pdfPage toContext:(CGContextRef)context {
- [super drawPage:pdfPage toContext:context];
-
- [self drawSelectionForPage:pdfPage inContext:context];
-
- BOOL isIncludText = NO;
- NSMutableArray *currentActiveAnnotations = [NSMutableArray array];
- NSMutableArray *currentPageAnnotations = [NSMutableArray array];
- for (CPDFAnnotation *an in self.activeAnnotations) {
- if([an.page isEqual:pdfPage]) {
- if([an isKindOfClass:[CPDFFreeTextAnnotation class]])
- isIncludText = YES;
-
- //多选注释框去除mark注释与便签注释
- if(!([an isKindOfClass:[CPDFMarkupAnnotation class]] || [an isKindOfClass:[CPDFTextAnnotation class]])) {
- [currentActiveAnnotations addObject:an];
- }
-
- [currentPageAnnotations addObject:an];
- }
- }
-
- if(currentActiveAnnotations.count > 1) {
- NSRect rect = [self selectionMultipleBoundsWithAnnotations:currentActiveAnnotations];
-
- CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
- CGContextSaveGState(context);
- CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
- CGContextSetStrokeColorWithColor(context, color);
- CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
- CGContextRestoreGState(context);
- CGContextSaveGState(context);
- if(isIncludText) {
- [CPDFListView DrawFreeTextResizeHandle:context rect:rect radius: 4.0 * lineWidth active:true];
- } else {
- [CPDFListView DrawResizeHandles:context rect:rect radius:4.0 * lineWidth active:true];
- }
- CGContextRestoreGState(context);
- }
-
- if(self.multiplAnnotationObject &&
- !CGRectIsEmpty(self.multiplAnnotationObject.drawRect) &&
- self.multiplAnnotationObject.page == pdfPage) {
- CGRect selectAnnotationBounds = self.multiplAnnotationObject.drawRect;
-
- NSRect rect = selectAnnotationBounds;
- CGFloat lineWidth = [self unitWidthOnPage:pdfPage];
- CGContextSaveGState(context);
- CGColorRef color = [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor;
- CGContextSetStrokeColorWithColor(context, color);
- CGContextStrokeRectWithWidth(context, CGRectInset(NSRectToCGRect(rect), 0,0), lineWidth);
- CGContextRestoreGState(context);
- }
-
- [currentPageAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
- if (annotation.page && [annotation.page isEqual:pdfPage]) {
- [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
- }
- }];
-
- [self.selectAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
- if (annotation.page && [annotation.page isEqual:pdfPage]) {
- [annotation drawSelectionHighlightForView:self inContext:context isHover:NO];
- }
- }];
-
- if (self.hoverAnnotation.page && [self.hoverAnnotation.page isEqual:pdfPage] && ![self.activeAnnotations containsObject:self.hoverAnnotation]) {
- [self.hoverAnnotation drawSelectionHighlightForView:self inContext:context isHover:YES];
- }
-
- if(!CGRectEqualToRect(self.multiplSelectBounds, CGRectZero) && [self.multiplSelectPage isEqual:pdfPage]) {
- @synchronized (self) {
- CGContextSetLineCap(context, kCGLineCapRound);
- CGContextSetLineWidth(context, 1.0);
- CGContextSetStrokeColorWithColor(context, [CPDFListViewConfig defaultManager].annotationBorderColor.CGColor);
- CGContextBeginPath(context);
- CGContextMoveToPoint(context, self.multiplSelectBounds.origin.x, self.multiplSelectBounds.origin.y);
- CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x+ self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y);
- CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x + self.multiplSelectBounds.size.width,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
- CGContextAddLineToPoint(context, self.multiplSelectBounds.origin.x,self.multiplSelectBounds.origin.y + + self.multiplSelectBounds.size.height);
- CGContextClosePath(context);
- CGFloat lengths[] = {5,5};
- CGContextSetLineDash(context, 0, lengths,2);
- CGContextStrokePath(context);
- }
- }
- }
- - (void)drawSelectionForPage:(CPDFPage *)pdfPage inContext:(CGContextRef)context {
- NSRect rect;
- NSUInteger pageIndex;
- @synchronized (self) {
- pageIndex = self.selectionPageIndex;
- rect = self.selectionRect;
- }
- if (pageIndex != NSNotFound) {
- BOOL isWidget = NO;
- for (CPDFAnnotation * annotation in self.activeAnnotations) {
- if ([annotation isForm]) {
- isWidget = YES;
- break;
- }
- }
-
- if (isWidget &&
- _toolMode != CFormToolMode) {
- return;
- }
-
- NSRect bounds = [pdfPage boundsForBox:[self displayBox]];
- CGFloat radius = HANDLE_SIZE * [self unitWidthOnPage:pdfPage];
- CGColorRef color = CGColorCreateGenericGray(0.0, 0.6);
- CGContextSetFillColorWithColor(context, color);
- CGColorRelease(color);
- CGContextBeginPath(context);
- CGContextAddRect(context, NSRectToCGRect(bounds));
- CGContextAddRect(context, NSRectToCGRect(rect));
- CGContextEOFillPath(context);
- if ([pdfPage pageIndex] != pageIndex) {
- color = CGColorCreateGenericGray(0.0, 0.3);
- CGContextSetFillColorWithColor(context, color);
- CGColorRelease(color);
- CGContextFillRect(context, NSRectToCGRect(rect));
- }
- [CPDFListView DrawResizeHandles:context rect:rect radius:radius active:true];
- }
- }
- - (void)removeShapeLayer {
- if (![self.shapeLayerTopH isEqual:nil] && ![self.shapeLayerBottomH isEqual:nil] && ![self.shapeLayerLeftV isEqual:nil] && ![self.shapeLayerRightV isEqual:nil]) {
- [self.shapeLayerTopH removeFromSuperlayer];
- [self.shapeLayerBottomH removeFromSuperlayer];
- [self.shapeLayerLeftV removeFromSuperlayer];
- [self.shapeLayerRightV removeFromSuperlayer];
- self.shapeLayerTopH = nil;
- self.shapeLayerBottomH = nil;
- self.shapeLayerLeftV = nil;
- self.shapeLayerRightV = nil;
- }
- }
- - (BOOL)consistentTypeWithAnnotation:(CPDFAnnotation *)annotation {
- if (self.annotationType == CAnnotationTypeSignSignature) {
- if (![annotation isKindOfClass:[CPDFSignatureAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeStamp) {
- if (![annotation isKindOfClass:[CPDFStampAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeAnchored) {
- if (![annotation isKindOfClass:[CPDFTextAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeLink) {
- if (![annotation isKindOfClass:[CPDFLinkAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeFreeText) {
- if (![annotation isKindOfClass:[CPDFFreeTextAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeLine || self.annotationType == CAnnotationTypeArrow || self.annotationType == CAnnotationTypeSquare || self.annotationType == CAnnotationTypeCircle) {
- if (![annotation isKindOfClass:[CPDFLineAnnotation class]] && ![annotation isKindOfClass:[CPDFSquareAnnotation class]] && ![annotation isKindOfClass:[CPDFCircleAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeHighlight || self.annotationType == CAnnotationTypeUnderline || self.annotationType == CAnnotationTypeStrikeOut) {
- if (![annotation isKindOfClass:[CPDFMarkupAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeInk) {
- if (![annotation isKindOfClass:[CPDFInkAnnotation class]])
- return NO;
- } else if (self.annotationType == CAnnotationTypeRadioButton) {
-
- } else if (self.annotationType == CAnnotationTypeCheckBox) {
-
- } else if (self.annotationType == CAnnotationTypeTextField) {
-
- } else if (self.annotationType == CAnnotationTypeComboBox) {
-
- } else if (self.annotationType == CAnnotationTypeListMenu) {
-
- } else if (self.annotationType == CAnnotationTypeActionButton) {
-
- } else if (self.annotationType == CAnnotationTypeSignature) {
-
- } else if (self.annotationType == CAnnotationTypeSignText) {
-
- } else if (self.annotationType == CAnnotationTypeSignFalse) {
-
- } else if (self.annotationType == CAnnotationTypeSignTure) {
-
- } else if (self.annotationType == CAnnotationTypeSignCircle) {
-
- } else if (self.annotationType == CAnnotationTypeSignLine) {
-
- } else if (self.annotationType == CAnnotationTypeSignDot) {
-
- } else if (self.annotationType == CAnnotationTypeSignConfig) {
-
- } else if (self.annotationType == CAnnotationTypeSignDate) {
-
- }
- return YES;
- }
- #pragma mark Zooming
- - (void)zoomToRect:(NSRect)rect onPage:(CPDFPage *)page {
- if (NSIsEmptyRect(rect) == NO) {
- BOOL isLegacy = [NSScroller respondsToSelector:@selector(preferredScrollerStyle)] == NO || [NSScroller preferredScrollerStyle] == NSScrollerStyleLegacy;
- NSRect bounds = [self bounds];
- CGFloat scale = 1.0;
- if (isLegacy) {
- bounds.size.width -= [NSScroller scrollerWidth];
- bounds.size.height -= [NSScroller scrollerWidth];
- }
- if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
- scale = NSHeight(bounds) / NSHeight(rect);
- else
- scale = NSWidth(bounds) / NSWidth(rect);
- [self setScaleFactor:scale];
- NSScrollView *scrollView = [self scrollView];
- if (isLegacy && ([scrollView hasHorizontalScroller] == NO || [scrollView hasVerticalScroller] == NO)) {
- if ([scrollView hasVerticalScroller])
- bounds.size.width -= [NSScroller scrollerWidth];
- if ([scrollView hasHorizontalScroller])
- bounds.size.height -= [NSScroller scrollerWidth];
- if (NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds))
- scale = NSHeight(bounds) / NSHeight(rect);
- else
- scale = NSWidth(bounds) / NSWidth(rect);
- [self setScaleFactor:scale];
- }
- [self goToRect:rect onPage:page];
-
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- CGPoint tPagePoint = CGPointMake(rect.origin.x, rect.origin.y+rect.size.height);
- [self goToTargetPoint:tPagePoint onPage:page atScrollPosition:CScrollPositionTop];
- });
- }
- }
- #pragma mark NSDraggingDestination protocol
- - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
- 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];
- NSPasteboard *pasteboard = [sender draggingPasteboard];
- if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]) {
- NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
- NSString *filePath = fileNames.firstObject;
- if (fileNames.count == 1 && [supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
- return NSDragOperationCopy;
- }
- }
- return NSDragOperationNone;
- }
- - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender {
- NSDragOperation dragOp = NSDragOperationNone;
- NSPasteboard *pboard = [sender draggingPasteboard];
- if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
- NSPoint location = [self convertPoint:[sender draggingLocation] fromView:nil];
- CPDFPage *page = [self pageForPoint:location nearest:NO];
- if (page) {
- NSArray *annotations = [page annotations];
- CPDFAnnotation *annotation = nil;
- NSInteger i = [annotations count];
- location = [self convertPoint:location toPage:page];
- while (i-- > 0) {
- annotation = [annotations objectAtIndex:i];
- if ([self annoHitTest:location Anno:annotation] &&
- ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, nil]] || [annotation hasBorder])) {
- // if ([annotation isEqual:highlightAnnotation] == NO) {
- // if (highlightAnnotation)
- // [self setNeedsDisplayForAnnotation:highlightAnnotation];
- // [self setHighlightAnnotation:annotation];
- // [self setNeedsDisplayForAnnotation:highlightAnnotation];
- // }
- dragOp = NSDragOperationGeneric;
- break;
- }
- }
- }
- if (dragOp == NSDragOperationNone /*&& highlightAnnotation*/) {
- // [self setNeedsDisplayForAnnotation:highlightAnnotation];
- // [self setHighlightAnnotation:nil];
- }
- } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
- dragOp = [super draggingUpdated:sender];
- }
- return dragOp;
- }
- - (BOOL)annoHitTest:(NSPoint)point Anno: (CPDFAnnotation *)anno{
- return [anno shouldDisplay] ? NSPointInRect(point, [self bounds]) : NO;
- }
- - (void)draggingExited:(id <NSDraggingInfo>)sender {
- NSPasteboard *pboard = [sender draggingPasteboard];
- if ([pboard canReadItemWithDataConformingToTypes:[NSArray arrayWithObjects:NSPasteboardTypeColor, SKPasteboardTypeLineStyle, nil]]) {
- // if (highlightAnnotation) {
- // [self setNeedsDisplayForAnnotation:highlightAnnotation];
- // [self setHighlightAnnotation:nil];
- // }
- } else if ([[CPDFListView superclass] instancesRespondToSelector:_cmd]) {
- [super draggingExited:sender];
- }
- }
- - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
- BOOL performedDrag = NO;
- NSPasteboard *pasteboard = [sender draggingPasteboard];
- if ([sender draggingSource] != self) {
- NSArray* filePaths = [pasteboard propertyListForType:NSFilenamesPboardType];
- 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];
-
- NSString *filePath = filePaths.firstObject;
- if ([supportArray containsObject:[filePath.pathExtension lowercaseString]]) {
- if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
- [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
- return NO;
- }
- if([[filePath.pathExtension lowercaseString] isEqual:@"pdf"]) {
- PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:filePath]];
- if([document isLocked]) {
- return NO;
- }
- }
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:filePath];
-
- NSPoint point = [sender draggingLocation];
- point = [self convertPoint:point fromView:nil];
- CPDFPage *page = [self pageForPoint:point nearest:YES];
- NSRect rect = NSMakeRect(point.x, point.y - 45, 360, 90);
- NSRect bounds = [self convertRect:rect toPage:page];
- if (page != nil) {
- CPDFListStampAnnotation *newAnnotation = [[CPDFListStampAnnotation alloc] initWithDocument:self.document image:image];
- newAnnotation.bounds = bounds;
- [newAnnotation setBorderBoundsWithImage:image];
-
- [self addAnnotation:newAnnotation toPage:page];
- [[self undoManager] setActionName:NSLocalizedString(@"Add Note", @"Undo action name")];
-
- [self updateActiveAnnotations:@[newAnnotation]];
- [self setNeedsDisplayAnnotation:newAnnotation];
- }
- return YES;
- }
- }
- return NO;
- }
- #pragma mark - NSPopoverDelegate
- - (void)popoverWillClose:(NSNotification *)notification {
- NSPopover *popover = notification.object;
-
- if([popover.contentViewController isKindOfClass:[CPDFListEditAnnotationViewController class]]) {
- CPDFListEditAnnotationViewController *listEditAnnotationViewController = (CPDFListEditAnnotationViewController *)popover.contentViewController;
- CPDFAnnotation *annotation = listEditAnnotationViewController.annotation;
- NSString *contensString = listEditAnnotationViewController.contentString;
- if([annotation isKindOfClass:[CPDFTextAnnotation class]]) {
- if(contensString && contensString.length > 0) {
- annotation.contents = listEditAnnotationViewController.contentString;
- [self setNeedsDisplayAnnotation:annotation];
- } else {
- if([self.activeAnnotations containsObject:annotation]) {
- [self.activeAnnotations removeObject:annotation];
- }
- [self removeAnnotation:annotation];
- }
- } else {
- annotation.contents = listEditAnnotationViewController.contentString;
- [self setNeedsDisplayAnnotation:annotation];
- }
- }
- self.popOver = nil;
- }
- - (void)handlePageChangedNotification:(NSNotification *)notification {
- if (self.isSinglePageMode || self.isTwoPageMode) {
- [self resetPDFToolTipRectsForAfterDelay];
- }
-
- self.copyCount = 0;
- }
- #pragma mark - Form Alignment
- - (KMPDFViewActiveFormsType)formAnnotionsType:(NSArray *)annotationArray {
-
- NSSet *set = [NSSet setWithArray:[annotationArray valueForKey:@"type"]];
- NSArray *array = [set allObjects];
-
- if (array.count > 1 || ![array.firstObject isEqualToString:@"Widget"]) {
- return KMPDFViewActiveFormsType_NotAllform;
- }
-
- PDFAnnotation *referenceAnnotation = annotationArray.firstObject;
- Class referenceAnnotationClass = [referenceAnnotation class];
- if ([referenceAnnotationClass isEqual:[CPDFButtonWidgetAnnotation class]]) {
- referenceAnnotationClass = [CPDFButtonWidgetAnnotation superclass];
- }
-
- if ([referenceAnnotationClass isEqual:[CPDFTextWidgetAnnotation class]]) {
- referenceAnnotationClass = [CPDFTextWidgetAnnotation superclass];
- }
-
- if ([referenceAnnotationClass isEqual:[CPDFChoiceWidgetAnnotation class]]) {
- referenceAnnotationClass = [CPDFChoiceWidgetAnnotation superclass];
- }
-
- if (annotationArray.count == 1) {
- if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]) {
- return KMPDFViewActiveFormsType_TextSingle;
- } else {
- return KMPDFViewActiveFormsType_PureSingle;
- }
- }
-
- for (NSInteger i = 0; i < annotationArray.count; i++) {
- PDFAnnotation *annotation = [annotationArray objectAtIndex:i];
- if (![annotation isKindOfClass:[CPDFButtonWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFTextWidgetAnnotation class]] && ![annotation isKindOfClass:[CPDFChoiceWidgetAnnotation class]]) {
- return KMPDFViewActiveFormsType_Mix;
- }
- }
-
- if ([referenceAnnotation isKindOfClass:[CPDFTextWidgetAnnotation class]]){
- return KMPDFViewActiveFormsType_Text;
- }
-
- return KMPDFViewActiveFormsType_Pure;
- }
- - (void)formsAnnotationAlign:(KMPDFActiveFormsAlignType)type {
- CGRect zeroRect = CGRectNull;
- CGRect highestRect = CGRectZero;
- CGRect widthestRect = CGRectZero;
-
- CPDFAnnotation *firstAnnotation = self.activeAnnotations.firstObject;
- CGRect leftestRect = firstAnnotation.bounds;
- CGRect rightestRect = firstAnnotation.bounds;
- CGRect topestRect = firstAnnotation.bounds;
- CGRect bottomestRect = firstAnnotation.bounds;
-
- CPDFAnnotation *leftestAnnotation = firstAnnotation;
- CPDFAnnotation *rightestAnnotation = firstAnnotation;
- CPDFAnnotation *topestAnnotation = firstAnnotation;
- CPDFAnnotation *bottomestAnnotation = firstAnnotation;
-
- CGFloat totalWidth = 0.;
- CGFloat totalHeight = 0.;
- for (CPDFAnnotation *annotation in self.activeAnnotations) {
- zeroRect = CGRectUnion(zeroRect, annotation.bounds);
- totalWidth += CGRectGetWidth(annotation.bounds);
- totalHeight += CGRectGetHeight(annotation.bounds);
- if (CGRectGetHeight(annotation.bounds) > CGRectGetHeight(highestRect)) {
- highestRect = annotation.bounds;
- }
-
- if (CGRectGetWidth(annotation.bounds) > CGRectGetWidth(widthestRect)) {
- widthestRect = annotation.bounds;
- }
-
- if (CGRectGetMinX(leftestRect) > CGRectGetMinX(annotation.bounds)) {
- leftestRect = annotation.bounds;
- leftestAnnotation = annotation;
- }
-
- if (CGRectGetMaxX(annotation.bounds) > CGRectGetMaxX(rightestRect)) {
- rightestRect = annotation.bounds;
- rightestAnnotation = annotation;
- }
-
- if (CGRectGetMaxY(annotation.bounds) > CGRectGetMaxY(topestRect)) {
- topestRect = annotation.bounds;
- topestAnnotation = annotation;
- }
-
- if (CGRectGetMinY(bottomestRect) > CGRectGetMinY(annotation.bounds)) {
- bottomestRect = annotation.bounds;
- bottomestAnnotation = annotation;
- }
- }
- if (type == KMPDFActiveFormsAlignType_Left ) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.x = zeroRect.origin.x;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_Right) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.x = CGRectGetMaxX(zeroRect) - bounds.size.width;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_Top) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.y = CGRectGetMaxY(zeroRect) - bounds.size.height;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_Bottom) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.y = CGRectGetMinY(zeroRect);
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_Horizontally) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.y = CGRectGetMidY(highestRect) - CGRectGetHeight(bounds)/2;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_Vertical) {
- NSMutableArray *newBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i< self.activeAnnotations.count; i++) {
- CPDFAnnotation *annotation = [self.activeAnnotations objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.x = CGRectGetMidX(widthestRect) - CGRectGetWidth(bounds)/2;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- }
- [self changeAnnotationsAlign:self.activeAnnotations newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_DisHorizontally) {
- CGFloat middleGap = CGRectGetWidth(zeroRect) - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
- CGFloat otherAnnotationsTotalWidth = totalWidth - CGRectGetWidth(leftestRect) - CGRectGetWidth(rightestRect);
-
- CGFloat gap = (middleGap - otherAnnotationsTotalWidth)/(self.activeAnnotations.count - 1);
- NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
- [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
- CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
- CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
- if (annotation1.bounds.origin.x < annotation2.bounds.origin.x) {
- return NSOrderedAscending;
- } else {
- return NSOrderedDescending;
- }
- }];
-
- [annotationsCopyArray removeObject:leftestAnnotation];
- [annotationsCopyArray removeObject:rightestAnnotation];
-
- NSMutableArray *newBoundsArray = [NSMutableArray array];
-
- CGFloat leftStartX = CGRectGetMaxX(leftestRect) + gap;
- for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
- CPDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.x = leftStartX;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- leftStartX += CGRectGetWidth(bounds) + gap;
- }
- [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
- } else if (type == KMPDFActiveFormsAlignType_DisVertical) {
- CGFloat middleGap = CGRectGetHeight(zeroRect) - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
- CGFloat otherAnnotationsTotalHeight = totalHeight - CGRectGetHeight(topestRect) - CGRectGetHeight(bottomestRect);
-
- CGFloat gap = (middleGap - otherAnnotationsTotalHeight)/(self.activeAnnotations.count - 1);
- NSMutableArray *annotationsCopyArray = [self.activeAnnotations mutableCopy];
- [annotationsCopyArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
- CPDFAnnotation *annotation1 = (CPDFAnnotation *)obj1;
- CPDFAnnotation *annotation2 = (CPDFAnnotation *)obj2;
- if (annotation1.bounds.origin.y < annotation2.bounds.origin.y) {
- return NSOrderedAscending;
- } else {
- return NSOrderedDescending;
- }
- }];
-
- [annotationsCopyArray removeObject:topestAnnotation];
- [annotationsCopyArray removeObject:bottomestAnnotation];
-
- NSMutableArray *newBoundsArray = [NSMutableArray array];
-
- CGFloat bottomStartY = CGRectGetMaxY(bottomestRect) + gap;
- for (NSInteger i = 0; i < annotationsCopyArray.count; i++) {
- PDFAnnotation *annotation = [annotationsCopyArray objectAtIndex:i];
- CGRect bounds = annotation.bounds;
- bounds.origin.y = bottomStartY;
- [newBoundsArray addObject:NSStringFromRect(bounds)];
- bottomStartY += CGRectGetHeight(bounds) + gap;
- }
- [self changeAnnotationsAlign:annotationsCopyArray newBounds:newBoundsArray];
- }
- }
- - (void)changeAnnotationsAlign:(NSArray *)annotationArray newBounds:(NSArray *)newBoundsArray {
- NSMutableArray * oldBoundsArray = [NSMutableArray array];
- for (NSInteger i = 0; i < annotationArray.count; i++) {
- CPDFAnnotation *annotation = [annotationArray objectAtIndex:i];
- [oldBoundsArray addObject:NSStringFromRect(annotation.bounds)];
- annotation.bounds = NSRectFromString([newBoundsArray objectAtIndex:i]);
- }
- [[[self undoManager] prepareWithInvocationTarget:self] changeAnnotationsAlign:annotationArray newBounds:oldBoundsArray];
- [self setNeedsDisplay:YES];
- }
- #pragma mark Services
- - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types {
- if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound) {
- NSMutableArray *writeTypes = [NSMutableArray array];
- NSString *pdfType = nil;
- NSData *pdfData = nil;
- NSString *tiffType = nil;
- NSData *tiffData = nil;
- NSRect selRect = NSIntegralRect(_selectionRect);
-
- // 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
- if ([[self document] allowsPrinting] && [[self document] isLocked] == NO) {
- if ([types containsObject:NSPasteboardTypePDF])
- pdfType = NSPasteboardTypePDF;
- else if ([types containsObject:NSPasteboardTypePDF])
- pdfType = NSPasteboardTypePDF;
- if (pdfType && (pdfData = [[self currentSelectionPage] pdfDataFor:selRect]))
- [writeTypes addObject:pdfType];
- }
- if ([types containsObject:NSPasteboardTypeTIFF])
- tiffType = NSPasteboardTypeTIFF;
- else if ([types containsObject:NSPasteboardTypeTIFF])
- tiffType = NSPasteboardTypeTIFF;
- if (tiffType && (tiffData = [[self currentSelectionPage] PDFListViewTIFFDataFor:selRect]))
- [writeTypes addObject:tiffType];
- if ([writeTypes count] > 0) {
- [pboard declareTypes:writeTypes owner:nil];
- if (pdfData)
- [pboard setData:pdfData forType:pdfType];
- if (tiffData)
- [pboard setData:tiffData forType:tiffType];
- return YES;
- }
- }
- if ([[self currentSelection] hasCharacters]) {
- if ([types containsObject:NSPasteboardTypeRTF] || [types containsObject:NSPasteboardTypeRTF]) {
- [pboard clearContents];
- NSAttributedString *attri = [[self currentSelection] attributedString];
- if (attri != nil) {
- [pboard writeObjects:[NSArray arrayWithObjects:attri, nil]];
- }
- return YES;
- } else if ([types containsObject:NSPasteboardTypeString] || [types containsObject:NSPasteboardTypeString]) {
- [pboard clearContents];
- NSString *str = [[self currentSelection] string];
- if (str != nil) {
- [pboard writeObjects:[NSArray arrayWithObjects:str, nil]];
- }
- return YES;
- }
- }
-
-
- return [[CPDFListView superclass] instancesRespondToSelector:_cmd];
- }
- - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType {
- if ([self toolMode] == CSelectToolMode && NSIsEmptyRect(_selectionRect) == NO && _selectionPageIndex != NSNotFound && returnType == nil &&
- (([[self document] allowsPrinting] && [[self document] isLocked] == NO && [sendType isEqualToString:NSPasteboardTypePDF]) || [sendType isEqualToString:NSPasteboardTypeTIFF])) {
- return self;
- }
- if ([[self currentSelection] hasCharacters] && returnType == nil && ([sendType isEqualToString:NSPasteboardTypeString] || [sendType isEqualToString:NSPasteboardTypeRTF])) {
- return self;
- }
- return [super validRequestorForSendType:sendType returnType:returnType];
- }
- #pragma mark Notification handling
- - (void)boundsDidChangeNotification:(NSNotification*)notification
- {
- id object = notification.object;
- NSClipView *pdfContentView = self.scrollView.contentView;
- if (object == pdfContentView) {
- if ([self.activeAnnotation isKindOfClass:[KMTableAnnotation class]] && [[(KMTableAnnotation*)self.activeAnnotation scrollView] superview]) {
- [(KMTableAnnotation*)self.activeAnnotation completeEditCellText];
- }
- }
- }
- @end
|