1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108 |
- //
- // KMHomeViewController.swift
- // PDF Reader Pro
- //
- // Created by wanjun on 2022/10/13.
- //
- import Cocoa
- @objc enum KMHomeToolState : Int {
- case OpenPDF = 0
- case CreatePDF
- case Home
- case PDFTools
- case FavoriteDocuments
- case CloudDocuments
- }
- @objc enum KMAIHomeToolState : Int {
- case Home = 0
- case AITranslation
- case AIRewriting
- case AIErrorCorrection
- }
- @objcMembers class KMHomeViewController: NSViewController {
- @IBOutlet weak var leftBox: NSBox!
- @IBOutlet weak var rightBox: NSBox!
- @IBOutlet weak var homeSplitView: NSSplitView!
- @IBOutlet weak var homeRightScrollViewView: NSScrollView!
- @IBOutlet weak var rightTopBox: NSBox!
- @IBOutlet weak var rightBottomBox: NSBox!
- @IBOutlet weak var rightFullBox: NSBox!
- @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint!
-
- @IBOutlet var fastToolViewController: KMHomeFastToolViewController!
- @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController!
- @IBOutlet var pdfToolsViewController: KMPDFToolsViewController!
- @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController!
-
- @IBOutlet weak var dragView: KMHomeDragView!
-
- // AI 临时UI
- @IBOutlet weak var aiHomeBox: KMBox!
- @IBOutlet weak var aiHomeImageView: NSImageView!
- @IBOutlet weak var aiHomeLabel: NSTextField!
- @IBOutlet weak var aiTranslationBox: KMBox!
- @IBOutlet weak var aiTranslationImageView: NSImageView!
- @IBOutlet weak var aiTranslationLabel: NSTextField!
- @IBOutlet weak var aiRewritingBox: KMBox!
- @IBOutlet weak var aiRewritingImageView: NSImageView!
- @IBOutlet weak var aiRewritingLabel: NSTextField!
- @IBOutlet weak var aiErrorCorrectionBox: KMBox!
- @IBOutlet weak var aiErrorCorrectionImageView: NSImageView!
- @IBOutlet weak var aiErrorCorrectionLabel: NSTextField!
- @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC!
- @IBOutlet var aiTranslationViewController: KMAITranslationVC!
- @IBOutlet var aiRewritingViewController: KMAIRewritingVC!
-
- @IBOutlet weak var creatPDFView: KMCreatPDFView!
-
- //HomeContentView
- @IBOutlet weak var homeContentView: KMHomeContentView!
- //广告 互推
- @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
- @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
- @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
-
- //合并
- var mergeWindowController: KMMergeWindowController?
-
- var aiHomeState: KMAIHomeToolState = .Home
-
- let ScrollerViewWidget: CGFloat = 15.0
-
- var homeWindowController : MainWindowController!
-
- var isShowQuickTour: Bool = false
- weak var myDocument: NSDocument?
- var currentWindowController: NSWindowController?
- var homeState: KMHomeToolState = .Home
-
- var urlToPDFWindowController: KMURLToPDFWindowController?
-
- var openPDFButtonVC: KMDesignButton?
- var createPDFButtonVC: KMDesignButton?
- var createPDFImage: KMDesignButton?
- var createPDFAddButtonVC: KMDesignButton?
- var homeButtonVC: KMTextImageButtonVC?
- var pdfToolsButtonVC: KMTextImageButtonVC?
- var cloudDocumentsButtonVC: KMTextImageButtonVC?
- var pdfSeriesButtonVC: KMTextImageButtonVC?
- var pdfOthersButtonVC: KMTextImageButtonVC?
- var popover: NSPopover?
- var deviceBrowserWC: KMDeviceBrowserWindowController?
- var progressController: SKProgressController?
- var timer: Timer?
- var timerCounter = 0.0
-
- //AI相关
-
- //试用相关
- var didTrialExpiredLoad: Bool = false
- var repeatTrialAlertLoad: Bool = false
-
- var guideWindowVC: KMFunctionGuideWindowController!
- var showCoupon: Bool = true
- var couponDueWindowVC: KMCouponDueWindowController!
-
- @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
-
- var currentController: NSWindowController?
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
-
- override func viewWillAppear() {
- super.viewWillAppear()
- // if !KMLightMemberManager.manager.isLogin() {
- // KMLightMemberManager.manager.canShowAdvancedView = true
- // }
- self.homeContentView.reloadData()
- #if VERSION_DMG
- let kDMGFirstInstallKey = "DMGFirstInstallKey"
- if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil {
- KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey)
- KMTools.openURL(urlString: "http://www.pdfreaderpro.com/thank-you-for-installation")
- }
- #else
- // [self loadAIInfo];
- #endif
- }
-
- override func viewWillDisappear() {
- super.viewWillDisappear()
-
- // self.homeContentView.reloadData()
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do view setup here.
-
- openPDFButtonVC = KMDesignButton.init(withType: .Text)
- createPDFButtonVC = KMDesignButton.init(withType: .Text)
- createPDFImage = KMDesignButton.init(withType: .Image)
- createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
- homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
- self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
- self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
- self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
-
- NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
- self.otherMouseDown(with: aEvent)
- return aEvent
- }
- self.initNetworkingData()
- // self.initLocalization()
- // self.initializeUI()
- self.initializeUI_DMG()
-
- self.setup()
- // refreshUI()
- self.updateUI()
- self.changeEffectiveAppearance()
-
- NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
- // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
- // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
- #if VERSION_DMG
- NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
- #endif
-
- NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
- self.loadFunctionGuide()
-
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
- refreshScrollView()
- }
-
- override func viewDidLayout() {
- super.viewDidLayout()
-
- refreshScrollView()
-
- // self.loadAITipIconGuide()
- }
-
- func initNetworkingData() {
- KMAdvertisementManager.manager.fetchDataWithResponseObject { [weak self] data, responseObject, error in
- KMPrint("获取广告数据成功")
- if data != nil {
- let content = data!.recommondContent
- let item = content?.recommondContentPDFPro
- var infos: [KMAdvertisementItemInfo] = []
- for info in item?.content ?? [] {
- if info.version == "recommondPDF-PDFtoOfficePack" {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false && IAPProductsManager.default().isAvailableAllFunction() {
- infos.append(info)
- }
- } else {
- infos.append(info)
- }
- }
- item?.content = infos
- self?.advertisementTableView.inputData = content
- self?.advertisementTableView.didSelect = { view, item in
- let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
- if string.count != 0 {
- NSWorkspace.shared.open(URL.init(string: string)!)
- }
- }
-
- self?.advertisementShowView.inputData = data!.advertisement
- self?.advertisementShowView.didSelect = { view, item in
- let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
- if string.count != 0 {
- NSWorkspace.shared.open(URL.init(string: string)!)
- }
-
- guard let firebaseInfo = item.firebase else {
- return
- }
- KMAdvertisementModelTransition.sendFireBaseEvent(firebase: firebaseInfo)
- }
-
- if let item = data?.StoreUserRecovery?.content?.first {
- let url = URL(string: KMAdvertisementModelTransition.transitionImagePath(image: item.image, highlight: false))
- KMAdvertisementImage.imageWithURL(url: url) { image in
- // 预加载
- }
-
- let saleUrl = URL(string: KMAdvertisementModelTransition.transitionImagePath(image: item.saleImage, highlight: false))
- KMAdvertisementImage.imageWithURL(url: saleUrl) { image in
- // 预加载
- }
- }
-
- if KMAdvertisementManager.manager.infoDict.allKeys.count > 0 {
- if let adsInfo = KMAdvertisementManager.manager.infoDict["adsInfo"] {
- let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["adsInfo"] as! NSDictionary
- let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
-
- let arrM = NSMutableArray.init()
- for dict in array {
- let adsInfo = KMAdsInfo.init()
- let mutableDictionary = NSMutableDictionary(dictionary: dict)
- adsInfo.infoDict = mutableDictionary
- arrM.add(adsInfo)
- }
- KMAdsInfoManager.shareInstance.adsInfoArrM = arrM
- }
-
- if let couponInfo = KMAdvertisementManager.manager.infoDict["couponContent"] {
- let infoDict: NSDictionary = KMAdvertisementManager.manager.infoDict["couponContent"] as! NSDictionary
- let array: [[String: Any]] = infoDict["content"] as! [[String : Any]]
- if array.isEmpty == false {
- let dict = array[0]
- let adsInfo = KMCouponInfo.init()
- let mutableDictionary = NSMutableDictionary(dictionary: dict)
- adsInfo.infoDict = mutableDictionary
- KMAdsInfoManager.shareInstance.couponInfo = adsInfo
- }
- }
- self?.checkTrialEndCouponInfo()
- }
- }
- }
- }
-
- func setup() {
- //creatPDF
- self.creatPDFView.openPDFAction = { [unowned self] view, sender in
- self.openPDFAction(sender)
- }
-
- self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
- self.creatPDFAction(sender)
- }
-
- //history
- self.homeContentView.historyDidSelect = { [unowned self] view, item in
- self.openHistoryFilePath(url: item.url!)
- }
-
- self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
- self.historyFile(deleteDocuments: [ item.url!])
- }
-
- self.homeContentView.historyShowPathAction = { [unowned self] view, item in
- if FileManager.default.fileExists(atPath: item.url!.path) {
- NSWorkspace.shared.activateFileViewerSelecting([item.url!])
- }
- }
-
- self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
- alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
- alert.beginSheetModal(for: self.view.window!) { response in
- if response == .alertFirstButtonReturn {
- let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
- self.historyFileDeleteAction(urls)
- }
- }
- }
-
- //quciktools
- self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
- self.fastToolItemAction(item.type!)
- }
-
- self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
- KMBatchQuickActionManager.defaultManager.actionType = .add
- self.fastToolItemAction(item.type!)
- }
-
- self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
- KMBatchQuickActionManager.defaultManager.actionType = .remove
- self.fastToolItemAction(item.type!)
- }
-
- if IAPProductsManager.default().isAvailableAllFunction() {
- self.advertisementShowView.isHidden = true
- } else {
- self.advertisementShowView.isHidden = false
- }
-
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
-
- }
-
- // MARK: Init
-
- func initializeUI() {
- rightTopBox.fillColor = .white
- rightBottomBox.fillColor = .white
- rightFullBox.fillColor = .white
-
- self.refreshRightBoxUI(.Home)
- fastToolViewController.delete = self
- historyFileViewController.delete = self
- pdfToolsViewController.delete = self
- dragView.delete = self
- }
-
- func initLocalization() {
- // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
-
- homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
- pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
- cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
- openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
- // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
- createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
- // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
- pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
- pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
- }
-
- // MARK: Action
- func initializeUI_DMG() -> Void {
- rightTopBox.fillColor = .white
- rightBottomBox.fillColor = .white
- rightFullBox.fillColor = .white
- self.aiHomeBox.fillColor = .clear
- self.aiHomeBox.cornerRadius = 8.0
- self.aiHomeImageView.image = NSImage(named: "icon_home")
- self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
- self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .Home {
- if mouseEntered {
- self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiHomeBox.fillColor = .clear
- }
- }
- }
- self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .Home {
- if downEntered {
- self.aiHomeState = .Home
-
- self.refreshAIUI()
- }
- }
- }
- self.aiTranslationBox.fillColor = .clear
- self.aiTranslationBox.cornerRadius = 8.0
- self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
- self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
- self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AITranslation {
- if mouseEntered {
- self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiTranslationBox.fillColor = .clear
- }
- }
- }
- self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AITranslation {
- if downEntered {
- self.aiHomeState = .AITranslation
-
- self.trackEvent_ai(eventName: "AI Translation")
-
- self.refreshAIUI()
- }
- }
- }
- self.aiRewritingBox.fillColor = .clear
- self.aiRewritingBox.cornerRadius = 8.0
- self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
- self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
- self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AIRewriting {
- if mouseEntered {
- self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiRewritingBox.fillColor = .clear
- }
- }
- }
- self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AIRewriting {
- if downEntered {
- self.aiHomeState = .AIRewriting
-
- self.trackEvent_ai(eventName: "AI Rewriting")
-
- self.refreshAIUI()
- }
- }
- }
- self.aiErrorCorrectionBox.fillColor = .clear
- self.aiErrorCorrectionBox.cornerRadius = 8.0
- self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
- self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
- self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
- if aiHomeState != .AIErrorCorrection {
- if mouseEntered {
- self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
- } else {
- self.aiErrorCorrectionBox.fillColor = .clear
- }
- }
- }
- self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
- if aiHomeState != .AIErrorCorrection {
- if downEntered {
- self.aiHomeState = .AIErrorCorrection
-
- self.trackEvent_ai(eventName: "AI Correction")
-
- self.refreshAIUI()
- }
- }
- }
-
- self.refreshAIUI()
-
- historyFileViewController.delete = self
- dragView.delete = self
- }
-
- func updateUI() {
- self.leftBox.fillColor = KMAppearance.Layout.l0Color()
- // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
- }
-
- @objc func changeEffectiveAppearance() {
- let isDarkModel = KMAdvertisementConfig.isDarkModel()
- if isDarkModel {
- self.view.appearance = NSAppearance(named: .darkAqua)
- } else {
- self.view.appearance = NSAppearance(named: .aqua)
- }
- self.updateUI()
- self.advertisementTableView.reloadData()
- }
-
- // MARK: Public Methods
-
- func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
- DispatchQueue.global(qos: .`default`).async {
- var isSuccessfully = false
- if pdf.isEncrypted {
- let dic = [
- CPDFDocumentWriteOption.userPasswordOption : password,
- CPDFDocumentWriteOption.ownerPasswordOption : password
- ]
- isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
- } else {
- isSuccessfully = pdf.write(to: pdf.documentURL)
- }
- if !isSuccessfully {
- if let data = pdf.dataRepresentation() {
- isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
- }
- }
-
- DispatchQueue.main.sync {
- if isSuccessfully {
- let workspace = NSWorkspace.shared
- let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
- workspace.activateFileViewerSelecting([url])
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
- alert.runModal()
- }
- }
- }
- }
-
- // MARK: Private Methods
- func refreshUI() -> Void {
- homeButtonVC?.updateUI()
- pdfToolsButtonVC?.updateUI()
- cloudDocumentsButtonVC?.updateUI()
- }
-
- func refreshAIUI() -> Void {
- self.aiHomeBox.fillColor = .clear
- self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiTranslationBox.fillColor = .clear
- self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiRewritingBox.fillColor = .clear
- self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
- self.aiErrorCorrectionBox.fillColor = .clear
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
- rightFullBox.isHidden = true
- rightTopBox.isHidden = true
- rightBottomBox.isHidden = true
- switch self.aiHomeState {
- case .Home:
- self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
-
- self.rightTopBox.isHidden = false
- self.rightBottomBox.isHidden = false
- self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
- self.rightBottomBox.contentView = self.historyFileViewController.view
- self.rightFullBox.contentView = nil
-
- self.rightTopBoxHeightConstraint.constant = 388.0
-
- self.dragView.isHidden = false
- break
- case .AITranslation:
- self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiTranslationViewController.view
-
- self.dragView.isHidden = false
- break
- case .AIRewriting:
- self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiRewritingViewController.view
- // self.aiRewritingViewController.state = .AIRewriting
- self.aiRewritingViewController.initLocalization()
- self.aiRewritingViewController.acquisition_uiState()
-
- self.dragView.isHidden = true
- break
- case .AIErrorCorrection:
- self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
- self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
- self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
- self.rightFullBox.isHidden = false
- self.rightTopBox.contentView = nil
- self.rightBottomBox.contentView = nil
- self.rightFullBox.contentView = self.aiRewritingViewController.view
- // self.aiRewritingViewController.state = .AIErrorCorrection
- self.aiRewritingViewController.initLocalization()
- self.aiRewritingViewController.acquisition_uiState()
-
- self.dragView.isHidden = true
- break
- default:
- break
- }
- }
-
- func fetchDifferentFilePath(filePath: String) -> String {
- var resultFilePath = filePath
- var index: Int = 0
- while (FileManager.default.fileExists(atPath: resultFilePath)) {
- index += 1
- let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
- resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
- }
-
- return resultFilePath;
- }
-
- func showProgressWindow() {
- let progress = SKProgressController()
- progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
- progress.window?.contentView?.wantsLayer = true
- progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
- progress.progressField.textColor = NSColor.white
- progress.message = NSLocalizedString("Translating...", comment: "")
- progress.closeBlock = { [weak self] in
-
- }
-
- self.progressController = progress
- self.view.window?.beginSheet(progress.window!)
- }
-
- func hiddenProgressWindow() {
- DispatchQueue.main.async {
- self.progressController?.doubleValue = 100.0
- }
- self.stopTimer()
- if (self.progressController != nil) {
- self.view.window?.endSheet((self.progressController?.window)!)
- self.progressController = nil
- }
- }
-
- func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
- let fileManager = FileManager.default
- do {
- let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
- if let fileSize = fileAttributes[.size] as? UInt64 {
- let megabyteSize = fileSize / (1024 * 1024)
- return megabyteSize >= 10
- }
- } catch {
- KMPrint("Error: \(error)")
- }
- return false
- }
-
- func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
- let url = URL(fileURLWithPath: filePath)
- guard let document = PDFDocument(url: url) else {
- return false
- }
-
- let pageCount = document.pageCount
- return pageCount > 30
- }
-
- @objc func timerTick() {
- timerCounter += 1.0
- self.progressController?.increment(by: 1.0)
-
- if timerCounter >= 95 {
- stopTimer()
- }
- }
-
- func stopTimer() {
- timer?.invalidate()
- timer = nil
- }
- // MARK: Common methods
-
- func workSpaceOpenUrl(_ url: NSString) {
- let httpUrl: NSURL = NSURL.init(string: url as String)!
- let tWorkSpace: NSWorkspace = NSWorkspace.shared
- if !tWorkSpace.open(httpUrl as URL) {
- tWorkSpace.open(httpUrl as URL)
- }
- }
- }
- //MARK: Open Creat PDF
- extension KMHomeViewController: NSPopoverDelegate {
- }
- extension KMHomeViewController {
- func openPDFAction(_ sender: KMBox) {
- if needShowTabbingHintWindow() {
- showTabbingHintWindow()
- return
- }
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = ["pdf", "PDF"]
- openPanel.allowsMultipleSelection = false
- openPanel.beginSheetModal(for: self.view.window!) { (result) in
- if result == NSApplication.ModalResponse.OK {
- let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
- if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
- self.reopenDocument(forPaths: openPanel.url!)
- }else {
- NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
-
- }
- }
- }
- }
- }
-
- func needShowTabbingHintWindow() -> Bool {
- let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
- if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
- return true
- }
- return false
- }
-
- func showTabbingHintWindow(){
- if !KMDataManager.default.isTabbingWin{
- KMDataManager.default.isTabbingWin = true
- let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
- tabbingWin.selectCallBack = { [weak self] continueOrNot in
- KMDataManager.default.isTabbingWin = false
- if continueOrNot {
- self?.reopenDocument(forPaths: nil)
- } else {
-
- }
- }
- self.km_beginSheet(windowC: tabbingWin)
- }
- }
-
- func creatPDFAction(_ sender: KMBox) {
- let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
- NSLocalizedString("New From Images", comment: ""),
- NSLocalizedString("New From Web Page", comment: ""),
- NSLocalizedString("Import From Camera", comment: ""),
- NSLocalizedString("Import From Scanner", comment: "")]
- let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
- vc.background = KMAppearance.Layout.bgColor()
- vc.textColor = KMAppearance.Layout.h0Color()
- vc.enterFillColor = KMAppearance.Interactive.s0Color()
- let createFilePopover: NSPopover = NSPopover.init()
- createFilePopover.contentViewController = vc
- createFilePopover.delegate = self
- createFilePopover.animates = true
- createFilePopover.behavior = .semitransient
- createFilePopover.setValue(true, forKey: "shouldHideAnchor")
- 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)
-
- vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
- if count == NSLocalizedString("New Blank Page", comment: "") {
- self.openBlankPage()
- } else if count == NSLocalizedString("Import From Camera", comment: "") {
- self.importFromCamera()
- } else if count == NSLocalizedString("Import From Scanner", comment: "") {
- self.importFromScanner()
- } else if count == NSLocalizedString("New From Web Page", comment: "") {
- self.importFromWebPage()
- } else if count == NSLocalizedString("New From Images", comment: "") {
- self.newFromImages()
- }
- createFilePopover.close()
- }
- }
-
- func openBlankPage() {
- // let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
- // let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
- // let filePath = savePath.deletingLastPathComponent
- // if FileManager.default.fileExists(atPath: filePath) == false {
- // try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
- // }
- //
- // let pdfDocument = CPDFDocument()
- // pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
- // pdfDocument?.write(to: URL(fileURLWithPath: savePath))
- // let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
- // if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
- // self.reopenDocument(forPaths: URL(fileURLWithPath: savePath))
- // }else {
- // NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
- // if error != nil {
- // NSApp.presentError(error!)
- // } else {
- // if document is KMMainDocument {
- // let newDocument = document
- // (newDocument as! KMMainDocument).isNewCreated = true
- // }
- // }
- // // self.homeContentView?.reloadData()
- // }
- // }
- NSApplication.newBlankDocument()
- }
-
- func importFromWebPage() {
- self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
-
- self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
- if FileManager.default.fileExists(atPath: filePath) {
- NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- } else {
- if document is KMMainDocument {
- (document as! KMMainDocument).isNewCreated = true
- }
- }
- // self.homeContentView.reloadData()
- }
- }
- })
- }
-
- func importFromScanner() {
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
- self?.openFile(withFilePath: url as URL)
- }
- vc.showWindow(NSApp.mainWindow)
- }
-
- func importFromCamera() {
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .camera
- vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
- self?.openFile(withFilePath: url as URL)
- }
- vc.showWindow(NSApp.mainWindow)
- }
-
- func newFromImages() {
- fastTool_ImageToPDF()
- // let openPanel = NSOpenPanel()
- // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
- // if IAPProductsManager.defaultManager().isAvailableAllFunction {
- // openPanel.allowsMultipleSelection = true
- // } else {
- // openPanel.allowsMultipleSelection = false
- // }
- // 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: "")
- // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
- // if result == .OK {
- // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
- // debugPrint("缺少图片转PDF")
- // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
- // var arr: [KMBatchOperateFile] = []
- // for url in openPanel.urls {
- // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
- // arr.append(file)
- // }
- //
- // if #available(macOS 10.13, *) {
- // baseWindowController.window?.makeKeyAndOrderFront(nil)
- // } else {
- // baseWindowController.showWindow(nil)
- // }
- // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
- // if #available(macOS 10.13, *) {
- // baseWindowController.release()
- // }
- // }
- // }
- // }
- }
-
- //MARK: Purchase
- @objc func purchaseStateUpdateNoti() {
- if IAPProductsManager.default().isAvailableAllFunction() {
- self.advertisementShowView.isHidden = true
-
- guard let content = self.advertisementTableView.inputData else {
- return // 如果 content 为 nil,提前退出
- }
- let item = content.recommondContentPDFPro
- var infos: [KMAdvertisementItemInfo] = []
- for info in item?.content ?? [] {
- if info.version == "recommondPDF-PDFtoOfficePack" {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() == false && IAPProductsManager.default().isAvailableAllFunction() {
- infos.append(info)
- }
- } else {
- infos.append(info)
- }
- }
- item?.content = infos
- self.advertisementTableView.inputData = content
- }
- }
-
- //MARK: - AI
-
- func showAITypeChooseView() -> Void {
- let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
- windowVC.chooseCurFileHandle = {[unowned self] windowVC in
- if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit: Bool = false
- var curDoc: KMMainDocument!
- for document in documentArray {
- if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
- didFileEdit = document.isDocumentEdited
- curDoc = document as! KMMainDocument
- break
- }
- }
- if didFileEdit {
- let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
- if FileManager.default.fileExists(atPath: tempFileURL.path) {
- do {
- try FileManager.default.removeItem(at: tempFileURL)
-
- } catch {
-
- }
- }
- if curDoc != nil {
- curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
- }
- }
- windowVC.window?.becomeMain()
- }
- }
- if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
-
- } else {
- windowVC.window?.center()
- windowVC.didSetOriginFrame = true
- }
- windowVC.eventLabel = "AITools_Onboard"
- windowVC.showWindow(nil)
- }
-
- func loadAITipIconGuide() {
- if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
- let guideWC = KMGuideInfoWindowController.currentWC()
- guideWC.type = .aiTipIconInfo
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.finishHandle = { [weak self] windowVC, type in
-
- }
- if self.view.window != nil {
- var rect = self.view.window?.frame
- rect!.size.height -= 20
- guideWC.window?.setFrame(rect!, display: true)
- guideWC.window?.minSize = rect!.size
- guideWC.window?.maxSize = rect!.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- }
- }
-
-
- //MARK: - 引导
- func loadFunctionGuide() -> Void {
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
- self.loadNewUserGuide()
- }
- }
-
- // MARK: - what's New
-
- func loadNewUserGuide() -> Void {
- if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
- guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
- guideWindowVC.type = .functionMulti
- guideWindowVC.showWindow(nil)
- guideWindowVC.window?.orderFront(nil)
-
- KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
- }
- }
-
- func checkRepeatTrialExpiredController() -> Void {
- //试用过期提示比较表弹窗
- if didTrialExpiredLoad == true {
- return
- }
- didTrialExpiredLoad = true
- let singleTon = KMPurchaseCompareDMGWindowController.init()
- singleTon.showWindow(nil)
- if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
- singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
- }
- }
-
- func checkRepeatTrialAlertController() -> Void {
- //允许二次试用时弹出二次试用引导弹窗
- if repeatTrialAlertLoad == true {
- return
- }
- repeatTrialAlertLoad = true
- let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
- vc?.showWindow(nil)
- }
-
- //MARK: 试用到期优惠券弹窗
- func checkTrialEndCouponInfo() {
- #if VERSION_DMG
- KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in
- if success == true {
- if result != nil {
- guard let dataDict = result!["data"] as? NSDictionary else {
- return
- }
- // if dataDict!["pop_up"] as? Bool == true {
- let discount = dataDict["discount"] as? Int
- let coupon_code = dataDict["coupon_code"] as? String
- let end_up_at = dataDict["end_up_at"] as? String
- let pop_up = dataDict["pop_up"] as? Bool
- if pop_up == true {
- if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey {
- if KMAdsInfoManager.shareInstance.couponInfo?.show == true {
- if (UserDefaults.standard.object(forKey: versionKey) != nil) {
-
- } else {
- UserDefaults.standard.set("Show", forKey: versionKey)
- UserDefaults.standard.synchronize()
- self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at)
- }
- }
- }
- }
- }
- } else {
- if KMVerificationWindowController.allowsShowExpired() {
- self?.checkRepeatTrialExpiredController()
- } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
- self?.checkRepeatTrialAlertController()
- }
- }
- }
- #endif
- }
-
- func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) {
- if self.couponDueWindowVC == nil {
- self.couponDueWindowVC = KMCouponDueWindowController(windowNibName: "KMCouponDueWindowController")
- }
- self.couponDueWindowVC.disCount = discount ?? 20
- self.couponDueWindowVC.couponCode = couponCode ?? ""
- self.couponDueWindowVC.endUpAt = endUpAt ?? ""
-
- self.couponDueWindowVC.showWindow(nil)
- self.couponDueWindowVC.reloadData()
-
- }
-
- // MARK: - Noti Actions
- func deviceVerifyFinishNotification(_ sender: Notification) {
- #if VERSION_DMG
-
- #endif
- }
-
- @objc func aiTipIconViewShowStateChangeNoti() {
-
- }
- }
|