KMHomeViewController.swift 35 KB

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