KMHomeViewController.swift 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. //
  2. // KMHomeViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/10/13.
  6. //
  7. import Cocoa
  8. @objc enum KMHomeToolState : Int {
  9. case OpenPDF = 0
  10. case CreatePDF
  11. case Home
  12. case PDFTools
  13. case FavoriteDocuments
  14. case CloudDocuments
  15. }
  16. @objc enum KMAIHomeToolState : Int {
  17. case Home = 0
  18. case AITranslation
  19. case AIRewriting
  20. case AIErrorCorrection
  21. }
  22. @objcMembers class KMHomeViewController: NSViewController {
  23. @IBOutlet weak var leftBox: NSBox!
  24. @IBOutlet weak var rightBox: NSBox!
  25. @IBOutlet weak var homeSplitView: NSSplitView!
  26. @IBOutlet weak var homeRightScrollViewView: NSScrollView!
  27. @IBOutlet weak var rightTopBox: NSBox!
  28. @IBOutlet weak var rightBottomBox: NSBox!
  29. @IBOutlet weak var rightFullBox: NSBox!
  30. @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint!
  31. @IBOutlet var fastToolViewController: KMHomeFastToolViewController!
  32. @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController!
  33. @IBOutlet var pdfToolsViewController: KMPDFToolsViewController!
  34. @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController!
  35. @IBOutlet weak var dragView: KMHomeDragView!
  36. // AI 临时UI
  37. @IBOutlet weak var aiHomeBox: KMBox!
  38. @IBOutlet weak var aiHomeImageView: NSImageView!
  39. @IBOutlet weak var aiHomeLabel: NSTextField!
  40. @IBOutlet weak var aiTranslationBox: KMBox!
  41. @IBOutlet weak var aiTranslationImageView: NSImageView!
  42. @IBOutlet weak var aiTranslationLabel: NSTextField!
  43. @IBOutlet weak var aiRewritingBox: KMBox!
  44. @IBOutlet weak var aiRewritingImageView: NSImageView!
  45. @IBOutlet weak var aiRewritingLabel: NSTextField!
  46. @IBOutlet weak var aiErrorCorrectionBox: KMBox!
  47. @IBOutlet weak var aiErrorCorrectionImageView: NSImageView!
  48. @IBOutlet weak var aiErrorCorrectionLabel: NSTextField!
  49. @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC!
  50. @IBOutlet var aiTranslationViewController: KMAITranslationVC!
  51. @IBOutlet var aiRewritingViewController: KMAIRewritingVC!
  52. @IBOutlet weak var creatPDFView: KMCreatPDFView!
  53. //HomeContentView
  54. @IBOutlet weak var homeContentView: KMHomeContentView!
  55. //广告 互推
  56. @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
  57. @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
  58. @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
  59. //合并
  60. var mergeWindowController: KMMergeWindowController?
  61. var aiHomeState: KMAIHomeToolState = .Home
  62. let ScrollerViewWidget: CGFloat = 15.0
  63. var homeWindowController : MainWindowController!
  64. var isShowQuickTour: Bool = false
  65. var myDocument: NSDocument?
  66. var currentWindowController: NSWindowController?
  67. var homeState: KMHomeToolState = .Home
  68. var urlToPDFWindowController: KMURLToPDFWindowController?
  69. var openPDFButtonVC: KMDesignButton?
  70. var createPDFButtonVC: KMDesignButton?
  71. var createPDFImage: KMDesignButton?
  72. var createPDFAddButtonVC: KMDesignButton?
  73. var homeButtonVC: KMTextImageButtonVC?
  74. var pdfToolsButtonVC: KMTextImageButtonVC?
  75. var cloudDocumentsButtonVC: KMTextImageButtonVC?
  76. var pdfSeriesButtonVC: KMTextImageButtonVC?
  77. var pdfOthersButtonVC: KMTextImageButtonVC?
  78. var popover: NSPopover?
  79. var deviceBrowserWC: KMDeviceBrowserWindowController?
  80. var progressController: SKProgressController?
  81. var timer: Timer?
  82. var timerCounter = 0.0
  83. //AI相关
  84. var aiTipView: AITipIconView?
  85. var aiTypeChooseView: AITypeChooseView?
  86. //试用相关
  87. var didTrialExpiredLoad: Bool = false
  88. var repeatTrialAlertLoad: Bool = false
  89. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  90. var currentController: NSWindowController?
  91. deinit {
  92. NotificationCenter.default.removeObserver(self)
  93. }
  94. override func viewWillAppear() {
  95. super.viewWillAppear()
  96. if !KMLightMemberManager.manager.isLogin() {
  97. KMLightMemberManager.manager.canShowAdvancedView = true
  98. }
  99. self.homeContentView.reloadData()
  100. #if VERSION_DMG
  101. let kDMGFirstInstallKey = "DMGFirstInstallKey"
  102. if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil {
  103. KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey)
  104. KMTools.openURL(urlString: "http://www.pdfreaderpro.com/thank-you-for-installation")
  105. }
  106. #else
  107. // [self loadAIInfo];
  108. #endif
  109. }
  110. override func viewWillDisappear() {
  111. super.viewWillDisappear()
  112. // self.homeContentView.reloadData()
  113. }
  114. override func viewDidLoad() {
  115. super.viewDidLoad()
  116. // Do view setup here.
  117. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  118. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  119. createPDFImage = KMDesignButton.init(withType: .Image)
  120. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  121. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  122. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  123. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  124. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  125. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  126. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  127. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  128. self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  129. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  130. self.otherMouseDown(with: aEvent)
  131. return aEvent
  132. }
  133. self.initNetworkingData()
  134. // self.initLocalization()
  135. // self.initializeUI()
  136. self.initializeUI_DMG()
  137. self.setup()
  138. // refreshUI()
  139. self.updateUI()
  140. self.changeEffectiveAppearance()
  141. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  142. NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  143. // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
  144. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
  145. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
  146. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  147. NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
  148. #if VERSION_DMG
  149. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
  150. #endif
  151. NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
  153. self.loadFunctionGuide()
  154. // self.loadAIIconView()
  155. }
  156. override func viewDidAppear() {
  157. super.viewDidAppear()
  158. refreshScrollView()
  159. }
  160. override func viewDidLayout() {
  161. super.viewDidLayout()
  162. refreshScrollView()
  163. // self.loadAITipIconGuide()
  164. }
  165. func initNetworkingData() {
  166. KMAdvertisementManager.manager.fetchDataWithResponseObject { [unowned self] data, responseObject, error in
  167. KMPrint("获取广告数据成功")
  168. if data != nil {
  169. advertisementTableView.inputData = data!.recommondContent
  170. advertisementTableView.didSelect = { view, item in
  171. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  172. if string.count != 0 {
  173. NSWorkspace.shared.open(URL.init(string: string)!)
  174. }
  175. }
  176. advertisementShowView.inputData = data!.advertisement
  177. advertisementShowView.didSelect = { view, item in
  178. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  179. if string.count != 0 {
  180. NSWorkspace.shared.open(URL.init(string: string)!)
  181. }
  182. }
  183. if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
  184. if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
  185. let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
  186. let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
  187. let arrM = NSMutableArray.init()
  188. for dict in array {
  189. let adsInfo = KMAdsInfo.init()
  190. let mutableDictionary = NSMutableDictionary(dictionary: dict)
  191. adsInfo.infoDict = mutableDictionary
  192. arrM.add(adsInfo)
  193. }
  194. KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
  195. }
  196. }
  197. }
  198. }
  199. }
  200. func setup() {
  201. //creatPDF
  202. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  203. self.openPDFAction(sender)
  204. }
  205. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  206. self.creatPDFAction(sender)
  207. }
  208. //history
  209. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  210. self.openHistoryFilePath(url: item.url!)
  211. }
  212. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  213. self.historyFile(deleteDocuments: [ item.url!])
  214. }
  215. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  216. if FileManager.default.fileExists(atPath: item.url!.path) {
  217. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  218. }
  219. }
  220. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  221. let alert = NSAlert()
  222. alert.alertStyle = .critical
  223. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  224. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  225. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  226. alert.beginSheetModal(for: self.view.window!) { response in
  227. if response == .alertFirstButtonReturn {
  228. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  229. self.historyFileDeleteAction(urls)
  230. }
  231. }
  232. }
  233. //quciktools
  234. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  235. self.fastToolItemAction(item.type!)
  236. }
  237. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  238. KMBatchQuickActionManager.defaultManager.actionType = .add
  239. self.fastToolItemAction(item.type!)
  240. }
  241. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  242. KMBatchQuickActionManager.defaultManager.actionType = .remove
  243. self.fastToolItemAction(item.type!)
  244. }
  245. if IAPProductsManager.default().isAvailableAllFunction() {
  246. self.advertisementShowView.isHidden = true
  247. } else {
  248. self.advertisementShowView.isHidden = false
  249. }
  250. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  251. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  252. }
  253. // MARK: Init
  254. func initializeUI() {
  255. rightTopBox.fillColor = .white
  256. rightBottomBox.fillColor = .white
  257. rightFullBox.fillColor = .white
  258. self.refreshRightBoxUI(.Home)
  259. fastToolViewController.delete = self
  260. historyFileViewController.delete = self
  261. pdfToolsViewController.delete = self
  262. dragView.delete = self
  263. }
  264. func initLocalization() {
  265. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  266. homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
  267. pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
  268. cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  269. openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
  270. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  271. createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
  272. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  273. pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  274. pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
  275. }
  276. // MARK: Action
  277. func initializeUI_DMG() -> Void {
  278. rightTopBox.fillColor = .white
  279. rightBottomBox.fillColor = .white
  280. rightFullBox.fillColor = .white
  281. self.aiHomeBox.fillColor = .clear
  282. self.aiHomeBox.cornerRadius = 8.0
  283. self.aiHomeImageView.image = NSImage(named: "icon_home")
  284. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  285. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  286. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  287. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  288. if aiHomeState != .Home {
  289. if mouseEntered {
  290. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  291. } else {
  292. self.aiHomeBox.fillColor = .clear
  293. }
  294. }
  295. }
  296. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  297. if aiHomeState != .Home {
  298. if downEntered {
  299. self.aiHomeState = .Home
  300. self.refreshAIUI()
  301. }
  302. }
  303. }
  304. self.aiTranslationBox.fillColor = .clear
  305. self.aiTranslationBox.cornerRadius = 8.0
  306. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  307. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  308. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  309. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  310. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  311. if aiHomeState != .AITranslation {
  312. if mouseEntered {
  313. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  314. } else {
  315. self.aiTranslationBox.fillColor = .clear
  316. }
  317. }
  318. }
  319. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  320. if aiHomeState != .AITranslation {
  321. if downEntered {
  322. self.aiHomeState = .AITranslation
  323. self.trackEvent_ai(eventName: "AI Translation")
  324. self.refreshAIUI()
  325. }
  326. }
  327. }
  328. self.aiRewritingBox.fillColor = .clear
  329. self.aiRewritingBox.cornerRadius = 8.0
  330. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  331. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  332. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  333. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  334. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  335. if aiHomeState != .AIRewriting {
  336. if mouseEntered {
  337. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  338. } else {
  339. self.aiRewritingBox.fillColor = .clear
  340. }
  341. }
  342. }
  343. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  344. if aiHomeState != .AIRewriting {
  345. if downEntered {
  346. self.aiHomeState = .AIRewriting
  347. self.trackEvent_ai(eventName: "AI Rewriting")
  348. self.refreshAIUI()
  349. }
  350. }
  351. }
  352. self.aiErrorCorrectionBox.fillColor = .clear
  353. self.aiErrorCorrectionBox.cornerRadius = 8.0
  354. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  355. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  356. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  357. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  358. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  359. if aiHomeState != .AIErrorCorrection {
  360. if mouseEntered {
  361. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  362. } else {
  363. self.aiErrorCorrectionBox.fillColor = .clear
  364. }
  365. }
  366. }
  367. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  368. if aiHomeState != .AIErrorCorrection {
  369. if downEntered {
  370. self.aiHomeState = .AIErrorCorrection
  371. self.trackEvent_ai(eventName: "AI Correction")
  372. self.refreshAIUI()
  373. }
  374. }
  375. }
  376. self.refreshAIUI()
  377. historyFileViewController.delete = self
  378. dragView.delete = self
  379. }
  380. func updateUI() {
  381. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  382. // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  383. }
  384. @objc func changeEffectiveAppearance() {
  385. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  386. if isDarkModel {
  387. self.view.appearance = NSAppearance(named: .darkAqua)
  388. } else {
  389. self.view.appearance = NSAppearance(named: .aqua)
  390. }
  391. self.updateUI()
  392. self.advertisementTableView.reloadData()
  393. }
  394. // MARK: Public Methods
  395. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  396. DispatchQueue.global(qos: .`default`).async {
  397. var isSuccessfully = false
  398. if pdf.isEncrypted {
  399. let dic = [
  400. CPDFDocumentWriteOption.userPasswordOption : password,
  401. CPDFDocumentWriteOption.ownerPasswordOption : password
  402. ]
  403. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  404. } else {
  405. isSuccessfully = pdf.write(to: pdf.documentURL)
  406. }
  407. if !isSuccessfully {
  408. if let data = pdf.dataRepresentation() {
  409. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  410. }
  411. }
  412. DispatchQueue.main.sync {
  413. if isSuccessfully {
  414. let workspace = NSWorkspace.shared
  415. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  416. workspace.activateFileViewerSelecting([url])
  417. } else {
  418. let alert = NSAlert()
  419. alert.alertStyle = .critical
  420. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  421. alert.runModal()
  422. }
  423. }
  424. }
  425. }
  426. // MARK: Private Methods
  427. func refreshUI() -> Void {
  428. homeButtonVC?.updateUI()
  429. pdfToolsButtonVC?.updateUI()
  430. cloudDocumentsButtonVC?.updateUI()
  431. }
  432. func refreshAIUI() -> Void {
  433. self.aiHomeBox.fillColor = .clear
  434. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  435. self.aiTranslationBox.fillColor = .clear
  436. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  437. self.aiRewritingBox.fillColor = .clear
  438. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  439. self.aiErrorCorrectionBox.fillColor = .clear
  440. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  441. rightFullBox.isHidden = true
  442. rightTopBox.isHidden = true
  443. rightBottomBox.isHidden = true
  444. switch self.aiHomeState {
  445. case .Home:
  446. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  447. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  448. self.rightTopBox.isHidden = false
  449. self.rightBottomBox.isHidden = false
  450. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  451. self.rightBottomBox.contentView = self.historyFileViewController.view
  452. self.rightFullBox.contentView = nil
  453. self.rightTopBoxHeightConstraint.constant = 388.0
  454. self.dragView.isHidden = false
  455. break
  456. case .AITranslation:
  457. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  458. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  459. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  460. self.rightFullBox.isHidden = false
  461. self.rightTopBox.contentView = nil
  462. self.rightBottomBox.contentView = nil
  463. self.rightFullBox.contentView = self.aiTranslationViewController.view
  464. self.dragView.isHidden = false
  465. break
  466. case .AIRewriting:
  467. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  468. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  469. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  470. self.rightFullBox.isHidden = false
  471. self.rightTopBox.contentView = nil
  472. self.rightBottomBox.contentView = nil
  473. self.rightFullBox.contentView = self.aiRewritingViewController.view
  474. // self.aiRewritingViewController.state = .AIRewriting
  475. self.aiRewritingViewController.initLocalization()
  476. self.aiRewritingViewController.acquisition_uiState()
  477. self.dragView.isHidden = true
  478. break
  479. case .AIErrorCorrection:
  480. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  481. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  482. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  483. self.rightFullBox.isHidden = false
  484. self.rightTopBox.contentView = nil
  485. self.rightBottomBox.contentView = nil
  486. self.rightFullBox.contentView = self.aiRewritingViewController.view
  487. // self.aiRewritingViewController.state = .AIErrorCorrection
  488. self.aiRewritingViewController.initLocalization()
  489. self.aiRewritingViewController.acquisition_uiState()
  490. self.dragView.isHidden = true
  491. break
  492. default:
  493. break
  494. }
  495. }
  496. func fetchDifferentFilePath(filePath: String) -> String {
  497. var resultFilePath = filePath
  498. var index: Int = 0
  499. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  500. index += 1
  501. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  502. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  503. }
  504. return resultFilePath;
  505. }
  506. func showProgressWindow() {
  507. let progress = SKProgressController()
  508. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  509. progress.window?.contentView?.wantsLayer = true
  510. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  511. progress.progressField.textColor = NSColor.white
  512. progress.message = NSLocalizedString("Translating...", comment: "")
  513. progress.closeBlock = { [unowned self] in
  514. }
  515. self.progressController = progress
  516. self.view.window?.beginSheet(progress.window!)
  517. }
  518. func hiddenProgressWindow() {
  519. DispatchQueue.main.async {
  520. self.progressController?.doubleValue = 100.0
  521. }
  522. self.stopTimer()
  523. if (self.progressController != nil) {
  524. self.view.window?.endSheet((self.progressController?.window)!)
  525. self.progressController = nil
  526. }
  527. }
  528. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  529. let fileManager = FileManager.default
  530. do {
  531. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  532. if let fileSize = fileAttributes[.size] as? UInt64 {
  533. let megabyteSize = fileSize / (1024 * 1024)
  534. return megabyteSize >= 10
  535. }
  536. } catch {
  537. KMPrint("Error: \(error)")
  538. }
  539. return false
  540. }
  541. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  542. let url = URL(fileURLWithPath: filePath)
  543. guard let document = PDFDocument(url: url) else {
  544. return false
  545. }
  546. let pageCount = document.pageCount
  547. return pageCount > 30
  548. }
  549. @objc func timerTick() {
  550. timerCounter += 1.0
  551. self.progressController?.increment(by: 1.0)
  552. if timerCounter >= 95 {
  553. stopTimer()
  554. }
  555. }
  556. func stopTimer() {
  557. timer?.invalidate()
  558. timer = nil
  559. }
  560. // MARK: Common methods
  561. func workSpaceOpenUrl(_ url: NSString) {
  562. let httpUrl: NSURL = NSURL.init(string: url as String)!
  563. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  564. if !tWorkSpace.open(httpUrl as URL) {
  565. tWorkSpace.open(httpUrl as URL)
  566. }
  567. }
  568. }
  569. //MARK: Open Creat PDF
  570. extension KMHomeViewController: NSPopoverDelegate {
  571. }
  572. extension KMHomeViewController {
  573. func openPDFAction(_ sender: KMBox) {
  574. if needShowTabbingHintWindow() {
  575. showTabbingHintWindow()
  576. return
  577. }
  578. let openPanel = NSOpenPanel()
  579. openPanel.allowedFileTypes = ["pdf", "PDF"]
  580. openPanel.allowsMultipleSelection = false
  581. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  582. if result == NSApplication.ModalResponse.OK {
  583. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  584. }
  585. }
  586. }
  587. }
  588. func needShowTabbingHintWindow() -> Bool {
  589. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  590. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  591. return true
  592. }
  593. return false
  594. }
  595. func showTabbingHintWindow(){
  596. if !KMDataManager.default.isTabbingWin{
  597. KMDataManager.default.isTabbingWin = true
  598. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  599. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  600. KMDataManager.default.isTabbingWin = false
  601. if continueOrNot {
  602. self?.reopenDocument(forPaths: nil)
  603. } else {
  604. }
  605. }
  606. self.km_beginSheet(windowC: tabbingWin)
  607. }
  608. }
  609. func creatPDFAction(_ sender: KMBox) {
  610. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  611. NSLocalizedString("New From Images", comment: ""),
  612. NSLocalizedString("New From Web Page", comment: ""),
  613. NSLocalizedString("Import From Camera", comment: ""),
  614. NSLocalizedString("Import From Scanner", comment: "")]
  615. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  616. vc.background = KMAppearance.Layout.bgColor()
  617. vc.textColor = KMAppearance.Layout.h0Color()
  618. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  619. let createFilePopover: NSPopover = NSPopover.init()
  620. createFilePopover.contentViewController = vc
  621. createFilePopover.delegate = self
  622. createFilePopover.animates = true
  623. createFilePopover.behavior = .semitransient
  624. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  625. createFilePopover.show(relativeTo: CGRect(x: sender.bounds.origin.x, y: 10, width: sender.bounds.size.width, height: sender.bounds.size.height), of: sender, preferredEdge: .minY)
  626. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  627. if count == NSLocalizedString("New Blank Page", comment: "") {
  628. self.openBlankPage()
  629. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  630. self.importFromCamera()
  631. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  632. self.importFromScanner()
  633. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  634. self.importFromWebPage()
  635. } else if count == NSLocalizedString("New From Images", comment: "") {
  636. self.newFromImages()
  637. }
  638. createFilePopover.close()
  639. }
  640. }
  641. func openBlankPage() {
  642. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  643. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  644. let filePath = savePath.deletingLastPathComponent
  645. if FileManager.default.fileExists(atPath: filePath) == false {
  646. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  647. }
  648. let pdfDocument = CPDFDocument()
  649. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  650. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  651. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  652. if error != nil {
  653. NSApp.presentError(error!)
  654. } else {
  655. if document is KMMainDocument {
  656. let newDocument = document
  657. (newDocument as! KMMainDocument).isNewCreated = true
  658. }
  659. }
  660. // self.homeContentView?.reloadData()
  661. }
  662. }
  663. func importFromWebPage() {
  664. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  665. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  666. if FileManager.default.fileExists(atPath: filePath) {
  667. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  668. if error != nil {
  669. NSApp.presentError(error!)
  670. } else {
  671. if document is KMMainDocument {
  672. (document as! KMMainDocument).isNewCreated = true
  673. }
  674. }
  675. // self.homeContentView.reloadData()
  676. }
  677. }
  678. })
  679. }
  680. func importFromScanner() {
  681. let vc = KMDeviceBrowserWindowController.shared
  682. vc.type = .scanner
  683. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  684. self?.openFile(withFilePath: url as URL)
  685. }
  686. vc.showWindow(NSApp.mainWindow)
  687. }
  688. func importFromCamera() {
  689. let vc = KMDeviceBrowserWindowController.shared
  690. vc.type = .camera
  691. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  692. self?.openFile(withFilePath: url as URL)
  693. }
  694. vc.showWindow(NSApp.mainWindow)
  695. }
  696. func newFromImages() {
  697. fastTool_ImageToPDF()
  698. // let openPanel = NSOpenPanel()
  699. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  700. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  701. // openPanel.allowsMultipleSelection = true
  702. // } else {
  703. // openPanel.allowsMultipleSelection = false
  704. // }
  705. // openPanel.message = NSLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on the keyboard and click on the target files one by one.", comment: "")
  706. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  707. // if result == .OK {
  708. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  709. // debugPrint("缺少图片转PDF")
  710. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  711. // var arr: [KMBatchOperateFile] = []
  712. // for url in openPanel.urls {
  713. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  714. // arr.append(file)
  715. // }
  716. //
  717. // if #available(macOS 10.13, *) {
  718. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  719. // } else {
  720. // baseWindowController.showWindow(nil)
  721. // }
  722. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  723. // if #available(macOS 10.13, *) {
  724. // baseWindowController.release()
  725. // }
  726. // }
  727. // }
  728. // }
  729. }
  730. //MARK: Purchase
  731. @objc func purchaseStateUpdateNoti() {
  732. if IAPProductsManager.default().isAvailableAllFunction() {
  733. self.advertisementShowView.isHidden = true
  734. }
  735. }
  736. //MARK: - AI
  737. func loadAIIconView() -> Void {
  738. NotificationCenter.default.addObserver(self, selector: #selector(aiTipIconViewShowStateChangeNoti), name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
  739. self.aiTipView = AITipIconView.createFromNib()
  740. self.aiTipView?.clickHandle = { [weak self] view in
  741. self?.showAITypeChooseView()
  742. }
  743. self.aiTipView?.rightClickHandle = { [weak self] view in
  744. AIInfoManager.default().showAIIcon = false
  745. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
  746. }
  747. self.aiTipView?.frame = CGRectMake(CGRectGetWidth(self.view.frame)-84, CGRectGetHeight(self.view.frame)-84-100, 72, 72)
  748. self.aiTipView?.autoresizingMask = [.minXMargin, .minYMargin]
  749. self.view.addSubview(self.aiTipView!)
  750. self.updateAITipViewShowState()
  751. }
  752. func updateAITipViewShowState() {
  753. if AIInfoManager.default().showAIIcon {
  754. self.aiTipView?.isHidden = false
  755. } else {
  756. self.aiTipView?.isHidden = true
  757. }
  758. }
  759. func showAITypeChooseView() -> Void {
  760. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  761. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  762. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  763. let documentArray = NSDocumentController.shared.documents
  764. var didFileEdit: Bool = false
  765. var curDoc: KMMainDocument!
  766. for document in documentArray {
  767. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  768. didFileEdit = document.isDocumentEdited
  769. curDoc = document as! KMMainDocument
  770. break
  771. }
  772. }
  773. if didFileEdit {
  774. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  775. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  776. do {
  777. try FileManager.default.removeItem(at: tempFileURL)
  778. } catch {
  779. }
  780. }
  781. if curDoc != nil {
  782. // curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  783. }
  784. }
  785. windowVC.window?.becomeMain()
  786. }
  787. }
  788. windowVC.window?.center()
  789. windowVC.eventLabel = "AITools_Onboard"
  790. windowVC.showWindow(nil)
  791. }
  792. func loadAITipIconGuide() {
  793. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  794. let guideWC = KMGuideInfoWindowController.currentWC()
  795. guideWC.type = .aiTipIconInfo
  796. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  797. guideWC.finishHandle = { [weak self] windowVC, type in
  798. }
  799. if self.view.window != nil {
  800. var rect = self.view.window?.frame
  801. rect!.size.height -= 20
  802. guideWC.window?.setFrame(rect!, display: true)
  803. guideWC.window?.minSize = rect!.size
  804. guideWC.window?.maxSize = rect!.size
  805. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  806. guideWC.show()
  807. }
  808. }
  809. }
  810. //MARK: - 引导
  811. func loadFunctionGuide() -> Void {
  812. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  813. self.loadNewUserGuide()
  814. }
  815. }
  816. // MARK: - what's New
  817. func loadNewUserGuide() -> Void {
  818. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  819. let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  820. guideWindowVC.type = .functionMulti
  821. guideWindowVC.showWindow(nil)
  822. guideWindowVC.window?.orderFront(nil)
  823. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  824. }
  825. }
  826. func checkRepeatTrialExpiredController() -> Void {
  827. //试用过期提示比较表弹窗
  828. if didTrialExpiredLoad == true {
  829. return
  830. }
  831. didTrialExpiredLoad = true
  832. let singleTon = KMPurchaseCompareDMGWindowController.init()
  833. singleTon.showWindow(nil)
  834. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  835. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  836. }
  837. }
  838. func checkRepeatTrialAlertController() -> Void {
  839. //允许二次试用时弹出二次试用引导弹窗
  840. if repeatTrialAlertLoad == true {
  841. return
  842. }
  843. repeatTrialAlertLoad = true
  844. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  845. vc?.showWindow(nil)
  846. }
  847. // MARK: - Noti Actions
  848. func deviceVerifyFinishNotification(_ sender: Notification) {
  849. #if VERSION_DMG
  850. if KMVerificationWindowController.allowsShowExpired() {
  851. self.checkRepeatTrialExpiredController()
  852. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  853. self.checkRepeatTrialAlertController()
  854. }
  855. #endif
  856. }
  857. @objc func aiTipIconViewShowStateChangeNoti() {
  858. self.updateAITipViewShowState()
  859. }
  860. }