KMHomeViewController.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. //
  2. // KMHomeViewController.swift
  3. // PDF Master
  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. var aiHomeState: KMAIHomeToolState = .Home
  60. let ScrollerViewWidget: CGFloat = 15.0
  61. var homeWindowController : MainWindowController!
  62. // 产品推广数据
  63. var productPromotionPDFProSeries: NSArray!
  64. var productPromotionOthers: NSArray!
  65. var productPromotionData: NSDictionary!
  66. var isShowQuickTour: Bool = false
  67. var myDocument: NSDocument?
  68. var currentWindowController: NSWindowController?
  69. var homeState: KMHomeToolState = .Home
  70. var urlToPDFWindowController: KMURLToPDFWindowController?
  71. var openPDFButtonVC: KMDesignButton!
  72. var createPDFButtonVC: KMDesignButton!
  73. var createPDFImage: KMDesignButton!
  74. var createPDFAddButtonVC: KMDesignButton!
  75. var homeButtonVC: KMTextImageButtonVC!
  76. var pdfToolsButtonVC: KMTextImageButtonVC!
  77. var cloudDocumentsButtonVC: KMTextImageButtonVC!
  78. var pdfSeriesButtonVC: KMTextImageButtonVC!
  79. var pdfOthersButtonVC: KMTextImageButtonVC!
  80. var popover: NSPopover?
  81. var deviceBrowserWC: KMDeviceBrowserWindowController?
  82. var progressController: SKProgressController?
  83. var timer: Timer?
  84. var timerCounter = 0.0
  85. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  86. deinit {
  87. }
  88. override func viewWillAppear() {
  89. super.viewWillAppear()
  90. if !KMLightMemberManager.manager.isLogin() {
  91. KMLightMemberManager.manager.canShowAdvancedView = true
  92. }
  93. }
  94. override func viewDidLoad() {
  95. super.viewDidLoad()
  96. // Do view setup here.
  97. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  98. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  99. createPDFImage = KMDesignButton.init(withType: .Image)
  100. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  101. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  102. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  103. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  104. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  105. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  106. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  107. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  108. self.productPromotionPDFProSeries = ["Windows", "iPhone / iPad", "Android"]
  109. self.productPromotionOthers = ["ComPDFKit", "SignFlow", "FiImage Editor", "FiImage Screen", "Free PDF Templates"]
  110. self.productPromotionData = ["Windows": ["Name" : "Windows", "Image" : "icon_home_logo_windows", "link":""],
  111. "iPhone / iPad" : ["Name" : "iPhone / iPad", "Image" : "icon_home_logo_mac", "link":""],
  112. "Android" : ["Name" : "Android", "Image" : "icon_home_logo_android", "link":""],
  113. "ComPDFKit" : ["Name" : "ComPDFKit", "Image" : "icon_home_logo_comPDFKit", "link":""],
  114. "SignFlow" : ["Name" : "SignFlow", "Image" : "icon_home_logo_signflow", "link":""],
  115. "FiImage Editor" : ["Name" : "FiImage Editor", "Image" : "icon_home_logo_editor", "link":""],
  116. "FiImage Screen" : ["Name" : "FiImage Screen", "Image" : "icon_home_logo_screen", "link":""],
  117. "Free PDF Templates" : ["Name" : "Free PDF Templates", "Image" : "icon_home_logo_templates"], "link":""]
  118. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  119. self.otherMouseDown(with: aEvent)
  120. return aEvent
  121. }
  122. self.initNetworkingData()
  123. // self.initLocalization()
  124. // self.initializeUI()
  125. self.initializeUI_DMG()
  126. self.setup()
  127. // refreshUI()
  128. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  129. }
  130. override func viewDidAppear() {
  131. super.viewDidAppear()
  132. refreshScrollView()
  133. }
  134. override func viewDidLayout() {
  135. super.viewDidLayout()
  136. refreshScrollView()
  137. }
  138. func initNetworkingData() {
  139. KMAdvertisementManager.manager.fetchDataWithResponseObject { [unowned self] data, responseObject, error in
  140. KMPrint("获取广告数据成功")
  141. if data != nil {
  142. advertisementTableView.inputData = data!.recommondContent
  143. advertisementTableView.didSelect = { view, item in
  144. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  145. if NSWorkspace.shared.open(URL.init(string: string)!) {
  146. NSWorkspace.shared.open(URL.init(string: string)!)
  147. }
  148. }
  149. advertisementShowView.inputData = data!.advertisement
  150. }
  151. }
  152. }
  153. func setup() {
  154. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  155. self.openPDFAction(sender)
  156. }
  157. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  158. self.creatPDFAction(sender)
  159. }
  160. self.homeContentView.historyDidSelect = { [unowned self] view, url in
  161. self.openFile(withFilePath: url)
  162. }
  163. }
  164. // MARK: Init
  165. func initializeUI() {
  166. // pdfToolsBox.fillColor = .clear
  167. // pdfToolsBox.contentView = pdfToolsButtonVC.view
  168. // pdfToolsButtonVC.target = self
  169. // pdfToolsButtonVC.action = #selector(self.homeToolAction(_:))
  170. // pdfToolsButtonVC.image = NSImage(named: "icon_home_sidebar_tool_false")!
  171. // pdfToolsButtonVC.image_hover = NSImage(named: "icon_home_sidebar_tool_false")!
  172. // pdfToolsButtonVC.image_click = NSImage(named: "icon_home_sidebar_tool_true")!
  173. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.norm", text: "navmenu.win-text.def", height: pdfToolsBoxHeight)
  174. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.hov", text: "navmenu.win-text.def", state:.Hov)
  175. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.sel", text: "navmenu.win-text.sel", state:.Sel)
  176. //
  177. // cloudDocumentsBox.fillColor = .clear
  178. // cloudDocumentsBox.contentView = cloudDocumentsButtonVC.view
  179. // cloudDocumentsButtonVC.target = self
  180. // cloudDocumentsButtonVC.action = #selector(self.homeToolAction(_:))
  181. // cloudDocumentsButtonVC.image = NSImage(named: "icon_home_sidebar_cloud_false")!
  182. // cloudDocumentsButtonVC.image_hover = NSImage(named: "icon_home_sidebar_cloud_false")!
  183. // cloudDocumentsButtonVC.image_click = NSImage(named: "icon_home_sidebar_cloud_true")!
  184. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.norm", text: "navmenu.win-text.def", height: cloudDocumentsBoxHeight)
  185. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.hov", text: "navmenu.win-text.def", state:.Hov)
  186. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.sel", text: "navmenu.win-text.sel", state:.Sel)
  187. //
  188. // pdfSeriesBox.fillColor = .clear
  189. // pdfSeriesBox.contentView = pdfSeriesButtonVC.view
  190. // pdfSeriesButtonVC.target = self
  191. // pdfSeriesButtonVC.action = #selector(self.productPromotionFoldOrUnfold(_:))
  192. // pdfSeriesButtonVC.type = .Right
  193. // pdfSeriesButtonVC.canHover = false
  194. // pdfSeriesButtonVC.imageWidth = 12.0
  195. // pdfSeriesButtonVC.imageHeight = 12.0
  196. // pdfSeriesButtonVC.image = NSImage(named: "icon_btn_expand_lv2_down_false")!
  197. // pdfSeriesButtonVC.navMenu(bg: "collapse.ad-list.bg", text: "collapse.ad-list.mac-text.norm", height: pdfSeriesBoxHeight)
  198. //
  199. // pdfOthersBox.fillColor = .clear
  200. // pdfOthersBox.contentView = pdfOthersButtonVC.view
  201. // pdfOthersButtonVC.target = self
  202. // pdfOthersButtonVC.action = #selector(self.productPromotionFoldOrUnfold(_:))
  203. // pdfOthersButtonVC.type = .Right
  204. // pdfOthersButtonVC.canHover = false
  205. // pdfOthersButtonVC.imageWidth = 12.0
  206. // pdfOthersButtonVC.imageHeight = 12.0
  207. // pdfOthersButtonVC.image = NSImage(named: "icon_btn_expand_lv2_down_false")!
  208. // pdfOthersButtonVC.navMenu(bg: "collapse.ad-list.bg", text: "collapse.ad-list.mac-text.norm", height: othersBoxHeightConstraint)
  209. // if self.activitiesBox.isHidden {
  210. // self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: self.productPromotionOthers, isInitialize: true)
  211. // } else {
  212. // self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: [], isInitialize: true)
  213. // }
  214. self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: self.productPromotionOthers, isInitialize: true)
  215. // self.activitiesBox.contentView = KMProductPromotionViewController.init().view
  216. // activitiesBox.cornerRadius = 8.0
  217. rightTopBox.fillColor = .white
  218. rightBottomBox.fillColor = .white
  219. rightFullBox.fillColor = .white
  220. // productPromotionBox.fillColor = .clear
  221. //
  222. // product_active_scrollView.verticalScrollElasticity = .none
  223. self.refreshRightBoxUI(.Home)
  224. fastToolViewController.delete = self
  225. historyFileViewController.delete = self
  226. pdfToolsViewController.delete = self
  227. dragView.delete = self
  228. }
  229. func initLocalization() {
  230. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  231. homeButtonVC.stringValue = NSLocalizedString("Home", comment: "")
  232. pdfToolsButtonVC.stringValue = NSLocalizedString("PDF Tools", comment: "")
  233. cloudDocumentsButtonVC.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  234. openPDFButtonVC.stringValue = NSLocalizedString("Open File", comment: "")
  235. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  236. createPDFButtonVC.stringValue = NSLocalizedString("Create PDF", comment: "")
  237. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  238. pdfSeriesButtonVC.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  239. pdfOthersButtonVC.stringValue = NSLocalizedString("Others", comment: "")
  240. }
  241. // MARK: Action
  242. func initializeUI_DMG() -> Void {
  243. rightTopBox.fillColor = .white
  244. rightBottomBox.fillColor = .white
  245. rightFullBox.fillColor = .white
  246. self.aiHomeBox.fillColor = .clear
  247. self.aiHomeBox.cornerRadius = 8.0
  248. self.aiHomeImageView.image = NSImage(named: "icon_home")
  249. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  250. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  251. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  252. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  253. if aiHomeState != .Home {
  254. if mouseEntered {
  255. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  256. } else {
  257. self.aiHomeBox.fillColor = .clear
  258. }
  259. }
  260. }
  261. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  262. if aiHomeState != .Home {
  263. if downEntered {
  264. self.aiHomeState = .Home
  265. self.refreshAIUI()
  266. }
  267. }
  268. }
  269. self.aiTranslationBox.fillColor = .clear
  270. self.aiTranslationBox.cornerRadius = 8.0
  271. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  272. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  273. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  274. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  275. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  276. if aiHomeState != .AITranslation {
  277. if mouseEntered {
  278. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  279. } else {
  280. self.aiTranslationBox.fillColor = .clear
  281. }
  282. }
  283. }
  284. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  285. if aiHomeState != .AITranslation {
  286. if downEntered {
  287. self.aiHomeState = .AITranslation
  288. self.trackEvent_ai(eventName: "AI Translation")
  289. self.refreshAIUI()
  290. }
  291. }
  292. }
  293. self.aiRewritingBox.fillColor = .clear
  294. self.aiRewritingBox.cornerRadius = 8.0
  295. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  296. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  297. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  298. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  299. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  300. if aiHomeState != .AIRewriting {
  301. if mouseEntered {
  302. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  303. } else {
  304. self.aiRewritingBox.fillColor = .clear
  305. }
  306. }
  307. }
  308. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  309. if aiHomeState != .AIRewriting {
  310. if downEntered {
  311. self.aiHomeState = .AIRewriting
  312. self.trackEvent_ai(eventName: "AI Rewriting")
  313. self.refreshAIUI()
  314. }
  315. }
  316. }
  317. self.aiErrorCorrectionBox.fillColor = .clear
  318. self.aiErrorCorrectionBox.cornerRadius = 8.0
  319. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  320. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  321. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  322. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  323. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  324. if aiHomeState != .AIErrorCorrection {
  325. if mouseEntered {
  326. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  327. } else {
  328. self.aiErrorCorrectionBox.fillColor = .clear
  329. }
  330. }
  331. }
  332. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  333. if aiHomeState != .AIErrorCorrection {
  334. if downEntered {
  335. self.aiHomeState = .AIErrorCorrection
  336. self.trackEvent_ai(eventName: "AI Correction")
  337. self.refreshAIUI()
  338. }
  339. }
  340. }
  341. self.refreshAIUI()
  342. historyFileViewController.delete = self
  343. dragView.delete = self
  344. }
  345. // MARK: Action
  346. @IBAction func productPromotionButtonAction(_ sender: NSButton) {
  347. self.productPromotionFoldOrUnfold(sender)
  348. }
  349. // MARK: Public Methods
  350. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  351. DispatchQueue.global(qos: .`default`).async {
  352. var isSuccessfully = false
  353. if pdf.isEncrypted {
  354. let dic = [
  355. CPDFDocumentWriteOption.userPasswordOption : password,
  356. CPDFDocumentWriteOption.ownerPasswordOption : password
  357. ]
  358. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  359. } else {
  360. isSuccessfully = pdf.write(to: pdf.documentURL)
  361. }
  362. if !isSuccessfully {
  363. isSuccessfully = NSData(data: pdf.dataRepresentation()).write(to: pdf.documentURL, atomically: true)
  364. }
  365. DispatchQueue.main.sync {
  366. if isSuccessfully {
  367. let workspace = NSWorkspace.shared
  368. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  369. workspace.activateFileViewerSelecting([url])
  370. } else {
  371. let alert = NSAlert()
  372. alert.alertStyle = .critical
  373. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  374. alert.runModal()
  375. }
  376. }
  377. }
  378. }
  379. // MARK: Private Methods
  380. func refreshUI() -> Void {
  381. homeButtonVC.updateUI()
  382. pdfToolsButtonVC.updateUI()
  383. cloudDocumentsButtonVC.updateUI()
  384. }
  385. func refreshAIUI() -> Void {
  386. self.aiHomeBox.fillColor = .clear
  387. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  388. self.aiTranslationBox.fillColor = .clear
  389. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  390. self.aiRewritingBox.fillColor = .clear
  391. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  392. self.aiErrorCorrectionBox.fillColor = .clear
  393. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  394. rightFullBox.isHidden = true
  395. rightTopBox.isHidden = true
  396. rightBottomBox.isHidden = true
  397. switch self.aiHomeState {
  398. case .Home:
  399. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  400. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  401. self.rightTopBox.isHidden = false
  402. self.rightBottomBox.isHidden = false
  403. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  404. self.rightBottomBox.contentView = self.historyFileViewController.view
  405. self.rightFullBox.contentView = nil
  406. self.rightTopBoxHeightConstraint.constant = 388.0
  407. self.dragView.isHidden = false
  408. break
  409. case .AITranslation:
  410. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  411. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  412. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  413. self.rightFullBox.isHidden = false
  414. self.rightTopBox.contentView = nil
  415. self.rightBottomBox.contentView = nil
  416. self.rightFullBox.contentView = self.aiTranslationViewController.view
  417. self.dragView.isHidden = false
  418. break
  419. case .AIRewriting:
  420. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  421. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  422. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  423. self.rightFullBox.isHidden = false
  424. self.rightTopBox.contentView = nil
  425. self.rightBottomBox.contentView = nil
  426. self.rightFullBox.contentView = self.aiRewritingViewController.view
  427. self.aiRewritingViewController.state = .AIRewriting
  428. self.aiRewritingViewController.initLocalization()
  429. self.aiRewritingViewController.acquisition_uiState()
  430. self.dragView.isHidden = true
  431. break
  432. case .AIErrorCorrection:
  433. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  434. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  435. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  436. self.rightFullBox.isHidden = false
  437. self.rightTopBox.contentView = nil
  438. self.rightBottomBox.contentView = nil
  439. self.rightFullBox.contentView = self.aiRewritingViewController.view
  440. self.aiRewritingViewController.state = .AIErrorCorrection
  441. self.aiRewritingViewController.initLocalization()
  442. self.aiRewritingViewController.acquisition_uiState()
  443. self.dragView.isHidden = true
  444. break
  445. default:
  446. break
  447. }
  448. }
  449. func refreshProductActiveSpacing() -> Void {
  450. // let height = self.view.frame.height - 32.0 - openPDFBoxHeight.constant - 16.0 - createPDFBoxHeight.constant - 24.0 - pdfSeriesBoxHeight.constant - pdfProSeriesBoxHeightConstraint.constant - 8 - othersBoxHeightConstraint.constant - pdfOthersBoxHeightConstraint.constant - 242 - 30
  451. //// print("height == %f", height)
  452. // if height > 24.0 {
  453. // self.product_active_spacing.constant = height
  454. // } else {
  455. // self.product_active_spacing.constant = 24.0
  456. // }
  457. }
  458. func fetchDifferentFilePath(filePath: String) -> String {
  459. var resultFilePath = filePath
  460. var index: Int = 0
  461. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  462. index += 1
  463. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  464. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  465. }
  466. return resultFilePath;
  467. }
  468. func showProgressWindow() {
  469. let progress = SKProgressController()
  470. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  471. progress.window?.contentView?.wantsLayer = true
  472. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  473. progress.progressField.textColor = NSColor.white
  474. progress.message = NSLocalizedString("Translating...", comment: "")
  475. progress.closeBlock = { [unowned self] in
  476. }
  477. self.progressController = progress
  478. self.view.window?.beginSheet(progress.window!)
  479. }
  480. func hiddenProgressWindow() {
  481. DispatchQueue.main.async {
  482. self.progressController?.doubleValue = 100.0
  483. }
  484. self.stopTimer()
  485. if (self.progressController != nil) {
  486. self.view.window?.endSheet((self.progressController?.window)!)
  487. self.progressController = nil
  488. }
  489. }
  490. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  491. let fileManager = FileManager.default
  492. do {
  493. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  494. if let fileSize = fileAttributes[.size] as? UInt64 {
  495. let megabyteSize = fileSize / (1024 * 1024)
  496. return megabyteSize >= 10
  497. }
  498. } catch {
  499. KMPrint("Error: \(error)")
  500. }
  501. return false
  502. }
  503. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  504. let url = URL(fileURLWithPath: filePath)
  505. guard let document = PDFDocument(url: url) else {
  506. return false
  507. }
  508. let pageCount = document.pageCount
  509. return pageCount > 30
  510. }
  511. @objc func timerTick() {
  512. timerCounter += 1.0
  513. self.progressController?.increment(by: 1.0)
  514. if timerCounter >= 95 {
  515. stopTimer()
  516. }
  517. }
  518. func stopTimer() {
  519. timer?.invalidate()
  520. timer = nil
  521. }
  522. // MARK: Common methods
  523. func workSpaceOpenUrl(_ url: NSString) {
  524. let httpUrl: NSURL = NSURL.init(string: url as String)!
  525. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  526. if !tWorkSpace.open(httpUrl as URL) {
  527. tWorkSpace.open(httpUrl as URL)
  528. }
  529. }
  530. }
  531. //MARK: Open Creat PDF
  532. extension KMHomeViewController: NSPopoverDelegate {
  533. }
  534. extension KMHomeViewController {
  535. func openPDFAction(_ sender: KMBox) {
  536. let openPanel = NSOpenPanel()
  537. openPanel.allowedFileTypes = ["pdf", "PDF"]
  538. openPanel.allowsMultipleSelection = false
  539. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  540. if result == NSApplication.ModalResponse.OK {
  541. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  542. if let error = error {
  543. NSApp.presentError(error)
  544. } else {
  545. self.view.window?.windowController?.close()
  546. }
  547. }
  548. }
  549. }
  550. }
  551. func creatPDFAction(_ sender: KMBox) {
  552. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  553. NSLocalizedString("New From Images", comment: ""),
  554. NSLocalizedString("New From Web Page", comment: ""),
  555. NSLocalizedString("Import From Camera", comment: ""),
  556. NSLocalizedString("Import From Scanner", comment: "")]
  557. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  558. let createFilePopover: NSPopover = NSPopover.init()
  559. createFilePopover.contentViewController = vc
  560. createFilePopover.delegate = self
  561. createFilePopover.animates = true
  562. createFilePopover.behavior = .semitransient
  563. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  564. 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)
  565. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  566. if count == NSLocalizedString("New Blank Page", comment: "") {
  567. self.openBlankPage()
  568. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  569. self.importFromCamera()
  570. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  571. self.importFromScanner()
  572. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  573. self.importFromWebPage()
  574. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  575. self.newFromImages()
  576. }
  577. createFilePopover.close()
  578. }
  579. }
  580. func openBlankPage() {
  581. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  582. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  583. let pdfDocument = CPDFDocument()
  584. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  585. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  586. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  587. if error != nil {
  588. NSApp.presentError(error!)
  589. } else {
  590. if document is KMMainDocument {
  591. let newDocument = document
  592. (newDocument as! KMMainDocument).isNewCreated = true
  593. }
  594. }
  595. }
  596. }
  597. func importFromWebPage() {
  598. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  599. self.urlToPDFWindowController?.beginSheetModalForWindow(NSApp.mainWindow!, completionHandler: { filePath in
  600. if FileManager.default.fileExists(atPath: filePath) {
  601. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  602. if error != nil {
  603. NSApp.presentError(error!)
  604. } else {
  605. if document is KMMainDocument {
  606. (document as! KMMainDocument).isNewCreated = true
  607. }
  608. }
  609. }
  610. }
  611. })
  612. }
  613. func importFromScanner() {
  614. let vc = KMDeviceBrowserWindowController.shared
  615. vc.type = .scanner
  616. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  617. self?.openFile(withFilePath: url as URL)
  618. }
  619. vc.showWindow(NSApp.mainWindow)
  620. }
  621. func importFromCamera() {
  622. let vc = KMDeviceBrowserWindowController.shared
  623. vc.type = .camera
  624. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  625. self?.openFile(withFilePath: url as URL)
  626. }
  627. vc.showWindow(NSApp.mainWindow)
  628. }
  629. func newFromImages() {
  630. let openPanel = NSOpenPanel()
  631. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  632. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  633. // openPanel.allowsMultipleSelection = true
  634. // } else {
  635. // openPanel.allowsMultipleSelection = false
  636. // }
  637. 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: "")
  638. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  639. if result == .OK {
  640. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  641. debugPrint("缺少图片转PDF")
  642. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  643. // var arr: [KMBatchOperateFile] = []
  644. // for url in openPanel.urls {
  645. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  646. // arr.append(file)
  647. // }
  648. //
  649. // if #available(macOS 10.13, *) {
  650. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  651. // } else {
  652. // baseWindowController.showWindow(nil)
  653. // }
  654. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  655. // if #available(macOS 10.13, *) {
  656. // baseWindowController.release()
  657. // }
  658. }
  659. }
  660. }
  661. }
  662. }