KMPDFEditAppendWindow.m 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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-20, 72, 20), 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-20, 72, 20);
  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. cell.iconImageView.image = [NSImage previewForFileWithPath:pdf.documentURL ofSize:NSMakeSize(120, 120) asIcon:YES];
  789. } else if (fileAttribute.filePath) {
  790. // if ([fileAttribute.filePath.pathExtension.lowercaseString isEqualToString:@"pdf"]) {
  791. cell.iconImageView.image = [NSImage previewForFileWithPath:[NSURL fileURLWithPath:fileAttribute.filePath] ofSize:NSMakeSize(120, 120) asIcon:YES];
  792. // } else {
  793. // cell.iconImageView.image = [NSImage previewForFileWithPath:fileAttribute.filePath ofSize:NSMakeSize(120, 120) asIcon:YES];
  794. // }
  795. } else {
  796. cell.iconImageView.image = nil;
  797. }
  798. return cell;
  799. }
  800. - (BOOL)tableView:(NSTableView *)tableView shouldSelectTableColumn:(NSTableColumn *)tableColumn
  801. {
  802. return NO;
  803. }
  804. #pragma mark -NSTableViewDelegate
  805. - (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard
  806. {
  807. // Copy the row numbers to the pasteboard.
  808. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  809. [pboard declareTypes:[NSArray arrayWithObject:MyTableCellViewDataType] owner:self];
  810. [pboard setData:zNSIndexSetData forType:MyTableCellViewDataType];
  811. return YES;
  812. }
  813. - (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation
  814. {
  815. if (dropOperation == NSTableViewDropOn) {
  816. return NSDragOperationNone;
  817. }
  818. BOOL isCanDrag = NO;
  819. NSDragOperation result = NSDragOperationNone;
  820. NSPasteboard *pboard = [info draggingPasteboard];
  821. if ([pboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]])
  822. {
  823. NSArray *fileNames = [pboard propertyListForType:NSFilenamesPboardType];
  824. for (NSString* path in fileNames) {
  825. if ([[KMImageAccessoryController supportedImageTypes] containsObject:path.pathExtension.lowercaseString]) {
  826. isCanDrag = YES;
  827. }else{
  828. isCanDrag = NO;
  829. break;
  830. }
  831. }
  832. }else if ([pboard availableTypeFromArray:[NSArray arrayWithObject:MyTableCellViewDataType]]){
  833. result = NSDragOperationEvery;
  834. }
  835. if (isCanDrag) {
  836. result = NSDragOperationCopy;
  837. }
  838. return result;
  839. }
  840. - (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation
  841. {
  842. BOOL result = NO;
  843. NSPasteboard *pboard = [info draggingPasteboard];
  844. _insertRow = row;
  845. if ([pboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]])
  846. {
  847. NSMutableArray *fileNames = [pboard propertyListForType:NSFilenamesPboardType];
  848. NSMutableArray *array = [NSMutableArray array];
  849. for(NSString *path in fileNames){
  850. if (![self isExistAtFilepath:path]) {
  851. continue;
  852. }
  853. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  854. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  855. self.allFileSize = self.allFileSize + fileSize;
  856. [array addObject:path];
  857. }
  858. [self addFiles:array];
  859. result = YES;
  860. } else if ([pboard availableTypeFromArray:[NSArray arrayWithObject:MyTableCellViewDataType]]){
  861. NSData* rowData = [pboard dataForType:MyTableCellViewDataType];
  862. NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
  863. NSMutableArray *moveArray = [[NSMutableArray alloc] init];
  864. NSMutableArray *allPhoto = [_files mutableCopy];
  865. NSInteger index = 0;
  866. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  867. KMFileAttribute * file = allPhoto[idx];
  868. [moveArray addObject:file];
  869. [_files removeObject:file];
  870. }];
  871. if (row > 0) {
  872. KMFileAttribute * indexFile = allPhoto[row -1];
  873. while([moveArray containsObject:indexFile]){
  874. row --;
  875. if ((row < 0)) {
  876. indexFile = nil;
  877. break;
  878. } else {
  879. indexFile = allPhoto[row];
  880. }
  881. }
  882. if(indexFile){
  883. index = [_files indexOfObject:indexFile]+1;
  884. }
  885. }
  886. for (NSInteger i = 0; i< moveArray.count; i++) {
  887. [_files insertObject:moveArray[i] atIndex:(index +i)];
  888. }
  889. [_tableView reloadData];
  890. result = YES;
  891. // [moveArray release];
  892. // [allPhoto release];
  893. } else {
  894. result = NO;
  895. }
  896. return result;
  897. }
  898. - (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row {
  899. KMBatchTableRowView *rowView = [[KMBatchTableRowView alloc] init];
  900. rowView.backgroundView.layer.backgroundColor = [NSColor colorWithRed:237/255.f green:238/255.f blue:240/255.f alpha:1.f].CGColor;
  901. rowView.backgroundView.layer.cornerRadius = 4.f;
  902. rowView.selectionInset = NSEdgeInsetsMake(0, 16, 0, 16);
  903. rowView.selectionRadius = 4.f;
  904. rowView.selectionBackgroundColorBlock = ^NSColor * _Nonnull{
  905. return [NSColor colorWithRed:206/255.f green:208/255.f blue:212/255.f alpha:0.6f];
  906. };
  907. return rowView;
  908. }
  909. - (void)tableViewSelectionDidChange:(NSNotification *)notification {
  910. }
  911. #pragma mark Buutton Action
  912. - (IBAction)buttonItemClicked_Cancel:(id)sender
  913. {
  914. _isSuccessfully = NO;
  915. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  916. [[self window] orderOut:self];
  917. }
  918. - (IBAction)buttonItemClicked_Append:(id)sender
  919. {
  920. if (!self.canMerge) {
  921. return;
  922. }
  923. KMImageTitleButton *customSizeButton = self.customSizeButton.subviews.lastObject;
  924. if (customSizeButton.state == NSControlStateValueOn) {
  925. NSInteger widthFloat = [self.pageSizeWidthTextField.stringValue integerValue];
  926. NSInteger heightFloat = [self.pageSizeHeightTextField.stringValue integerValue];
  927. NSString *widthString = [NSString stringWithFormat:@"%ld",widthFloat];
  928. NSString *heightString = [NSString stringWithFormat:@"%ld",heightFloat];
  929. if (![widthString isEqualToString:self.pageSizeWidthTextField.stringValue] ||![heightString isEqualToString:self.pageSizeHeightTextField.stringValue]||widthFloat <= 0 ||heightFloat <= 0 ) {
  930. NSBeep();
  931. return;
  932. }else{
  933. self.newPageSize = CGSizeMake(widthFloat, heightFloat);
  934. }
  935. }
  936. //初始化数组
  937. if (!self.rootPDFOutlineArray) {
  938. self.rootPDFOutlineArray = [NSMutableArray new];
  939. }else{
  940. [self.rootPDFOutlineArray removeAllObjects];
  941. }
  942. //如果是合并,文件路径不存在,或者文件个数小于等于1 return
  943. if (_editType == KMPDFPageEditMerge) {
  944. if (_files.count <= 1 ) {
  945. NSAlert *alert = [[NSAlert alloc] init];
  946. [alert setAlertStyle:NSAlertStyleCritical];
  947. [alert setMessageText:NSLocalizedString(@"To start merging, please select at least 2 files.", nil)];
  948. [alert runModal];
  949. return;
  950. }
  951. }
  952. _isSuccessfully = NO;
  953. [self.nCancelVC setEnabled:NO];
  954. self.canMerge = NO;
  955. BOOL allPage = YES;//只有是全部才支持大纲的合并
  956. for (KMFileAttribute *file in _files) {
  957. if (!file.selectPages) {
  958. dispatch_async(dispatch_get_main_queue(), ^{
  959. NSAlert *alert = [[NSAlert alloc] init];
  960. [alert setAlertStyle:NSAlertStyleCritical];
  961. [alert setMessageText:[NSString stringWithFormat:@"%@ %@",[file.filePath lastPathComponent],NSLocalizedString(@"Invalid page range or the page number is out of range. Please try again.", nil)]];
  962. [alert runModal];
  963. [self.nCancelVC setEnabled:YES];
  964. self.canMerge = YES;
  965. });
  966. return;
  967. }
  968. }
  969. [_progress setHidden:NO];
  970. [_progress startAnimation:nil];
  971. self.loading_backgroundView.hidden = NO;
  972. for(KMFileAttribute *file in _files){
  973. //只要有一个文件不是全部page,那么就不合并大纲
  974. if (allPage == YES) {
  975. allPage = file.bAllPage;
  976. }
  977. //通过路径获取文件
  978. PDFDocument *tdocument = file.myPDFDocument;
  979. if (tdocument == nil) {
  980. tdocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:[file filePath]]];
  981. file.myPDFDocument = tdocument;
  982. }
  983. //所有的outline数组
  984. NSMutableArray *PDFOutlineArr = [NSMutableArray new];
  985. //需要解锁
  986. if (file.isLocked) {
  987. [tdocument unlockWithPassword:file.password];
  988. }
  989. //如果根存在,那么遍历出所有的outline,添加到数组中,如果不存在,那么就创建一个根
  990. if (tdocument.outlineRoot) {
  991. [self.rootPDFOutlineArray addObject:tdocument.outlineRoot];
  992. [self fetchAllOfChildren:tdocument.outlineRoot containerArray:PDFOutlineArr];
  993. [PDFOutlineArr removeObject:tdocument.outlineRoot];
  994. } else {
  995. PDFOutline *rootOutline = [[PDFOutline alloc] init];
  996. tdocument.outlineRoot = rootOutline;
  997. if (tdocument.outlineRoot) {
  998. [self.rootPDFOutlineArray addObject:tdocument.outlineRoot];
  999. }
  1000. }
  1001. // for (CPDFOutline *tOutline in PDFOutlineArr) {
  1002. //这段代码主要是调用他的getter方法;outline显示正确
  1003. // [tOutline.destination.page dataRepresentation];
  1004. // }
  1005. for (NSNumber *number in file.selectPages) {
  1006. PDFPage *page = [tdocument pageAtIndex:[number integerValue]-1];
  1007. [self.PDFDocument insertPage:page atIndex:[self.PDFDocument pageCount]];
  1008. // [self.PDFDocument insertPageObject:page atIndex:self.PDFDocument.pageCount];
  1009. [self.insertIndexSet addIndex:(self.PDFDocument.pageCount - 1)];
  1010. }
  1011. _isSuccessfully = YES;
  1012. }
  1013. KMFileAttribute *file = self.files.firstObject;
  1014. NSString *fileName = file.filePath.stringByDeletingPathExtension.lastPathComponent;
  1015. fileName = [NSString stringWithFormat:@"%@_Merged", fileName];
  1016. if (_editType == KMPDFPageEditMerge) {
  1017. _isSuccessfully = NO;
  1018. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1019. PDFOutline *rootline = [[PDFOutline alloc] init];
  1020. self.PDFDocument.outlineRoot = rootline;
  1021. if (allPage) {
  1022. NSInteger insertIndex = 0;
  1023. for (NSUInteger i = 0; i < self.rootPDFOutlineArray.count; i++) {
  1024. PDFOutline *rootPDFOutline = self->_rootPDFOutlineArray[i];
  1025. for (NSUInteger j = 0; j < rootPDFOutline.numberOfChildren; j ++) {
  1026. [self.PDFDocument.outlineRoot insertChild:[rootPDFOutline childAtIndex:j] atIndex: insertIndex];
  1027. insertIndex ++;
  1028. }
  1029. }
  1030. }
  1031. dispatch_async(dispatch_get_main_queue(), ^{
  1032. if (self.limit) {
  1033. [self handerReDraw];
  1034. }
  1035. KMSavePanelAccessoryController *savePanelAccessoryViewController = [[KMSavePanelAccessoryController alloc] init];
  1036. NSSavePanel *savePanel = [NSSavePanel savePanel];
  1037. savePanel.nameFieldStringValue = fileName;
  1038. savePanel.allowedFileTypes = @[@"pdf"];
  1039. savePanel.accessoryView = savePanelAccessoryViewController.view;
  1040. self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  1041. [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  1042. if (result) {
  1043. NSString * outputSavePanel = savePanel.URL.path;
  1044. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1045. self->_isSuccessfully = [self.PDFDocument writeToFile:outputSavePanel];
  1046. if (!self->_isSuccessfully) {
  1047. self->_isSuccessfully = [self.PDFDocument.dataRepresentation writeToFile:outputSavePanel atomically:YES];
  1048. }
  1049. dispatch_async(dispatch_get_main_queue(), ^{
  1050. [self->_progress setHidden:YES];
  1051. [self.nCancelVC setEnabled:YES];
  1052. self.canMerge = YES;
  1053. self.loading_backgroundView.hidden = YES;
  1054. if (self->_isSuccessfully) {
  1055. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1056. [[self window] orderOut:self];
  1057. if (self.saveAsPDFFilePath) {
  1058. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1059. if (autoOpen) {
  1060. self.saveAsPDFFilePath(outputSavePanel);
  1061. self.saveAsPDFFilePath = nil;
  1062. } else {
  1063. [self viewFileAtFinder:outputSavePanel];
  1064. }
  1065. } else {
  1066. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1067. if (autoOpen) {
  1068. [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:outputSavePanel] display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1069. }];
  1070. } else {
  1071. [self viewFileAtFinder:outputSavePanel];
  1072. }
  1073. }
  1074. } else {
  1075. NSAlert *alert = [[NSAlert alloc] init];
  1076. [alert setAlertStyle:NSAlertStyleCritical];
  1077. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1078. NSModalResponse response = [alert runModal];
  1079. if (response == 0 ) {
  1080. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1081. [[self window] orderOut:self];
  1082. }
  1083. }
  1084. });
  1085. });
  1086. } else {
  1087. [self->_progress setHidden:YES];
  1088. [self.nCancelVC setEnabled:YES];
  1089. self.canMerge = YES;
  1090. self.loading_backgroundView.hidden = YES;
  1091. }
  1092. }];
  1093. });
  1094. });
  1095. } else {
  1096. [self.nCancelVC setEnabled:YES];
  1097. self.canMerge = YES;
  1098. if (allPage) {
  1099. if (!self.PDFDocument.outlineRoot) {
  1100. PDFOutline *outline = [[PDFOutline alloc] init];
  1101. self.PDFDocument.outlineRoot = outline;
  1102. }
  1103. for (NSInteger i = 0; i < self.rootPDFOutlineArray.count; i++) {
  1104. PDFOutline *rootPDFOutline = _rootPDFOutlineArray[i];
  1105. for (NSInteger j = 0; j < rootPDFOutline.numberOfChildren; j ++) {
  1106. [self.PDFDocument.outlineRoot insertChild:[rootPDFOutline childAtIndex:j] atIndex:self.PDFDocument.outlineRoot.numberOfChildren];
  1107. }
  1108. }
  1109. }
  1110. if (_isSuccessfully) {
  1111. if (self.limit) {
  1112. [self handerReDraw];
  1113. }
  1114. KMSavePanelAccessoryController *savePanelAccessoryViewController = [[KMSavePanelAccessoryController alloc] init];
  1115. NSSavePanel *savePanel = [NSSavePanel savePanel];
  1116. savePanel.nameFieldStringValue = fileName;
  1117. savePanel.allowedFileTypes = @[@"pdf"];
  1118. savePanel.accessoryView = savePanelAccessoryViewController.view;
  1119. self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  1120. [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
  1121. if (result) {
  1122. NSString * outputSavePanel = savePanel.URL.path;
  1123. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1124. self->_isSuccessfully = [self.PDFDocument writeToFile:outputSavePanel];
  1125. if (!self->_isSuccessfully) {
  1126. self->_isSuccessfully = [self.PDFDocument.dataRepresentation writeToFile:outputSavePanel atomically:YES];
  1127. }
  1128. dispatch_async(dispatch_get_main_queue(), ^{
  1129. [self->_progress setHidden:YES];
  1130. [self.nCancelVC setEnabled:YES];
  1131. self.canMerge = YES;
  1132. self.loading_backgroundView.hidden = YES;
  1133. if (self->_isSuccessfully) {
  1134. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1135. [[self window] orderOut:self];
  1136. if (self.saveAsPDFFilePath) {
  1137. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1138. if (autoOpen) {
  1139. self.saveAsPDFFilePath(outputSavePanel);
  1140. self.saveAsPDFFilePath = nil;
  1141. } else {
  1142. [self viewFileAtFinder:outputSavePanel];
  1143. }
  1144. } else {
  1145. BOOL autoOpen = self.savePanelAccessoryViewController.needOpen;
  1146. if (autoOpen) {
  1147. [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[NSURL fileURLWithPath:outputSavePanel] display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1148. }];
  1149. } else {
  1150. [self viewFileAtFinder:outputSavePanel];
  1151. }
  1152. }
  1153. } else {
  1154. NSAlert *alert = [[NSAlert alloc] init];
  1155. [alert setAlertStyle:NSAlertStyleCritical];
  1156. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1157. NSModalResponse response = [alert runModal];
  1158. if (response == 0 ) {
  1159. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1160. [[self window] orderOut:self];
  1161. }
  1162. }
  1163. });
  1164. });
  1165. } else {
  1166. [self->_progress setHidden:YES];
  1167. [self.nCancelVC setEnabled:YES];
  1168. self.canMerge = YES;
  1169. self.loading_backgroundView.hidden = YES;
  1170. }
  1171. }];
  1172. } else {
  1173. NSAlert *alert = [[NSAlert alloc] init];
  1174. [alert setAlertStyle:NSAlertStyleCritical];
  1175. [alert setMessageText:[NSString stringWithFormat:NSLocalizedString(@"Failed to merge!", nil)]];
  1176. NSModalResponse response = [alert runModal];
  1177. if (response == 0 ) {
  1178. [NSApp endSheet:[self window] returnCode:[(NSView *)sender tag]];
  1179. [[self window] orderOut:self];
  1180. }
  1181. }
  1182. }
  1183. }
  1184. - (IBAction)buttonItemClicked_Clear:(id)sender
  1185. {
  1186. [_files removeAllObjects];
  1187. [self updateButtonState];
  1188. [self.tableView reloadData];
  1189. self.allFileSize = 0;
  1190. }
  1191. - (IBAction)buttonItemClicked_AddFile:(id)sender
  1192. {
  1193. NSMenu *menu = [[NSMenu alloc] init];
  1194. NSMenuItem *addFileItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add files", "") action:@selector(itemAddFileAction) keyEquivalent:@""];
  1195. addFileItem.target = self;
  1196. [menu addItem:addFileItem];
  1197. NSMenuItem *addFolderitem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add Folder", "") action:@selector(itemAddFolderAction) keyEquivalent:@""];
  1198. addFolderitem.target = self;
  1199. [menu addItem:addFolderitem];
  1200. NSMenuItem *addOpenFileitem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"add Open Files", "") action:@selector(itemAddOpenFileAction) keyEquivalent:@""];
  1201. addOpenFileitem.target = self;
  1202. [menu addItem:addOpenFileitem];
  1203. [menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(100, 10) inView:sender];
  1204. }
  1205. - (void)itemAddFileAction {
  1206. NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
  1207. [openPanel setAllowedFileTypes:[KMImageAccessoryController supportedImageTypes]];
  1208. [openPanel setAllowsMultipleSelection:YES];
  1209. openPanel.message = NSLocalizedString(@"Press ⌘/⇧ to select multiple files", nil);
  1210. [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
  1211. if (result == NSModalResponseOK) {
  1212. NSMutableArray *array = [NSMutableArray array];
  1213. for (NSURL *fileURL in [openPanel URLs]) {
  1214. if (fileURL) {
  1215. if (![self isExistAtFilepath:fileURL.path]) {
  1216. continue;
  1217. }
  1218. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
  1219. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  1220. self.allFileSize = self.allFileSize + fileSize;
  1221. [array addObject:fileURL.path];
  1222. }
  1223. }
  1224. [self addFiles:array];
  1225. }
  1226. }];
  1227. }
  1228. - (void)itemAddFolderAction {
  1229. NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
  1230. [openPanel setAllowedFileTypes:[KMImageAccessoryController supportedImageTypes]];
  1231. [openPanel setAllowsMultipleSelection:YES];
  1232. openPanel.canChooseFiles = NO;
  1233. openPanel.canChooseDirectories = YES;
  1234. openPanel.message = NSLocalizedString(@"Press ⌘/⇧ to select multiple files", nil);
  1235. [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
  1236. if (result == NSModalResponseOK) {
  1237. NSMutableArray *result = [NSMutableArray array];
  1238. for (NSURL *url in openPanel.URLs) {
  1239. [self findAllFiles:url result:result];
  1240. }
  1241. NSMutableArray *array = [NSMutableArray array];
  1242. for (NSURL *fileURL in result) {
  1243. if (fileURL) {
  1244. if (![self isExistAtFilepath:fileURL.path]) {
  1245. continue;
  1246. }
  1247. NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
  1248. CGFloat fileSize = [[attrib objectForKey:NSFileSize] floatValue];
  1249. self.allFileSize = self.allFileSize + fileSize;
  1250. [array addObject:fileURL.path];
  1251. }
  1252. }
  1253. [self addFiles:array];
  1254. }
  1255. }];
  1256. }
  1257. - (void)itemAddOpenFileAction {
  1258. [_lockFilePathArr removeAllObjects];
  1259. _lockFileIndex = 0;
  1260. for (NSWindow *window in NSApp.windows) {
  1261. NSWindowController *controller = [window windowController];
  1262. if (![controller isKindOfClass:[CTBrowserWindowController class]]) {
  1263. continue;
  1264. }
  1265. CTTabStripModel *model = ((CTBrowserWindowController *)controller).browser.tabStripModel;
  1266. for (int i = 0; i < model.count; i++) {
  1267. KMMainDocument *document = (KMMainDocument *)[model tabContentsAtIndex:i];
  1268. // if (document.windowControllers.count == 0) {
  1269. // break;
  1270. // }
  1271. if (document.isHome) {
  1272. continue;
  1273. }
  1274. KMMainViewController *mainViewController = document.mainViewController;
  1275. if ([self.PDFDocument.documentURL.path isEqualToString:document.fileURL.path]) {
  1276. continue;
  1277. }
  1278. if (![self isExistAtFilepath:document.fileURL.path]) {
  1279. continue;
  1280. }
  1281. CPDFDocument *pdfDocument = mainViewController.listView.document;
  1282. if (pdfDocument.isLocked || (!pdfDocument.allowsCopying || !pdfDocument.allowsPrinting)) {
  1283. [_lockFilePathArr addObject:pdfDocument.documentURL.path];
  1284. } else {
  1285. KMFileAttribute *file = [[KMFileAttribute alloc] init];
  1286. file.filePath = document.fileURL.path;
  1287. file.pdfDocument = mainViewController.document;
  1288. [_files addObject:file];
  1289. }
  1290. }
  1291. }
  1292. [self updateButtonState];
  1293. [_tableView reloadData];
  1294. if ([_lockFilePathArr count]) {
  1295. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1296. if (self.files.count == 0) {
  1297. self.insertRow = 0;
  1298. } else {
  1299. self.insertRow = self.files.count;
  1300. }
  1301. [self openPasswordWindow];
  1302. });
  1303. }
  1304. }
  1305. - (void)findAllFiles:(NSURL *)folderURL result:(NSMutableArray *)result {
  1306. NSFileManager *fm = [NSFileManager defaultManager];
  1307. BOOL isDirectory = NO;
  1308. [fm fileExistsAtPath:folderURL.path isDirectory:&isDirectory];
  1309. if (!isDirectory) {
  1310. return;
  1311. }
  1312. NSArray *contents = [fm contentsOfDirectoryAtURL:folderURL includingPropertiesForKeys:nil options:0 error:nil];
  1313. if (contents.count == 0) {
  1314. return;
  1315. }
  1316. NSArray *array = @[@"jpg",@"cur",@"bmp",@"jpeg",@"gif",@"png",@"tiff",@"tif",/*@"pic",*/@"ico",@"icns",@"tga",@"psd",@"eps",@"hdr",@"jp2",@"jpc",@"pict",@"sgi",@"heic",@"pdf"];
  1317. for (NSURL *documentURL in contents) {
  1318. BOOL isDirectory = NO;
  1319. [fm fileExistsAtPath:documentURL.path isDirectory:&isDirectory];
  1320. if (isDirectory) {
  1321. [self findAllFiles:documentURL result:result];
  1322. } else {
  1323. if (![array containsObject:[documentURL.pathExtension lowercaseString]]) {
  1324. continue;
  1325. }
  1326. [result addObject:documentURL];
  1327. }
  1328. }
  1329. }
  1330. - (IBAction)buttonClicked_ChooseSize:(KMImageTitleButton *)sender {
  1331. int i = 0;
  1332. for (KMImageTitleButton *button in @[self.originalSizeButton, self.A4SizeButton, self.A3SizeButton,
  1333. self.USLetterSizeButton, self.USLegalButton, self.customSizeButton]) {
  1334. KMImageTitleButton *radio = button.subviews.lastObject;
  1335. radio.state = NSControlStateValueOff;
  1336. radio.imageName = @"btn_radio_unsel_on";
  1337. i += 1;
  1338. }
  1339. sender.state = NSControlStateValueOn;
  1340. sender.imageName = @"btn_radio_sel_on";
  1341. KMImageTitleButton *customSizeButton = self.customSizeButton.subviews.lastObject;
  1342. self.pageSizeHeightTextField.enabled = self.pageSizeWidthTextField.enabled = [sender isEqual:customSizeButton];
  1343. switch (sender.contentButton.tag) {
  1344. case 0:
  1345. break;
  1346. case 1:
  1347. self.newPageSize = CGSizeMake(595, 841);
  1348. break;
  1349. case 2:
  1350. self.newPageSize = CGSizeMake(841, 1190);
  1351. break;
  1352. case 3:
  1353. self.newPageSize = CGSizeMake(612, 792);
  1354. break;
  1355. case 4:
  1356. self.newPageSize = CGSizeMake(612, 1108);
  1357. break;
  1358. case 5:
  1359. self.newPageSize = CGSizeMake(595, 841);
  1360. self.pageSizeWidthTextField.stringValue = [NSString stringWithFormat:@"%.0f",self.newPageSize.width];
  1361. self.pageSizeHeightTextField.stringValue = [NSString stringWithFormat:@"%.0f",self.newPageSize.height];
  1362. break;
  1363. default:
  1364. break;
  1365. }
  1366. }
  1367. #pragma mark - Private Method
  1368. //获取所有的子节点
  1369. - (void)fetchAllOfChildren:(PDFOutline *)aOutline containerArray:(NSMutableArray *)aMArray
  1370. {
  1371. if (![aMArray containsObject:aOutline]) {
  1372. [aMArray addObject:aOutline];
  1373. }
  1374. for (NSInteger i = 0; i < aOutline.numberOfChildren; i++) {
  1375. [aMArray addObject:[aOutline childAtIndex:i]];
  1376. [self fetchAllOfChildren:[aOutline childAtIndex:i] containerArray:aMArray];
  1377. }
  1378. }
  1379. @end