KMPDFEditAppendWindow.m 72 KB

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