KMOCRPDFWindowController.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. //
  2. // KMOCRPDFWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/14.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. class KMOCRPDFWindowController: NSWindowController, NSWindowDelegate, KMGOCRManagerDelegate, NSPopoverDelegate,NSTextFieldDelegate{
  10. var resultString: String = ""
  11. var ocrDictionary: NSMutableDictionary?
  12. var currentIndexPage: Int = 0{
  13. didSet {
  14. if PDFView.document.pageCount > currentIndexPage {
  15. currentIndexPage = 0
  16. self.currentPageLabel.stringValue = "\(currentIndexPage + 1)"
  17. // let page = self.PDFView.document.page(at: UInt(currentIndexPage))
  18. self.PDFView.go(toPageIndex: currentIndexPage, animated: true)
  19. }
  20. }
  21. }
  22. var PDFView: CPDFView!
  23. @IBOutlet var prePdfBGView: NSView!
  24. @IBOutlet var currentPageLabel: NSTextField!
  25. @IBOutlet var totalPageLabel: NSTextField!
  26. @IBOutlet var pageLabel: NSTextField!
  27. @IBOutlet var planLabel: NSTextField!
  28. @IBOutlet var ocrCopyButton: NSButton!
  29. @IBOutlet var pageRangeBox: NSComboBox!
  30. @IBOutlet var planComboBox: NSPopUpButton!
  31. @IBOutlet var progressIndicator: NSProgressIndicator!
  32. @IBOutlet var progressControl: NSProgressIndicator!
  33. @IBOutlet var failedBox: NSBox!
  34. @IBOutlet var failedLabel: NSTextField!
  35. @IBOutlet var cancelButton: NSButton!
  36. @IBOutlet var startButton: NSButton!
  37. @IBOutlet var languageLabel: NSTextField!
  38. @IBOutlet var ocrResultLabel: NSTextField!
  39. @IBOutlet var languageButton: NSButton!
  40. @IBOutlet var txtTextView: NSTextView!
  41. @IBOutlet var deleteButton: NSButton!
  42. @IBOutlet var emptyBox: NSBox!
  43. @IBOutlet var emptyLabel: NSTextField!
  44. var errorOCRArrays: Array<Any>?
  45. var pageIndexs: Array<Any>?
  46. var password: String = ""
  47. var pathFile: String = ""
  48. var pdfDocument: CPDFDocument?
  49. @IBOutlet var saveButton: NSButton!
  50. @IBOutlet var box1: NSBox!
  51. @IBOutlet var boxLabel1: NSTextField!
  52. @IBOutlet var previewLabel: NSTextField!
  53. @IBOutlet var savePDFButton: NSButton!
  54. var ocrCurrentIndex: Int = 0
  55. var appleOCRManger: KMGOCRManager?
  56. var googleOCRManger: KMGOCRManager?
  57. var savedFileName: String = ""
  58. private var _fileAttri: KMFileAttribute?
  59. func getOCRResrultsFolderPath() -> String {
  60. var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
  61. path?.append("/")
  62. path?.append(Bundle.main.bundleIdentifier!)
  63. if (FileManager.default.fileExists(atPath: path!) == false) {
  64. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  65. }
  66. path?.append("/")
  67. path?.append("OCR_Resrults")
  68. return path!
  69. }
  70. convenience init(cpdfDocument: CPDFDocument, pwd: String?) {
  71. self.init(windowNibName: "KMOCRPDFWindowController")
  72. self.pdfDocument = cpdfDocument
  73. self.password = pwd ?? ""
  74. let url: URL? = cpdfDocument.documentURL
  75. var lastPathComponent = url?.deletingPathExtension()
  76. if let str = lastPathComponent?.lastPathComponent {
  77. if str.count > 0 {
  78. self.pathFile = str
  79. }else {
  80. self.pathFile = NSLocalizedString("Untitled", comment: "")
  81. }
  82. } else {
  83. self.pathFile = NSLocalizedString("Untitled", comment: "")
  84. }
  85. self._fileAttri = KMFileAttribute()
  86. self._fileAttri?.password = self.pdfDocument?.password ?? ""
  87. self._fileAttri?.filePath = self.pdfDocument?.documentURL.path ?? ""
  88. }
  89. convenience init(filePath: String, pwd: String?) {
  90. self.init(windowNibName: "KMOCRPDFWindowController")
  91. self.password = pwd ?? ""
  92. let pathExtension = filePath.lastPathComponent.customPathExtension
  93. if pathExtension.count > 0{
  94. if pathExtension.lowercased() == "pdf" {
  95. pdfDocument = CPDFDocument(url: URL(fileURLWithPath: filePath))
  96. } else {
  97. if let image = NSImage(contentsOf: URL(fileURLWithPath: filePath)) {
  98. self.pdfDocument = CPDFDocument()
  99. _ = pdfDocument?.km_insertPage(image.size, withImage: filePath, at: pdfDocument?.pageCount ?? 0)
  100. }
  101. }
  102. }
  103. self.pathFile = filePath.lastPathComponent.deletingPathExtension
  104. self._fileAttri = KMFileAttribute()
  105. self._fileAttri?.password = self.pdfDocument?.password ?? ""
  106. self._fileAttri?.filePath = self.pdfDocument?.documentURL.path ?? ""
  107. }
  108. deinit {
  109. NotificationCenter.default.removeObserver(self)
  110. KMGOCRManager.default().delegate = nil
  111. appleOCRManger?.cancelRecognition()
  112. appleOCRManger?.delegate = nil
  113. googleOCRManger?.cancelRecognition()
  114. googleOCRManger?.delegate = nil
  115. }
  116. override func windowDidLoad() {
  117. super.windowDidLoad()
  118. let preView: CPDFView = CPDFView(frame: self.prePdfBGView.bounds)
  119. self.prePdfBGView.addSubview(preView)
  120. self.PDFView = preView
  121. self.pageLabel.stringValue = NSLocalizedString("Page Range", comment: "")
  122. self.planLabel.stringValue = NSLocalizedString("OCR Plan", comment: "")
  123. self.planComboBox.removeAllItems()
  124. self.planComboBox.addItems(withTitles: [NSLocalizedString("Plan 1 (Online)", comment: ""), NSLocalizedString("Plan 2 (Offline)", comment: "")])
  125. let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
  126. if plan == 0 {
  127. KMGOCRManager.default().ocrType = .google
  128. self.planComboBox.selectItem(at: 0)
  129. } else {
  130. KMGOCRManager.default().ocrType = .apple
  131. self.planComboBox.selectItem(at: 1)
  132. }
  133. self.pageRangeBox.addItems(withObjectValues: [NSLocalizedString("All Pages", comment: ""), NSLocalizedString("Current Page", comment: ""), NSLocalizedString("Odd Pages Only", comment: ""), NSLocalizedString("Even Pages Only", comment: ""), NSLocalizedString("e.g. 1,3-5,10", comment: "")])
  134. self.pageRangeBox.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  135. self.pageRangeBox.selectItem(at: 0)
  136. self.pageRangeBox.isEditable = false
  137. if self.pageRangeBox.indexOfSelectedItem == 4 {
  138. self.window?.makeFirstResponder(self.pageRangeBox)
  139. self.pageRangeBox.stringValue = ""
  140. self.pageRangeBox.isEditable = true
  141. }
  142. self.emptyLabel.stringValue = NSLocalizedString("Recognize text from Image-based or Scanned PDF with OCR", comment: "")
  143. self.failedLabel.stringValue = NSLocalizedString("OCR failed. Please try to change the OCR Plan to \"Plan 2 (Offline)\"", comment: "")
  144. self.txtTextView.textColor = NSColor.textColor
  145. self.txtTextView.enclosingScrollView?.autohidesScrollers = true
  146. self.ocrResultLabel.stringValue = NSLocalizedString("OCR Results", comment: "")
  147. self.ocrCopyButton?.toolTip = KMLocalizedString("Copy and edit text from documents with OCR.", nil)
  148. self.deleteButton?.toolTip = NSLocalizedString("Delete", comment: "")
  149. self.deleteButton?.title = NSLocalizedString("Delete", comment: "")
  150. self.ocrCopyButton?.title = NSLocalizedString("Copy", comment: "")
  151. self.errorOCRArrays = []
  152. self.pageIndexs = []
  153. self.ocrCopyButton.isEnabled = false
  154. self.deleteButton.isEnabled = false
  155. self.saveButton.isEnabled = false
  156. self.savePDFButton.isEnabled = false
  157. self.boxLabel1.stringValue = NSLocalizedString("Settings", comment: "")
  158. self.previewLabel.stringValue = NSLocalizedString("Preview", comment: "")
  159. self.saveButton.title = NSLocalizedString("Save as TXT", comment: "")
  160. self.savePDFButton.title = NSLocalizedString("Save as PDF", comment: "")
  161. self.saveButton.toolTip = NSLocalizedString("Export as a searchable PDF or text file.", comment: "")
  162. self.savePDFButton.toolTip = NSLocalizedString("Export as a searchable PDF or text file.", comment: "")
  163. self.cancelButton.title = NSLocalizedString("Cancel", comment: "")
  164. self.startButton.title = NSLocalizedString("OCR", comment: "")
  165. self.languageLabel.stringValue = NSLocalizedString("Select OCR Language:", comment: "")
  166. self.updateLanguageButton((KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageStringKey) as? [String]))
  167. NotificationCenter.default.addObserver(self, selector: #selector(OCRSelectedLanguagesChangeNotification(notification:)), name: NSNotification.Name("KMOCRSelectedLanguagesChangeNotification"), object: nil)
  168. NotificationCenter.default.addObserver(self, selector: #selector(OCRSelectedPlanChangeNotification(notification:)), name: NSNotification.Name("KMOCRSelectedPlanChangeNotification"), object: nil)
  169. self.progressControl.isHidden = true
  170. emptyBox.isHidden = false
  171. failedBox.isHidden = true
  172. self.PDFView.document = self.pdfDocument
  173. self.PDFView.autoScales = true
  174. self.reloadPDFData()
  175. if !(self.pdfDocument?.isLocked ?? false) && ((self.pdfDocument?.unlock(withPassword: self.password)) != nil) {
  176. } else {
  177. KMBaseWindowController.checkPassword(url: self.pdfDocument!.documentURL, type: .owner) { success, pwd in
  178. if success {
  179. self.pdfDocument?.unlock(withPassword: pwd)
  180. self.password = pwd
  181. self.reloadPDFData()
  182. } else {
  183. self.close()
  184. }
  185. }
  186. }
  187. NotificationCenter.default.addObserver(self, selector: #selector(PDFViewDocumentChangedNotification(notification:)), name: NSNotification.Name.PDFViewPageChanged, object: nil)
  188. }
  189. func windowShouldClose(_ sender: NSWindow) -> Bool {
  190. close()
  191. return true
  192. }
  193. override func close() {
  194. if ((self.window?.isSheet) != nil) {
  195. // self.km_endSheet()
  196. self.window?.sheetParent?.endSheet(self.window!)
  197. } else {
  198. super.close()
  199. }
  200. }
  201. func reloadPDFData() { // 隐藏PDFView滑动条
  202. self.PDFView.documentView()?.enclosingScrollView?.hasVerticalScroller = false
  203. self.PDFView.documentView()?.enclosingScrollView?.hasHorizontalScroller = false
  204. let pageCount: Int = Int(self.pdfDocument?.pageCount ?? 0)
  205. let currentPageIndex = self.pdfDocument?.index(for: self.PDFView.currentPage())
  206. self.currentPageLabel.stringValue = "\((currentPageIndex ?? 0) + 1)"
  207. self.totalPageLabel.stringValue = "/ \(pageCount)"
  208. }
  209. //MARK: KMOCRSelectedLanguagesChangeNotification
  210. @objc func OCRSelectedLanguagesChangeNotification(notification: NSNotification) {
  211. if let selectedLanguages = notification.object as? [String] {
  212. updateLanguageButton(selectedLanguages)
  213. }
  214. }
  215. @objc func OCRSelectedPlanChangeNotification(notification: NSNotification) {
  216. let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
  217. if plan == 0 {
  218. self.planComboBox.selectItem(at: 0)
  219. } else {
  220. self.planComboBox.selectItem(at: 1)
  221. }
  222. KMGOCRManager.default().selectedLanguages = NSMutableArray()
  223. updateLanguageButton(KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageStringKey) as? [String])
  224. }
  225. @objc func PDFViewDocumentChangedNotification(notification: NSNotification) {
  226. let page: CPDFPage = self.PDFView.currentPage()
  227. let pageIndex = self.PDFView.document.index(for: page)
  228. self.currentPageLabel.stringValue = "\(pageIndex + 1)"
  229. }
  230. func updateLanguageButton(_ languages: [String]?) {
  231. if languages?.count ?? 0 < 1 {
  232. self.languageButton.title = NSLocalizedString("Auto Detection", comment: "")
  233. return
  234. }
  235. var languageName: String? = nil
  236. if languages?.count ?? 0 > 0 {
  237. for i in 0..<(languages?.count ?? 0) {
  238. let language = languages?[i]
  239. if i == 0 {
  240. languageName = language
  241. } else {
  242. languageName = languageName?.appendingFormat(",%@", language ?? "")
  243. }
  244. }
  245. } else {
  246. languageName = ""
  247. }
  248. self.languageButton.title = languageName ?? ""
  249. }
  250. func imageRep(withSize size: NSSize, scale: CGFloat, drawingHandler: (NSRect) -> Void) -> Any? {
  251. let bmpImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bitmapFormat: .alphaFirst, bytesPerRow: 0, bitsPerPixel: 0)
  252. // bmpImageRep?.bitmapImageRepByRetaggingWithColorSpace = .sRGB
  253. bmpImageRep?.size = size
  254. NSGraphicsContext.saveGraphicsState()
  255. NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bmpImageRep!)
  256. // drawingHandler(.zero, size)
  257. drawingHandler(NSRect(origin: NSZeroPoint, size: size))
  258. NSGraphicsContext.restoreGraphicsState()
  259. return bmpImageRep
  260. }
  261. func bitmapImage(withSize size: NSSize, drawingHandler: (NSRect) -> Void) -> NSImage? {
  262. let image = NSImage(size: size)
  263. let scale = KMImageScale
  264. image.addRepresentation(imageRep(withSize: size, scale: scale, drawingHandler: drawingHandler) as! NSBitmapImageRep)
  265. return image
  266. }
  267. func thumbnail(with page: CPDFPage) -> NSImage? {
  268. let bounds = page.bounds(for: .cropBox)
  269. var pageSize = bounds.size
  270. var scale: CGFloat = 1.0
  271. var thumbnailSize: NSSize
  272. var pageRect = NSZeroRect
  273. var image: NSImage?
  274. let aSize = pageSize.width
  275. if page.rotation % 180 == 90 {
  276. pageSize = NSSize(width: pageSize.height, height: pageSize.width)
  277. }
  278. if aSize > 0.0 {
  279. if pageSize.height > pageSize.width {
  280. thumbnailSize = NSSize(width: round(aSize * pageSize.width / pageSize.height), height: aSize)
  281. } else {
  282. thumbnailSize = NSSize(width: aSize, height: round(aSize * pageSize.height / pageSize.width))
  283. }
  284. let kKMMaxPixelsLimit = 75000000
  285. let totalPixelNumber = Int((thumbnailSize.width * KMImageScale) * (thumbnailSize.height * KMImageScale))
  286. if totalPixelNumber >= kKMMaxPixelsLimit {
  287. let sizeScale = sqrt(Float(kKMMaxPixelsLimit - 1000) / Float(totalPixelNumber))
  288. thumbnailSize = NSSize(width: floor(thumbnailSize.width * CGFloat(sizeScale)), height: floor(thumbnailSize.height * CGFloat(sizeScale)))
  289. }
  290. scale = max(thumbnailSize.width / pageSize.width, (thumbnailSize.height) / pageSize.height)
  291. } else {
  292. thumbnailSize = NSSize(width: pageSize.width, height: pageSize.height)
  293. }
  294. if thumbnailSize.width.isNaN || thumbnailSize.height.isNaN || thumbnailSize.width == 0.0 || thumbnailSize.height == 0.0 {
  295. thumbnailSize = NSSize(width: 186.0, height: 256.0)
  296. }
  297. pageRect.size = thumbnailSize
  298. image = bitmapImage(withSize: thumbnailSize) { rect in
  299. NSGraphicsContext.current?.imageInterpolation = .high
  300. NSGraphicsContext.saveGraphicsState()
  301. NSColor.white.setFill()
  302. pageRect.fill()
  303. NSGraphicsContext.restoreGraphicsState()
  304. if abs(scale - 1.0) > 0.0 {
  305. let transform = NSAffineTransform()
  306. transform.scale(by: scale)
  307. transform.concat()
  308. }
  309. page.draw(with: .cropBox, to: (NSGraphicsContext.current?.cgContext as! CGContext))
  310. NSGraphicsContext.current?.imageInterpolation = .default
  311. }
  312. return image
  313. }
  314. func savedName() -> String {
  315. var resultArrays: Array<Any> = []
  316. var ocrIndexArrays: Array<Any> = []
  317. let sortedKeys = self.ocrDictionary?.allKeys.sorted(by: {
  318. ($0 as? String)?.compare($1 as? String ?? "") == .orderedAscending
  319. })
  320. for i in 0 ..< (sortedKeys?.count ?? 0) {
  321. let keyS = sortedKeys?[i]
  322. ocrIndexArrays.append(keyS as Any)
  323. resultArrays.append(self.ocrDictionary?[keyS as Any] as Any)
  324. }
  325. var fileName = self.savedFileName
  326. if fileName.count > 50 {
  327. fileName = String(fileName.prefix(50))
  328. }
  329. if sortedKeys?.count ?? 0 > 1 {
  330. fileName = "\(self.pathFile) Pages \(fileName) _OCR"
  331. } else {
  332. fileName = "\(self.pathFile) Page \(fileName) _OCR"
  333. }
  334. var returnName = fileName
  335. switch self.pageRangeBox.indexOfSelectedItem {
  336. case 0:
  337. returnName = "\(self.pathFile)_OCR"
  338. case 2:
  339. returnName = "\(self.pathFile) Odd_OCR"
  340. case 3:
  341. returnName = "\(self.pathFile) Even_OCR"
  342. default:
  343. break
  344. }
  345. return returnName
  346. }
  347. func savePDF() {
  348. var resultArrays: Array<Any> = []
  349. var ocrIndexArrays: Array<Any> = []
  350. let sortedKeys = self.ocrDictionary?.allKeys.sorted(by: { ($0 as? String)?.compare($1 as? String ?? "") == .orderedAscending })
  351. for i in 0 ..< (sortedKeys?.count ?? 0) {
  352. let keyS = sortedKeys?[i]
  353. ocrIndexArrays.append(keyS as Any)
  354. resultArrays.append(self.ocrDictionary?[keyS as Any] as Any)
  355. }
  356. let fileName = self.savedFileName
  357. let saveAccessCtr = KMSavePanelAccessoryController()
  358. let outputSavePanel = NSSavePanel()
  359. outputSavePanel.allowedFileTypes = ["pdf"]
  360. outputSavePanel.nameFieldStringValue = fileName
  361. outputSavePanel.accessoryView = saveAccessCtr.view
  362. outputSavePanel.beginSheetModal(for: self.window!) { [self] (result) in
  363. if result == .OK {
  364. let savePDFPath = outputSavePanel.url?.path ?? ""
  365. if !FileManager.default.fileExists(atPath: getOCRResrultsFolderPath()) {
  366. try? FileManager.default.createDirectory(atPath: getOCRResrultsFolderPath(), withIntermediateDirectories: false, attributes: nil)
  367. }
  368. var imagePath = [Any]()
  369. for i in 0..<ocrIndexArrays.count {
  370. let rPath = (getOCRResrultsFolderPath() as NSString).appendingPathComponent("\(i).png")
  371. if let index = ocrIndexArrays[i] as? NSNumber, let page = self.pdfDocument?.page(at: UInt(index.intValue)), let image = self.thumbnail(with: page) {
  372. try? image.tiffRepresentation?.write(to: URL(fileURLWithPath: rPath), options: .atomic)
  373. }
  374. imagePath.append(rPath)
  375. }
  376. KMGOCRManager.default().createPDFFile(savePDFPath, imagePaths: imagePath, results: resultArrays, scale: KMImageScale)
  377. if saveAccessCtr.openAutomaticButton.state == .on {
  378. self.cancelButtonAction("")
  379. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePDFPath), display: true, completionHandler: {document,documentWasAlreadyOpen,error in
  380. })
  381. } else {
  382. self.viewFileAtFinder(savePDFPath)
  383. }
  384. }
  385. }
  386. }
  387. func viewFileAtFinder(_ fileName: String) {
  388. let workspace = NSWorkspace.shared
  389. let url = URL(fileURLWithPath: fileName)
  390. workspace.activateFileViewerSelecting([url])
  391. }
  392. func saveText() {
  393. let sortedKeys = self.ocrDictionary?.allKeys.sorted(by: { ($0 as? String)?.compare($1 as? String ?? "") == .orderedAscending })
  394. let fileName = self.savedFileName
  395. let saveAccessCtr = KMSavePanelAccessoryController()
  396. let outputSavePanel = NSSavePanel()
  397. outputSavePanel.allowedFileTypes = ["txt"]
  398. outputSavePanel.nameFieldStringValue = fileName
  399. outputSavePanel.accessoryView = saveAccessCtr.view
  400. outputSavePanel.beginSheetModal(for: self.window!) { (result) in
  401. if result == .OK {
  402. let outputURL = outputSavePanel.url
  403. try? self.txtTextView?.string.write(to: outputURL!, atomically: true, encoding: .utf8)
  404. if saveAccessCtr.openAutomaticButton?.state == .on {
  405. NSWorkspace.shared.open(outputURL!)
  406. } else {
  407. self.viewFileAtFinder(outputURL?.path ?? "")
  408. }
  409. }
  410. }
  411. }
  412. func fileNameWithNums(_ nums: [NSNumber]) -> String {
  413. var fileName: String? = nil
  414. if nums.count > 0 {
  415. if nums.count == 1 {
  416. if let num = nums.first {
  417. let idx = num.intValue + 1
  418. return "\(idx)"
  419. }
  420. }
  421. var sortIndex = NSSet()
  422. for num in nums {
  423. let idx = num.intValue + 1
  424. // sortIndex.insert(NSNumber(value: idx))
  425. sortIndex.adding(NSNumber(value: idx))
  426. }
  427. let sort = NSSortDescriptor(key: nil, ascending: true)
  428. let sortDesc = [sort]
  429. let sortArray = sortIndex.sortedArray(using: sortDesc)
  430. var a = 0
  431. var b = 0
  432. if sortArray.count == 1 {
  433. let num: NSNumber = sortArray.last as! NSNumber
  434. fileName = "\(num.intValue)"
  435. return fileName ?? ""
  436. }
  437. for i in 0 ..< sortArray.count {
  438. let num = sortArray[i]
  439. if fileName?.count ?? 0 > 0 {
  440. if (num as AnyObject).intValue == b + 1 {
  441. b = (num as AnyObject).intValue
  442. if (i == sortArray.count - 1) {
  443. fileName = (fileName ?? "") + "\(a)-\(b)"
  444. }
  445. } else {
  446. if a == b {
  447. fileName = (fileName ?? "") + "\(a),"
  448. } else {
  449. fileName = (fileName ?? "") + "\(a)-\(b),"
  450. }
  451. a = (num as AnyObject).intValue
  452. b = (num as AnyObject).intValue
  453. if (i == sortArray.count - 1) {
  454. fileName = (fileName ?? "") + "\(a)"
  455. }
  456. }
  457. } else {
  458. fileName = ""
  459. a = (num as AnyObject).intValue
  460. b = (num as AnyObject).intValue
  461. }
  462. }
  463. return fileName ?? ""
  464. }
  465. return ""
  466. }
  467. @IBAction func cancelButtonAction(_ sender: Any) {
  468. KMGOCRManager.default().cancelRecognition()
  469. self.close()
  470. }
  471. @IBAction func startButtonAction(_ sender: Any) {
  472. self.ocrCurrentIndex = 0
  473. txtTextView.string = ""
  474. ocrDictionary = NSMutableDictionary()
  475. let pdfDocument = self.pdfDocument
  476. errorOCRArrays?.removeAll()
  477. pageIndexs?.removeAll()
  478. if self.pageRangeBox.indexOfSelectedItem == 0 {
  479. for i in 0..<(pdfDocument?.pageCount ?? 0) {
  480. pageIndexs?.append(NSNumber(value: i))
  481. }
  482. } else if self.pageRangeBox.indexOfSelectedItem == 1 {
  483. let page = PDFView.currentPage()
  484. let pageIndex = PDFView.document?.index(for: page)
  485. pageIndexs?.append(NSNumber(value: pageIndex!))
  486. } else if self.pageRangeBox.indexOfSelectedItem == 2 {
  487. for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 == 0 {
  488. pageIndexs?.append(NSNumber(value: i))
  489. }
  490. } else if self.pageRangeBox.indexOfSelectedItem == 3 {
  491. for i in 0..<(pdfDocument?.pageCount ?? 0) where i % 2 != 0 {
  492. pageIndexs?.append(NSNumber(value: i))
  493. }
  494. } else {
  495. var attribute = self._fileAttri
  496. if attribute == nil {
  497. attribute = KMFileAttribute()
  498. self._fileAttri = attribute
  499. attribute?.password = self.pdfDocument?.password ?? ""
  500. attribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
  501. }
  502. // attribute.pdfDocument = pdfDocument
  503. attribute?.bAllPage = false
  504. attribute?.pagesType = .custom
  505. attribute?.pagesString = self.pageRangeBox.stringValue
  506. let selectPages = attribute?.fetchSelectPages() ?? []
  507. if selectPages.count > 0 {
  508. for num in selectPages {
  509. pageIndexs?.append(NSNumber(value: num - 1))
  510. }
  511. }
  512. }
  513. batchesOCR()
  514. }
  515. func batchesOCR() {
  516. savedFileName = savedName()
  517. let intervalOCR: UInt = 10
  518. var selctPageImages: NSMutableArray = NSMutableArray()
  519. for i in 0..<intervalOCR {
  520. if ocrCurrentIndex + Int(i) >= self.pageIndexs?.count ?? 0 { continue }
  521. autoreleasepool {
  522. let index = self.pageIndexs?[self.ocrCurrentIndex + Int(i)] as! NSNumber
  523. let page = self.pdfDocument?.page(at: UInt(index.intValue))
  524. let img: NSImage = thumbnail(with: page!)!
  525. let data: NSData = img.tiffRepresentation! as NSData
  526. selctPageImages.add(data)
  527. }
  528. }
  529. if selctPageImages.count < 1 && ocrCurrentIndex == 0 {
  530. let alert = NSAlert()
  531. alert.alertStyle = .critical
  532. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  533. if #available(OSX 10.11, *) {
  534. alert.beginSheetModal(for: self.window!, completionHandler: nil)
  535. } else {
  536. alert.runModal()
  537. }
  538. }
  539. if selctPageImages.count < 1 {
  540. return
  541. }
  542. if appleOCRManger != nil {
  543. appleOCRManger?.cancelRecognition()
  544. appleOCRManger?.delegate = nil
  545. appleOCRManger = nil
  546. }
  547. if googleOCRManger != nil {
  548. googleOCRManger?.cancelRecognition()
  549. googleOCRManger?.delegate = nil
  550. googleOCRManger = nil
  551. }
  552. ocrCopyButton.isEnabled = false
  553. saveButton.isEnabled = false
  554. savePDFButton.isEnabled = false
  555. startButton.isEnabled = false
  556. deleteButton.isEnabled = false
  557. progressControl.isHidden = false
  558. progressControl.startAnimation(nil)
  559. emptyBox.isHidden = true
  560. failedBox.isHidden = true
  561. DispatchQueue.main.async {
  562. let languages = KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageCodeKey)
  563. if self.planComboBox.indexOfSelectedItem == 0 {
  564. self.googleOCRManger = KMGOCRManager()
  565. self.googleOCRManger?.ocrType = .google
  566. self.googleOCRManger?.delegate = self
  567. self.googleOCRManger?.recognitionImages((selctPageImages as! [Any]), withLanguages: languages as? [Any])
  568. } else {
  569. self.appleOCRManger = KMGOCRManager()
  570. self.appleOCRManger?.ocrType = .apple
  571. self.appleOCRManger?.delegate = self
  572. self.appleOCRManger?.recognitionImages((selctPageImages as! [Any]), withLanguages: languages as? [Any])
  573. }
  574. }
  575. }
  576. @IBAction func planSelectButtonAction(_ sender: NSPopUpButton) {
  577. let plan = UserDefaults.standard.integer(forKey: "KMOCRCurrentPlanKey")
  578. if plan != sender.indexOfSelectedItem {
  579. KMGOCRManager.default().selectedLanguages = NSMutableArray()
  580. updateLanguageButton(KMGOCRManager.default().selectedLanguages?.value(forKeyPath: KMGOCRLanguageStringKey) as? [String])
  581. }
  582. UserDefaults.standard.set(sender.indexOfSelectedItem, forKey: "KMOCRCurrentPlanKey")
  583. UserDefaults.standard.synchronize()
  584. if self.planComboBox.indexOfSelectedItem == 0 {
  585. KMGOCRManager.default().ocrType = .google
  586. } else {
  587. KMGOCRManager.default().ocrType = .apple
  588. }
  589. NotificationCenter.default.post(name: NSNotification.Name("KMOCRSelectedPlanChangeNotification"), object: nil)
  590. }
  591. @IBAction func languageButtonAction(_ sender: Any) {
  592. let popover = NSPopover()
  593. popover.delegate = self
  594. popover.contentViewController = KMLanguageViewController(nibName: "KMLanguageViewController", bundle: Bundle.main)
  595. popover.animates = true
  596. popover.behavior = .transient
  597. popover.show(relativeTo: (sender as! NSView).bounds, of: sender as! NSView, preferredEdge: .minX)
  598. }
  599. @IBAction func helpButtonAction(_ sender: Any) {
  600. let helpController = NSViewController()
  601. let textView = NSTextView(frame: NSRectToCGRect(NSMakeRect(0, 0, 300.0, 50.0)))
  602. textView.backgroundColor = NSColor.clear
  603. textView.isEditable = false
  604. textView.layer?.cornerRadius = 6
  605. let tStrAuto = NSLocalizedString("Choose automatic language detection for better OCR results.", comment: "")
  606. textView.alignment = .justified
  607. textView.string = "\n\(tStrAuto)"
  608. helpController.view = textView
  609. let popover = NSPopover()
  610. popover.delegate = self
  611. popover.contentViewController = helpController
  612. popover.animates = true
  613. popover.behavior = .transient
  614. popover.show(relativeTo: (sender as! NSView).bounds, of: sender as! NSView, preferredEdge: .minY)
  615. }
  616. @IBAction func buttonItemClick_CopyTxt(_ sender: NSButton) {
  617. let pasteboard = NSPasteboard.general
  618. pasteboard.clearContents()
  619. let str: NSPasteboardWriting = self.txtTextView.string as NSPasteboardWriting
  620. pasteboard.writeObjects([str])
  621. let _ = CustomAlertView.alertView(message: NSLocalizedString("Copy successful!", comment: ""), fromView: sender.superview!, withStyle: .black)
  622. }
  623. @IBAction func buttonItemClick_Delete(_ sender: NSButton) {
  624. ocrCopyButton.isEnabled = false
  625. saveButton.isEnabled = false
  626. savePDFButton.isEnabled = false
  627. deleteButton.isEnabled = false
  628. emptyBox.isHidden = false
  629. failedBox.isHidden = true
  630. resultString = ""
  631. txtTextView.string = ""
  632. ocrDictionary = NSMutableDictionary()
  633. }
  634. @IBAction func boxItemClicked_PageRange(_ sender: NSButton) {
  635. if 4 != pageRangeBox.indexOfSelectedItem {
  636. self.window?.makeFirstResponder(self)
  637. pageRangeBox.isEditable = false
  638. } else {
  639. pageRangeBox.stringValue = ""
  640. pageRangeBox.isEditable = true
  641. self.window?.makeFirstResponder(pageRangeBox)
  642. }
  643. }
  644. @IBAction func nextButtonAction(_ sender: NSButton) {
  645. self.PDFView.goToNextPage(nil)
  646. self.reloadPDFData()
  647. }
  648. @IBAction func previousButtonAction(_ sender: NSButton) {
  649. self.PDFView.goToPreviousPage(nil)
  650. self.reloadPDFData()
  651. }
  652. @IBAction func buttonClicked_SaveButton(_ sender: NSButton) {
  653. self.saveText()
  654. }
  655. @IBAction func savePDFButtonAction(_ sender: NSButton) {
  656. self.savePDF()
  657. }
  658. func controlTextDidEndEditing(_ notification: Notification) {
  659. guard let textField = notification.object as? NSTextField else { return }
  660. if textField == currentPageLabel {
  661. let index = Int(currentPageLabel.stringValue) ?? 0
  662. let pageCount = pdfDocument?.pageCount
  663. let currentPageIndex = pdfDocument?.index(for: PDFView.currentPage())
  664. if index > 0 && index <= pageCount ?? 0 {
  665. PDFView.go(to: pdfDocument?.page(at: UInt(index-1))!)
  666. reloadPDFData()
  667. } else {
  668. currentPageLabel.stringValue = "\((currentPageIndex ?? 0)+1)"
  669. }
  670. }
  671. }
  672. func controlTextDidChange(_ notification: Notification) {
  673. guard let textField = notification.object as? NSTextField else { return }
  674. if textField == currentPageLabel {
  675. let string = textField.formatter?.string(for: NSNumber(value: Int(textField.stringValue) ?? 0))
  676. textField.stringValue = string ?? ""
  677. }
  678. }
  679. func popoverDidClose(_ notification: Notification) {
  680. }
  681. func gocrManagerDidStartOCR(_ manager: KMGOCRManager!) {
  682. }
  683. //MARK: KMGOCRManagerDelegate
  684. func gocrManagerDidFinishOCR(_ manager: KMGOCRManager!) {
  685. self.batchesOCR()
  686. }
  687. func gocrManager(_ manager: KMGOCRManager!, didCancelOCRImageAt index: Int) {
  688. }
  689. func gocrManager(_ manager: KMGOCRManager!, didStartOCRImageAt index: Int) {
  690. DispatchQueue.main.async {
  691. self.pageRangeBox.isEnabled = false
  692. self.languageButton.isEnabled = false
  693. self.planComboBox.isEnabled = false
  694. }
  695. }
  696. func gocrManager(_ manager: KMGOCRManager!, didFinishOCRImageAt index: Int, results: [KMGOCRResult]!) {
  697. self.dealWithResults(results, OCRImageAtIndex: index)
  698. }
  699. func gocrManager(_ manager: KMGOCRManager!, didFailureOCRImageAt index: Int, error: Error!) {
  700. let pagenum = self.pageIndexs?[index] as! NSNumber
  701. if (error != nil) {
  702. self.errorOCRArrays?.append(pagenum)
  703. }
  704. self.dealWithResults([], OCRImageAtIndex: index)
  705. }
  706. func dealWithResults(_ rlts: [KMGOCRResult]?, OCRImageAtIndex index: Int) {
  707. if index >= self.pageIndexs?.count ?? 0 {
  708. return
  709. }
  710. let key = self.pageIndexs?[self.ocrCurrentIndex] as! NSNumber
  711. if ocrDictionary == nil {
  712. ocrDictionary = NSMutableDictionary()
  713. }
  714. ocrDictionary?.setObject(rlts as Any, forKey: key)
  715. let sortedKeys = self.ocrDictionary?.allKeys.sorted(by: { ($0 as! NSNumber).compare($1 as! NSNumber) == .orderedAscending })
  716. var textString = ""
  717. for key in sortedKeys! {
  718. let results: Array<KMGOCRResult> = self.ocrDictionary?.object(forKey: key) as! Array<KMGOCRResult>
  719. var rStr = ""
  720. if results.count > 0 {
  721. rStr = results[0].text
  722. }
  723. if textString.count > 0 {
  724. textString += "\n\n"
  725. }
  726. textString += String(format: NSLocalizedString("Page %ld", comment: ""), (key as! NSNumber).intValue + 1)
  727. textString += "\n"
  728. textString += rStr
  729. }
  730. self.txtTextView.string = textString
  731. self.resultString = textString
  732. self.ocrCurrentIndex += 1
  733. if self.ocrCurrentIndex >= (self.pageIndexs?.count ?? 0) - 1 {
  734. self.progressControl.stopAnimation(nil)
  735. self.progressControl.isHidden = true
  736. self.saveButton.isEnabled = true
  737. self.savePDFButton.isEnabled = true
  738. self.ocrCopyButton.isEnabled = true
  739. self.deleteButton.isEnabled = true
  740. self.startButton.isEnabled = true
  741. self.planComboBox.isEnabled = true
  742. self.pageRangeBox.isEnabled = true
  743. self.languageButton.isEnabled = true
  744. if self.errorOCRArrays?.count ?? 0 < 1 {
  745. } else if self.errorOCRArrays?.count == self.pageIndexs?.count {
  746. if KMGOCRManager.default().ocrType == .google {
  747. self.failedLabel.stringValue = NSLocalizedString("OCR failed.Please try to change the OCR Plan to \"Plan 2 (Offline)\"", comment: "")
  748. self.failedBox.isHidden = false
  749. } else {
  750. let alert = NSAlert()
  751. alert.alertStyle = NSAlert.Style.critical
  752. alert.messageText = ""
  753. if #available(macOS 10.15, *) {
  754. alert.informativeText = NSLocalizedString("Unable to perform OCR on this document. Please try again later.", comment: "")
  755. } else {
  756. alert.informativeText = NSLocalizedString("OCR failed, please try again. Note: OCR Plan 2(Offline) is supported in macOS 10.15+.", comment: "")
  757. self.failedLabel.stringValue = NSLocalizedString("OCR failed, please try again. Note: OCR Plan 2(Offline) is supported in macOS 10.15+.", comment: "")
  758. self.failedBox.isHidden = false
  759. }
  760. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  761. let response = alert.runModal()
  762. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  763. }
  764. }
  765. } else {
  766. var contextString = String(format: "%@", NSLocalizedString("Some problems occurred during the last operation:", comment: ""))
  767. contextString += "\n"
  768. if self.errorOCRArrays?.count ?? 0 > 1 {
  769. contextString += NSLocalizedString("Pages", comment: "")
  770. } else {
  771. contextString += NSLocalizedString("Page", comment: "")
  772. }
  773. if self.errorOCRArrays?.count ?? 0 > 0 {
  774. contextString += String(format: ": %@", self.fileNameWithNums(self.errorOCRArrays as! Array<NSNumber>))
  775. }
  776. let alert = NSAlert()
  777. alert.alertStyle = NSAlert.Style.critical
  778. alert.messageText = NSLocalizedString("Completed", comment: "")
  779. alert.informativeText = contextString
  780. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  781. let response = alert.runModal()
  782. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  783. }
  784. }
  785. }
  786. }
  787. }