KMPDFEditAppendWindow.m 72 KB

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