KMPDFEditAppendWindow.m 75 KB

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