KMPDFEditAppendWindow.m 77 KB

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