KMPDFEditAppendWindow.m 74 KB

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