KMPDFEditAppendWindow.m 74 KB

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