KMPDFEditAppendWindow.m 74 KB

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