KMPDFEditAppendWindow.m 74 KB

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