KMPDFEditAppendWindow.m 74 KB

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