KMPDFEditViewController.swift 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113
  1. //
  2. // KMPDFEditViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/1/6.
  6. //
  7. typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set<IndexPath>) -> ()
  8. typealias KMIndexChooseBlock = (_ index: Int) -> Void
  9. class KMPDFEditViewController: KMPDFThumbViewBaseController {
  10. static let kNoPagesSelectedTipMessage = "No pages selected. Please select one or more pages first to organize."
  11. @IBOutlet weak var topBarBox: NSBox!
  12. @IBOutlet weak var contentBox: NSBox!
  13. @IBOutlet weak var thumbnailSizeView: NSView!
  14. @IBOutlet weak var lineBoxView: NSView!
  15. var toolBar = KMPDFEditToolbar(frame: NSZeroRect)
  16. override var thumbnailView: KMPDFThumbnailView {
  17. get {
  18. if (super.thumbnailView is KMPageEditThumbnailView) {
  19. return super.thumbnailView
  20. }
  21. super.thumbnailView = KMPageEditThumbnailView()
  22. return super.thumbnailView
  23. }
  24. set {
  25. super.thumbnailView = newValue
  26. }
  27. }
  28. var pageEditThumbnailView: KMPageEditThumbnailView {
  29. get {
  30. return self.thumbnailView as! KMPageEditThumbnailView
  31. }
  32. }
  33. override var menuItems: [[KMPDFThumbViewMenu.Item]] {
  34. get {
  35. return [[.insert ,.extract], [.leftRotate, .rightRotate, .copy, .paste, .reverse],
  36. [.delete], [.share]]
  37. }
  38. }
  39. private var pdfDocument: CPDFDocument?
  40. var listView: CPDFView?
  41. var pageIsUpdate: Bool = true
  42. var selectedPages: [Int] = []
  43. private let defaultItemSize = NSMakeSize(215, 250)
  44. var itemSize: NSSize = NSMakeSize(215, 250)
  45. // index=1 双击退出;index=2 打印
  46. var itemClick: KMCommonClickBlock?
  47. private var _isEdited = false
  48. var isEdited: Bool {
  49. return self._isEdited
  50. }
  51. var documentEditedCallback: KMCommonBlock?
  52. var selectionDidChange: KMPDFEditViewControllerSelectionDidChange?
  53. internal var viewFirstAppear = true
  54. private var _listViewCurrentIndex: Int = 0
  55. var listViewCurrentIndex: Int {
  56. get {
  57. return self._listViewCurrentIndex
  58. }
  59. }
  60. private var fileAttri_: KMFileAttribute?
  61. private var popOver_: NSPopover?
  62. required init?(coder: NSCoder) {
  63. super.init(coder: coder)
  64. }
  65. init(_ document: CPDFDocument) {
  66. super.init(nibName: "KMPDFEditViewController", bundle: nil)
  67. self.pdfDocument = document
  68. self.kmUndoManager = UndoManager()
  69. self.fileAttri_ = KMFileAttribute()
  70. self.fileAttri_?.password = document.password ?? ""
  71. self.fileAttri_?.filePath = document.documentURL.path
  72. }
  73. override func viewDidAppear() {
  74. super.viewDidAppear()
  75. let isLocked = self.pdfDocument?.isLocked ?? false
  76. let first = self.viewFirstAppear
  77. if (isLocked == false && self.viewFirstAppear) {
  78. self.viewFirstAppear = false
  79. if let doc = self.pdfDocument {
  80. self.thumbnailView.document = doc
  81. }
  82. self.thumbnailView.reloadData()
  83. }
  84. if let view = self.listView { // 存储阅读视图的当前页面索引
  85. self._listViewCurrentIndex = view.currentPageIndex
  86. }
  87. var item: Int = 0
  88. if (self.selectedPages.isEmpty) {
  89. let index = self.listView?.currentPageIndex ?? 0
  90. self.selectPages(indexs: IndexSet(integer: index))
  91. self.toolBar.setPageRangeString("\(index+1)")
  92. item = index
  93. } else {
  94. var indexs: IndexSet = []
  95. for pageIndex in self.selectedPages {
  96. let pageCnt = self.listView?.document?.pageCount ?? 0
  97. if (pageIndex < 0 || pageIndex >= pageCnt) {
  98. continue
  99. }
  100. indexs.insert(pageIndex)
  101. }
  102. self.selectPages(indexs: indexs)
  103. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted()))
  104. item = indexs.sorted().last ?? 0
  105. }
  106. if first {
  107. let cnt = self.thumbnailView.document?.pageCount ?? 0
  108. if cnt > 0 {
  109. var ips = Set<IndexPath>()
  110. ips.insert(IndexPath(item: item, section: 0))
  111. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .bottom)
  112. }
  113. }
  114. self.view.window?.makeFirstResponder(self)
  115. self._showPDFEditDetails()
  116. }
  117. override func viewDidLoad() {
  118. super.viewDidLoad()
  119. self._isEdited = false
  120. // 显示拖放移动动效
  121. // self.thumbnailView.dragMoveEffectAnimated = true
  122. // self.thumbnailView.collectionView.backgroundColor(NSColor.km_init(hex: "#CED0D4"))
  123. self.thumbnailView.collectionView.wantsLayer = true
  124. // self.thumbnailView.collectionView.layer?.backgroundColor = KMAppearance.PDFViewBackgroundColor().cgColor
  125. if KMAppearance.isDarkMode() {
  126. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
  127. } else {
  128. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
  129. }
  130. self.thumbnailSizeView.wantsLayer = true
  131. self.thumbnailSizeView.layer?.backgroundColor = KMAppearance.Layout.b80Color().cgColor
  132. self.lineBoxView.wantsLayer = true
  133. self.lineBoxView.layer?.backgroundColor = KMAppearance.Layout.h2Color().cgColor
  134. var allowedFileTypes: [String] = []
  135. // if let _types = KMConvertPDFManager.supportFileType() {
  136. allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
  137. // } else {
  138. // allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  139. // }
  140. self.thumbnailView.kmAllowedFileTypes = allowedFileTypes
  141. let toolBar = self.toolBar
  142. self.topBarBox.contentView = toolBar
  143. self.topBarBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  144. toolBar.itemClick = { [unowned self] item, index in
  145. guard let type = KMPageEditType(rawValue: index) else {
  146. if (index == KMPageEditType.insert_files) {
  147. self.insertFileAction()
  148. self.trackEvent(type: .insert, index: index)
  149. } else if (index == KMPageEditType.insert_blank_page) {
  150. self.insertBlankPageAction()
  151. self.trackEvent(type: .insert, index: index)
  152. } else if (index == KMPageEditType.insert_custom_page) {
  153. self.item_insertCustomPage(sender: nil)
  154. self.trackEvent(type: .insert, index: index)
  155. } else if (index == KMPageEditType.insert_fromImage) {
  156. self.item_insertFromImage(sender: nil)
  157. self.trackEvent(type: .insert, index: index)
  158. } else if (index == KMPageEditType.insert_fromClipboard) {
  159. self.item_insertFromClipboard(sender: nil)
  160. self.trackEvent(type: .insert, index: index)
  161. } else if (index == KMPageEditType.insert_fromScanner) {
  162. self.item_insertFromScanner(sender: nil)
  163. self.trackEvent(type: .insert, index: index)
  164. } else if (index == KMPageEditType.extract_selected_pages) {
  165. self.extractSelectPageItemAction()
  166. } else if (index == KMPageEditType.split_selected_pages) {
  167. self.splitMenuAction()
  168. }
  169. return
  170. }
  171. if (type == .leftRotate) {
  172. self.leftRotateAction()
  173. } else if (type == .rightRotate) {
  174. self.rightRotateAction()
  175. } else if (type == .zoomOut) {
  176. self.zoomOutButtonAction(sender: item?.zoomOutButton)
  177. } else if (type == .zoomIn) {
  178. self.zoomInButtonAction(sender: item?.zoomInButton)
  179. } else if (type == .extract) {
  180. self.extractAction()
  181. } else if (type == .replace) {
  182. self.replaceAction()
  183. } else if (type == .split) {
  184. self.splitAction()
  185. } else if (type == .reverse) {
  186. self.reverseAction()
  187. } else if (type == .delete) {
  188. self.deleteAction()
  189. } else if (type == .pageRange) {
  190. } else if (type == .insert) {
  191. self.trackEvent(type: .insert)
  192. } else if (type == .copy) {
  193. self.copyAction()
  194. } else if (type == .paste) {
  195. self.pasteAction()
  196. }
  197. }
  198. toolBar.pageRangeitemClick = { [weak self] type in
  199. self?.km_comboBoxSelectionDidChange(type)
  200. }
  201. toolBar.pageRangeValueDidChange = { [weak self] value, _ in
  202. if let data = self?.toolBar.pageRangeView {
  203. self?.km_controlTextDidEndEditing(data)
  204. }
  205. }
  206. let view = self.thumbnailView
  207. self.contentBox.contentView?.addSubview(view)
  208. view.frame = self.contentBox.contentView?.bounds ?? .zero
  209. view.autoresizingMask = [.width, .height]
  210. self.pageEditThumbnailView.delegate = self
  211. self.pageEditThumbnailView.selectionDidChange = { [weak self] selectedIndexs in
  212. guard let self = self else {
  213. return
  214. }
  215. self.selectionDidChange?(selectedIndexs)
  216. self.view.window?.makeFirstResponder(self)
  217. let enabled = (selectedIndexs.count > 0)
  218. for i in 0 ..< self.toolBar.toolBar.items.count {
  219. let item = self.toolBar.toolBar.items[i]
  220. if item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier
  221. || item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier {
  222. item.unEnabled = !enabled
  223. }
  224. }
  225. if (self.pageIsUpdate == false) {
  226. self.pageIsUpdate = true
  227. return
  228. }
  229. var indexs: Array<Int> = []
  230. for indexPath in selectedIndexs {
  231. indexs.append(indexPath.item)
  232. }
  233. indexs.sort(){$0 < $1}
  234. self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs))
  235. if self.listView != nil { // 存储阅读视图的当前页面索引
  236. if indexs.count != 0 {
  237. self._listViewCurrentIndex = indexs.last!
  238. }
  239. }
  240. }
  241. }
  242. override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  243. super.interfaceThemeDidChanged(appearance)
  244. self.thumbnailView.collectionView.wantsLayer = true
  245. if KMAppearance.isDarkMode() {
  246. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor
  247. } else {
  248. self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor
  249. }
  250. Task { @MainActor in
  251. let ips = self.thumbnailView.selectionIndexPaths
  252. self.thumbnailView.collectionView.reloadData()
  253. self.thumbnailView.selectionIndexPaths = ips
  254. }
  255. }
  256. override func keyDown(with event: NSEvent) {
  257. // super.keyDown(with: event)
  258. let cmd = event.modifierFlags.contains(.command)
  259. let shift = event.modifierFlags.contains(.shift)
  260. let code = event.keyCode
  261. let isLeft = code == 123
  262. let isUp = code == 126
  263. let isRight = code == 124
  264. let isDown = code == 125
  265. if cmd {
  266. if code == 0 { // cmd + a
  267. self.km_comboBoxSelectionDidChange(.all)
  268. return
  269. }
  270. // let ips = self.thumbnailView.selectionIndexPaths
  271. // let indexs = self.indexpathsToIndexs(indexpaths: ips)
  272. //// let idx = indexs.last ?? 0
  273. // var selectedIndexs = indexs
  274. // let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
  275. // let firstIdx = 0
  276. // let lastIdx = max(numberItems-1, 0)
  277. // if isLeft { // +
  278. // if self.isEmptySelection() {
  279. // selectedIndexs.insert(lastIdx)
  280. // } else {
  281. // if let idx = selectedIndexs.first, idx > 0 {
  282. // selectedIndexs.insert(idx-1)
  283. // }
  284. // }
  285. // } else if isRight { // -
  286. // if self.isEmptySelection() {
  287. // selectedIndexs.insert(firstIdx)
  288. // } else {
  289. // if let idx = selectedIndexs.last, idx < lastIdx {
  290. // selectedIndexs.insert(idx+1)
  291. // }
  292. // }
  293. // } else {
  294. // var numberPerLine = 0
  295. // let itemW = self.thumbnailView.itemSize.width
  296. // if itemW > 0 {
  297. // numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
  298. // }
  299. // if isUp {
  300. // if self.isEmptySelection() {
  301. // selectedIndexs.insert(lastIdx)
  302. // } else {
  303. // if let idx = selectedIndexs.first, idx > 0 {
  304. // selectedIndexs.insert(max(idx-numberPerLine, 0))
  305. // }
  306. // }
  307. // } else if isDown {
  308. // if self.isEmptySelection() {
  309. // selectedIndexs.insert(firstIdx)
  310. // } else {
  311. // if let idx = selectedIndexs.last, idx < lastIdx {
  312. // selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
  313. // }
  314. // }
  315. // }
  316. // }
  317. //
  318. // if selectedIndexs.isEmpty == false {
  319. // let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
  320. // self.thumbnailView.selectionIndexPaths = ips
  321. // self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  322. // }
  323. } else if shift {
  324. } else {
  325. let ips = self.thumbnailView.selectionIndexPaths
  326. let indexs = self.indexpathsToIndexs(indexpaths: ips)
  327. let idx = indexs.last ?? 0
  328. var selectedIndexs = IndexSet()
  329. let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0)
  330. let firstIdx = 0
  331. let lastIdx = max(numberItems-1, 0)
  332. if isLeft {
  333. if self.isEmptySelection() {
  334. selectedIndexs.insert(lastIdx)
  335. } else {
  336. if idx > 0 {
  337. selectedIndexs.insert(idx-1)
  338. }
  339. }
  340. } else if isRight {
  341. if self.isEmptySelection() {
  342. selectedIndexs.insert(firstIdx)
  343. } else {
  344. if idx < lastIdx {
  345. selectedIndexs.insert(idx+1)
  346. }
  347. }
  348. } else {
  349. var numberPerLine = 0
  350. let itemW = self.thumbnailView.itemSize.width
  351. if itemW > 0 {
  352. numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW)
  353. }
  354. if isUp {
  355. if self.isEmptySelection() {
  356. selectedIndexs.insert(lastIdx)
  357. } else {
  358. selectedIndexs.insert(max(idx-numberPerLine, 0))
  359. }
  360. } else if isDown {
  361. if self.isEmptySelection() {
  362. selectedIndexs.insert(firstIdx)
  363. } else {
  364. selectedIndexs.insert(min(idx+numberPerLine, lastIdx))
  365. }
  366. }
  367. }
  368. if selectedIndexs.isEmpty == false {
  369. let ips = self.indexsToIndexpaths(indexs: selectedIndexs)
  370. self.thumbnailView.selectionIndexPaths = ips
  371. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  372. }
  373. }
  374. }
  375. // MARK: Private Methods
  376. private func getSelecteIndex() -> Int {
  377. let index = self.getPasteIndex()
  378. if (index != NSNotFound) {
  379. return index
  380. }
  381. return 0
  382. }
  383. private func getSelectedPage() -> CPDFPage? {
  384. return self.pdfDocument?.page(at: UInt(getSelecteIndex()))
  385. }
  386. private func selectPages(indexs: IndexSet) {
  387. var indexpaths: Set<IndexPath> = []
  388. for index in indexs {
  389. indexpaths.insert(IndexPath(item: index, section: 0))
  390. }
  391. self.selectPages(indexpaths: indexpaths)
  392. }
  393. private func km_becomeFirstResponder() {
  394. DispatchQueue.main.async {
  395. self.view.window?.makeFirstResponder(self)
  396. }
  397. }
  398. fileprivate func dealPdfDocumentDidEditCallback(type: KMPageEditType = .none) {
  399. self._isEdited = true
  400. // 提醒外面文档已编辑
  401. guard let callback = self.documentEditedCallback else {
  402. return
  403. }
  404. callback(type)
  405. }
  406. private func _progressHUD(message: String, style: KMCustomAlertStyle = .blue) {
  407. _ = CustomAlertView.alertView(message: message, fromView: self.thumbnailView, withStyle: style)
  408. }
  409. private func _showPDFEditDetails() {
  410. var insertItem: KMToolbarItemView?
  411. for item in self.toolBar.toolBar.items {
  412. if item.itemIdentifier == KMToolbarPageEditInsetItemIdentifier {
  413. insertItem = item
  414. break
  415. }
  416. }
  417. if insertItem?.window == nil {
  418. return
  419. }
  420. let showConvertDetails = KMPageEditPopViewController.showPageEditDetails()
  421. if (showConvertDetails) {
  422. let item = insertItem
  423. let popViewController = KMPageEditPopViewController()
  424. self.popOver_ = NSPopover()
  425. self.popOver_?.contentViewController = popViewController
  426. self.popOver_?.animates = false
  427. self.popOver_?.setBackgroundColor(KMAppearance.Interactive.a0Color())
  428. self.popOver_?.behavior = .transient
  429. // self.popOver.appearance = NSPopoverAppearanceMinimal;
  430. // self.popOver_?.appearance = .minimal
  431. self.popOver_?.contentSize = popViewController.view.frame.size
  432. self.popOver_?.show(relativeTo: item?.bounds ?? .zero, of: item!, preferredEdge: .maxY)
  433. }
  434. }
  435. // MARK: - 清空选择
  436. private func clearSelectPages() {
  437. self.selectPages(indexs: IndexSet())
  438. }
  439. override func refreshUI(indexpaths: Set<IndexPath> = [], keepSelected: Bool = false) {
  440. super.refreshUI(indexpaths: indexpaths, keepSelected: keepSelected)
  441. self.listView?.layoutDocumentView()
  442. }
  443. override func cutAction() {
  444. if IAPProductsManager.default().isAvailableAllFunction() == false {
  445. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  446. return
  447. }
  448. let pageCnt = self.pdfDocument?.pageCount ?? 0
  449. if (self.thumbnailView.selectionIndexPaths.count == pageCnt) {
  450. self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
  451. return
  452. }
  453. super.cutAction()
  454. }
  455. override func copyAction() {
  456. self.trackEvent_copy()
  457. super.copyAction()
  458. }
  459. override func deleteAction() {
  460. if IAPProductsManager.default().isAvailableAllFunction() == false {
  461. let winC = KMPurchaseCompareWindowController.sharedInstance()
  462. if self.kEventTag == 1 {
  463. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  464. } else {
  465. winC?.kEventName = "Reading_Delete_BuyNow"
  466. }
  467. winC?.showWindow(nil)
  468. return
  469. }
  470. if self.isEmptySelection() {
  471. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  472. return
  473. }
  474. let msg = String(format: NSLocalizedString("Are you sure to delete page %@ ?", comment: ""), KMTools.parseIndexSet(indexSet: self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths)))
  475. Task {
  476. let res = await KMAlertTool.runModel(message: msg, buttons: [NSLocalizedString("Delete", comment: ""), NSLocalizedString("Cancel", comment: "")])
  477. if res != .alertFirstButtonReturn {
  478. return
  479. }
  480. self.trackEvent(type: .delete)
  481. super.deleteAction()
  482. self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier)
  483. }
  484. }
  485. override func deleteIndexPaths(indexpaths: Set<IndexPath>) {
  486. guard let pageCount = self.thumbnailView.document?.pageCount else {
  487. KMPrint("pageCount invalid.")
  488. return
  489. }
  490. if (indexpaths.count == pageCount) {
  491. self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: ""))
  492. return
  493. }
  494. self.dealPdfDocumentDidEditCallback(type: .delete)
  495. super.deleteIndexPaths(indexpaths: indexpaths)
  496. }
  497. override func leftRotateAction() {
  498. if IAPProductsManager.default().isAvailableAllFunction() == false {
  499. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  500. return
  501. }
  502. self.trackEvent(type: .leftRotate)
  503. super.leftRotateAction()
  504. // self.toolBar.unSelectItem(for: KMToolbarPageEditLeftRotateItemIdentifier)
  505. }
  506. override func leftRotateIndexpaths(indexpaths: Set<IndexPath>) {
  507. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  508. return
  509. }
  510. super.leftRotateIndexpaths(indexpaths: indexpaths)
  511. self.dealPdfDocumentDidEditCallback(type: .leftRotate)
  512. }
  513. override func rightRotateAction() {
  514. if IAPProductsManager.default().isAvailableAllFunction() == false {
  515. let winC = KMPurchaseCompareWindowController.sharedInstance()
  516. if self.kEventTag == 1 {
  517. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  518. } else {
  519. winC?.kEventName = "Reading_Rotate_BuyNow"
  520. }
  521. winC?.showWindow(nil)
  522. return
  523. }
  524. if self.isEmptySelection() {
  525. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  526. return
  527. }
  528. self.trackEvent(type: .rightRotate)
  529. super.rightRotateAction()
  530. // self.toolBar.unSelectItem(for: KMToolbarPageEditRightRotateItemIdentifier)
  531. }
  532. override func rightRotateIndexpaths(indexpaths: Set<IndexPath>) {
  533. if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) {
  534. return
  535. }
  536. super.rightRotateIndexpaths(indexpaths: indexpaths)
  537. self.dealPdfDocumentDidEditCallback(type: .rightRotate)
  538. }
  539. override func insertPages(pages: Array<CPDFPage>, at indexs: IndexSet) {
  540. super.insertPages(pages: pages, at: indexs)
  541. if (!indexs.isEmpty) {
  542. self.selectPages(indexs: indexs)
  543. self.dealPdfDocumentDidEditCallback(type: .insert)
  544. }
  545. }
  546. override func pasteAction() {
  547. if IAPProductsManager.default().isAvailableAllFunction() == false {
  548. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  549. return
  550. }
  551. if (self.canPaste()) {
  552. super.pasteAction()
  553. self.dealPdfDocumentDidEditCallback(type: .paste)
  554. } else {
  555. if KMThumbnailManager.manager.copyPages.count <= 0 {
  556. self._progressHUD(message: KMLocalizedString("No copied page selected. Please select and copy a page first."))
  557. }
  558. }
  559. }
  560. @objc func pasteActonForEmpty(_ sender: NSMenuItem) {
  561. guard let indexpaths = sender.representedObject as? IndexPath else {
  562. NSSound.beep()
  563. return
  564. }
  565. let idx = max(0, indexpaths.item-1)
  566. // self.pastePage(at: indexpaths.item)
  567. self.pastePage(at: idx)
  568. }
  569. override func pastePage(at index: Int) {
  570. if IAPProductsManager.default().isAvailableAllFunction() == false {
  571. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  572. return
  573. }
  574. super.pastePage(at: index)
  575. }
  576. override func extractAction() {
  577. if IAPProductsManager.default().isAvailableAllFunction() == false {
  578. let winC = KMPurchaseCompareWindowController.sharedInstance()
  579. if self.kEventTag == 1 {
  580. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  581. } else {
  582. winC?.kEventName = "Reading_Extract_BuyNow"
  583. }
  584. winC?.showWindow(nil)
  585. return
  586. }
  587. if self.isEmptySelection() {
  588. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  589. return
  590. }
  591. self.trackEvent(type: .extract)
  592. super.extractAction()
  593. DispatchQueue.main.async {
  594. self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier)
  595. }
  596. }
  597. override func replaceAction() {
  598. if IAPProductsManager.default().isAvailableAllFunction() == false {
  599. let winC = KMPurchaseCompareWindowController.sharedInstance()
  600. if self.kEventTag == 1 {
  601. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  602. } else {
  603. winC?.kEventName = "Reading_Replace_BuyNow"
  604. }
  605. winC?.showWindow(nil)
  606. return
  607. }
  608. if self.isEmptySelection() {
  609. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  610. return
  611. }
  612. self.trackEvent(type: .replace)
  613. super.replaceAction()
  614. DispatchQueue.main.async {
  615. self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier)
  616. }
  617. }
  618. override func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
  619. self.model.insertedDocumentSet.formUnion(documents)
  620. super.replacePages(of: targetIndexpaths, with: documents)
  621. }
  622. // 插入规则:选中后面插入[多选插入第后个后面];没有选中,插入阅读页当前页;
  623. override func getInsertIndex() -> Int {
  624. let ips = self.thumbnailView.selectionIndexPaths.sorted()
  625. if ips.isEmpty {
  626. return self.listView?.currentPageIndex ?? 0
  627. }
  628. return ips.last?.item ?? 0
  629. }
  630. override func splitAction() {
  631. if IAPProductsManager.default().isAvailableAllFunction() == false {
  632. let winC = KMPurchaseCompareWindowController.sharedInstance()
  633. if self.kEventTag == 1 {
  634. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  635. } else {
  636. winC?.kEventName = "Reading_Split_BuyNow"
  637. }
  638. winC?.showWindow(nil)
  639. return
  640. }
  641. if self.isEmptySelection() {
  642. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  643. return
  644. }
  645. guard let doc = self.pdfDocument else {
  646. NSSound.beep()
  647. return
  648. }
  649. let windowC = SplitWindowController(document: doc)
  650. windowC.fileAttribute?.pagesType = .custom
  651. let ips = self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths).sorted()
  652. let string = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: ips)
  653. windowC.fileAttribute?.pagesString = string
  654. self.km_beginSheet(windowC: windowC)
  655. }
  656. func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  657. if IAPProductsManager.default().isAvailableAllFunction() == false {
  658. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  659. return
  660. }
  661. if self.isEmptySelection() {
  662. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  663. return
  664. }
  665. self._splitMethod(windowC: windowC, model: model, limit: limit)
  666. }
  667. func splitMenuAction() {
  668. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  669. // #if VERSION_DMG
  670. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  671. // #else
  672. // KMToolCompareWindowController * vc = [KMToolCompareWindowController toolCompareWithType:KMCompareWithToolType_PageEdit setSelectIndex:1];
  673. // [vc startModal:nil];
  674. // #endif
  675. // return;
  676. // }
  677. if IAPProductsManager.default().isAvailableAllFunction() == false {
  678. let winC = KMPurchaseCompareWindowController.sharedInstance()
  679. if self.kEventTag == 1 {
  680. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  681. } else {
  682. winC?.kEventName = "Reading_Split_BuyNow"
  683. }
  684. winC?.showWindow(nil)
  685. return
  686. }
  687. let pdf = self.thumbnailView.document
  688. let pages = self.thumbnailView.selectionIndexPaths
  689. if (pages.isEmpty == false) {
  690. if self.fileAttri_ == nil {
  691. self.fileAttri_ = KMFileAttribute()
  692. self.fileAttri_?.password = self.thumbnailView.document?.password ?? ""
  693. self.fileAttri_?.filePath = self.thumbnailView.document?.documentURL.path ?? ""
  694. }
  695. let fileAttribute = self.fileAttri_
  696. fileAttribute?.bAllPage = false
  697. fileAttribute?.pagesType = .custom
  698. fileAttribute?.pdfDocument = pdf
  699. fileAttribute?.pagesString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.indexpathsToIndexs(indexpaths: pages).sorted())
  700. fileAttribute?.pageCnt = Int(self.thumbnailView.document?.pageCount ?? 0)
  701. let pages = fileAttribute?.fetchSelectPages() ?? []
  702. if pages.isEmpty {
  703. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil))
  704. } else {
  705. let panel = NSOpenPanel()
  706. panel.canChooseFiles = false
  707. panel.canChooseDirectories = true
  708. panel.canCreateDirectories = true
  709. panel.beginSheetModal(for: self.view.window!) { result in
  710. if (result == .OK) {
  711. let outputURL = panel.urls.first!
  712. var tFolderPath = outputURL.path
  713. var index = 0
  714. var folderName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent
  715. if folderName == nil {
  716. folderName = KMLocalizedString("Untitled", nil)
  717. }
  718. var folderPath = "\(tFolderPath)/\(folderName ?? "")"
  719. //创建目录
  720. while (FileManager.default.fileExists(atPath: folderPath)) {
  721. index += 1
  722. folderPath = "\(tFolderPath)/\(folderName ?? "")_\(index)"
  723. // folderPath = [tFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld",folderName,index]];
  724. }
  725. tFolderPath = folderPath
  726. let result = try?FileManager.default.createDirectory(atPath: tFolderPath, withIntermediateDirectories: true)
  727. if (result == nil) {
  728. // if (![[NSFileManager defaultManager] createDirectoryAtPath:tFolderPath withIntermediateDirectories:YES attributes:nil error:nil]) {
  729. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  730. return
  731. }
  732. let vc = KMProgressWindowController()
  733. NSApp.beginSheet(vc.window!, modalFor: self.view.window!, modalDelegate: nil, didEnd: nil, contextInfo: nil)
  734. DispatchQueue.global().async {
  735. // NSArray * successArray = [self.pdfDocument splitByFileWithPages:fileAttribute folerPath:tFolderPath fileName:folderName];
  736. let successArray = self.pdfDocument?.splitByFileWithPages(fileAttribute!, folerPath: tFolderPath, fileName: folderName ?? "") ?? []
  737. DispatchQueue.main.async {
  738. if successArray.count > 0 {
  739. let filePath = successArray.first ?? ""
  740. let workSpace = NSWorkspace.shared
  741. workSpace.activateFileViewerSelecting([URL(fileURLWithPath: filePath)])
  742. } else {
  743. KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil))
  744. }
  745. NSApp.endSheet(vc.window!)
  746. vc.close()
  747. }
  748. }
  749. }
  750. }
  751. }
  752. } else{
  753. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  754. }
  755. }
  756. override func reverseAction() {
  757. if IAPProductsManager.default().isAvailableAllFunction() == false {
  758. let winC = KMPurchaseCompareWindowController.sharedInstance()
  759. winC?.kEventName = "Reading_Reverse_BuyNow"
  760. winC?.showWindow(nil)
  761. return
  762. }
  763. let cnt = self.thumbnailView.selectionIndexPaths.count
  764. if cnt < 2 {
  765. self._progressHUD(message: KMLocalizedString("No page selected. Please select at least two pages to organize."))
  766. return
  767. }
  768. self.trackEvent(type: .reverse)
  769. self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier)
  770. self.reverseMenuAction(sender: nil)
  771. }
  772. func showSplitWindow(callback: @escaping (KMPageEditSplitWindowController, KMPageEditSplitSettingModel)->Void) {
  773. let model = KMPageEditSplitSettingModel()
  774. model.documentURL = self.listView?.document.documentURL
  775. if let pagecnt = self.thumbnailView.document?.pageCount {
  776. model.pageCount = Int(pagecnt)
  777. }
  778. model.fileName = model.documentURL?.lastPathComponent ?? ""
  779. model.pathExtension = model.fileName?.components(separatedBy: ".").last
  780. if (self.isEmptySelection() == false) {
  781. model.type = 2
  782. model.pageRangeType = 2
  783. var selectedIndexs: Array<Int> = []
  784. for indexpath in self.thumbnailView.selectionIndexPaths {
  785. selectedIndexs.append(indexpath.item)
  786. }
  787. model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs)
  788. } else {
  789. model.type = 0
  790. }
  791. let windowController = KMPageEditSplitWindowController(model)
  792. self.km_beginSheet(windowC: windowController)
  793. windowController.itemClick = { [weak self] index, value in
  794. if (index == 1) { /// 取消
  795. self?.km_endSheet()
  796. return
  797. }
  798. guard let _windowC = self?.kmCurrentWindowC as? KMPageEditSplitWindowController else {
  799. self?.km_endSheet()
  800. return
  801. }
  802. callback(_windowC, model)
  803. }
  804. }
  805. private func _splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) {
  806. let outputModel = windowC.model as! KMPageEditSplitSettingModel
  807. DispatchQueue.main.async {
  808. let panel = NSOpenPanel()
  809. panel.canChooseFiles = false
  810. panel.canChooseDirectories = true
  811. panel.canCreateDirectories = true
  812. panel.beginSheetModal(for: NSWindow.currentWindow()) { response in
  813. if (response == .cancel) {
  814. return
  815. }
  816. let file_indexs = outputModel.getSplitIndexSets ?? []
  817. if (file_indexs.count <= 0) {
  818. return
  819. }
  820. DispatchQueue.main.async {
  821. self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: ""))
  822. self.progressC?.maxValue = Double(file_indexs.count)
  823. let _document = self.listView?.document
  824. let filePath = "\(panel.url!.path)/\(_document?.documentURL.deletingPathExtension().lastPathComponent ?? "")"
  825. let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath)
  826. // Swift.debugPrint(uniqueFilePath)
  827. if (!FileManager.default.fileExists(atPath: uniqueFilePath)) {
  828. try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true)
  829. }
  830. var filepaths: [String] = []
  831. for i in 0 ..< file_indexs.count {
  832. let indexs = file_indexs[i]
  833. if (indexs.isEmpty) {
  834. continue
  835. }
  836. let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1))
  837. filepaths.append(filepath)
  838. let newDocument = CPDFDocument()
  839. newDocument?.importPages(indexs, from: _document, at: 0)
  840. self.progressC?.increment(by: 1.0)
  841. newDocument?.write(to: URL(fileURLWithPath: filepath))
  842. }
  843. self.hiddenProgressWindow()
  844. self.km_endSheet()
  845. if let _urlString = filepaths.first?.deletingLastPathComponent {
  846. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)])
  847. }
  848. }
  849. }
  850. }
  851. }
  852. // MARK: Undo / Redo
  853. @objc private func reversePages(indexs: IndexSet) {
  854. if let doc = self.thumbnailView.document {
  855. KMThumbnailCache.shared.clearCache()
  856. // KMPageEditTools.reverse(doc, indexs
  857. // ) { result, error in
  858. // if (result) {
  859. // self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  860. //
  861. // self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  862. // }
  863. // }
  864. var theIdxs = indexs
  865. var res = false
  866. for i in 0 ..< indexs.count {
  867. guard let first = theIdxs.first else {
  868. break
  869. }
  870. guard let last = theIdxs.last else {
  871. break
  872. }
  873. if first == last {
  874. break
  875. }
  876. res = self.pdfDocument?.exchangePage(at: UInt(first), withPageAt: UInt(last)) ?? false
  877. if res {
  878. theIdxs.remove(first)
  879. theIdxs.remove(last)
  880. }
  881. }
  882. if res {
  883. self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true)
  884. self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs)
  885. }
  886. }
  887. }
  888. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  889. if (indexs.count <= 0) {
  890. return
  891. }
  892. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  893. // 插入位置偏移量
  894. var toIndexOffset: Int = 0
  895. // 需要移动的页面index数组
  896. var newPages: [CPDFPage] = []
  897. var currentPage: CPDFPage?
  898. var originalIndex = self.listViewCurrentIndex
  899. // 从后面往前删除
  900. for index in indexs.reversed() {
  901. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  902. if (newPage == nil) {
  903. continue
  904. }
  905. newPages.insert(newPage!, at: 0)
  906. self.pdfDocument?.removePage(at: UInt(index))
  907. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  908. toIndexOffset += 1
  909. }
  910. if (currentPage == nil) && (originalIndex == index) {
  911. currentPage = newPage
  912. }
  913. }
  914. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  915. toIndexOffset -= 1
  916. }
  917. let insertIndex = max(0, toIndex-toIndexOffset)
  918. var selectIndexs: IndexSet = []
  919. for (index, page) in newPages.enumerated() {
  920. self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  921. selectIndexs.insert(insertIndex+index)
  922. if (currentPage?.pageIndex() == page.pageIndex()) {
  923. // self._listViewCurrentIndex = insertIndex+index
  924. }
  925. }
  926. // 新增 undo
  927. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  928. target.clearSelectPages()
  929. target.dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  930. }
  931. KMThumbnailCache.shared.clearCache()
  932. // 刷新UI
  933. self.refreshUI()
  934. if (reversed == false) {
  935. self.selectPages(indexs: selectIndexs)
  936. }
  937. }
  938. @objc private func new_dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) {
  939. if (indexs.count <= 0) {
  940. return
  941. }
  942. self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex)
  943. // 插入位置偏移量
  944. var toIndexOffset: Int = 0
  945. // 需要移动的页面index数组
  946. var newPages: [CPDFPage] = []
  947. var currentPage: CPDFPage?
  948. var originalIndex = self.listViewCurrentIndex
  949. // 从后面往前删除
  950. for index in indexs.reversed() {
  951. let newPage = (self.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage
  952. if (newPage == nil) {
  953. continue
  954. }
  955. newPages.insert(newPage!, at: 0)
  956. // self.pdfDocument?.removePage(at: UInt(index))
  957. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  958. toIndexOffset += 1
  959. }
  960. if (currentPage == nil) && (originalIndex == index) {
  961. currentPage = newPage
  962. }
  963. }
  964. var after = false
  965. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  966. toIndexOffset -= 1
  967. after = true
  968. }
  969. let insertIndex = max(0, toIndex-toIndexOffset)
  970. var selectIndexs: IndexSet = []
  971. for (index, page) in newPages.enumerated() {
  972. // self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index))
  973. selectIndexs.insert(insertIndex+index)
  974. if (currentPage?.pageIndex() == page.pageIndex()) {
  975. // self._listViewCurrentIndex = insertIndex+index
  976. }
  977. // self.pdfDocument?.movePage(at: UInt(index), withPageAt: UInt(insertIndex+index))
  978. }
  979. var theToIndex = toIndex
  980. if indexs.count == 1 {
  981. theToIndex = insertIndex
  982. }
  983. if after {
  984. var offset = 0
  985. for index in indexs {
  986. self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(theToIndex))
  987. offset += 1
  988. }
  989. } else {
  990. var offset = 0
  991. for index in indexs.reversed() {
  992. self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(theToIndex))
  993. offset += 1
  994. }
  995. }
  996. // 新增 undo
  997. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  998. target.clearSelectPages()
  999. target.new_dragPages_reversed(indexs, toIndex, newPages, dp: dp)
  1000. }
  1001. KMThumbnailCache.shared.clearCache()
  1002. // 刷新UI
  1003. self.refreshUI()
  1004. if (reversed == false) {
  1005. self.selectPages(indexs: selectIndexs)
  1006. }
  1007. }
  1008. @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1009. if (indexs.count <= 0) {
  1010. return
  1011. }
  1012. // 插入位置偏移量
  1013. var toIndexOffset: Int = 0
  1014. for index in indexs {
  1015. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1016. toIndexOffset += 1
  1017. }
  1018. }
  1019. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1020. toIndexOffset -= 1
  1021. }
  1022. let insertIndex = max(0, toIndex-toIndexOffset)
  1023. // 需要移动的页面index数组
  1024. var datas: [Int] = []
  1025. for index in insertIndex ..< (insertIndex + indexs.count) {
  1026. datas.append(index)
  1027. }
  1028. // 从后面开始删除
  1029. for index in datas.reversed() {
  1030. self.pdfDocument?.removePage(at: UInt(index))
  1031. }
  1032. // 再插入到对应的位置
  1033. for (index,value) in indexs.enumerated() {
  1034. var page: CPDFPage?
  1035. if (index < pages.count) {
  1036. page = pages[index]
  1037. }
  1038. if (page != nil) {
  1039. self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1040. }
  1041. }
  1042. // 新增 undo
  1043. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1044. target.dragPages(indexs, toIndex, dp: dp, reversed: true)
  1045. }
  1046. // 刷新UI
  1047. self.refreshUI()
  1048. }
  1049. @objc private func new_dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) {
  1050. if (indexs.count <= 0) {
  1051. return
  1052. }
  1053. // 插入位置偏移量
  1054. var toIndexOffset: Int = 0
  1055. for index in indexs {
  1056. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1057. toIndexOffset += 1
  1058. }
  1059. }
  1060. var after = false
  1061. if (indexs.last! < toIndex && dp == .on) { // 往后拖拽
  1062. toIndexOffset -= 1
  1063. after = true
  1064. }
  1065. let insertIndex = max(0, toIndex-toIndexOffset)
  1066. // 需要移动的页面index数组
  1067. var datas: [Int] = []
  1068. for index in insertIndex ..< (insertIndex + indexs.count) {
  1069. datas.append(index)
  1070. }
  1071. // 从后面开始删除
  1072. for index in datas.reversed() {
  1073. // self.pdfDocument?.removePage(at: UInt(index))
  1074. }
  1075. // 再插入到对应的位置
  1076. for (index,value) in indexs.enumerated() {
  1077. var page: CPDFPage?
  1078. if (index < pages.count) {
  1079. page = pages[index]
  1080. }
  1081. if (page != nil) {
  1082. // self.pdfDocument?.insertPageObject(page!, at: UInt(value))
  1083. }
  1084. }
  1085. if after {
  1086. // var offset = 0
  1087. for (index,value) in indexs.enumerated() {
  1088. let idx = datas[index]
  1089. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1090. // offset += 1
  1091. }
  1092. // for index in datas.reversed() {
  1093. // self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(toIndex))
  1094. // offset += 1
  1095. // }
  1096. } else {
  1097. // var offset = 0
  1098. for (index,value) in indexs.reversed().enumerated() {
  1099. let idx = datas.reversed()[index]
  1100. self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value))
  1101. }
  1102. // for index in indexs {
  1103. // self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(toIndex))
  1104. // offset += 1
  1105. // }
  1106. }
  1107. // 新增 undo
  1108. self.kmUndoManager?.registerUndo(withTarget: self) { target in
  1109. target.new_dragPages(indexs, toIndex, dp: dp, reversed: true)
  1110. }
  1111. KMThumbnailCache.shared.clearCache()
  1112. // 刷新UI
  1113. self.refreshUI()
  1114. }
  1115. // MARK: topBar 事件
  1116. @objc func zoomOutButtonAction(sender: NSButton?) {
  1117. if (self.itemSize.width > self.defaultItemSize.width) {
  1118. return
  1119. }
  1120. if (self.itemSize.width < self.defaultItemSize.width) {
  1121. self.itemSize = self.defaultItemSize
  1122. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1123. self.itemSize = NSSize(width: self.defaultItemSize.width*2, height: self.defaultItemSize.height*2)
  1124. }
  1125. // self.toolBar.zoomInButton?.isEnabled = true
  1126. // if (self.itemSize.width > self.defaultItemSize.width) {
  1127. // sender?.isEnabled = false
  1128. // }
  1129. KMThumbnailCache.shared.clearCache()
  1130. self.pageEditThumbnailView.zoomOut()
  1131. }
  1132. @objc func zoomInButtonAction(sender: NSButton?) {
  1133. if (self.itemSize.width < self.defaultItemSize.width) {
  1134. return
  1135. }
  1136. if (self.itemSize.width > self.defaultItemSize.width) {
  1137. self.itemSize = self.defaultItemSize
  1138. } else if (self.itemSize.width == self.defaultItemSize.width) {
  1139. self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5)
  1140. }
  1141. // self.toolBar.zoomOutButton?.isEnabled = true
  1142. // if (self.itemSize.width < self.defaultItemSize.width) {
  1143. // sender?.isEnabled = false
  1144. // }
  1145. KMThumbnailCache.shared.clearCache()
  1146. self.pageEditThumbnailView.zoomIn()
  1147. }
  1148. // MARK: menu 菜单事件
  1149. override func menuNeedsUpdate(_ menu: NSMenu) {
  1150. // let row = self.thumbnailView.collectionView.selectionIndexes
  1151. // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil)
  1152. let point = self.view.window?.currentEvent?.locationInView(self.thumbnailView.collectionView) ?? .zero
  1153. let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point)
  1154. menu.removeAllItems()
  1155. if indexpaths == nil || indexpaths!.isEmpty { // 空白处点击
  1156. if KMThumbnailManager.manager.copyPages.isEmpty { // 不能粘贴
  1157. // if self.canPaste() {
  1158. return
  1159. }
  1160. let item_ = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pasteActonForEmpty), target: self)
  1161. // item_?.keyEquivalent = KMKeyEquivalent.paste
  1162. let repObj = self.thumbnailView.collectionView.km_indexPathForItem(at: point, nearest: true)
  1163. item_?.representedObject = repObj
  1164. return
  1165. }
  1166. super.menuNeedsUpdate(menu)
  1167. }
  1168. @objc func item_insertCustomPage(sender: NSMenuItem?) {
  1169. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1170. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1171. if self.kEventTag == 1 {
  1172. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1173. } else {
  1174. winC?.kEventName = "Reading_InsertBlankPage_BuyNow"
  1175. }
  1176. winC?.showWindow(nil)
  1177. return
  1178. }
  1179. guard let doc = self.pdfDocument else {
  1180. NSSound.beep()
  1181. return
  1182. }
  1183. let windowC = KMPDFEditInsertBlankPageWindow(document: doc)
  1184. windowC.currentPage = self.getSelecteIndex() + 1
  1185. windowC.insertLocation = 3
  1186. windowC.callback = { [weak self] pdfDoc, _, pages, insertI in
  1187. if pages != nil {
  1188. // mm 单位的大小
  1189. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  1190. self?.km_endSheet()
  1191. return
  1192. }
  1193. var pageSize = _winC.pageSize
  1194. let direction = windowC.pageRotation == 0 ? 0 : 1
  1195. if (direction == 0) { // 纵向
  1196. if (pageSize.width > pageSize.height) { // 需要交换
  1197. let tmp = pageSize.width
  1198. pageSize.width = pageSize.height
  1199. pageSize.height = tmp
  1200. } else {
  1201. // no things.
  1202. }
  1203. } else { // 横向
  1204. if (pageSize.width > pageSize.height) {
  1205. // no things.
  1206. } else { // 需要交换
  1207. let tmp = pageSize.width
  1208. pageSize.width = pageSize.height
  1209. pageSize.height = tmp
  1210. }
  1211. }
  1212. /// 插入位置
  1213. let document = CPDFDocument()
  1214. document?.insertPage(pageSize, at: 0)
  1215. if let page: CPDFPage = (document?.page(at: 0)) {
  1216. self?.insertPages(pages: [page], at: IndexSet(integer: insertI))
  1217. }
  1218. let ips: Set<IndexPath> = [IndexPath(item: insertI, section: 0)]
  1219. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1220. }
  1221. self?.km_endSheet()
  1222. }
  1223. self.km_beginSheet(windowC: windowC)
  1224. }
  1225. @objc func item_insertFromImage(sender: NSMenuItem?) {
  1226. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1227. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1228. if self.kEventTag == 1 {
  1229. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1230. } else {
  1231. winC?.kEventName = "Reading_InsertImage_BuyNow"
  1232. }
  1233. winC?.showWindow(nil)
  1234. return
  1235. }
  1236. let openPanel = NSOpenPanel()
  1237. openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  1238. openPanel.allowsMultipleSelection = true
  1239. openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
  1240. openPanel.canChooseDirectories = false
  1241. openPanel.allowsMultipleSelection = false
  1242. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1243. if result == NSApplication.ModalResponse.OK {
  1244. if let fileURL = openPanel.urls.first {
  1245. // self.choosePositionWindow {[weak self] index in
  1246. // /// 插入位置
  1247. if let imag = NSImage(contentsOfFile: fileURL.path ) {
  1248. let index = self.getInsertIndex() + 1
  1249. let document = CPDFDocument()
  1250. _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0)
  1251. if let page: CPDFPage = (document?.page(at: 0)) {
  1252. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1253. }
  1254. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1255. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1256. }
  1257. // }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void {
  1263. // guard let doc = self.pdfDocument else {
  1264. // NSSound.beep()
  1265. // return
  1266. // }
  1267. // let windowC = KMFileInsertPositionWindowController(document: doc)
  1268. // windowC.currentPage = self.getSelecteIndex() + 1
  1269. // windowC.insertLocation = 3
  1270. // windowC.callback = { [weak self] pdfDoc, _, insertI in
  1271. // if insertI >= 0 {
  1272. // if (completion != nil) {
  1273. // completion(insertI);
  1274. // }
  1275. // }
  1276. // self?.km_endSheet()
  1277. // }
  1278. // self.km_beginSheet(windowC: windowC)
  1279. }
  1280. @objc func item_insertFromClipboard(sender: NSMenuItem?) {
  1281. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1282. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1283. if self.kEventTag == 1 {
  1284. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1285. } else {
  1286. winC?.kEventName = "Reading_InsertClipboard_BuyNow"
  1287. }
  1288. winC?.showWindow(nil)
  1289. return
  1290. }
  1291. // self.choosePositionWindow {[weak self] index in
  1292. /// 插入位置
  1293. var error: NSError?
  1294. guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
  1295. return
  1296. }
  1297. let index = self.getInsertIndex() + 1
  1298. if let page: CPDFPage = (document.page(at: 0)) {
  1299. self.insertPages(pages: [page], at: IndexSet(integer: index))
  1300. }
  1301. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1302. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1303. // }
  1304. }
  1305. @objc func item_insertFromScanner(sender: NSMenuItem?) {
  1306. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1307. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1308. if self.kEventTag == 1 {
  1309. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1310. } else {
  1311. winC?.kEventName = "Reading_InsertSacnner_BuyNow"
  1312. }
  1313. winC?.showWindow(nil)
  1314. return
  1315. }
  1316. let vc = KMDeviceBrowserWindowController.shared
  1317. vc.type = .scanner
  1318. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1319. // self?.choosePositionWindow {[weak self] index in
  1320. /// 插入位置
  1321. if let imag = NSImage(contentsOfFile: url.path! ) {
  1322. let index = (self?.getInsertIndex())! + 1
  1323. let document = CPDFDocument()
  1324. _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0)
  1325. if let page: CPDFPage = (document?.page(at: 0)) {
  1326. self?.insertPages(pages: [page], at: IndexSet(integer: index))
  1327. }
  1328. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1329. self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1330. }
  1331. // }
  1332. vc.close()
  1333. }
  1334. vc.showWindow(NSApp.mainWindow)
  1335. }
  1336. func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
  1337. var document: CPDFDocument? = nil
  1338. var data: Data? = nil
  1339. if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
  1340. data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
  1341. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
  1342. data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
  1343. } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
  1344. data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
  1345. } else {
  1346. let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
  1347. let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
  1348. if images?.count ?? 0 > 0 {
  1349. data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
  1350. } else if strings?.count ?? 0 > 0 {
  1351. data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
  1352. }
  1353. }
  1354. if let data = data {
  1355. document = CPDFDocument(data: data)
  1356. } else if let outError = outError {
  1357. outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
  1358. }
  1359. return document
  1360. }
  1361. func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
  1362. guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
  1363. let pdfData = NSMutableData(capacity: tiffData.count)
  1364. let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
  1365. var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
  1366. let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
  1367. ctxt!.beginPDFPage(nil)
  1368. ctxt!.draw(cgImage, in: rect)
  1369. ctxt!.endPDFPage()
  1370. ctxt!.closePDF()
  1371. return pdfData as? Data
  1372. }
  1373. func extractSelectPageItemAction() {
  1374. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1375. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1376. if self.kEventTag == 1 {
  1377. winC?.kEventName = "Onbrd_EditPage_BuyNow"
  1378. } else {
  1379. winC?.kEventName = "Reading_Extract_BuyNow"
  1380. }
  1381. winC?.showWindow(nil)
  1382. return
  1383. }
  1384. let indexs = self.thumbnailView.selectionIndexPaths
  1385. if indexs.isEmpty {
  1386. self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage))
  1387. return
  1388. }
  1389. self.extractPages(indexpaths: indexs, oneDocumentPerPage: false) { result, params in }
  1390. }
  1391. // MARK: toolBar 菜单事件
  1392. @objc func reverseMenuAction(sender: AnyObject?) {
  1393. let selectedIndexs = self.thumbnailView.selectionIndexPaths
  1394. if (selectedIndexs.count < 2 ) {
  1395. let alertView = CustomAlertView.alertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), fromView: self.thumbnailView, withStyle: .blue)
  1396. alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1397. alertView?.layer?.cornerRadius = 4
  1398. return
  1399. }
  1400. self.reversePages(indexs: self.indexpathsToIndexs(indexpaths: selectedIndexs))
  1401. self.dealPdfDocumentDidEditCallback(type: .reverse)
  1402. }
  1403. override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? {
  1404. var item_: NSMenuItem?
  1405. if (item.sel == KMPDFThumbViewMenu.insertSelector) {
  1406. item_ = menu.addItem(withTitle: NSLocalizedString("Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self)
  1407. } else if (item.sel == KMPDFThumbViewMenu.splitSelector) {
  1408. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1409. item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self)
  1410. }
  1411. } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) {
  1412. if (self.thumbnailView.selectionIndexPaths.count > 1) {
  1413. item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self)
  1414. }
  1415. } else {
  1416. return super.addMenuItem(menu: menu, item: item)
  1417. }
  1418. return item_
  1419. }
  1420. // MARK: - Zoom Methods
  1421. @IBAction func buttonClicked_Bigger(_ sender: AnyObject?) {
  1422. // if (self.thumbnailView.thumbnailSize.width == 100.) {
  1423. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1424. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1425. // self.thumbnailView.thumbnailSize = CGSizeMake(400, 400);
  1426. // }
  1427. self.zoomOutButtonAction(sender: sender as? NSButton)
  1428. }
  1429. @IBAction func buttonClicked_Smaller(_ sender: AnyObject?) {
  1430. // if (self.thumbnailView.thumbnailSize.width == 400.) {
  1431. // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200);
  1432. // } else if (self.thumbnailView.thumbnailSize.width == 200.) {
  1433. // self.thumbnailView.thumbnailSize = CGSizeMake(100, 100);
  1434. // }
  1435. self.zoomInButtonAction(sender: sender as? NSButton)
  1436. }
  1437. override func mouseMoved(with event: NSEvent) {
  1438. super.mouseMoved(with: event)
  1439. self.view.window?.mouseMoved(with: event)
  1440. }
  1441. }
  1442. extension KMPDFEditViewController {
  1443. //MARK: menu Action
  1444. @objc func insertPageItemAction(menu:NSMenuItem) {
  1445. if (menu.tag == 0) {
  1446. self.insertBlankPageAction()
  1447. } else if (menu.tag == 1) {
  1448. self.item_insertCustomPage(sender: nil)
  1449. } else if (menu.tag == 2) {
  1450. self.insertFileAction()
  1451. }
  1452. }
  1453. @objc func sharePageItemAction(menu:NSMenuItem) {
  1454. guard let item = menu.parent else {
  1455. NSSound.beep()
  1456. return
  1457. }
  1458. let index = (item.representedObject as? IndexSet)?.first ?? -1
  1459. if Int(index) >= 0 {
  1460. let doucument = self.pdfDocument
  1461. // let page = doucument.page(at: UInt(index))
  1462. let filename : String = doucument?.documentURL.lastPathComponent ?? ""
  1463. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
  1464. try? FileManager.default.removeItem(atPath: folderPath)
  1465. let pdfdocument = CPDFDocument()
  1466. let ret = pdfdocument?.importPages((item.representedObject as? IndexSet) ?? [], from: self.thumbnailView.document, at: 0) ?? false
  1467. let url = URL(fileURLWithPath: folderPath)
  1468. if ret {
  1469. let success = pdfdocument?.write(to:url) ?? false
  1470. // if success {
  1471. // let workspace = NSWorkspace.shared
  1472. // workspace.activateFileViewerSelecting([url])
  1473. // }
  1474. }
  1475. let represent = menu.representedObject as? NSSharingService
  1476. represent?.perform(withItems: [url])
  1477. }
  1478. }
  1479. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  1480. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  1481. self.refreshUIForKeepSelecteds()
  1482. }
  1483. @objc func printItemAction(menu:NSMenuItem) {
  1484. var datas: [Int] = []
  1485. for indexpath in self.thumbnailView.selectionIndexPaths {
  1486. datas.append(indexpath.item)
  1487. }
  1488. guard let callback = self.itemClick else {
  1489. return
  1490. }
  1491. callback(2, datas.sorted())
  1492. }
  1493. override func menuItemAction_extract(_ sender: Any?) {
  1494. self.extractSelectPageItemAction()
  1495. }
  1496. }
  1497. extension KMPDFEditViewController {
  1498. override func menuItemAction_print(_ sender: Any?) {
  1499. if let item = sender as? NSMenuItem {
  1500. self.printItemAction(menu: item)
  1501. }
  1502. }
  1503. override func menuItemAction_showPageSize(_ sender: Any?) {
  1504. if let item = sender as? NSMenuItem {
  1505. self.showPageSizeItemAction(menu: item)
  1506. }
  1507. }
  1508. override func menuItemAction_share(_ sender: Any?) {
  1509. if let item = sender as? NSMenuItem {
  1510. self.sharePageItemAction(menu: item)
  1511. }
  1512. }
  1513. }
  1514. // MARK: - KMSelectPopButtonDelegate
  1515. extension KMPDFEditViewController {
  1516. func km_comboBoxSelectionDidChange(_ obj: KMPageRange) {
  1517. self.pageIsUpdate = false
  1518. var indexpaths: Set<IndexPath> = []
  1519. let type: KMPageRange? = obj
  1520. let pageCnt = self.pdfDocument?.pageCount ?? 0
  1521. for i in 0 ..< pageCnt {
  1522. if (type == .all) {
  1523. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1524. } else if (type == .odd) {
  1525. if (i % 2 == 1) {
  1526. continue
  1527. }
  1528. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1529. } else if (type == .even) {
  1530. if (i % 2 == 0) {
  1531. continue
  1532. }
  1533. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1534. } else if (type == .horizontal) {
  1535. let page = self.pdfDocument?.page(at: i)
  1536. guard let isVertical = page?.isVertical(), !isVertical else {
  1537. continue
  1538. }
  1539. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1540. } else if (type == .vertical) {
  1541. let page = self.pdfDocument?.page(at: i)
  1542. guard let isHorizontal = page?.isHorizontal(), !isHorizontal else {
  1543. continue
  1544. }
  1545. indexpaths.insert(IndexPath(item: Int(i), section: 0))
  1546. }
  1547. }
  1548. if (type == .custom) {
  1549. let windowC = KMPDFEditPageRangeWindowController()
  1550. windowC.pdfDocument = self.pdfDocument
  1551. windowC.pageSelectCallBack = { [weak self] pagesArray in
  1552. var indexpaths = Set<IndexPath>()
  1553. for page in pagesArray {
  1554. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1555. }
  1556. self?.km_endSheet()
  1557. self?.selectPages(indexpaths: indexpaths)
  1558. self?.thumbnailView.collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom)
  1559. }
  1560. self.km_beginSheet(windowC: windowC)
  1561. } else {
  1562. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1563. }
  1564. }
  1565. func km_controlTextDidEndEditing(_ obj: KMDesignSelect) {
  1566. self.view.window?.makeFirstResponder(self)
  1567. for index in 0 ..< obj.numberOfItems {
  1568. if (obj.items[index] == obj.stringValue) {
  1569. return
  1570. }
  1571. }
  1572. let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView?.stringValue ?? "", pageCount: Int((self.listView?.document.pageCount) ?? 0))
  1573. if (pages.isEmpty) {
  1574. let alert = NSAlert()
  1575. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1576. alert.runModal()
  1577. self.toolBar.setPageRangeString("")
  1578. DispatchQueue.main.async {
  1579. self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField)
  1580. }
  1581. return
  1582. }
  1583. var indexpaths: Set<IndexPath> = []
  1584. for page in pages {
  1585. if (page >= 1) {
  1586. indexpaths.insert(IndexPath(item: page-1, section: 0))
  1587. }
  1588. }
  1589. self.pageIsUpdate = false
  1590. self.pageEditThumbnailView.selectPages(at: indexpaths)
  1591. }
  1592. }
  1593. // MARK: -
  1594. // MARK: KMThumbnailViewDelegate
  1595. extension KMPDFEditViewController: KMThumbnailViewDelegate {
  1596. func thumbnailView(thumbanView: KMThumbnailView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
  1597. return IAPProductsManager.default().isAvailableAllFunction()
  1598. }
  1599. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  1600. return true
  1601. }
  1602. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  1603. self.km_add_file_multi(fileUrls: files) { index, params in
  1604. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  1605. return
  1606. }
  1607. let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  1608. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  1609. if (_fileUrl!.path.isPDFValid() == false) {
  1610. let alert = NSAlert()
  1611. alert.alertStyle = .critical
  1612. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1613. alert.runModal()
  1614. }
  1615. }
  1616. } completionBlock: { [weak self] documents in
  1617. var insertIndex: Int = indexpath.item
  1618. var pages: Array<CPDFPage> = []
  1619. var indexs = IndexSet()
  1620. self?.model.insertedDocumentSet.formUnion(documents)
  1621. for document in documents {
  1622. for i in 0 ..< document.pageCount {
  1623. if let page = document.page(at: i) {
  1624. pages.append(page)
  1625. indexs.insert(insertIndex)
  1626. insertIndex += 1
  1627. }
  1628. }
  1629. }
  1630. self?.insertPages(pages: pages, at: indexs)
  1631. }
  1632. }
  1633. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  1634. let toIndex = max(0, indexpath.item)
  1635. var indexs = IndexSet()
  1636. for indexpath in dragedIndexPaths {
  1637. indexs.insert(indexpath.item)
  1638. }
  1639. var dp = NSCollectionView.DropOperation.on
  1640. if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation {
  1641. dp = _dp
  1642. }
  1643. self.new_dragPages(indexs, toIndex, dp: dp)
  1644. if (dragedIndexPaths.count > 0) {
  1645. self.dealPdfDocumentDidEditCallback()
  1646. }
  1647. }
  1648. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  1649. // if (!self.canPayFunction) {
  1650. // return false
  1651. // }
  1652. return true
  1653. }
  1654. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  1655. return NSEdgeInsets(top: 6, left: 40, bottom: 0, right: 40)
  1656. }
  1657. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  1658. self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155)
  1659. if (!self.thumbnailView.isShowPageSize) {
  1660. return NSMakeSize(self.itemSize.width, self.itemSize.height+26)
  1661. }
  1662. return self.itemSize
  1663. }
  1664. func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int {
  1665. if let count = self.pdfDocument?.pageCount {
  1666. return Int(count)
  1667. }
  1668. return 0
  1669. }
  1670. func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem {
  1671. let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.km.dequeueReusableCell(for: indexpath)
  1672. cellView.isShowPageSize = self.thumbnailView.isShowPageSize
  1673. if let data = self.pdfDocument?.page(at: UInt(indexpath.item)) {
  1674. cellView.setPage(page: data)
  1675. }
  1676. let bks = self.listView?.document.bookmarks()
  1677. var hasBookmark = false
  1678. for bk in bks ?? [] {
  1679. if indexpath.item == bk.pageIndex {
  1680. hasBookmark = true
  1681. break
  1682. }
  1683. }
  1684. cellView.bkIcon.isHidden = !hasBookmark
  1685. cellView.doubleClickAction = { [weak self] _ in
  1686. guard let callback = self?.itemClick else {
  1687. return
  1688. }
  1689. callback(1, indexpath.item)
  1690. }
  1691. cellView.mouseDownAction = { [unowned self] _ in
  1692. let selectionIndexPaths = self.thumbnailView.selectionIndexPaths
  1693. if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) {
  1694. return
  1695. }
  1696. self.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1697. }
  1698. cellView.rightMouseDownAction = { [weak self] _ in
  1699. self?.selectPages(indexs: IndexSet.init(integer: indexpath.item))
  1700. }
  1701. return cellView
  1702. }
  1703. }
  1704. // MARK: - 系统菜单栏
  1705. extension KMPDFEditViewController {
  1706. override func undo(_ sender: Any?) {
  1707. super.undo(sender)
  1708. self.km_becomeFirstResponder()
  1709. }
  1710. override func redo(_ sender: Any?) {
  1711. super.redo(sender)
  1712. self.km_becomeFirstResponder()
  1713. }
  1714. }
  1715. // MARK: - KMExtensions
  1716. extension KMPDFEditViewController {
  1717. override func deleteAfter(indexpaths: Set<IndexPath>) {
  1718. self.clearSelectPages()
  1719. self.km_becomeFirstResponder()
  1720. }
  1721. override func copyAfter(indexpaths: Set<IndexPath>) {
  1722. self.km_becomeFirstResponder()
  1723. }
  1724. override func pasteAfter(at index: Int) {
  1725. self.km_becomeFirstResponder()
  1726. }
  1727. override func cutAfter(indexpaths: Set<IndexPath>) {
  1728. self.clearSelectPages()
  1729. self.km_becomeFirstResponder()
  1730. }
  1731. override func leftRotateAfter(indexpaths: Set<IndexPath>) {
  1732. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1733. self.km_becomeFirstResponder()
  1734. }
  1735. override func rightRotateAfter(indexpaths: Set<IndexPath>) {
  1736. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document)
  1737. self.km_becomeFirstResponder()
  1738. }
  1739. override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) {
  1740. var indexpaths = Set<IndexPath>()
  1741. var insertIndex = index
  1742. for _ in pages {
  1743. indexpaths.insert(IndexPath(item: insertIndex, section: 0))
  1744. insertIndex += 1
  1745. }
  1746. self.thumbnailView.selectionIndexPaths = indexpaths
  1747. self.dealPdfDocumentDidEditCallback(type: .replace)
  1748. }
  1749. override func insertBlankPageAfter(size: NSSize, at index: Int) {
  1750. self.selectPages(indexs: IndexSet(integer: index))
  1751. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  1752. self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  1753. self.dealPdfDocumentDidEditCallback(type: .insert)
  1754. }
  1755. func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) {
  1756. if (indexs.isEmpty) {
  1757. return
  1758. }
  1759. // listView 当前页面 被拖拽
  1760. if (indexs.contains(self._listViewCurrentIndex)) {
  1761. // let idx = indexs.firstIndex(of: self._listViewCurrentIndex)
  1762. var idx: Int = 0
  1763. for index in indexs {
  1764. if (index == self._listViewCurrentIndex) {
  1765. break
  1766. }
  1767. idx += 1
  1768. }
  1769. // 插入位置偏移量
  1770. var toIndexOffset: Int = 0
  1771. // 从后面往前删除
  1772. for index in indexs.reversed() {
  1773. let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage
  1774. if (newPage == nil) {
  1775. continue
  1776. }
  1777. if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex
  1778. toIndexOffset += 1
  1779. }
  1780. }
  1781. if (indexs.last! < toIndex) { // 往后拖拽
  1782. toIndexOffset -= 1
  1783. }
  1784. let insertIndex = max(0, toIndex-toIndexOffset)
  1785. self._listViewCurrentIndex = insertIndex+idx
  1786. } else {
  1787. var forwardCnt = 0
  1788. var nextCnt = 0
  1789. for index in indexs {
  1790. if (index > self._listViewCurrentIndex) {
  1791. nextCnt += 1
  1792. } else {
  1793. forwardCnt += 1
  1794. }
  1795. }
  1796. if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式
  1797. self._listViewCurrentIndex += nextCnt
  1798. } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式
  1799. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1800. } else { // 插入到目标位置 [跟插入到目标后面一样]
  1801. self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt)
  1802. }
  1803. }
  1804. }
  1805. }
  1806. // MARK: - Analytics (埋点)
  1807. extension KMPDFEditViewController {
  1808. func trackEvent(type: KMPageEditType, index: Int = 0) -> Void {
  1809. if (type == .insert) {
  1810. if index == 0 {
  1811. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [
  1812. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1813. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1814. } else if index == KMPageEditType.insert_blank_page || index == KMPageEditType.insert_custom_page {
  1815. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertBlankPage"], platform: .AppCenter)
  1816. } else if index == KMPageEditType.insert_files {
  1817. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertPDF"], platform: .AppCenter)
  1818. } else if index == KMPageEditType.insert_fromImage {
  1819. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertImage"], platform: .AppCenter)
  1820. } else if index == KMPageEditType.insert_fromClipboard {
  1821. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertClipboard"], platform: .AppCenter)
  1822. } else if index == KMPageEditType.insert_fromScanner {
  1823. self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertScanner"], platform: .AppCenter)
  1824. }
  1825. } else if (type == .extract) {
  1826. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [
  1827. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1828. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1829. } else if (type == .leftRotate || type == .rightRotate) {
  1830. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [
  1831. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1832. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1833. } else if (type == .replace) {
  1834. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [
  1835. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1836. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1837. } else if (type == .split) {
  1838. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [
  1839. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1840. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1841. } else if (type == .reverse) {
  1842. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [
  1843. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1844. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1845. } else if (type == .delete) {
  1846. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [
  1847. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1848. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1849. }
  1850. }
  1851. func trackEvent_copy() -> Void {
  1852. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [
  1853. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit,
  1854. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  1855. }
  1856. }