KMPDFEditAppendWindow.m 71 KB

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