KMNHomeViewController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // KMNHomeViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2024/10/8.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. class KMNHomeViewController: NSViewController {
  10. @IBOutlet var leftContendBox: NSBox!
  11. @IBOutlet var homeOpenView: KMHomeOpenView!
  12. @IBOutlet var homeRecommondView: KMHomeRecommondView!
  13. @IBOutlet var rightInfoView: KMHomeRightView!
  14. @IBOutlet var homeDragView: KMHomeDragView!
  15. var demoVC: WCCompWindowController = WCCompWindowController(windowNibName: "WCCompWindowController")
  16. override func viewDidLoad() {
  17. super.viewDidLoad()
  18. // Do view setup here.
  19. self.configLeftContendView()
  20. self.configRightContendView()
  21. self.initAdvertisementData()
  22. homeDragView.delegate = self
  23. }
  24. override func viewDidAppear() {
  25. super.viewDidAppear()
  26. rightInfoView.resetScrollerStyle()
  27. rightInfoView.reloadData()
  28. }
  29. func configLeftContendView() {
  30. leftContendBox.fillColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle")
  31. homeOpenView.delegate = self
  32. self.homeRecommondView.reloadData()
  33. }
  34. func configRightContendView() {
  35. rightInfoView.delegate = self
  36. rightInfoView.reloadData()
  37. }
  38. func initAdvertisementData() {
  39. KMAdvertisementManager.manager.fetchDataWithResponseObject { [weak self] data, responseObject, error in
  40. KMPrint("获取广告数据成功")
  41. if data != nil {
  42. let content = data!.recommondContent
  43. let item = content?.recommondContentPDFPro
  44. var infos: [KMAdvertisementItemInfo] = []
  45. for info in item?.content ?? [] {
  46. if info.version == "recommondPDF-PDFtoOfficePack" {
  47. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false {
  48. infos.append(info)
  49. }
  50. } else {
  51. infos.append(info)
  52. }
  53. }
  54. item?.content = infos
  55. if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
  56. if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
  57. let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
  58. let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  59. let arrM = NSMutableArray.init()
  60. for dict in array {
  61. let adsInfo = KMAdsInfo.init()
  62. let mutableDictionary = NSMutableDictionary(dictionary: dict)
  63. adsInfo.infoDict = mutableDictionary
  64. arrM.add(adsInfo)
  65. }
  66. KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
  67. }
  68. if let couponInfo = KMAdvertisementManager.manager.infoDict["couponContent"] {
  69. let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["couponContent"] as! NSDictionary
  70. let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  71. if array.isEmpty == false {
  72. let dict = array[0]
  73. let adsInfo = KMCouponInfo.init()
  74. let mutableDictionary = NSMutableDictionary(dictionary: dict)
  75. adsInfo.infoDict = mutableDictionary
  76. KMAdsInfoManager.shareInstance.couponInfo = adsInfo
  77. }
  78. }
  79. }
  80. }
  81. DispatchQueue.main.async {
  82. self?.homeRecommondView.reloadData()
  83. }
  84. }
  85. }
  86. @IBAction func showDemo(_ sender: Any) {
  87. demoVC.window?.center()
  88. demoVC.showWindow(nil)
  89. }
  90. }
  91. //MARK: - KMHomeOpenViewDelegate
  92. extension KMNHomeViewController: KMHomeOpenViewDelegate {
  93. func homeOpenViewDidChooseFileURLs(_ view: KMHomeOpenView?, _ urls: [URL]) {
  94. if let url = urls.first {
  95. }
  96. }
  97. }
  98. //MARK: - KMHomeRightViewDelegate
  99. extension KMNHomeViewController: KMHomeRightViewDelegate {
  100. //点击管理快捷工具按钮
  101. func homeRightViewDidManageQuickTools(_ view: KMHomeRightView) {
  102. let quickToolWindowController: KMNQuickToolWindowController = KMNQuickToolWindowController.init(windowNibName: "KMNQuickToolWindowController")
  103. quickToolWindowController.own_beginSheetModal(for: self.view.window) { string in
  104. }
  105. }
  106. //点击快捷工具列表中的某一项
  107. func homeRightViewDidQuickToolsItemClicked(_ view: KMHomeRightView, _ toolType: HomeQuickToolType) {
  108. print("HomeQuickToolType = %d", toolType.rawValue)
  109. }
  110. //最近文件列表删除更新结束后回调
  111. func homeRightViewDidRecentFilesUpdated(_ view: KMHomeRightView) {
  112. }
  113. //选择打开文件
  114. func homeRightViewDidChooseFileToOpen(_ view: KMHomeRightView, _ fileURL: URL) {
  115. }
  116. }
  117. //MARK: - KMNQuickToolWindowDelegate
  118. extension KMNHomeViewController: KMNQuickToolWindowDelegate {
  119. func quickToolWindowControllerUpdate() {
  120. // KMNHomeQuickToolManager.defaultManager.quickToolsItemMutableArray
  121. }
  122. }
  123. //MARK: - KMHomeDragViewDelegate
  124. extension KMNHomeViewController: KMHomeDragViewDelegate {
  125. func homeDragView(_ viewController: KMHomeDragView, filePath: URL) {
  126. self.openFile(withFilePath: filePath)
  127. }
  128. }
  129. //MARK: - Open Files
  130. extension KMNHomeViewController {
  131. func openFile(withFilePath path: URL) -> Void {
  132. let type = path.pathExtension.lowercased()
  133. if (type == "pdf") {
  134. self.openHistoryFilePath(url: path)
  135. } else if (type == "jpg") ||
  136. (type == "cur") ||
  137. (type == "bmp") ||
  138. (type == "jpeg") ||
  139. (type == "gif") ||
  140. (type == "png") ||
  141. (type == "tiff") ||
  142. (type == "tif") ||
  143. (type == "ico") ||
  144. (type == "icns") ||
  145. (type == "tga") ||
  146. (type == "psd") ||
  147. (type == "eps") ||
  148. (type == "hdr") ||
  149. (type == "jp2") ||
  150. (type == "jpc") ||
  151. (type == "pict") ||
  152. (type == "sgi") ||
  153. (type == "heic") {
  154. openImageFile(url: path)
  155. } else if (type == "doc") ||
  156. (type == "docx") ||
  157. (type == "xls") ||
  158. (type == "xlsx") ||
  159. (type == "ppt") ||
  160. (type == "pptx") ||
  161. (type == "pptx") {
  162. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  163. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  164. openOfficeFile(url: path)
  165. }
  166. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  167. self.rightInfoView.reloadData()
  168. }
  169. }
  170. func openHistoryFilePath(url: URL) -> Void {
  171. if !url.path.isPDFValid() {
  172. let alert = NSAlert()
  173. alert.alertStyle = .critical
  174. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  175. alert.beginSheetModal(for: view.window!) { [weak self] result in
  176. self?.rightInfoView.reloadData()
  177. }
  178. return
  179. }
  180. if url.pathExtension.lowercased() == "pdf" {
  181. let pdfDoc = CPDFDocument.init(url: url)
  182. if pdfDoc != nil {
  183. let document = NSDocumentController.shared.document(for: url)
  184. var alreadyOpen = false
  185. for openDocument in NSDocumentController.shared.documents {
  186. if document == openDocument {
  187. alreadyOpen = true
  188. }
  189. }
  190. if !alreadyOpen {
  191. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  192. if controll?.browser?.tabCount() ?? 0 > 1{
  193. if !IAPProductsManager.default().isAvailableAllFunction() {
  194. showLimitWindowAlert(url: url)
  195. return
  196. }else {
  197. }
  198. }
  199. }
  200. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  201. var selectDocument: KMMainDocument? = nil
  202. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  203. selectDocument = (document as! KMMainDocument)
  204. }
  205. if selectDocument != nil {
  206. if selectDocument?.browser != nil {
  207. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument) ?? 0
  208. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex), userGesture: true)
  209. let isVisible: Bool = selectDocument?.browser.window.isVisible ?? false
  210. let isMiniaturized: Bool = selectDocument?.browser.window.isMiniaturized ?? false
  211. if isVisible {
  212. selectDocument?.browser.window.orderFront(nil)
  213. } else if isMiniaturized {
  214. selectDocument?.browser.window.orderFront(nil)
  215. }
  216. }
  217. } else {
  218. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  219. }
  220. }
  221. } else {
  222. let alert = NSAlert()
  223. alert.alertStyle = .critical
  224. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  225. alert.beginSheetModal(for: view.window!) { [weak self] result in
  226. self?.rightInfoView.reloadData()
  227. }
  228. }
  229. } else {
  230. NSWorkspace.shared.open(url)
  231. }
  232. }
  233. func openImageFile(url: URL) -> Void {
  234. var filePath = url.path
  235. let fileName: NSString = url.lastPathComponent as NSString
  236. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent
  237. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  238. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  239. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  240. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  241. }
  242. if (!FileManager.default.fileExists(atPath: path as String)) {
  243. FileManager.default.createFile(atPath: path as String, contents: nil)
  244. }
  245. let document = CPDFDocument.init()
  246. var success = false
  247. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  248. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  249. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  250. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  251. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  252. }
  253. // 加载 PNG 图像
  254. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  255. KMPrint("Failed to load PNG image")
  256. return
  257. }
  258. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  259. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  260. guard let bitmap = bitmap else {
  261. return
  262. }
  263. let rect = NSRect(origin: .zero, size: bitmap.size)
  264. bitmap.draw(in: rect)
  265. // 将 PNG 图像数据转换为 JPG 图像数据
  266. guard let jpgData = bitmap.representation(using: .jpeg, properties: [:]) else {
  267. KMPrint("Failed to convert PNG to JPG")
  268. return
  269. }
  270. // 保存 JPG 图像数据到文件
  271. let fileURL = URL(fileURLWithPath: jpgPath)
  272. do {
  273. try jpgData.write(to: fileURL)
  274. filePath = fileURL.path
  275. KMPrint("JPG image saved successfully")
  276. } catch {
  277. KMPrint("Failed to save JPG image: \(error.localizedDescription)")
  278. }
  279. }
  280. let image = NSImage(contentsOfFile: filePath)
  281. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  282. if insertPageSuccess != nil {
  283. //信号量控制异步
  284. let semaphore = DispatchSemaphore(value: 0)
  285. DispatchQueue.global().async {
  286. success = ((document?.write(toFile: path)) != nil)
  287. semaphore.signal()
  288. }
  289. semaphore.wait()
  290. } else {
  291. }
  292. if success {
  293. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, isOpened, error in
  294. if error != nil {
  295. NSApp.presentError(error!)
  296. } else {
  297. if FileManager.default.fileExists(atPath: filePath) {
  298. try? FileManager.default.removeItem(atPath: filePath)
  299. }
  300. if document is KMMainDocument {
  301. let newDocument = document
  302. (newDocument as! KMMainDocument).isNewCreated = true
  303. }
  304. }
  305. }
  306. }
  307. }
  308. func openOfficeFile(url: URL) -> Void {
  309. let filePath = url.path
  310. let folderPath = "convertToPDF.pdf"
  311. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  312. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  313. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  314. }
  315. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  316. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  317. }
  318. if savePath == nil {
  319. return
  320. }
  321. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  322. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  323. if FileManager.default.fileExists(atPath: savePath!) {
  324. try?FileManager.default.removeItem(atPath: savePath!)
  325. }
  326. let alert = NSAlert.init()
  327. alert.alertStyle = .critical
  328. var infoString = ""
  329. if errorDic != nil {
  330. for key in (errorDic! as Dictionary).keys {
  331. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  332. }
  333. }
  334. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  335. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  336. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  337. alert.runModal()
  338. return
  339. }
  340. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in
  341. }
  342. }
  343. }
  344. func showLimitWindowAlert(url: URL?) {
  345. if !KMDataManager.default.isTabbingWin{
  346. KMDataManager.default.isTabbingWin = true
  347. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  348. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  349. KMDataManager.default.isTabbingWin = false
  350. if continueOrNot {
  351. self?.reopenDocument(forPaths: url)
  352. } else {
  353. }
  354. }
  355. self.km_beginSheet(windowC: tabbingWin)
  356. }
  357. }
  358. func reopenDocument(forPaths path: URL?) -> Void {
  359. if path == nil {
  360. let browser = KMBrowser.init() as KMBrowser
  361. browser.windowController = KMBrowserWindowController.init(browser: browser)
  362. browser.addHomeTabContents()
  363. browser.windowController.showWindow(self)
  364. }else {
  365. let browser = KMBrowser.init() as KMBrowser
  366. browser.windowController = KMBrowserWindowController.init(browser: browser)
  367. browser.addHomeTabContents()
  368. browser.windowController.showWindow(self)
  369. NSDocumentController.shared.km_safe_openDocument(withContentsOf: path!, display: true) { doc, open, err in
  370. }
  371. }
  372. }
  373. func fetchUniquePath(_ originalPath: String) -> String {
  374. var path = originalPath
  375. let dManager = FileManager.default
  376. if !dManager.fileExists(atPath: path) {
  377. if path.extension.count < 1 {
  378. path = path.stringByAppendingPathExtension("pdf")
  379. }
  380. return path
  381. } else {
  382. let originalFullFileName = path.lastPathComponent
  383. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  384. let originalExtension = path.extension
  385. let startIndex: Int = 0
  386. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  387. let fileLocatePath = originalPath.substring(to: endIndex)
  388. var i = 1
  389. while (1 != 0) {
  390. var newName = String(format: "%@%ld", originalFileName, i)
  391. newName = String(format: "%@%@", newName, originalExtension)
  392. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  393. if !dManager.fileExists(atPath: newPath) {
  394. return newPath
  395. } else {
  396. i+=1
  397. continue
  398. }
  399. }
  400. }
  401. }
  402. func fetchDifferentFilePath(filePath: String) -> String {
  403. var resultFilePath = filePath
  404. var index: Int = 0
  405. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  406. index += 1
  407. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  408. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  409. }
  410. return resultFilePath;
  411. }
  412. }