KMPDFEditAppendWindow.m 74 KB

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