KMPDFEditAppendWindow.m 67 KB

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