KMPDFEditAppendWindow.m 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  1. //
  2. // KMPDFEditAppendWindow.m
  3. // PDF Reader
  4. //
  5. // Created by 丁林圭 on 2017/5/11.
  6. // Copyright © 2017年 zhangjie. All rights reserved.
  7. //
  8. #import "KMPDFEditAppendWindow.h"
  9. #import <Quartz/Quartz.h>
  10. #import <Masonry/Masonry.h>
  11. #import <PDF_Reader_Pro-Swift.h>
  12. #import "CTBrowserWindowController.h"
  13. @interface KMPDFEditAppendTabelViewCell()
  14. @property (assign) IBOutlet NSTextField *pageCountLabel;
  15. @property (assign) IBOutlet NSTextField *indexLabel;
  16. @property (assign) IBOutlet NSTextField *fileNameLabel;
  17. @property (assign) IBOutlet NSTextField *pageRangeLabel;
  18. @property (assign) IBOutlet NSTextField *sizeLabel;
  19. @property (assign) IBOutlet NSImageView *fileImage;
  20. @property (assign) IBOutlet NSComboBox *pageRangeBox;
  21. @property (nonatomic, copy) void(^removeCallBack)(void);
  22. @end
  23. @implementation KMPDFEditAppendTabelViewCell
  24. - (void)dealloc {}
  25. - (IBAction)buttonClicked_Remove:(id)sender {
  26. if (self.removeCallBack) {
  27. self.removeCallBack();
  28. }
  29. }
  30. - (void)awakeFromNib {
  31. [super awakeFromNib];
  32. }
  33. @end
  34. @interface KMAppendPDFPage: PDFPage
  35. @property (nonatomic, strong)PDFPage *drawingPage;
  36. @end
  37. @implementation KMAppendPDFPage
  38. - (void)dealloc {}
  39. //- (void)drawWithBox:(PDFDisplayBox)box {
  40. // [super drawWithBox:box];
  41. //
  42. // CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
  43. // CGSize pageSize = [self boundsForBox:kPDFDisplayBoxCropBox].size;
  44. // [self drawPageWithContext:context Page:self.drawingPage PageSize:pageSize];
  45. //}
  46. - (void)drawWithBox:(PDFDisplayBox)box toContext:(CGContextRef)context {
  47. [super drawWithBox:box toContext:context];
  48. CGSize pageSize = [self boundsForBox:kPDFDisplayBoxCropBox].size;
  49. [self drawPageWithContext:context Page:self.drawingPage PageSize:pageSize];
  50. }
  51. - (void)drawPageWithContext:(CGContextRef) context
  52. Page:(PDFPage *)page
  53. PageSize:(CGSize)pageSize
  54. {
  55. CGSize originalSize = [page boundsForBox:kPDFDisplayBoxCropBox].size;
  56. //如果page的旋转角度为90,或者270,宽高交换
  57. if (page.rotation%180) {
  58. originalSize = CGSizeMake(originalSize.height, originalSize.width);
  59. }
  60. CGFloat wRatio = pageSize.width/originalSize.width;
  61. CGFloat hRatio = pageSize.height/originalSize.height;
  62. CGFloat ratio = MIN(wRatio, hRatio);
  63. CGContextSaveGState(context);
  64. CGFloat xTransform = (pageSize.width - originalSize.width * ratio)/2;
  65. CGFloat yTransform = (pageSize.height - originalSize.height * ratio)/2;
  66. CGContextTranslateCTM(context, xTransform, yTransform);
  67. CGContextScaleCTM(context, ratio, ratio);
  68. NSImage *image = [NSImage imageNamed:@"KMImageNameWatermark"];
  69. if (@available(macOS 10.12, *)) {
  70. [page drawWithBox:kPDFDisplayBoxCropBox toContext:context];
  71. // [image drawInRect:NSMakeRect(10, 350, 100, 30) fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
  72. NSData *data = [image TIFFRepresentation];
  73. CGImageRef imageRef;
  74. if (data) {
  75. CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)data, NULL);
  76. imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
  77. CGContextDrawImage(context, CGRectMake(0, pageSize.height-32, 120, 32), imageRef);
  78. }
  79. [page transformContext:context forBox:kPDFDisplayBoxCropBox];
  80. } else {
  81. [NSGraphicsContext saveGraphicsState];
  82. [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:YES]];
  83. [page drawWithBox:kPDFDisplayBoxCropBox toContext:context];
  84. [NSGraphicsContext restoreGraphicsState];
  85. [page transformContext:context forBox:kPDFDisplayBoxCropBox];
  86. }
  87. CGContextRestoreGState(context);
  88. }
  89. @end
  90. #define MyTableCellViewDataType @"MyTableCellViewDataType"
  91. static NSString * const KMTableColumnFileNameID = @"fileName";
  92. static NSString * const KMTableColumnPageRangeID = @"pageRangD";
  93. static NSString * const KMTableColumnSizeID = @"size";
  94. static KMPDFEditAppendWindow *windowController = nil;
  95. @interface KMPDFEditAppendWindow ()<NSTableViewDataSource,NSTableViewDelegate,NSComboBoxDelegate, KMSelectPopButtonDelegate>
  96. {
  97. BOOL _isSuccessfully;
  98. NSInteger _insertRow;
  99. }
  100. @property (nonatomic, assign) NSInteger insertRow;
  101. @property (weak) IBOutlet NSBox *tableHeaderBox;
  102. @property (weak) IBOutlet NSTextField *fileNameLabel;
  103. @property (weak) IBOutlet NSTextField *pageRangeLabel;
  104. @property (weak) IBOutlet NSTextField *sizeLabel;
  105. @property (weak) IBOutlet NSBox *tableHeaderBottomLine;
  106. @property (assign) IBOutlet NSTableView *tableView;
  107. @property (assign) IBOutlet NSButton *removeButton;
  108. @property (assign) IBOutlet NSButton *appendButton;
  109. @property (assign) IBOutlet NSButton *cancelButton;
  110. //@property (assign) IBOutlet NSButton *addFileButton;
  111. @property (assign) IBOutlet NSBox *clearBox;
  112. @property (assign) IBOutlet NSBox *nMergeBox;
  113. @property (assign) IBOutlet NSBox *nCancelBox;
  114. @property (weak) IBOutlet NSBox *addBox;
  115. @property (nonatomic, strong) KMDesignSelect *addFileButton;
  116. @property (assign) IBOutlet NSProgressIndicator *progress;
  117. //宽输入框
  118. @property (assign) IBOutlet NSTextField *pageSizeWidthTextField;
  119. //宽高输入连接符
  120. @property (assign) IBOutlet NSTextField *pageSizeWidthHeightConnectorTextField;
  121. //高输入框
  122. @property (assign) IBOutlet NSTextField *pageSizeHeightTextField;
  123. //宽高单位
  124. @property (assign) IBOutlet NSTextField *pageSizeUnitLabel;
  125. @property (nonatomic,retain) NSMutableArray *files;
  126. @property (nonatomic,retain) NSArray *addFiles;
  127. @property (nonatomic, retain) NSMutableIndexSet *insertIndexSet;
  128. @property (nonatomic,retain) NSString *password;
  129. @property (nonatomic,retain) PDFDocument *PDFDocument;
  130. @property (nonatomic,assign) KMPDFPageEditType editType;
  131. @property (nonatomic,assign) CGFloat allFileSize;
  132. @property (nonatomic,retain) NSMutableArray *rootPDFOutlineArray;
  133. @property (nonatomic,assign) CGSize newPageSize;
  134. @property (nonatomic,retain) NSMutableArray *lockFilePathArr;
  135. @property (nonatomic,assign) NSInteger lockFileIndex;
  136. @property (weak) IBOutlet NSView *originalSizeButton;
  137. @property (weak) IBOutlet KMImageTitleButton *A4SizeButton;
  138. @property (weak) IBOutlet KMImageTitleButton *A3SizeButton;
  139. @property (weak) IBOutlet KMImageTitleButton *USLetterSizeButton;
  140. @property (weak) IBOutlet KMImageTitleButton *USLegalButton;
  141. @property (weak) IBOutlet KMImageTitleButton *customSizeButton;
  142. @property (assign) IBOutlet NSBox *box;
  143. @property (assign) IBOutlet NSTextField *boxLabel;
  144. @property (assign) IBOutlet KMBlankView *myBlankView;
  145. @property (weak) IBOutlet NSTextField *limitLable;
  146. @property (weak) IBOutlet NSImageView *limitTipIv;
  147. @property (nonatomic, strong) PasswordWindowController *passwordWindowController;
  148. @property (nonatomic, strong) KMSavePanelAccessoryController *savePanelAccessoryViewController;
  149. @property (nonatomic, assign) BOOL canMerge;
  150. @property (nonatomic, strong) KMDesignButton *clearVC;
  151. @property (nonatomic, strong) KMDesignButton *nMergeVC;
  152. @property (nonatomic, strong) KMDesignButton *nCancelVC;
  153. @property (nonatomic, strong) NSButton *loading_backgroundView;
  154. @property (nonatomic, strong) NSAlert *alert;
  155. @property (nonatomic, assign) BOOL limit;
  156. @end
  157. @implementation KMPDFEditAppendWindow
  158. - (void)dealloc
  159. {
  160. _tableView.delegate = nil;
  161. _tableView.dataSource = nil;
  162. #if VERSION_DMG
  163. [[NSNotificationCenter defaultCenter] removeObserver:self];
  164. #endif
  165. }
  166. //没有打开文档,选择he'bing
  167. - (id)initWithFilePaths:(NSArray *)files
  168. {
  169. if (self = [super initWithWindowNibName:@"KMPDFEditAppendWindow"]) {
  170. self.PDFDocument = [[PDFDocument alloc] init];
  171. self.addFiles = files;
  172. self.editType = KMPDFPageEditMerge;
  173. _lockFilePathArr = [[NSMutableArray alloc] init];
  174. _files = [[NSMutableArray alloc] init];
  175. }
  176. return self;
  177. }
  178. - (id)initWithPDFDocument:(PDFDocument *)document password:(NSString *)password
  179. {
  180. if (self = [super initWithWindowNibName:@"KMPDFEditAppendWindow"]) {
  181. // self.PDFDocument = document;
  182. self.PDFDocument = [[PDFDocument alloc] init];
  183. self.editType = KMPDFPageEditAppend;
  184. _lockFilePathArr = [[NSMutableArray alloc] init];
  185. _files = [[NSMutableArray alloc] init];
  186. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  187. file.myPDFDocument = document;
  188. file.filePath = document.documentURL.path;
  189. file.oriFilePath = self.oriDucumentUrl.path;
  190. if (password && password.length > 0) {
  191. file.password = password;
  192. file.isLocked = YES;
  193. }
  194. [self.files addObject:file];
  195. }
  196. return self;
  197. }
  198. - (void)setOriDucumentUrl:(NSURL *)oriDucumentUrl {
  199. _oriDucumentUrl = oriDucumentUrl;
  200. KMFileAttribute *file = self.files.firstObject;
  201. file.oriFilePath = oriDucumentUrl.path;
  202. }
  203. - (void)km_windowWillCloseNotifation:(NSNotification *)noti {
  204. __weak typeof(self) weakSelf = self;
  205. BOOL result = [KMLightMemberManager.manager canPayFunction];
  206. self.limit = !result;
  207. if (result) {
  208. self.limitLable.hidden = YES;
  209. self.limitTipIv.hidden = YES;
  210. } else {
  211. // [KMLightMemberManager.manager canUseAdvancedWithNeedNetworking:NO completionHandler:^(BOOL isLogin) {
  212. // dispatch_sync(dispatch_get_main_queue(), ^{
  213. // if (isLogin) {
  214. // weakSelf.limitLable.hidden = NO;
  215. // weakSelf.limitTipIv.hidden = NO;
  216. // } else {
  217. // weakSelf.limitLable.hidden = YES;
  218. // weakSelf.limitTipIv.hidden = YES;
  219. // }
  220. // });
  221. // }];
  222. }
  223. }
  224. - (void)windowDidLoad {
  225. [super windowDidLoad];
  226. #if VERSION_DMG
  227. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(km_windowWillCloseNotifation:) name:NSWindowWillCloseNotification object:nil];
  228. #endif
  229. if ([self mergeCountIsReach]) {
  230. NSLog(@"合并次数已达到限制. count: %ld", [self getMergeCount]);
  231. }
  232. self.window.contentView.wantsLayer = YES;
  233. // self.window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
  234. self.clearVC = [[KMDesignButton alloc] initWithType: DesignButtonTypeImage];
  235. self.nMergeVC = [[KMDesignButton alloc] initWithType: DesignButtonTypeText];
  236. self.nCancelVC = [[KMDesignButton alloc] initWithType: DesignButtonTypeText];
  237. // self.nMergeVC.button.keyEquivalent = @"\\r";
  238. self.clearBox.fillColor = NSColor.clearColor;
  239. self.clearBox.contentView = self.clearVC.view;
  240. self.nMergeBox.fillColor = NSColor.clearColor;
  241. self.nMergeBox.contentView = self.nMergeVC.view;
  242. self.nCancelBox.fillColor = NSColor.clearColor;
  243. self.nCancelBox.contentView = self.nCancelVC.view;
  244. self.box.cornerRadius = 0;
  245. self.box.fillColor = [NSColor colorWithRed:247/255.f green:248/255.f blue:250/255.f alpha:1.f];
  246. self.window.title = NSLocalizedString(@"Merge PDF Files",nil);
  247. self.pageSizeWidthTextField.enabled = NO;
  248. self.pageSizeHeightTextField.enabled = NO;
  249. self.pageSizeWidthTextField.stringValue = @"595";
  250. self.pageSizeHeightTextField.stringValue = @"841";
  251. self.pageSizeWidthTextField.formatter = [[TextFieldFormatter alloc] init];
  252. self.pageSizeHeightTextField.formatter = [[TextFieldFormatter alloc] init];
  253. NSArray *titles = @[NSLocalizedString(@"Original Size", nil),@"A4",@"A3",
  254. NSLocalizedString(@"U.S.Letter", nil),NSLocalizedString(@"U.S.Legal", nil),NSLocalizedString(@"Custom", nil)];
  255. __weak typeof(self) weakSelf = self;
  256. int i = 0;
  257. for (KMImageTitleButton *button in @[self.originalSizeButton, self.A4SizeButton, self.A3SizeButton,
  258. self.USLetterSizeButton, self.USLegalButton, self.customSizeButton]) {
  259. KMImageTitleButton *radio = [[KMImageTitleButton alloc] init];
  260. [button addSubview:radio];
  261. radio.frame = button.bounds;
  262. radio.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  263. radio.titleLabel.textColor = [NSColor colorWithRed:223/255.f green:225/255.f blue:229/255.f alpha:1.f];
  264. radio.title = titles[i];
  265. if (i == 0) {
  266. radio.state = NSControlStateValueOn;
  267. radio.imageName = @"btn_radio_sel_on";
  268. } else {
  269. radio.state = NSControlStateValueOff;
  270. radio.imageName = @"btn_radio_unsel_on";
  271. }
  272. radio.titleLabel.textColor = [NSColor colorWithRed:223/255.f green:225/255.f blue:229/255.f alpha:1.f];
  273. radio.titleLabel.font = [NSFont fontWithName:@"SFProText-Regular" size:14];
  274. radio.action = ^(KMImageTitleButton *view, NSButton *button) {
  275. [weakSelf buttonClicked_ChooseSize:view];
  276. };
  277. radio.contentButton.tag = i;
  278. i += 1;
  279. }
  280. self.nCancelVC.target = self;
  281. self.nCancelVC.action = @selector(buttonItemClicked_Cancel:);
  282. self.nCancelVC.stringValue = NSLocalizedString(@"Cancel", nil);
  283. [self.nCancelVC buttonWithType:TokenButtonTypeSec size:TokenButtonSizeM height:[[NSLayoutConstraint alloc] init]];
  284. _removeButton.title = NSLocalizedString(@"Remove", nil);
  285. self.clearVC.target = self;
  286. self.clearVC.action = @selector(buttonItemClicked_Clear:);
  287. self.clearVC.image = [NSImage imageNamed:@"icon_btn_clear_false_norm"];
  288. self.clearVC.image_hov = [NSImage imageNamed:@"icon_btn_clear_false_hov"];
  289. self.clearVC.image_act = [NSImage imageNamed:@"icon_btn_clear_false_act"];
  290. self.clearVC.image_disabled = [NSImage imageNamed:@"icon_btn_clear_Disabled_norm"];
  291. [self.clearVC buttonWithType:TokenButtonTypeSec_Icon size:TokenButtonSizeM height:[[NSLayoutConstraint alloc] init]];
  292. [_addFileButton setTitle:NSLocalizedString(@"Add Files", nil)];
  293. self.nMergeVC.target = self;
  294. self.nMergeVC.action = @selector(buttonItemClicked_Append:);
  295. self.nMergeVC.stringValue = NSLocalizedString(@"Merge", nil);
  296. [self.nMergeVC buttonWithType:TokenButtonTypeCta size:TokenButtonSizeM height:[[NSLayoutConstraint alloc] init]];
  297. self.tableView.delegate = self;
  298. self.tableView.dataSource = self;
  299. self.tableView.allowsMultipleSelection = YES;
  300. [_tableView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, NSPasteboardTypeString, NSPasteboardTypePDF, MyTableCellViewDataType, nil]];
  301. NSArray *tableHeaderTitles = @[NSLocalizedString(@"File Name", nil),NSLocalizedString(@"Page Range", nil),NSLocalizedString(@"Size", nil)];
  302. i = 0;
  303. for (NSTextField *label in @[self.fileNameLabel, self.pageRangeLabel, self.sizeLabel]) {
  304. label.stringValue = tableHeaderTitles[i];
  305. label.textColor = [NSColor colorWithRed:97/255.f green:100/255.f blue:105/255.f alpha:1.f];
  306. label.font = [NSFont fontWithName:@"SFProText-Regular" size:12];
  307. i += 1;
  308. }
  309. self.tableHeaderBottomLine.fillColor = [NSColor colorWithRed:223/255.f green:225/255.f blue:229/255.f alpha:1.f];
  310. [self.tableView removeTableColumn:self.tableView.tableColumns.firstObject];
  311. NSTableColumn *column1 = [[NSTableColumn alloc] initWithIdentifier:KMTableColumnFileNameID];
  312. column1.width = 446+16;
  313. column1.title = NSLocalizedString(@"File Name", nil);
  314. [self.tableView addTableColumn:column1];
  315. NSTableColumn *column2 = [[NSTableColumn alloc] initWithIdentifier:KMTableColumnPageRangeID];
  316. column2.width = 160+8;
  317. column2.title = NSLocalizedString(@"Page Range", nil);
  318. [self.tableView addTableColumn:column2];
  319. NSTableColumn *column3 = [[NSTableColumn alloc] initWithIdentifier:KMTableColumnSizeID];
  320. column3.width = 139+12;
  321. column3.title = NSLocalizedString(@"Size", nil);
  322. [self.tableView addTableColumn:column3];
  323. self.tableView.rowHeight = 76;
  324. _insertIndexSet = [[NSMutableIndexSet alloc] init];
  325. [self addFiles:_addFiles];
  326. [_progress setHidden:YES];
  327. [self.tableView addSubview:self.myBlankView];
  328. [self.myBlankView registerDragged];
  329. [self.myBlankView mas_makeConstraints:^(MASConstraintMaker *make) {
  330. make.left.top.width.equalTo(self.tableView);
  331. make.height.equalTo(self.tableView).offset(0);
  332. }];
  333. self.myBlankView.wantsLayer = YES;
  334. self.myBlankView.layer.backgroundColor = [NSColor clearColor].CGColor;
  335. self.myBlankView.titleLabel.stringValue = NSLocalizedString(@"Select Files", nil);
  336. self.myBlankView.titleLabel.textColor = [NSColor colorWithRed:97/255.f green:100/255.f blue:105/255.f alpha:1];
  337. self.myBlankView.titleLabel.font = [NSFont fontWithName:@"SFProText-Regular" size:14];
  338. self.myBlankView.secondTitleLabel.stringValue = NSLocalizedString(@"Drop files here or Click “+”. Drag files to reorder as you need. You can also add files or folders via the lower left button.", nil);
  339. self.myBlankView.secondTitleLabel.textColor = [NSColor colorWithRed:148/255.f green:152/255.f blue:156/255.f alpha:1];
  340. self.myBlankView.secondTitleLabel.font = [NSFont fontWithName:@"SFProText-Regular" size:12];
  341. self.myBlankView.imageView.image = [NSImage imageNamed:@"KMImageNameEmptyAddNormal"];
  342. self.myBlankView.allowedFileTypes = [KMImageAccessoryController supportedImageTypes];
  343. self.myBlankView.mouseActionCallBack = ^(KMBlankViewMouseEventType mouseType) {
  344. if (mouseType == KMBlankViewMouseEventTypeMouseEnter) {
  345. weakSelf.myBlankView.imageView.image = [NSImage imageNamed:@"KMImageNameEmptyAddHover"];
  346. } else if (mouseType == KMBlankViewMouseEventTypeMouseExit) {
  347. weakSelf.myBlankView.imageView.image = [NSImage imageNamed:@"KMImageNameEmptyAddNormal"];
  348. } else if (mouseType == KMBlankViewMouseEventTypeMouseDown) {
  349. weakSelf.myBlankView.imageView.image = [NSImage imageNamed:@"KMImageNameEmptyAddHover"];
  350. [weakSelf itemAddFileAction];
  351. } else if (mouseType == KMBlankViewMouseEventTypeMouseUp) {
  352. weakSelf.myBlankView.imageView.image = [NSImage imageNamed:@"KMImageNameEmptyAddHover"];
  353. }
  354. };
  355. self.myBlankView.dragSuccessBlock = ^(NSArray<NSString *> * fileNames) {
  356. NSMutableArray *array = [NSMutableArray array];
  357. for(NSString *path in fileNames){
  358. if (![weakSelf isExistAtFilepath:path]) {
  359. continue;
  360. }
  361. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  362. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  363. weakSelf.allFileSize = weakSelf.allFileSize + fileSize;
  364. // weakSelf.allFileSize = weakSelf.allFileSize - fileSize;
  365. [array addObject:path];
  366. }
  367. [weakSelf addFiles:array];
  368. };
  369. [self updateButtonState];
  370. id outputBookMarkObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"kmAppendOutputPath"];
  371. if ([outputBookMarkObject isKindOfClass:[NSData class]]) {
  372. NSData* outputBookMarkData = (NSData*)outputBookMarkObject;
  373. NSURL *bookmarkedURL = [NSURL URLByResolvingBookmarkData:outputBookMarkData options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:nil];
  374. [bookmarkedURL startAccessingSecurityScopedResource];
  375. if (bookmarkedURL) {
  376. // _outputText.stringValue = [bookmarkedURL path];
  377. }
  378. }
  379. self.boxLabel.stringValue = NSLocalizedString(@"Page size:", nil);
  380. self.boxLabel.textColor = [NSColor colorWithRed:37/255.f green:38/255.f blue:41/255.f alpha:1.f];
  381. self.boxLabel.font = [NSFont fontWithName:@"SFProText-Regular" size:16];
  382. self.addFileButton = [[KMDesignSelect alloc] initWithType:1];
  383. self.addBox.fillColor = [NSColor clearColor];
  384. self.addBox.contentView = self.addFileButton.view;
  385. [self.addFileButton removeAllItems];
  386. [self.addFileButton addItemsWithObjectValues:@[NSLocalizedString(@"Add Files", ""),NSLocalizedString(@"Add Folder", ""),NSLocalizedString(@"Add Open Files", "")]];
  387. [self.addFileButton selectItemAt:0];
  388. self.addFileButton.editable = false; //默认属性,初始化可不设置
  389. self.addFileButton.delete = self;
  390. [self.addFileButton updateUI];
  391. self.loading_backgroundView = [[NSButton alloc] init];
  392. [self.window.contentView addSubview:self.loading_backgroundView];
  393. self.loading_backgroundView.frame = self.window.contentView.bounds;
  394. self.loading_backgroundView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  395. self.loading_backgroundView.title = @"";
  396. self.loading_backgroundView.bordered = NO;
  397. self.loading_backgroundView.wantsLayer = YES;
  398. self.loading_backgroundView.layer.backgroundColor = [NSColor clearColor].CGColor;
  399. self.loading_backgroundView.hidden = YES;
  400. self.limitLable.stringValue = NSLocalizedString(@"Merge 2 files at a time", "");
  401. self.limitLable.font = [NSFont SFProTextRegularFont:12];
  402. self.limitLable.textColor = [NSColor km_initWithHex:@"#F3465B" alpha:1];
  403. self.limit = NO;
  404. BOOL result = [KMLightMemberManager.manager canPayFunction];
  405. self.limit = !result;
  406. if (result) {
  407. self.limitLable.hidden = YES;
  408. self.limitTipIv.hidden = YES;
  409. } else {
  410. //#if VERSION_DMG
  411. // [KMLightMemberManager.manager canUseAdvancedWithNeedNetworking:NO completionHandler:^(BOOL isLogin) {
  412. // dispatch_sync(dispatch_get_main_queue(), ^{
  413. // if (isLogin) {
  414. // weakSelf.limitLable.hidden = NO;
  415. // weakSelf.limitTipIv.hidden = NO;
  416. // } else {
  417. // weakSelf.limitLable.hidden = YES;
  418. // weakSelf.limitTipIv.hidden = YES;
  419. // }
  420. // });
  421. // }];
  422. //
  423. //#else
  424. self.limitLable.hidden = NO;
  425. self.limitTipIv.hidden = NO;
  426. //#endif
  427. }
  428. }
  429. - (void)updateButtonState
  430. {
  431. if (_files.count > 0) {
  432. self.myBlankView.hidden = YES;
  433. self.tableHeaderBox.hidden = NO;
  434. [_removeButton setEnabled:YES];
  435. [self.clearVC setEnabled:YES];
  436. if (self.files.count > 1) {
  437. [self.nMergeVC setEnabled:YES];
  438. self.canMerge = YES;
  439. } else {
  440. self.canMerge = NO;
  441. [self.nMergeVC setEnabled:NO];
  442. }
  443. } else {
  444. self.myBlankView.hidden = NO;
  445. self.tableHeaderBox.hidden = YES;
  446. [_removeButton setEnabled:NO];
  447. [self.clearVC setEnabled:NO];
  448. self.canMerge = NO;
  449. [self.nMergeVC setEnabled:NO];
  450. }
  451. }
  452. #pragma mark -NSTextFieldDelegate
  453. - (void)controlTextDidChange:(NSNotification *)obj
  454. {
  455. NSTextField *textField = (NSTextField*)[obj object];
  456. NSInteger index = textField.tag;
  457. [[_files objectAtIndex:index] setPagesString:textField.stringValue];
  458. }
  459. #pragma mark Show Methods
  460. - (void)didEndSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
  461. if (contextInfo != NULL) {
  462. void (^handler)(BOOL isSuccessfully ,NSIndexSet * selectedIndexSet) = CFBridgingRelease(contextInfo);
  463. handler(_isSuccessfully,self.insertIndexSet);
  464. }
  465. windowController = nil;
  466. }
  467. - (void)beginSheetModalForWindow:(NSWindow *)window completionHandler:(void (^)(BOOL isSuccessfully,NSIndexSet * selectedIndexSet))handler
  468. {
  469. if (windowController.window.isSheet) {
  470. #if DEBUG
  471. NSLog(@"合并窗口已显示");
  472. #endif
  473. return;
  474. }
  475. windowController = self;
  476. [NSApp beginSheet:[self window]
  477. modalForWindow:window
  478. modalDelegate:self
  479. didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
  480. contextInfo:handler ? CFBridgingRetain(handler) : NULL];
  481. }
  482. #pragma mark Private methor
  483. - (void)viewFileAtFinder:(NSString *)filePath
  484. {
  485. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  486. NSURL *url = [NSURL fileURLWithPath:filePath];
  487. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  488. }
  489. - (void)addFiles:(NSArray*)files
  490. {
  491. [_lockFilePathArr removeAllObjects];
  492. _lockFileIndex = 0;
  493. for (NSString *filePath in files) {
  494. if ([filePath.pathExtension.lowercaseString isEqualToString:@"pdf"]) {
  495. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  496. file.filePath = filePath;
  497. PDFDocument *document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:filePath]];
  498. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  499. self.allFileSize = [[attrib objectForKey:NSFileSize] floatValue];
  500. if ([document isLocked]) {
  501. [_lockFilePathArr addObject:filePath];
  502. } else if ([KMTools hasPermissionsLimit:document]) {
  503. [_lockFilePathArr addObject:filePath];
  504. } else {
  505. if ([NSDocument isDamageWithUrl:[NSURL fileURLWithPath:filePath]]) {
  506. NSAlert *alert = [[NSAlert alloc] init];
  507. alert.messageText = NSLocalizedString(@"The file was not added successfully, please select the file again.", @"");
  508. [alert runModal];
  509. } else {
  510. [_files addObject:file];
  511. }
  512. }
  513. } else {
  514. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  515. file.filePath = filePath;
  516. PDFDocument *document = [[PDFDocument alloc] init];
  517. NSImage *image = [[NSImage alloc] initWithContentsOfFile:filePath];
  518. if (image == nil) {
  519. continue;
  520. }
  521. // [document insertPage:image.size withImage:filePath atIndex:0];
  522. [document insertPage:[[PDFPage alloc] initWithImage:image] atIndex:0];
  523. file.myPDFDocument = document;
  524. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  525. self.allFileSize = [[attrib objectForKey:NSFileSize] floatValue];
  526. if ([NSDocument isDamageWithUrl:[NSURL fileURLWithPath:filePath]]) {
  527. NSAlert *alert = [[NSAlert alloc] init];
  528. alert.messageText = NSLocalizedString(@"The file was not added successfully, please select the file again.", @"");
  529. [alert runModal];
  530. } else {
  531. [_files addObject:file];
  532. }
  533. }
  534. }
  535. [self updateButtonState];
  536. [_tableView reloadData];
  537. if ([_lockFilePathArr count]) {
  538. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  539. if (self.files.count == 0) {
  540. self.insertRow = 0;
  541. } else {
  542. self.insertRow = self.files.count;
  543. }
  544. [self openPasswordWindow];
  545. });
  546. }
  547. }
  548. - (BOOL)isExistAtFilepath:(NSString *)filePath
  549. {
  550. NSMutableArray *array = [NSMutableArray array];
  551. for (KMFileAttribute *file in self.files) {
  552. [array addObject:file.filePath];
  553. }
  554. if ([array containsObject:filePath]) {
  555. return NO;
  556. }
  557. return YES;
  558. }
  559. -(void)openPasswordWindow
  560. {
  561. if ([_lockFilePathArr count] > _lockFileIndex) {
  562. NSString *filePath = [_lockFilePathArr objectAtIndex:_lockFileIndex];
  563. __weak typeof(self) weakSelf = self;
  564. [KMPasswordInputWindow openWindowWithWindow:self.window type:KMPasswordInputWindowTypeOwner url:[NSURL fileURLWithPath:filePath] callback:^(enum KMPasswordInputWindowResult result, NSString * _Nullable password) {
  565. if (password.length > 0) {
  566. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  567. file.filePath = filePath;
  568. file.isLocked = YES;
  569. file.password = password;
  570. [weakSelf.files insertObject:file atIndex:weakSelf.insertRow];
  571. weakSelf.insertRow ++;
  572. }
  573. weakSelf.lockFileIndex++;
  574. // if ([self.lockFilePathArr count] > self.lockFileIndex) {
  575. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  576. [weakSelf openPasswordWindow];
  577. });
  578. // } else {
  579. [weakSelf.tableView reloadData];
  580. [weakSelf updateButtonState];
  581. // }
  582. }];
  583. }
  584. }
  585. - (void)comboBoxAction:(NSInteger)itemIndex atRow:(NSInteger)row
  586. {
  587. NSInteger index = row;
  588. // 数组不存在,或者索引超出数组长度
  589. if ((!_files) || (index > ((NSInteger)[_files count] - 1))) {
  590. return;
  591. }
  592. if (itemIndex == 0) {
  593. KMFileAttribute *currentFile = [_files objectAtIndex:index];
  594. [currentFile setBAllPage:YES];
  595. currentFile.pagesType = KMPageRangeAll;
  596. [self.window makeFirstResponder:self];
  597. } else if (itemIndex == 1) {
  598. KMFileAttribute *currentFile = [_files objectAtIndex:index];
  599. currentFile.pagesType = KMPageRangeOdd;
  600. [currentFile setBAllPage:NO];
  601. PDFDocument *tDocument = currentFile.myPDFDocument;
  602. if (tDocument == nil) {
  603. tDocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:currentFile.filePath]];
  604. }
  605. if ([currentFile isLocked]) {
  606. [tDocument unlockWithPassword:currentFile.password];
  607. }
  608. NSString *tPagesString = @"";
  609. for (NSInteger i = 0; i < tDocument.pageCount; i++) {
  610. if (i%2 == 0) {
  611. if (tPagesString.length == 0) {
  612. tPagesString = [tPagesString stringByAppendingString:[NSString stringWithFormat:@"%ld",i +1]];
  613. }else{
  614. tPagesString = [tPagesString stringByAppendingString:[NSString stringWithFormat:@",%ld",i +1]];
  615. }
  616. }
  617. }
  618. currentFile.pagesString = tPagesString;
  619. [self.window makeFirstResponder:self];
  620. } else if (itemIndex == 2) {
  621. KMFileAttribute *currentFile = [_files objectAtIndex:index];
  622. currentFile.pagesType = KMPageRangeEven;
  623. [currentFile setBAllPage:NO];
  624. NSString *tPagesString = @"";
  625. PDFDocument *tDocument = currentFile.myPDFDocument;
  626. if (tDocument == nil) {
  627. tDocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:currentFile.filePath]];
  628. }
  629. if ([currentFile isLocked]) {
  630. [tDocument unlockWithPassword:currentFile.password];
  631. }
  632. for (NSInteger i = 0; i <tDocument.pageCount; i++) {
  633. if (i%2) {
  634. if (tPagesString.length == 0) {
  635. tPagesString = [tPagesString stringByAppendingString:[NSString stringWithFormat:@"%ld",i +1]];
  636. }else{
  637. tPagesString = [tPagesString stringByAppendingString:[NSString stringWithFormat:@",%ld",i +1]];
  638. }
  639. }
  640. }
  641. currentFile.pagesString = tPagesString;
  642. [self.window makeFirstResponder:self];
  643. } else {
  644. KMFileAttribute *currentFile = [_files objectAtIndex:index];
  645. currentFile.pagesType = KMPageRangeCustom;
  646. currentFile.pagesString = @"";
  647. [currentFile setBAllPage:NO];
  648. }
  649. }
  650. - (void)handerReDraw
  651. {
  652. //如果选择的是原始尺寸,不处理
  653. // KMImageTitleButton *originalSizeButton = self.originalSizeButton.subviews.lastObject;
  654. // if (originalSizeButton.state == NSControlStateValueOn) {
  655. // }else{
  656. //重新选择了界面尺寸,那么就要重绘
  657. // if (self.newPageSize.width < 0) {
  658. // NSBeep();
  659. // return;
  660. // }else{
  661. NSMutableArray *pagesArray = [NSMutableArray array];
  662. NSInteger pageCount = self.PDFDocument.pageCount;
  663. for (NSInteger i = 0; i < pageCount; i ++) {
  664. [pagesArray addObject:[self.PDFDocument pageAtIndex:0]];
  665. [self.PDFDocument removePageAtIndex:0];
  666. }
  667. for (NSInteger i = 0; i < pageCount; i ++) {
  668. PDFPage *oPage = pagesArray[i];
  669. NSRect pageBounds = [oPage boundsForBox:kPDFDisplayBoxCropBox];
  670. KMAppendPDFPage *page = [[KMAppendPDFPage alloc] init];
  671. [page setBounds:NSMakeRect(0, 0, pageBounds.size.width, pageBounds.size.height) forBox:kPDFDisplayBoxMediaBox];
  672. page.drawingPage = oPage;
  673. // [self.PDFDocument insertPageObject:page atIndex:i];
  674. PDFAnnotationLink *linkA = [[PDFAnnotationLink alloc] init];
  675. linkA.bounds = NSMakeRect(0, pageBounds.size.height-32, 120, 32);
  676. linkA.URL = [NSURL URLWithString:@"https://www.pdfreaderpro.com/store"];
  677. [page addAnnotation:linkA];
  678. [self.PDFDocument insertPage:page atIndex:i];
  679. }
  680. //如果是自定义大小,删除所有的outline,因为合并出来的outline是无效的
  681. if (self.PDFDocument.outlineRoot) {
  682. NSInteger childCount = [self.PDFDocument.outlineRoot numberOfChildren];
  683. NSMutableArray *PDFOutlineArray = [NSMutableArray array];
  684. for (NSInteger i = 0 ; i < childCount; i ++) {
  685. [PDFOutlineArray addObject:[self.PDFDocument.outlineRoot childAtIndex:i]];
  686. }
  687. for (PDFOutline *deleteOutline in PDFOutlineArray) {
  688. [deleteOutline removeFromParent];
  689. }
  690. }
  691. // }
  692. // }
  693. }
  694. - (BOOL)hasOpenFiles {
  695. NSArray *array = [KMTools getOpenDocumentURLs];
  696. if (array.count == 0) {
  697. return NO;
  698. }
  699. for (NSURL *fileURL in array) {
  700. if ([self isExistAtFilepath:fileURL.path]) {
  701. return YES;
  702. }
  703. }
  704. return NO;
  705. }
  706. #pragma mark - KMSelectPopButtonDelegate
  707. - (void)km_comboBoxSelectionDidChange:(KMDesignSelect *)obj {
  708. if ([self.addFileButton isEqual:obj]) {
  709. NSInteger index = self.addFileButton.indexOfSelectedItem;
  710. if (index < 0) {
  711. index = 0;
  712. }
  713. if (index == 0) {
  714. [self itemAddFileAction];
  715. } else if (index == 1) {
  716. [self itemAddFolderAction];
  717. } else if (index == 2) {
  718. [self itemAddOpenFileAction];
  719. }
  720. }
  721. }
  722. - (void)km_controlTextDidChange:(KMDesignSelect *)obj {
  723. }
  724. - (void)km_controlTextDidEndEditing:(KMDesignSelect *)obj {
  725. }
  726. - (void)km_SelectPopoverWillShow:(KMDesignSelect *)obj {
  727. if ([self hasOpenFiles]) {
  728. obj.disItems = @[];
  729. } else {
  730. obj.disItems = @[NSLocalizedString(@"Add Open Files", "")];
  731. }
  732. }
  733. #pragma mark tabelView
  734. - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
  735. {
  736. return _files.count;
  737. }
  738. - (nullable id)tableView:(NSTableView *)tableView viewForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row
  739. {
  740. KMFileAttribute *fileAttribute = [_files objectAtIndex:row];
  741. PDFDocument *pdf = fileAttribute.myPDFDocument;
  742. if (pdf == nil) {
  743. pdf = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:fileAttribute.filePath]];
  744. }
  745. if ([pdf isLocked]) {
  746. [pdf unlockWithPassword:fileAttribute.password];
  747. }
  748. if (tableColumn.identifier == KMTableColumnPageRangeID) {
  749. KMPDFMergePageRangeTabelViewCell *cell = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
  750. if (cell == nil) {
  751. cell = [[KMPDFMergePageRangeTabelViewCell alloc] init];
  752. }
  753. cell.wantsLayer = YES;
  754. cell.layer.backgroundColor = [NSColor clearColor].CGColor;
  755. cell.pageCount = pdf.pageCount;
  756. [cell updatePageRange:fileAttribute.pagesType pageStrings:fileAttribute.pagesString isFirstResponser:NO];
  757. // if (fileAttribute.pageRangeError) {
  758. // [cell updateRageRangeState:10];
  759. // }
  760. __weak typeof(self) weakSelf = self;
  761. cell.callback = ^(NSInteger index) {
  762. [weakSelf comboBoxAction:index atRow:row];
  763. };
  764. cell.textDidChange = ^(NSString * _Nonnull string) {
  765. if (row >= weakSelf.files.count) {
  766. return;
  767. }
  768. KMFileAttribute *file = [weakSelf.files objectAtIndex:row];
  769. [file setPagesString:string];
  770. // file.pageRangeError = NO;
  771. // dispatch_async(dispatch_get_main_queue(), ^{
  772. // [weakSelf.tableView reloadData];
  773. // });
  774. };
  775. cell.textDidEndEdit = ^(NSString * _Nonnull string, KMPDFMergePageRangeTabelViewCell *pageRangeCell) {
  776. if (row >= weakSelf.files.count || [string isEqual: @""]) {
  777. return;
  778. }
  779. KMFileAttribute *file = [weakSelf.files objectAtIndex:row];
  780. if (!file.fetchSelectPages) {
  781. // file.pageRangeError = YES;
  782. if (weakSelf.alert) {
  783. return;
  784. }
  785. dispatch_async(dispatch_get_main_queue(), ^{
  786. // [weakSelf.tableView reloadData];
  787. NSAlert *alert = [[NSAlert alloc] init];
  788. // weakSelf.alert = alert;
  789. [alert setAlertStyle:NSAlertStyleCritical];
  790. [alert setMessageText:[NSString stringWithFormat:@"%@ %@",[file.filePath lastPathComponent],NSLocalizedString(@"Invalid page range or the page number is out of range. Please try again.", nil)]];
  791. [alert runModal];
  792. file.pagesString = @"";
  793. [pageRangeCell updatePageRange:file.pagesType pageStrings:file.pagesString isFirstResponser:NO];
  794. // dispatch_async(dispatch_get_main_queue(), ^{
  795. // weakSelf.alert = nil;
  796. // });
  797. // [weakSelf.tableView reloadData];
  798. // [weakSelf.tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:row] columnIndexes:[NSIndexSet indexSetWithIndex:1]];
  799. });
  800. } else {
  801. [pageRangeCell updatePageRange:file.pagesType pageStrings:file.pagesString isFirstResponser:YES];
  802. }
  803. };
  804. return cell;
  805. }
  806. if (tableColumn.identifier == KMTableColumnSizeID) {
  807. KMPDFMergeSizeTabelViewCell *cell = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
  808. if (cell == nil) {
  809. cell = [[KMPDFMergeSizeTabelViewCell alloc] init];
  810. }
  811. NSString *filePath = pdf.documentURL.path;
  812. if (!filePath) {
  813. filePath = fileAttribute.filePath;
  814. }
  815. NSDictionary *attributesDic = [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil];
  816. float size = [[attributesDic objectForKey:NSFileSize] floatValue]/1024;
  817. cell.label.stringValue = [NSString stringWithFormat:@"%0.1f %c", truesize(size) , moniker(size)];
  818. cell.button.hidden = YES;
  819. __weak typeof(self) weakSelf = self;
  820. cell.callback = ^{
  821. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:fileAttribute.filePath error:nil];
  822. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  823. weakSelf.allFileSize = weakSelf.allFileSize - fileSize;
  824. [weakSelf.files removeObject:fileAttribute];
  825. [weakSelf.tableView reloadData];
  826. [weakSelf updateButtonState];
  827. };
  828. return cell;
  829. }
  830. KMPDFMergeFileNameTabelViewCell *cell = [tableView makeViewWithIdentifier:@"fileName" owner:self];
  831. if (cell == nil) {
  832. cell = [[KMPDFMergeFileNameTabelViewCell alloc] init];
  833. }
  834. NSString *fileName = [fileAttribute.filePath lastPathComponent];
  835. if (fileAttribute.oriFilePath.length > 0) {
  836. fileName = fileAttribute.oriFilePath.stringByDeletingPathExtension.lastPathComponent;
  837. }
  838. cell.numberLabel.stringValue = [NSString stringWithFormat:@"%ld",(row + 1)];;
  839. cell.fileNameLabel.stringValue = fileName;
  840. cell.pageNumberLabel.stringValue = [NSString stringWithFormat:@"%ld %@",pdf.pageCount,NSLocalizedString(@"Pages", nil)];;
  841. // cell.iconImageView.image = [[pdf pageAtIndex:0] thumbnailWithSize:60*2 forBox:kPDFDisplayBoxCropBox];
  842. if (pdf.documentURL) {
  843. if (fileAttribute.password.length > 0) {
  844. cell.iconImageView.image = [[pdf pageAtIndex:0] thumbnailOfSize:NSMakeSize(120, 120) forBox:kPDFDisplayBoxCropBox];
  845. } else {
  846. cell.iconImageView.image = [NSImage previewForFileWithPath:pdf.documentURL ofSize:NSMakeSize(120, 120) asIcon:YES];
  847. }
  848. } else if (fileAttribute.filePath) {
  849. // if ([fileAttribute.filePath.pathExtension.lowercaseString isEqualToString:@"pdf"]) {
  850. cell.iconImageView.image = [NSImage previewForFileWithPath:[NSURL fileURLWithPath:fileAttribute.filePath] ofSize:NSMakeSize(120, 120) asIcon:YES];
  851. // } else {
  852. // cell.iconImageView.image = [NSImage previewForFileWithPath:fileAttribute.filePath ofSize:NSMakeSize(120, 120) asIcon:YES];
  853. // }
  854. } else {
  855. cell.iconImageView.image = nil;
  856. }
  857. return cell;
  858. }
  859. - (BOOL)tableView:(NSTableView *)tableView shouldSelectTableColumn:(NSTableColumn *)tableColumn
  860. {
  861. return NO;
  862. }
  863. #pragma mark -NSTableViewDelegate
  864. - (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard
  865. {
  866. // Copy the row numbers to the pasteboard.
  867. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  868. [pboard declareTypes:[NSArray arrayWithObject:MyTableCellViewDataType] owner:self];
  869. [pboard setData:zNSIndexSetData forType:MyTableCellViewDataType];
  870. return YES;
  871. }
  872. - (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation
  873. {
  874. if (dropOperation == NSTableViewDropOn) {
  875. return NSDragOperationNone;
  876. }
  877. BOOL isCanDrag = NO;
  878. NSDragOperation result = NSDragOperationNone;
  879. NSPasteboard *pboard = [info draggingPasteboard];
  880. if ([pboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]])
  881. {
  882. NSArray *fileNames = [pboard propertyListForType:NSFilenamesPboardType];
  883. for (NSString* path in fileNames) {
  884. if ([[KMImageAccessoryController supportedImageTypes] containsObject:path.pathExtension.lowercaseString]) {
  885. isCanDrag = YES;
  886. }else{
  887. isCanDrag = NO;
  888. break;
  889. }
  890. }
  891. }else if ([pboard availableTypeFromArray:[NSArray arrayWithObject:MyTableCellViewDataType]]){
  892. result = NSDragOperationEvery;
  893. }
  894. if (isCanDrag) {
  895. result = NSDragOperationCopy;
  896. }
  897. return result;
  898. }
  899. - (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation
  900. {
  901. BOOL result = NO;
  902. NSPasteboard *pboard = [info draggingPasteboard];
  903. _insertRow = row;
  904. if ([pboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]])
  905. {
  906. NSMutableArray *fileNames = [pboard propertyListForType:NSFilenamesPboardType];
  907. NSMutableArray *array = [NSMutableArray array];
  908. for(NSString *path in fileNames){
  909. if (![self isExistAtFilepath:path]) {
  910. continue;
  911. }
  912. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  913. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  914. self.allFileSize = self.allFileSize + fileSize;
  915. [array addObject:path];
  916. }
  917. [self addFiles:array];
  918. result = YES;
  919. } else if ([pboard availableTypeFromArray:[NSArray arrayWithObject:MyTableCellViewDataType]]){
  920. NSData* rowData = [pboard dataForType:MyTableCellViewDataType];
  921. NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
  922. NSMutableArray *moveArray = [[NSMutableArray alloc] init];
  923. NSMutableArray *allPhoto = [_files mutableCopy];
  924. NSInteger index = 0;
  925. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  926. KMFileAttribute * file = allPhoto[idx];
  927. [moveArray addObject:file];
  928. [_files removeObject:file];
  929. }];
  930. if (row > 0) {
  931. KMFileAttribute * indexFile = allPhoto[row -1];
  932. while([moveArray containsObject:indexFile]){
  933. row --;
  934. if ((row < 0)) {
  935. indexFile = nil;
  936. break;
  937. } else {
  938. indexFile = allPhoto[row];
  939. }
  940. }
  941. if(indexFile){
  942. index = [_files indexOfObject:indexFile]+1;
  943. }
  944. }
  945. for (NSInteger i = 0; i< moveArray.count; i++) {
  946. [_files insertObject:moveArray[i] atIndex:(index +i)];
  947. }
  948. [_tableView reloadData];
  949. result = YES;
  950. // [moveArray release];
  951. // [allPhoto release];
  952. } else {
  953. result = NO;
  954. }
  955. return result;
  956. }
  957. - (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row {
  958. KMBatchTableRowView *rowView = [[KMBatchTableRowView alloc] init];
  959. rowView.backgroundView.layer.backgroundColor = [NSColor colorWithRed:237/255.f green:238/255.f blue:240/255.f alpha:1.f].CGColor;
  960. rowView.backgroundView.layer.cornerRadius = 4.f;
  961. rowView.selectionInset = NSEdgeInsetsMake(0, 16, 0, 16);
  962. rowView.selectionRadius = 4.f;
  963. rowView.selectionBackgroundColorBlock = ^NSColor * _Nonnull{
  964. return [NSColor colorWithRed:206/255.f green:208/255.f blue:212/255.f alpha:0.6f];
  965. };
  966. return rowView;
  967. }
  968. - (void)tableViewSelectionDidChange:(NSNotification *)notification {
  969. }
  970. #pragma mark Buutton Action
  971. - (void)_clearData {
  972. for (KMFileAttribute *file in self.files) {
  973. if (file.oriFilePath.length > 0 && [[NSFileManager defaultManager] fileExistsAtPath:file.filePath]) {
  974. [[NSFileManager defaultManager] removeItemAtURL:[NSURL fileURLWithPath:file.filePath] error:nil];
  975. }
  976. }
  977. }
  978. - (IBAction)buttonItemClicked_Cancel:(id)sender
  979. {
  980. [self _clearData];
  981. _isSuccessfully = NO;
  982. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  983. [[self window] orderOut:self];
  984. }
  985. - (IBAction)buttonItemClicked_Append:(id)sender
  986. {
  987. if (!self.canMerge) {
  988. return;
  989. }
  990. //#if VERSION_DMG
  991. // [KMLightMemberManager.manager canUseAdvancedWithNeedNetworking:NO completionHandler:^(BOOL result) {
  992. // dispatch_async(dispatch_get_main_queue(), ^{
  993. // if (result) {
  994. // [self doAppend];
  995. // } else {
  996. // [KMComparativeTableViewController showWithWindow:self.window :KMComparativeInputTypeMerge inputType:KMSubscribeWaterMarkTypeMerge];
  997. // }
  998. // });
  999. // }];
  1000. //#else
  1001. [self doAppend];
  1002. //#endif
  1003. }
  1004. - (IBAction)doAppend {
  1005. // if (KMLightMemberManager.manager.purchaseState != KMPurchaseManagerStateSubscription && _files.count > 2) {
  1006. //// [KMSubscribeWaterMarkWindowController showWithWindow: self.window isContinue: false limit type:KMSubscribeWaterMarkTypeMerge subscribeDidClick:^{
  1007. ////
  1008. //// } completion:^(BOOL isSub, BOOL isWater, BOOL isClose) {
  1009. ////
  1010. //// }];
  1011. // [KMSubscribeWaterMarkWindowController showWithWindow:self.window isContinue:false limit:[self mergeCountIsReach] type:KMSubscribeWaterMarkTypeMerge subscribeDidClick:^{
  1012. //
  1013. // } completion:^(BOOL, BOOL, BOOL) {
  1014. //
  1015. // }];
  1016. // return;
  1017. // } else if (KMLightMemberManager.manager.purchaseState != KMPurchaseManagerStateSubscription && _files.count <= 2) {
  1018. // __weak typeof(self) weakSelf = self;
  1019. //// [KMSubscribeWaterMarkWindowController showWithWindow: self.window isContinue:true type:KMSubscribeWaterMarkTypeMerge subscribeDidClick:^{
  1020. ////
  1021. //// } completion:^(BOOL isSub, BOOL isWater, BOOL isClose) {
  1022. //// if (isWater) {
  1023. //// dispatch_async(dispatch_get_main_queue(), ^{
  1024. //// [weakSelf buttonItemClick_Append: sender];
  1025. //// });
  1026. //// }
  1027. //// }];
  1028. // BOOL isContinue = YES;
  1029. // BOOL limit = [self mergeCountIsReach];
  1030. // if (limit) {
  1031. // isContinue = NO;
  1032. // }
  1033. //
  1034. // [KMSubscribeWaterMarkWindowController showWithWindow:self.window isContinue:isContinue limit:limit type:KMSubscribeWaterMarkTypeMerge subscribeDidClick:^{
  1035. //
  1036. // } completion:^(BOOL isSub, BOOL isWater, BOOL isClose) {
  1037. // if (isClose) {
  1038. // return;
  1039. // }
  1040. // if (isSub) {
  1041. // dispatch_async(dispatch_get_main_queue(), ^{
  1042. // [weakSelf buttonItemClick_Append: nil];
  1043. // });
  1044. // return;
  1045. // }
  1046. // if (isWater && !limit) {
  1047. // dispatch_async(dispatch_get_main_queue(), ^{
  1048. // [weakSelf buttonItemClick_Append: nil];
  1049. // });
  1050. // return;
  1051. // }
  1052. // }];
  1053. // return;
  1054. // }
  1055. [self buttonItemClick_Append: nil];
  1056. }
  1057. - (void)buttonItemClick_Append:(id)sender {
  1058. KMImageTitleButton *customSizeButton = self.customSizeButton.subviews.lastObject;
  1059. if (customSizeButton.state == NSControlStateValueOn) {
  1060. NSInteger widthFloat = [self.pageSizeWidthTextField.stringValue integerValue];
  1061. NSInteger heightFloat = [self.pageSizeHeightTextField.stringValue integerValue];
  1062. NSString *widthString = [NSString stringWithFormat:@"%ld",widthFloat];
  1063. NSString *heightString = [NSString stringWithFormat:@"%ld",heightFloat];
  1064. if (![widthString isEqualToString:self.pageSizeWidthTextField.stringValue] ||![heightString isEqualToString:self.pageSizeHeightTextField.stringValue]||widthFloat <= 0 ||heightFloat <= 0 ) {
  1065. NSBeep();
  1066. return;
  1067. }else{
  1068. self.newPageSize = CGSizeMake(widthFloat, heightFloat);
  1069. }
  1070. }
  1071. //初始化数组
  1072. if (!self.rootPDFOutlineArray) {
  1073. self.rootPDFOutlineArray = [NSMutableArray new];
  1074. }else{
  1075. [self.rootPDFOutlineArray removeAllObjects];
  1076. }
  1077. //如果是合并,文件路径不存在,或者文件个数小于等于1 return
  1078. if (_editType == KMPDFPageEditMerge) {
  1079. if (_files.count <= 1 ) {
  1080. NSAlert *alert = [[NSAlert alloc] init];
  1081. [alert setAlertStyle:NSAlertStyleCritical];
  1082. [alert setMessageText:NSLocalizedString(@"To start merging, please select at least 2 files.", nil)];
  1083. [alert runModal];
  1084. return;
  1085. }
  1086. }
  1087. _isSuccessfully = NO;
  1088. [self.nCancelVC setEnabled:NO];
  1089. self.canMerge = NO;
  1090. BOOL allPage = YES;//只有是全部才支持大纲的合并
  1091. for (KMFileAttribute *file in _files) {
  1092. if (!file.fetchSelectPages) {
  1093. dispatch_async(dispatch_get_main_queue(), ^{
  1094. NSAlert *alert = [[NSAlert alloc] init];
  1095. [alert setAlertStyle:NSAlertStyleCritical];
  1096. [alert setMessageText:[NSString stringWithFormat:@"%@ %@",[file.filePath lastPathComponent],NSLocalizedString(@"Invalid page range or the page number is out of range. Please try again.", nil)]];
  1097. [alert runModal];
  1098. [self.nCancelVC setEnabled:YES];
  1099. self.canMerge = YES;
  1100. });
  1101. return;
  1102. }
  1103. }
  1104. [_progress setHidden:NO];
  1105. [_progress startAnimation:nil];
  1106. self.loading_backgroundView.hidden = NO;
  1107. for(KMFileAttribute *file in _files){
  1108. //只要有一个文件不是全部page,那么就不合并大纲
  1109. if (allPage == YES) {
  1110. allPage = file.bAllPage;
  1111. }
  1112. //通过路径获取文件
  1113. PDFDocument *tdocument = file.myPDFDocument;
  1114. if (tdocument == nil) {
  1115. tdocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:[file filePath]]];
  1116. file.myPDFDocument = tdocument;
  1117. }
  1118. //所有的outline数组
  1119. NSMutableArray *PDFOutlineArr = [NSMutableArray new];
  1120. //需要解锁
  1121. if (file.isLocked) {
  1122. [tdocument unlockWithPassword:file.password];
  1123. }
  1124. //如果根存在,那么遍历出所有的outline,添加到数组中,如果不存在,那么就创建一个根
  1125. if (tdocument.outlineRoot) {
  1126. [self.rootPDFOutlineArray addObject:tdocument.outlineRoot];
  1127. [self fetchAllOfChildren:tdocument.outlineRoot containerArray:PDFOutlineArr];
  1128. [PDFOutlineArr removeObject:tdocument.outlineRoot];
  1129. } else {
  1130. PDFOutline *rootOutline = [[PDFOutline alloc] init];
  1131. tdocument.outlineRoot = rootOutline;
  1132. if (tdocument.outlineRoot) {
  1133. [self.rootPDFOutlineArray addObject:tdocument.outlineRoot];
  1134. }
  1135. }
  1136. // for (CPDFOutline *tOutline in PDFOutlineArr) {
  1137. //这段代码主要是调用他的getter方法;outline显示正确
  1138. // [tOutline.destination.page dataRepresentation];
  1139. // }
  1140. for (NSNumber *number in file.fetchSelectPages) {
  1141. PDFPage *page = [tdocument pageAtIndex:[number integerValue]-1];
  1142. [self.PDFDocument insertPage:page atIndex:[self.PDFDocument pageCount]];
  1143. // [self.PDFDocument insertPageObject:page atIndex:self.PDFDocument.pageCount];
  1144. [self.insertIndexSet addIndex:(self.PDFDocument.pageCount - 1)];
  1145. }
  1146. _isSuccessfully = YES;
  1147. }
  1148. KMFileAttribute *file = self.files.firstObject;
  1149. NSString *fileName = file.filePath.stringByDeletingPathExtension.lastPathComponent;
  1150. if (file.oriFilePath.length > 0) {
  1151. fileName = file.oriFilePath.stringByDeletingPathExtension.lastPathComponent;
  1152. }
  1153. fileName = [NSString stringWithFormat:@"%@_Merged", fileName];
  1154. if (_editType == KMPDFPageEditMerge) {
  1155. _isSuccessfully = NO;
  1156. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1157. PDFOutline *rootline = [[PDFOutline alloc] init];
  1158. self.PDFDocument.outlineRoot = rootline;
  1159. if (allPage) {
  1160. NSInteger insertIndex = 0;
  1161. for (NSUInteger i = 0; i < self.rootPDFOutlineArray.count; i++) {
  1162. PDFOutline *rootPDFOutline = self->_rootPDFOutlineArray[i];
  1163. for (NSUInteger j = 0; j < rootPDFOutline.numberOfChildren; j ++) {
  1164. [self.PDFDocument.outlineRoot insertChild:[rootPDFOutline childAtIndex:j] atIndex: insertIndex];
  1165. insertIndex ++;
  1166. }
  1167. }
  1168. }
  1169. dispatch_async(dispatch_get_main_queue(), ^{
  1170. if (self.limit) {
  1171. [self handerReDraw];
  1172. }
  1173. KMSavePanelAccessoryController *savePanelAccessoryViewController = [[KMSavePanelAccessoryController alloc] init];
  1174. NSSavePanel *savePanel = [NSSavePanel savePanel];
  1175. savePanel.nameFieldStringValue = fileName;
  1176. savePanel.allowedFileTypes = @[@"pdf"];
  1177. savePanel.accessoryView = savePanelAccessoryViewController.view;
  1178. self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  1179. [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  1180. if (result) {
  1181. NSString * outputSavePanel = savePanel.URL.path;
  1182. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1183. self->_isSuccessfully = [self.PDFDocument writeToFile:outputSavePanel];
  1184. if (!self->_isSuccessfully) {
  1185. self->_isSuccessfully = [self.PDFDocument.dataRepresentation writeToFile:outputSavePanel atomically:YES];
  1186. }
  1187. dispatch_async(dispatch_get_main_queue(), ^{
  1188. [self->_progress setHidden:YES];
  1189. [self.nCancelVC setEnabled:YES];
  1190. self.canMerge = YES;
  1191. self.loading_backgroundView.hidden = YES;
  1192. if (self->_isSuccessfully) {
  1193. [self _clearData];
  1194. [self recordMergeCount];
  1195. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1196. [[self window] orderOut:self];
  1197. if (self.saveAsPDFFilePath) {
  1198. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1199. if (autoOpen) {
  1200. self.saveAsPDFFilePath(outputSavePanel);
  1201. self.saveAsPDFFilePath = nil;
  1202. } else {
  1203. [self viewFileAtFinder:outputSavePanel];
  1204. }
  1205. } else {
  1206. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1207. if (autoOpen) {
  1208. [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:outputSavePanel] display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1209. }];
  1210. } else {
  1211. [self viewFileAtFinder:outputSavePanel];
  1212. }
  1213. }
  1214. } else {
  1215. NSAlert *alert = [[NSAlert alloc] init];
  1216. [alert setAlertStyle:NSAlertStyleCritical];
  1217. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1218. NSModalResponse response = [alert runModal];
  1219. if (response == 0 ) {
  1220. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1221. [[self window] orderOut:self];
  1222. }
  1223. }
  1224. });
  1225. });
  1226. } else {
  1227. [self->_progress setHidden:YES];
  1228. [self.nCancelVC setEnabled:YES];
  1229. self.canMerge = YES;
  1230. self.loading_backgroundView.hidden = YES;
  1231. }
  1232. }];
  1233. });
  1234. });
  1235. } else {
  1236. [self.nCancelVC setEnabled:YES];
  1237. self.canMerge = YES;
  1238. if (allPage) {
  1239. if (!self.PDFDocument.outlineRoot) {
  1240. PDFOutline *outline = [[PDFOutline alloc] init];
  1241. self.PDFDocument.outlineRoot = outline;
  1242. }
  1243. for (NSInteger i = 0; i < self.rootPDFOutlineArray.count; i++) {
  1244. PDFOutline *rootPDFOutline = _rootPDFOutlineArray[i];
  1245. for (NSInteger j = 0; j < rootPDFOutline.numberOfChildren; j ++) {
  1246. [self.PDFDocument.outlineRoot insertChild:[rootPDFOutline childAtIndex:j] atIndex:self.PDFDocument.outlineRoot.numberOfChildren];
  1247. }
  1248. }
  1249. }
  1250. if (_isSuccessfully) {
  1251. if (self.limit) {
  1252. [self handerReDraw];
  1253. }
  1254. KMSavePanelAccessoryController *savePanelAccessoryViewController = [[KMSavePanelAccessoryController alloc] init];
  1255. NSSavePanel *savePanel = [NSSavePanel savePanel];
  1256. savePanel.nameFieldStringValue = fileName;
  1257. savePanel.allowedFileTypes = @[@"pdf"];
  1258. savePanel.accessoryView = savePanelAccessoryViewController.view;
  1259. self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  1260. [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  1261. if (result) {
  1262. NSString * outputSavePanel = savePanel.URL.path;
  1263. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1264. self->_isSuccessfully = [self.PDFDocument writeToFile:outputSavePanel];
  1265. if (!self->_isSuccessfully) {
  1266. self->_isSuccessfully = [self.PDFDocument.dataRepresentation writeToFile:outputSavePanel atomically:YES];
  1267. }
  1268. dispatch_async(dispatch_get_main_queue(), ^{
  1269. [self->_progress setHidden:YES];
  1270. [self.nCancelVC setEnabled:YES];
  1271. self.canMerge = YES;
  1272. self.loading_backgroundView.hidden = YES;
  1273. if (self->_isSuccessfully) {
  1274. [self _clearData];
  1275. [self recordMergeCount];
  1276. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1277. [[self window] orderOut:self];
  1278. if (self.saveAsPDFFilePath) {
  1279. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1280. if (autoOpen) {
  1281. self.saveAsPDFFilePath(outputSavePanel);
  1282. self.saveAsPDFFilePath = nil;
  1283. } else {
  1284. [self viewFileAtFinder:outputSavePanel];
  1285. }
  1286. } else {
  1287. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1288. if (autoOpen) {
  1289. [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:outputSavePanel] display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1290. }];
  1291. } else {
  1292. [self viewFileAtFinder:outputSavePanel];
  1293. }
  1294. }
  1295. } else {
  1296. NSAlert *alert = [[NSAlert alloc] init];
  1297. [alert setAlertStyle:NSAlertStyleCritical];
  1298. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1299. NSModalResponse response = [alert runModal];
  1300. if (response == 0 ) {
  1301. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1302. [[self window] orderOut:self];
  1303. }
  1304. }
  1305. });
  1306. });
  1307. } else {
  1308. [self->_progress setHidden:YES];
  1309. [self.nCancelVC setEnabled:YES];
  1310. self.canMerge = YES;
  1311. self.loading_backgroundView.hidden = YES;
  1312. }
  1313. }];
  1314. } else {
  1315. NSAlert *alert = [[NSAlert alloc] init];
  1316. [alert setAlertStyle:NSAlertStyleCritical];
  1317. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1318. NSModalResponse response = [alert runModal];
  1319. if (response == 0 ) {
  1320. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1321. [[self window] orderOut:self];
  1322. }
  1323. }
  1324. }
  1325. }
  1326. - (IBAction)buttonItemClicked_Clear:(id)sender
  1327. {
  1328. [_files removeAllObjects];
  1329. [self updateButtonState];
  1330. [self.tableView reloadData];
  1331. self.allFileSize = 0;
  1332. }
  1333. - (IBAction)buttonItemClicked_AddFile:(id)sender
  1334. {
  1335. NSMenu *menu = [[NSMenu alloc] init];
  1336. NSMenuItem *addFileItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add files", "") action:@selector(itemAddFileAction) keyEquivalent:@""];
  1337. addFileItem.target = self;
  1338. [menu addItem:addFileItem];
  1339. NSMenuItem *addFolderitem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add Folder", "") action:@selector(itemAddFolderAction) keyEquivalent:@""];
  1340. addFolderitem.target = self;
  1341. [menu addItem:addFolderitem];
  1342. NSMenuItem *addOpenFileitem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add Open Files", "") action:@selector(itemAddOpenFileAction) keyEquivalent:@""];
  1343. addOpenFileitem.target = self;
  1344. [menu addItem:addOpenFileitem];
  1345. [menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(100, 10) inView:sender];
  1346. }
  1347. - (void)itemAddFileAction {
  1348. NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
  1349. [openPanel setAllowedFileTypes:[KMImageAccessoryController supportedImageTypes]];
  1350. [openPanel setAllowsMultipleSelection:YES];
  1351. openPanel.message = NSLocalizedString(@"Press ⌘/⇧ to select multiple files", nil);
  1352. [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
  1353. if (result == NSModalResponseOK) {
  1354. NSMutableArray *array = [NSMutableArray array];
  1355. for (NSURL *fileURL in [openPanel URLs]) {
  1356. if (fileURL) {
  1357. if (![self isExistAtFilepath:fileURL.path]) {
  1358. continue;
  1359. }
  1360. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
  1361. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  1362. self.allFileSize = self.allFileSize + fileSize;
  1363. [array addObject:fileURL.path];
  1364. }
  1365. }
  1366. [self addFiles:array];
  1367. }
  1368. }];
  1369. }
  1370. - (void)itemAddFolderAction {
  1371. NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
  1372. [openPanel setAllowedFileTypes:[KMImageAccessoryController supportedImageTypes]];
  1373. [openPanel setAllowsMultipleSelection:YES];
  1374. openPanel.canChooseFiles = NO;
  1375. openPanel.canChooseDirectories = YES;
  1376. openPanel.message = NSLocalizedString(@"Press ⌘/⇧ to select multiple files", nil);
  1377. [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
  1378. if (result == NSModalResponseOK) {
  1379. NSMutableArray *result = [NSMutableArray array];
  1380. for (NSURL *url in openPanel.URLs) {
  1381. [self findAllFiles:url result:result];
  1382. }
  1383. NSMutableArray *array = [NSMutableArray array];
  1384. for (NSURL *fileURL in result) {
  1385. if (fileURL) {
  1386. if (![self isExistAtFilepath:fileURL.path]) {
  1387. continue;
  1388. }
  1389. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
  1390. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  1391. self.allFileSize = self.allFileSize + fileSize;
  1392. [array addObject:fileURL.path];
  1393. }
  1394. }
  1395. [self addFiles:array];
  1396. }
  1397. }];
  1398. }
  1399. - (void)itemAddOpenFileAction {
  1400. [_lockFilePathArr removeAllObjects];
  1401. _lockFileIndex = 0;
  1402. for (NSWindow *window in NSApp.windows) {
  1403. NSWindowController *controller = [window windowController];
  1404. if (![controller isKindOfClass:[CTBrowserWindowController class]]) {
  1405. continue;
  1406. }
  1407. CTTabStripModel *model = ((CTBrowserWindowController *)controller).browser.tabStripModel;
  1408. for (int i = 0; i < model.count; i++) {
  1409. KMMainDocument *document = (KMMainDocument *)[model tabContentsAtIndex:i];
  1410. // if (document.windowControllers.count == 0) {
  1411. // break;
  1412. // }
  1413. if (document.isHome) {
  1414. continue;
  1415. }
  1416. KMMainViewController *mainViewController = document.mainViewController;
  1417. if ([self.PDFDocument.documentURL.path isEqualToString:document.fileURL.path]) {
  1418. continue;
  1419. }
  1420. if (![self isExistAtFilepath:document.fileURL.path]) {
  1421. continue;
  1422. }
  1423. CPDFDocument *pdfDocument = mainViewController.listView.document;
  1424. if (pdfDocument.isLocked || (!pdfDocument.allowsCopying || !pdfDocument.allowsPrinting)) {
  1425. [_lockFilePathArr addObject:pdfDocument.documentURL.path];
  1426. } else {
  1427. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  1428. file.filePath = document.fileURL.path;
  1429. file.pdfDocument = mainViewController.document;
  1430. [_files addObject:file];
  1431. }
  1432. }
  1433. }
  1434. [self updateButtonState];
  1435. [_tableView reloadData];
  1436. if ([_lockFilePathArr count]) {
  1437. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1438. if (self.files.count == 0) {
  1439. self.insertRow = 0;
  1440. } else {
  1441. self.insertRow = self.files.count;
  1442. }
  1443. [self openPasswordWindow];
  1444. });
  1445. }
  1446. }
  1447. - (void)findAllFiles:(NSURL *)folderURL result:(NSMutableArray *)result {
  1448. NSFileManager *fm = [NSFileManager defaultManager];
  1449. BOOL isDirectory = NO;
  1450. [fm fileExistsAtPath:folderURL.path isDirectory:&isDirectory];
  1451. if (!isDirectory) {
  1452. return;
  1453. }
  1454. NSArray *contents = [fm contentsOfDirectoryAtURL:folderURL includingPropertiesForKeys:nil options:0 error:nil];
  1455. if (contents.count == 0) {
  1456. return;
  1457. }
  1458. NSArray *array = @[@"jpg",@"cur",@"bmp",@"jpeg",@"gif",@"png",@"tiff",@"tif",/*@"pic",*/@"ico",@"icns",@"tga",@"psd",@"eps",@"hdr",@"jp2",@"jpc",@"pict",@"sgi",@"heic",@"pdf"];
  1459. for (NSURL *documentURL in contents) {
  1460. BOOL isDirectory = NO;
  1461. [fm fileExistsAtPath:documentURL.path isDirectory:&isDirectory];
  1462. if (isDirectory) {
  1463. [self findAllFiles:documentURL result:result];
  1464. } else {
  1465. if (![array containsObject:[documentURL.pathExtension lowercaseString]]) {
  1466. continue;
  1467. }
  1468. [result addObject:documentURL];
  1469. }
  1470. }
  1471. }
  1472. - (IBAction)buttonClicked_ChooseSize:(KMImageTitleButton *)sender {
  1473. int i = 0;
  1474. for (KMImageTitleButton *button in @[self.originalSizeButton, self.A4SizeButton, self.A3SizeButton,
  1475. self.USLetterSizeButton, self.USLegalButton, self.customSizeButton]) {
  1476. KMImageTitleButton *radio = button.subviews.lastObject;
  1477. radio.state = NSControlStateValueOff;
  1478. radio.imageName = @"btn_radio_unsel_on";
  1479. i += 1;
  1480. }
  1481. sender.state = NSControlStateValueOn;
  1482. sender.imageName = @"btn_radio_sel_on";
  1483. KMImageTitleButton *customSizeButton = self.customSizeButton.subviews.lastObject;
  1484. self.pageSizeHeightTextField.enabled = self.pageSizeWidthTextField.enabled = [sender isEqual:customSizeButton];
  1485. switch (sender.contentButton.tag) {
  1486. case 0:
  1487. break;
  1488. case 1:
  1489. self.newPageSize = CGSizeMake(595, 841);
  1490. break;
  1491. case 2:
  1492. self.newPageSize = CGSizeMake(841, 1190);
  1493. break;
  1494. case 3:
  1495. self.newPageSize = CGSizeMake(612, 792);
  1496. break;
  1497. case 4:
  1498. self.newPageSize = CGSizeMake(612, 1108);
  1499. break;
  1500. case 5:
  1501. self.newPageSize = CGSizeMake(595, 841);
  1502. self.pageSizeWidthTextField.stringValue = [NSString stringWithFormat:@"%.0f",self.newPageSize.width];
  1503. self.pageSizeHeightTextField.stringValue = [NSString stringWithFormat:@"%.0f",self.newPageSize.height];
  1504. break;
  1505. default:
  1506. break;
  1507. }
  1508. }
  1509. #pragma mark - Private Method
  1510. //获取所有的子节点
  1511. - (void)fetchAllOfChildren:(PDFOutline *)aOutline containerArray:(NSMutableArray *)aMArray
  1512. {
  1513. if (![aMArray containsObject:aOutline]) {
  1514. [aMArray addObject:aOutline];
  1515. }
  1516. for (NSInteger i = 0; i < aOutline.numberOfChildren; i++) {
  1517. [aMArray addObject:[aOutline childAtIndex:i]];
  1518. [self fetchAllOfChildren:[aOutline childAtIndex:i] containerArray:aMArray];
  1519. }
  1520. }
  1521. @end
  1522. static NSString *kKMMergeCountKey = @"KMMergeCountKey";
  1523. static NSInteger kKMMergeCountMax = 2;
  1524. @implementation KMPDFEditAppendWindow (KMExtension)
  1525. - (BOOL)mergeCountIsReach {
  1526. #if VERSION_DMG
  1527. return NO;
  1528. #else
  1529. if ([KMLightMemberManager manager].isLogin) {
  1530. return NO;
  1531. }
  1532. NSInteger cnt = [self getMergeCount];
  1533. if (cnt >= kKMMergeCountMax) {
  1534. return YES;
  1535. }
  1536. return NO;
  1537. #endif
  1538. }
  1539. - (void)recordMergeCount {
  1540. NSInteger cnt = [self getMergeCount];
  1541. [[NSUserDefaults standardUserDefaults] setInteger:cnt+1 forKey:kKMMergeCountKey];
  1542. [[NSUserDefaults standardUserDefaults] synchronize];
  1543. }
  1544. - (void)clearMergeCount {
  1545. [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:kKMMergeCountKey];
  1546. [[NSUserDefaults standardUserDefaults] synchronize];
  1547. }
  1548. - (NSInteger)getMergeCount {
  1549. return [[NSUserDefaults standardUserDefaults] integerForKey:kKMMergeCountKey];
  1550. }
  1551. @end