KMPDFEditAppendWindow.m 74 KB

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