KMPDFEditAppendWindow.m 74 KB

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