KMPDFEditAppendWindow.m 74 KB

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