KMPDFEditAppendWindow.m 71 KB

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