KMPDFEditAppendWindow.m 69 KB

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