KMPDFEditAppendWindow.m 70 KB

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