KMPDFEditAppendWindow.m 76 KB

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