KMPDFEditAppendWindow.m 74 KB

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