KMLeftSideViewController.swift 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. @objc protocol KMLeftSideViewControllerDelegate {
  9. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  10. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  11. @objc optional func searchAction(searchString:String, isCase:Bool)
  12. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  13. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  14. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  15. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  16. @objc optional func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?)
  17. }
  18. extension KMLeftSideViewController.Key {
  19. static let disableTableToolTipsKey = "SKDisableTableToolTips"
  20. }
  21. class KMLeftSideViewController: KMSideViewController {
  22. @IBOutlet var segmentedControl: KMSegmentedControl!
  23. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  24. @IBOutlet var tocOutlineView: KMTocOutlineView!
  25. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  26. @IBOutlet var findTableView: KMBotaTableView!
  27. @IBOutlet var groupedFindTableView: KMBotaTableView!
  28. @IBOutlet var snapshotTableView: KMBotaTableView!
  29. @IBOutlet weak var leftListView: NSView!
  30. @IBOutlet var searchViewController: KMBotaSearchViewController!
  31. @IBOutlet weak var toolButtonBox: NSBox!
  32. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  33. @IBOutlet weak var snapshotNormalView: NSView!
  34. @IBOutlet weak var snapshotLabel: NSTextField!
  35. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  36. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  37. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  38. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  39. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  40. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  41. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  42. @IBOutlet weak var snapshotDoneButton: NSButton!
  43. @IBOutlet weak var outlineView: NSView!
  44. @IBOutlet weak var outlineMoreButton: NSButton!
  45. @IBOutlet weak var outlineAddButton: NSButton!
  46. @IBOutlet weak var outlineSearchButton: NSButton!
  47. @IBOutlet weak var outlineLabel: NSTextField!
  48. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  49. @IBOutlet weak var outlineDoneButton: NSButton!
  50. @IBOutlet weak var noteView: NSView!
  51. @IBOutlet weak var noteMoreButton: NSButton!
  52. @IBOutlet weak var noteFilterButton: NSButton!
  53. @IBOutlet weak var noteSearchButton: NSButton!
  54. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  55. @IBOutlet weak var noteTitleLabel: NSTextField!
  56. @IBOutlet weak var noteHeaderView: NSView!
  57. @IBOutlet weak var sortTypeBox: KMBox!
  58. @IBOutlet weak var sortTypeLabel: NSTextField!
  59. @IBOutlet weak var noteSortButton: NSButton!
  60. @IBOutlet weak var noteDoneButton: NSButton!
  61. @IBOutlet weak var thumbnailView: NSView!
  62. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  63. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  64. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  65. @IBOutlet weak var emptySearchBox: NSBox!
  66. @IBOutlet weak var emptySearchLabel: NSTextField!
  67. var stopRepeatLoad: Bool = false
  68. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  69. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  70. vc.view.wantsLayer = true
  71. return vc
  72. }()
  73. lazy var leftView: KMBotaLeftView = {
  74. let view = KMBotaLeftView()
  75. return view
  76. }()
  77. static let kMinSidePaneWidth: CGFloat = 270
  78. static let kTinySize: Float = 32.0
  79. static let kSmallSize: Float = 64.0
  80. static let kLargeSize: Float = 128.0
  81. static let kHugeSize: Float = 256.0
  82. static let kFudgeSize: Float = 0.1
  83. static let kOutlineRootBookmarkItem = "Bookmarks"
  84. var isFirst = false //打开阅读页初始化
  85. var type : KMLeftMethodMode = KMLeftMethodMode()
  86. var isShowPanel : Bool = false
  87. weak var delegate: KMLeftSideViewControllerDelegate?
  88. let noteColumnId = NSUserInterfaceItemIdentifier(rawValue: "note")
  89. let authorColumnId = NSUserInterfaceItemIdentifier(rawValue: "author")
  90. struct Key {}
  91. var mwcFlags: MwcFlags = MwcFlags()
  92. let scalingIncrement: Float = 0.1
  93. var filterButtonLayer: NSView?
  94. var moreButtonLayer: KMButtonLayer?
  95. // 缩略图
  96. var thumbnails: [KMThumbnail] = []
  97. var isDisplayPageSize = false
  98. var thumbnailCacheSize: CGFloat = 32 * 3
  99. var updatingThumbnailSelection = false
  100. // 大纲
  101. var isSearchOutlineMode = false
  102. var outlineIgnoreCaseFlag = false
  103. var tocType: KMFoldType = .none
  104. var renamePDFOutline: CPDFOutline?
  105. var renamePDFOutlineTextField: NSTextField?
  106. private var _dragPDFOutline: CPDFOutline?
  107. var updatingOutlineSelection = false
  108. // 注释
  109. var noteTypeDict: [String : Any] = [:]
  110. private var _noteSortType: KMNoteSortType = .none
  111. var noteSortType: KMNoteSortType {
  112. get {
  113. return self._noteSortType
  114. }
  115. set {
  116. self._noteSortType = newValue
  117. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  118. }
  119. }
  120. var isAscendSort = false {
  121. didSet {
  122. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  123. }
  124. }
  125. var isRenameNoteOutline = false
  126. // 所有注释
  127. var allAnnotations: [CPDFAnnotation] = []
  128. // 注释搜索模式标记
  129. var noteSearchMode = false
  130. // 注释搜索数组
  131. var noteSearchArray: [KMBotaAnnotationModel] = []
  132. // 注释搜索 忽略大小写标识
  133. var caseInsensitiveNoteSearch = false
  134. // 注释列表数据源
  135. var annoListModel: KMAnnotationListModel?
  136. var editNoteTextField: NSTextField?
  137. weak var editNote: CPDFAnnotation?
  138. // 快照
  139. var snapshotCacheSize: CGFloat = 32 * 3
  140. var isSearchSnapshotMode = false
  141. var snapshots: [KMSnapshotModel] = []
  142. var dirtySnapshots: [KMSnapshotWindowController] = []
  143. var searchSnapshots: [KMSnapshotModel] = []
  144. var dataUpdating = false
  145. // 搜索
  146. private var _findState: KMFindState = .none
  147. var findState: KMFindState {
  148. get {
  149. return self._findState
  150. }
  151. set {
  152. if self._findState != newValue {
  153. self._findState = newValue
  154. self.displayFindState()
  155. if self._findState == .content {
  156. self.search(self.searchField)
  157. } else if self.findState == .note {
  158. self.searchNotes(nil)
  159. } else if self.findState == .snapshot {
  160. self.searchNotes(self.searchField)
  161. }
  162. }
  163. }
  164. }
  165. var searchResults : [KMSearchMode] = [] {
  166. didSet {
  167. self.updataLeftSideFindView()
  168. }
  169. }
  170. var groupSearchResults: [KMSearchMode] = []
  171. var findPaneState: KMFindPaneState = .singular
  172. var searchResultIndex: Int = 0
  173. var leftMargin: CGFloat = 0
  174. private var _copysPages: [CPDFPage] = []
  175. var copyPages: [CPDFPage] {
  176. get {
  177. return self._copysPages
  178. }
  179. }
  180. var dragIn = false
  181. let model = KMBotaModel()
  182. private let KPDFThumbnailDoucumentURLForDraggedTypes = NSPasteboard.PasteboardType("KPDFThumbnailDoucumentURLForDraggedTypes")
  183. private var deletePages_ = Set<CPDFPage>()
  184. let userFbHanddler = KMUserFeekbackHanddler()
  185. deinit {
  186. KMPrint("KMLeftSideViewController deinit.")
  187. NotificationCenter.default.removeObserver(self)
  188. DistributedNotificationCenter.default().removeObserver(self)
  189. }
  190. override var nibName: NSNib.Name? {
  191. return "LeftSideView"
  192. }
  193. convenience init(type : KMLeftMethodMode) {
  194. self.init()
  195. self.type = type
  196. }
  197. override func viewDidLoad() {
  198. super.viewDidLoad()
  199. self.reloadThumbnailSize()
  200. self.reloadSnapshotSize()
  201. }
  202. func showPanelView(show: Bool) {
  203. self.isShowPanel = show
  204. if show {
  205. self.leftView.segmentedControl.selectedSegment = 0
  206. } else {
  207. self.leftView.segmentedControl.selectedSegment = UInt8.max
  208. self.type.methodType = .None
  209. self.delegate?.controlStateChange?(self, show: false)
  210. }
  211. }
  212. func refreshMethodType(methodType: BotaType) {
  213. let newType = KMLeftMethodMode()
  214. var show = true
  215. if self.type.methodType != methodType {
  216. newType.methodType = methodType
  217. }
  218. if self.type.methodType == methodType {
  219. show = false
  220. } else if methodType == .None {
  221. show = false
  222. }
  223. self.type = newType;
  224. self.delegate?.controlStateChange?(self,show:show)
  225. }
  226. override func loadView() {
  227. super.loadView()
  228. self.initSubView()
  229. self.initDefalutValue()
  230. self.searchViewController.loadView()
  231. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  232. self.searchField = self.searchViewController.searchField
  233. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  234. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  235. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  236. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  237. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  238. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  239. self.searchViewController.segmentedControl.selectedSegment = 0
  240. self.searchViewController.segmentedControl.block = { [weak self] segIndex in
  241. if segIndex == 0 {
  242. self?.findPaneState = .singular
  243. self?.displayFindViewAnimating(false)
  244. } else {
  245. self?.findPaneState = .grouped
  246. self?.displayGroupedFindViewAnimating(false)
  247. }
  248. }
  249. self.leftView.helpButton.coverAction = { [weak self] button, action in
  250. if action == .enter {
  251. self?.userFbHanddler.showUserFbPopView(sender: button)
  252. }
  253. }
  254. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  255. self.toolButtonBox.isHidden = false
  256. self.toolButtonBoxLayoutConstraint.constant = 40.0
  257. if (segIndex == 0) {
  258. if self.type.methodType == .Thumbnail {
  259. self.leftView.segmentedControl.selectedSegment = UInt8.max
  260. self.refreshMethodType(methodType: .None)
  261. return
  262. }
  263. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Thumbnail"])
  264. self.refreshMethodType(methodType: .Thumbnail)
  265. DispatchQueue.main.async {
  266. self.toolButtonBox.contentView = self.thumbnailView
  267. self.displayThumbnailViewAnimating(false)
  268. }
  269. } else if (segIndex == 1) {
  270. if self.type.methodType == .Outline {
  271. self.leftView.segmentedControl.selectedSegment = UInt8.max
  272. self.refreshMethodType(methodType: .None)
  273. return
  274. }
  275. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Outline"])
  276. self.refreshMethodType(methodType: .Outline)
  277. DispatchQueue.main.async {
  278. self.toolButtonBox.contentView = self.outlineView
  279. self.displayTocViewAnimating(false)
  280. }
  281. } else if (segIndex == 2) {
  282. if self.type.methodType == .Annotation {
  283. self.leftView.segmentedControl.selectedSegment = UInt8.max
  284. self.refreshMethodType(methodType: .None)
  285. return
  286. }
  287. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Annotation"])
  288. self.refreshMethodType(methodType: .Annotation)
  289. DispatchQueue.main.async {
  290. self.toolButtonBox.contentView = self.noteView
  291. self.displayNoteViewAnimating(false)
  292. }
  293. } else if (segIndex == 3) {
  294. if self.type.methodType == .snapshot {
  295. self.leftView.segmentedControl.selectedSegment = UInt8.max
  296. self.refreshMethodType(methodType: .None)
  297. return
  298. }
  299. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Snapshot"])
  300. self.refreshMethodType(methodType: .snapshot)
  301. self.toolButtonBox.contentView = self.snapshotNormalView
  302. self.updateSnapshotFilterPredicate()
  303. self.displaySnapshotViewAnimating(false)
  304. self.updataLeftSideSnapView()
  305. } else if (segIndex == 4) {
  306. if self.type.methodType == .Search {
  307. self.leftView.segmentedControl.selectedSegment = UInt8.max
  308. self.refreshMethodType(methodType: .None)
  309. return
  310. }
  311. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Search"])
  312. self.refreshMethodType(methodType: .Search)
  313. DispatchQueue.main.async {
  314. self.toolButtonBox.isHidden = true
  315. self.toolButtonBoxLayoutConstraint.constant = 0
  316. self.displayFindViewAnimating(false)
  317. }
  318. }
  319. }
  320. let menu = NSMenu()
  321. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  322. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  323. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  324. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  325. self.searchField.action = #selector(search)
  326. self.searchField.target = self
  327. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  328. // //支持拖拽的文字类型
  329. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  330. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  331. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  332. if KMDataManager.ud_bool(forKey: Self.Key.disableTableToolTipsKey) == false {
  333. self.tocOutlineView.hasImageToolTips = true
  334. self.findTableView.hasImageToolTips = true
  335. self.groupedFindTableView.hasImageToolTips = true
  336. }
  337. self._updateViewColor()
  338. }
  339. func initSubView() {
  340. self.view.addSubview(self.leftView)
  341. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  342. self.leftView.autoresizingMask = [.height]
  343. self.thumb_initSubViews()
  344. self.outline_initSubViews()
  345. self.note_initSubViews()
  346. self.snapshot_initSubViews()
  347. self.search_initSubViews()
  348. }
  349. func initDefalutValue() {
  350. self.view.wantsLayer = true
  351. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  352. self.leftView.wantsLayer = true
  353. self.leftView.layer?.backgroundColor = .white
  354. self.leftListView.wantsLayer = true
  355. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  356. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  357. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  358. self.emptySearchBox.isHidden = true
  359. self.thumb_initDefalutValue()
  360. self.outline_initDefalutValue()
  361. self.note_initDefalutValue()
  362. self.snapshot_initDefalutValue()
  363. self.search_initDefalutValue()
  364. }
  365. func displayThumbnailViewAnimating(_ animate: Bool) {
  366. if let enclosingScrollView = self.thumbnailTableView.enclosingScrollView {
  367. self.replaceSideView(enclosingScrollView, animate: animate)
  368. }
  369. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  370. frame.origin.y = 0
  371. frame.origin.x = self.leftMargin
  372. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  373. self.thumbnailTableView.enclosingScrollView?.frame = frame
  374. self.resetThumbnails()
  375. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  376. frame.origin.y = 0
  377. frame.origin.x = self.leftMargin
  378. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  379. self.noteOutlineView.enclosingScrollView?.frame = frame
  380. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  381. frame.origin.y = 0
  382. frame.origin.x = self.leftMargin
  383. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  384. self.snapshotTableView.enclosingScrollView?.frame = frame
  385. self.updateThumbnailSelection()
  386. }
  387. func displayFindViewAnimating(_ animate: Bool) {
  388. self.replaceSideView(self.searchViewController.view, animate: animate)
  389. if (self.findState != .content) {
  390. self.findState = .content
  391. } else {
  392. self.displayFindState()
  393. }
  394. var frame = self.searchViewController.view.frame
  395. frame.origin.y = 0
  396. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  397. self.searchViewController.view.frame = frame
  398. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  399. frame.origin.y = 0
  400. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  401. self.noteOutlineView.enclosingScrollView?.frame = frame
  402. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  403. frame.origin.y = 0
  404. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  405. self.snapshotTableView.enclosingScrollView?.frame = frame
  406. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  407. self.updataLeftSideSnapView()
  408. }
  409. func displayFindState() {
  410. if (self.findState == .content) {
  411. self.displayFind()
  412. } else if (self.findState == .note) {
  413. self.displayNoteFind()
  414. } else if (self.findState == .snapshot) {
  415. self.displaySnapshotFind()
  416. }
  417. }
  418. func updataLeftSideFindView() {
  419. if (self.findState != .content) {
  420. return
  421. }
  422. if (self.searchResults.count > 0) {
  423. self.searchViewController.emptyBox.isHidden = true
  424. self.searchViewController.searchResultsView.isHidden = false
  425. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  426. } else {
  427. self.searchViewController.emptyBox.isHidden = false
  428. self.searchViewController.searchResultsView.isHidden = true
  429. }
  430. }
  431. func displayGroupedFindViewAnimating(_ animate: Bool) {
  432. self.replaceSideView(self.searchViewController.view , animate: animate)
  433. if (self.findState != .content) {
  434. self.findState = .content
  435. } else {
  436. self.displayFindState()
  437. }
  438. var frame = self.searchViewController.view.frame
  439. frame.origin.y = 0
  440. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  441. self.searchViewController.view.frame = frame
  442. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  443. frame.origin.y = 0
  444. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  445. self.noteOutlineView.enclosingScrollView?.frame = frame
  446. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  447. frame.origin.y = 0
  448. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  449. self.snapshotTableView.enclosingScrollView?.frame = frame
  450. self.updataLeftSideSnapView()
  451. }
  452. func displayNoteViewAnimating(_ animate: Bool) {
  453. self.searchViewController.contentView = nil
  454. if let data = self.noteOutlineView.enclosingScrollView {
  455. self.replaceSideView(data, animate: animate)
  456. }
  457. if (self.findState != .note) {
  458. self.findState = .note
  459. } else {
  460. self.displayFindState()
  461. }
  462. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  463. frame.origin.y = 0
  464. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  465. self.noteOutlineView.enclosingScrollView?.frame = frame
  466. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  467. frame.origin.y = 0
  468. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  469. self.snapshotTableView.enclosingScrollView?.frame = frame
  470. let view = self.noteOutlineView.enclosingScrollView
  471. let viewFrame = view?.frame ?? .zero
  472. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  473. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  474. self.reloadAnnotation()
  475. }
  476. func displaySnapshotViewAnimating(_ animate: Bool) {
  477. self.searchViewController.contentView = nil
  478. if let data = self.snapshotTableView.enclosingScrollView {
  479. self.replaceSideView(data, animate: animate)
  480. }
  481. if (self.findState != .snapshot) {
  482. self.findState = .snapshot
  483. } else {
  484. self.displayFindState()
  485. }
  486. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  487. frame.origin.y = 0
  488. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  489. self.snapshotTableView.enclosingScrollView?.frame = frame
  490. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  491. frame.origin.y = 0
  492. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  493. self.noteOutlineView.enclosingScrollView?.frame = frame
  494. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  495. frame.origin.y = 0
  496. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  497. self.tocOutlineView.enclosingScrollView?.frame = frame
  498. Task { @MainActor in
  499. self.snapshotTableView.reloadData()
  500. }
  501. }
  502. func displayFind() {
  503. self.searchField = self.searchViewController.searchField
  504. let menu = NSMenu()
  505. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  506. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  507. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  508. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  509. self.searchViewController.searchField.action = #selector(search)
  510. self.searchViewController.searchField.target = self
  511. if (self.findPaneState == .singular) {
  512. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  513. self.findTableView.wantsLayer = true
  514. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  515. DispatchQueue.main.async {
  516. self.findTableView.reloadData()
  517. }
  518. } else if (self.findPaneState == .grouped) {
  519. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  520. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  521. array.sort(){$0.datas.count > $1.datas.count}
  522. self.groupSearchResults = array
  523. self.groupedFindTableView.reloadData()
  524. }
  525. }
  526. func displayTocViewAnimating(_ animate: Bool) {
  527. if Thread.current.isMainThread {
  528. self.tocOutlineView.reloadData()
  529. } else {
  530. Task { @MainActor in
  531. self.tocOutlineView.reloadData()
  532. }
  533. }
  534. if let data = self.tocOutlineView.enclosingScrollView {
  535. self.replaceSideView(data, animate: animate)
  536. }
  537. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  538. frame.origin.y = 0
  539. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  540. self.tocOutlineView.enclosingScrollView?.frame = frame
  541. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  542. frame.origin.y = 0
  543. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  544. self.noteOutlineView.enclosingScrollView?.frame = frame
  545. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  546. frame.origin.y = 0
  547. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  548. self.snapshotTableView.enclosingScrollView?.frame = frame
  549. let view = self.tocOutlineView.enclosingScrollView
  550. let viewFrame = view?.frame ?? .zero
  551. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  552. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  553. DispatchQueue.main.async {
  554. self.tocOutlineView.reloadData()
  555. self.updateOutlineSelection()
  556. }
  557. }
  558. func displayNoteFind() {
  559. self.searchField = self.noteSearchField
  560. let menu = NSMenu()
  561. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  562. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  563. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  564. self.noteSearchField.action = #selector(searchNotes)
  565. self.noteSearchField.target = self
  566. }
  567. func displaySnapshotFind() {
  568. self.searchField = self.snapshotSearchField;
  569. let menu = NSMenu()
  570. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  571. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  572. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  573. self.snapshotSearchField.action = #selector(searchNotes)
  574. self.snapshotSearchField.target = self
  575. self.snapshotSearchField.delegate = self
  576. }
  577. func resetThumbnails(ks: Bool = true) {
  578. self.thumbnails.removeAll()
  579. let pageLabels = self.pdfDocument()?.pageLabels() ?? []
  580. if (pageLabels.isEmpty == false) {
  581. for (i, label) in pageLabels.enumerated() {
  582. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  583. thumbnail.dirty = true
  584. self.thumbnails.append(thumbnail)
  585. }
  586. }
  587. DispatchQueue.main.async {
  588. let ris = self.thumbnailTableView.selectedRowIndexes
  589. self.thumbnailTableView.reloadData()
  590. if ks {
  591. self.thumbnailTableView.km_safe_selectRowIndexes(ris, byExtendingSelection: false)
  592. }
  593. }
  594. }
  595. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  596. let button = sender as? NSButton
  597. let tag = button?.tag ?? 0
  598. if (tag == 310) {
  599. self.outlineSearchField.isHidden = true
  600. self.outlineDoneButton.isHidden = true
  601. self.outlineLabel.isHidden = false
  602. self.outlineSearchButton.isHidden = false
  603. self.outlineMoreButton.isHidden = false
  604. self.outlineAddButton.isHidden = false
  605. } else if (tag == 311) {
  606. self.noteSearchField.isHidden = true
  607. self.noteTitleLabel.isHidden = false
  608. self.noteSearchButton.isHidden = false
  609. self.noteDoneButton.isHidden = true
  610. self.noteFilterButton.isHidden = false
  611. self.noteMoreButton.isHidden = false
  612. } else if (tag == 312) {
  613. self.snapshotSearchField.isHidden = true
  614. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  615. self.snapshotNormalSearchButton.isHidden = false
  616. self.snapshotDoneButton.isHidden = true
  617. self.snapshotLabel.isHidden = false
  618. self.snapshotNormalZoomOutButton.isHidden = false
  619. self.snapshotNormalZoomInButton.isHidden = false
  620. }
  621. }
  622. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  623. let tag = sender.tag
  624. if (tag == 0 || tag == 1) {
  625. var scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  626. if (scaling <= 0) {
  627. scaling = 1
  628. }
  629. if (tag == 0) { // Zoom In
  630. scaling += self.scalingIncrement
  631. } else if (tag == 1) { // Zoom Out
  632. scaling -= self.scalingIncrement
  633. if scaling <= 0.4 {
  634. return
  635. }
  636. }
  637. KMDataManager.ud_set(scaling, forKey: Self.Key.thumbSizeScaling)
  638. let selectRow = self.thumbnailTableView.selectedRow
  639. self.thumbnailTableView.reloadData()
  640. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  641. } else if (tag == 2 || tag == 3) {
  642. var scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  643. if (scaling <= 0) {
  644. scaling = 1
  645. }
  646. if (tag == 2) { // Zoom In
  647. scaling += self.scalingIncrement
  648. } else if (tag == 3) { // Zoom Out
  649. scaling -= self.scalingIncrement
  650. }
  651. KMDataManager.ud_set(scaling, forKey: Self.Key.snapshotSizeScaling)
  652. let selectRow = self.snapshotTableView.selectedRow
  653. self.snapshotTableView.reloadData()
  654. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  655. }
  656. }
  657. func tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  658. if tv.isEqual(to: self.thumbnailTableView) {
  659. self._copysPages.removeAll()
  660. for idx in rowIndexes {
  661. if (idx != NSNotFound) {
  662. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  663. self._copysPages.append(page)
  664. }
  665. }
  666. }
  667. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  668. }
  669. }
  670. }
  671. // MARK: - KMBotaTableViewDelegate
  672. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  673. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  674. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  675. return rowIndexes.count > 0
  676. }
  677. return false
  678. }
  679. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  680. if aTableView.isEqual(to: self.thumbnailTableView) {
  681. if self._copysPages.count > 0 {
  682. return true
  683. }
  684. }
  685. return false
  686. }
  687. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  688. if aTableView.isEqual(to: self.snapshotTableView) {
  689. return rowIndexes.count > 0
  690. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  691. if self.pageCount() <= 1 {
  692. return false
  693. }
  694. return true
  695. }
  696. return false
  697. }
  698. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  699. if IAPProductsManager.default().isAvailableAllFunction() == false {
  700. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  701. return
  702. }
  703. if aTableView.isEqual(to: self.thumbnailTableView) {
  704. if self._copysPages.count > 0 {
  705. let index = self.currentPageIndex()
  706. if (index == NSNotFound) {
  707. return
  708. }
  709. let idx = index + 1
  710. for page in self._copysPages.reversed() {
  711. self.pdfDocument()?.insertPageObject(page, at: UInt(idx))
  712. self.layoutDocumentView()
  713. self.resetThumbnails()
  714. let pageIndex = min(idx, self.pageCount()-1)
  715. self.listView?.go(toPageIndex: Int(pageIndex), animated: true)
  716. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  717. }
  718. }
  719. }
  720. }
  721. func tableViewMoveLeft(_ aTableView: NSTableView) {
  722. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  723. self.updateFindResultHighlightsForDirection(.selectingPrevious)
  724. }
  725. }
  726. func tableViewMoveRight(_ aTableView: NSTableView) {
  727. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  728. self.updateFindResultHighlightsForDirection(.selectingNext)
  729. }
  730. }
  731. func tableViewMoveUp(_ aTableView: NSTableView) {
  732. if aTableView.isEqual(to: self.findTableView) {
  733. self.findTableView.km_safe_selectRowIndexes(.init(integer: self.findTableView.selectedRow-1), byExtendingSelection: false)
  734. self.findTableView.scrollRowToVisible(self.findTableView.selectedRow)
  735. }
  736. }
  737. func tableViewMoveDown(_ aTableView: NSTableView) {
  738. if aTableView.isEqual(to: self.findTableView) {
  739. self.findTableView.km_safe_selectRowIndexes(.init(integer: self.findTableView.selectedRow+1), byExtendingSelection: false)
  740. self.findTableView.scrollRowToVisible(self.findTableView.selectedRow)
  741. }
  742. }
  743. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  744. if aTableView.isEqual(to: self.findTableView) {
  745. if rowIndex >= self.searchResults.count {
  746. return nil
  747. }
  748. let model = self.searchResults[rowIndex]
  749. let selection = model.selection
  750. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  751. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  752. let point = NSPoint(x: x, y: y)
  753. return CPDFDestination(document: self.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: self.scaleFactor().cgFloat)
  754. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  755. if rowIndex >= self.groupSearchResults.count {
  756. return nil
  757. }
  758. // let model = self.groupSearchResults[rowIndex]
  759. // let selection = model.selection
  760. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  761. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  762. }
  763. return nil
  764. }
  765. }
  766. // MARK: - 扩展
  767. extension KMLeftSideViewController {
  768. public func selectType(_ type: BotaType) {
  769. // 更新 type
  770. var show = true
  771. if (self.type.methodType == .None) {
  772. show = true
  773. } else {
  774. if (self.type.methodType == type) {
  775. show = false
  776. } else {
  777. show = true
  778. }
  779. }
  780. self.type = self.getMethodMode(show ? type : .None)
  781. // 将事件传递出去
  782. self.delegate?.controlStateChange?(self,show:show)
  783. }
  784. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  785. let mode = KMLeftMethodMode()
  786. mode.methodType = type
  787. switch type {
  788. case .None:
  789. mode.methodName = ""
  790. break
  791. case .Thumbnail:
  792. mode.methodName = thumbnailMethodKey
  793. break
  794. case .Outline:
  795. mode.methodName = outlineMethodKey
  796. break
  797. case .BookMark:
  798. mode.methodName = bookMarkMethodKey
  799. break
  800. case .Annotation:
  801. mode.methodName = anntationMethodKey
  802. break
  803. case .Search:
  804. mode.methodName = searchMethodKey
  805. break
  806. case .From:
  807. mode.methodName = formMethodKey
  808. break
  809. case .Signature:
  810. mode.methodName = signatureMethodKey
  811. break
  812. case .snapshot:
  813. mode.methodName = snapshotMethodKey
  814. }
  815. return mode
  816. }
  817. }
  818. //MARK: Cache
  819. extension KMLeftSideViewController {
  820. func clearNotification() {}
  821. }
  822. // MARK: - Private Methods
  823. extension KMLeftSideViewController {
  824. func updateViewColor() {
  825. self._updateViewColor()
  826. }
  827. private func _updateViewColor() {
  828. if(KMAppearance.isDarkMode()){
  829. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  830. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  831. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  832. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  833. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  834. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  835. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  836. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  837. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  838. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  839. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  840. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  841. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  842. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  843. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  844. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  845. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  846. } else {
  847. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  848. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  849. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  850. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  851. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  852. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  853. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  854. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  855. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  856. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  857. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  858. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  859. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  860. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  861. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  862. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  863. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  864. }
  865. }
  866. func hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  867. var label = outline.label ?? ""
  868. var searchLabel = searchString
  869. if self.outlineIgnoreCaseFlag {
  870. label = label.lowercased()
  871. searchLabel = searchLabel.lowercased()
  872. }
  873. if label.contains(searchLabel) {
  874. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  875. return true
  876. } else {
  877. var subHas = false
  878. for i in 0 ..< outline.numberOfChildren {
  879. if let subOutline = outline.child(at: i) {
  880. subHas = self.hasContainString(searchString, rootOutline: subOutline)
  881. } else {
  882. continue
  883. }
  884. if (subHas) {
  885. break
  886. }
  887. }
  888. return subHas
  889. }
  890. }
  891. }
  892. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  893. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  894. func numberOfRows(in tableView: NSTableView) -> Int {
  895. if tableView.isEqual(to: self.thumbnailTableView) {
  896. return self.thumbnails.count
  897. } else if tableView.isEqual(to: self.findTableView) {
  898. return self.searchResults.count
  899. } else if tableView.isEqual(to: self.groupedFindTableView) {
  900. return self.groupSearchResults.count
  901. } else if tableView.isEqual(to: self.snapshotTableView) {
  902. if self.isSearchSnapshotMode {
  903. return self.searchSnapshots.count
  904. }
  905. return self.snapshots.count
  906. }
  907. return 0
  908. }
  909. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  910. if tableView.isEqual(to: self.thumbnailTableView) {
  911. let cell = tableView.makeView(withIdentifier: KMThumbnailTableviewCell.km_identifier, owner: self) as! KMThumbnailTableviewCell
  912. let thumbnail = self.thumbnails[row]
  913. cell.pageNumLabel.stringValue = thumbnail.label
  914. cell.pageView.isThumb = true
  915. cell.pageView.page = self.pdfDocument()?.page(at: UInt(row))
  916. // if thumbnail.dirty {
  917. // cell.pageView.updateThumbnial(needReset: true)
  918. // thumbnail.dirty = false
  919. // }
  920. if (self.isDisplayPageSize) {
  921. cell.sizeLabel.isHidden = false
  922. //获取Page的真实尺寸
  923. let page = self.pdfDocument()?.page(at: UInt(row))
  924. let rect = page?.bounds(for: .cropBox) ?? .zero
  925. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (NSWidth(rect)/595 * 210))
  926. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (NSHeight(rect)/842 * 297))
  927. if let data = page?.rotation, data == 90 || data == 270 {
  928. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  929. } else {
  930. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  931. }
  932. } else {
  933. cell.sizeLabel.stringValue = "0 mm"
  934. cell.sizeLabel.isHidden = true
  935. }
  936. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  937. if (self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  938. cell.isSelectCell = true
  939. } else {
  940. cell.isSelectCell = false
  941. }
  942. return cell
  943. } else if (tableView.isEqual(to: self.findTableView)) {
  944. let cell = tableView.makeView(withIdentifier: KMFindTableviewCell.km_identifier, owner: self) as! KMFindTableviewCell
  945. let selection = searchResults[row]
  946. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  947. cell.resultLabel.attributedStringValue = selection.attributedString
  948. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  949. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  950. cell.resultLabel.stringValue = "\(Int(selection.selectionPageIndex) + 1)"
  951. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  952. }
  953. return cell
  954. } else if tableView.isEqual(to: self.snapshotTableView) {
  955. let cell = tableView.makeView(withIdentifier: KMSnapshotTableViewCell.km_identifier, owner: self) as! KMSnapshotTableViewCell
  956. var snapshot: KMSnapshotModel?
  957. if self.isSearchSnapshotMode {
  958. snapshot = self.searchSnapshots[row]
  959. } else {
  960. snapshot = self.snapshots[row]
  961. }
  962. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  963. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  964. if let data = snapshot?.windowC?.hasWindow, data {
  965. cell.snapshotImageView.isHidden = false
  966. } else {
  967. cell.snapshotImageView.isHidden = true
  968. }
  969. cell.isSelectCell = snapshot?.isSelected ?? false
  970. if (row == tableView.selectedRow) {
  971. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  972. } else {
  973. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  974. }
  975. return cell
  976. }
  977. return nil
  978. }
  979. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  980. if tableView.isEqual(to: self.thumbnailTableView) {
  981. let scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  982. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  983. let newScaling: CGFloat = scaling.cgFloat + 0.1
  984. let newThumbnailHeight = thumbnailSize.width * newScaling
  985. if (newThumbnailHeight > Self.kMinSidePaneWidth) {
  986. self.thumbnailZoomOutButton.isEnabled = false
  987. } else {
  988. self.thumbnailZoomOutButton.isEnabled = true
  989. }
  990. if ((scaling - 0.1) < 0.4) {
  991. self.thumbnailZoomInButton.isEnabled = false
  992. } else {
  993. self.thumbnailZoomInButton.isEnabled = true
  994. }
  995. var labelHeight = 0.0
  996. if (self.isDisplayPageSize) {
  997. labelHeight = 56.0
  998. } else {
  999. labelHeight = 41.5
  1000. }
  1001. let cellHeight = thumbnailSize.height + labelHeight
  1002. var thumbSize: NSSize = .zero
  1003. if (scaling > 0) {
  1004. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1005. } else {
  1006. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  1007. }
  1008. return thumbSize.height
  1009. } else if tableView.isEqual(to: self.snapshotTableView) {
  1010. let scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  1011. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? NSMakeSize(120, 63)
  1012. var newScaling = scaling + 0.1
  1013. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat
  1014. if (newSnapshotHeight > Self.kMinSidePaneWidth) {
  1015. self.snapshotNormalZoomInButton.isEnabled = false
  1016. } else {
  1017. self.snapshotNormalZoomInButton.isEnabled = true
  1018. }
  1019. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  1020. self.snapshotNormalZoomOutButton.isEnabled = false
  1021. } else {
  1022. self.snapshotNormalZoomOutButton.isEnabled = true
  1023. }
  1024. let cellHeight = snapshotSize.height + 24.0
  1025. var thumbSize: NSSize = .zero
  1026. if (scaling > 0) {
  1027. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1028. } else {
  1029. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  1030. }
  1031. return thumbSize.height
  1032. } else if (tableView.isEqual(to: self.findTableView)) {
  1033. return 40.0
  1034. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1035. return 16
  1036. }
  1037. return tableView.rowHeight
  1038. }
  1039. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1040. if (tableView.isEqual(to: self.findTableView)) {
  1041. let rowView = KMBotaTableRowView()
  1042. return rowView
  1043. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1044. let rowView = KMGroupFindTableRowView()
  1045. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1046. let model = self.groupSearchResults[row]
  1047. rowView.number = model.datas.count
  1048. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1049. return rowView
  1050. }
  1051. return nil
  1052. }
  1053. func tableViewSelectionIsChanging(_ notification: Notification) {
  1054. }
  1055. func tableViewSelectionDidChange(_ notification: Notification) {
  1056. if self.stopRepeatLoad == true {
  1057. } else {
  1058. self.delegate?.controller?(controller: self, listViewSelectionDidChange: notification.object, info: nil)
  1059. }
  1060. if self.findTableView.isEqual(to: notification.object) {
  1061. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1062. let row = self.findTableView.selectedRow
  1063. if row >= 0 {
  1064. let model = self.searchResults[row]
  1065. self.listView?.go(to: model.selection, animated: true)
  1066. self.listView?.setHighlightedSelection(model.selection, animated: true)
  1067. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  1068. }
  1069. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1070. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1071. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1072. self.thumbnailTableView.ks_reloadData()
  1073. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1074. let row = self.snapshotTableView.selectedRow
  1075. // 更新选中数据
  1076. for (i, model) in self.snapshots.enumerated() {
  1077. model.isSelected = i == row
  1078. }
  1079. if (row != -1) {
  1080. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1081. if let data = controller?.window?.isVisible, data {
  1082. controller?.window?.orderFront(self)
  1083. }
  1084. }
  1085. self.snapshotTableView.ks_reloadData()
  1086. }
  1087. }
  1088. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1089. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1090. return NSDragOperation(rawValue: 0)
  1091. }
  1092. let pboard = info.draggingPasteboard
  1093. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1094. return .move
  1095. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1096. guard let pbItems = pboard.pasteboardItems else {
  1097. return NSDragOperation(rawValue: 0)
  1098. }
  1099. var hasValidFile = false
  1100. for item in pbItems {
  1101. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1102. continue
  1103. }
  1104. let type = _url.pathExtension.lowercased()
  1105. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1106. hasValidFile = true
  1107. }
  1108. }
  1109. if (!hasValidFile) {
  1110. return NSDragOperation(rawValue: 0)
  1111. } else {
  1112. return .move
  1113. }
  1114. }
  1115. return NSDragOperation(rawValue: 0)
  1116. }
  1117. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1118. var result = false
  1119. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1120. return result
  1121. }
  1122. let pasteboard = info.draggingPasteboard
  1123. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1124. result = true
  1125. guard let rowData = pasteboard.data(forType: .localDraggedTypes) else {
  1126. return false
  1127. }
  1128. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet ?? IndexSet()
  1129. guard let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes) else {
  1130. return false
  1131. }
  1132. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData) as? String
  1133. if url != nil && url != self.pdfDocument()?.documentURL.absoluteString {
  1134. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1135. let fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1136. if (fileNames.count == 1) {
  1137. let path = fileNames.first ?? ""
  1138. let pathExtension = path.pathExtension.lowercased()
  1139. if pathExtension == "pdf" {
  1140. var index = row
  1141. var insertIndexSet = IndexSet()
  1142. let pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1143. if let data = pdf?.isEncrypted, data {
  1144. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path), type: .owner) { success, resultPassword in
  1145. if success && resultPassword.isEmpty == false {
  1146. self.model.insertedDocumentSet.insert(pdf!)
  1147. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1148. if let page = pdf?.page(at: i).copy() as? CPDFPage {
  1149. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1150. insertIndexSet.insert(index)
  1151. index += 1
  1152. }
  1153. }
  1154. self.insertPages(insertIndexSet, pageAt: index-1)
  1155. }
  1156. }
  1157. } else {
  1158. if let data = pdf {
  1159. self.model.insertedDocumentSet.insert(data)
  1160. }
  1161. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1162. let page = pdf?.page(at: i)
  1163. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1164. insertIndexSet.insert(index)
  1165. index += 1
  1166. }
  1167. self.insertPages(insertIndexSet, pageAt: index-1)
  1168. }
  1169. }
  1170. return true
  1171. }
  1172. }
  1173. }
  1174. var pageIndex = 0
  1175. var pages: [CPDFPage] = []
  1176. for idx in rowIndexes {
  1177. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1178. pages.append(page)
  1179. }
  1180. }
  1181. var toPage: CPDFPage?
  1182. if row < self.pageCount() {
  1183. toPage = self.pdfDocument()?.page(at: UInt(row))
  1184. }
  1185. var toPageIndex = 0
  1186. if (toPage != nil) {
  1187. toPageIndex = Int(self.pdfDocument()?.index(for: toPage) ?? 0)
  1188. } else {
  1189. toPageIndex = self.pageCount()
  1190. }
  1191. for i in 0 ..< pages.count {
  1192. let page = pages[i]
  1193. self.pdfDocument()?.insertPageObject(page, at: UInt(toPageIndex+i))
  1194. pageIndex += 1
  1195. self.listView?.go(toPageIndex: toPageIndex+i-1, animated: false)
  1196. }
  1197. self.layoutDocumentView()
  1198. for idx in rowIndexes {
  1199. if idx < toPageIndex {
  1200. if((idx+pageIndex) < self.pageCount()) {
  1201. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1202. self.deletePages_.insert(page)
  1203. }
  1204. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1205. }
  1206. } else {
  1207. if((idx+pageIndex) < self.pageCount()) {
  1208. if let page = self.pdfDocument()?.page(at: UInt(idx+pageIndex)) {
  1209. self.deletePages_.insert(page)
  1210. }
  1211. self.pdfDocument()?.removePage(at: IndexSet(integer: idx+pageIndex))
  1212. }
  1213. }
  1214. }
  1215. if rowIndexes.isEmpty == false {
  1216. self.listView?.updateActiveAnnotations([])
  1217. if let win = self.view.window {
  1218. KMTools.setDocumentEditedState(window: win)
  1219. }
  1220. }
  1221. self.layoutDocumentView()
  1222. self.resetThumbnails()
  1223. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1224. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1225. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1226. return false
  1227. }
  1228. let fileNames = pasteboard.propertyList(forType: .fileURL)
  1229. var insertIndexSet = IndexSet()
  1230. var index = row
  1231. if fileNames != nil {
  1232. let path = fileNames as? String ?? ""
  1233. let url = URL(string: path)
  1234. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1235. if pathExtension == "pdf" {
  1236. let pdf = CPDFDocument(url: url!)
  1237. if let data = pdf?.isEncrypted, data {
  1238. self.view.window?.windowController?.kCheckPassword(url: url!, type: .owner, completion: { [weak self] success, resultPassword in
  1239. if success && resultPassword.isEmpty == false {
  1240. pdf?.unlock(withPassword: resultPassword)
  1241. self?.model.insertedDocumentSet.insert(pdf!)
  1242. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1243. if let page = pdf?.page(at: i) {
  1244. self?.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1245. insertIndexSet.insert(index)
  1246. index += 1
  1247. }
  1248. }
  1249. self?.insertPages(insertIndexSet, pageAt: index-1)
  1250. }
  1251. })
  1252. } else {
  1253. if let data = pdf {
  1254. self.model.insertedDocumentSet.insert(data)
  1255. }
  1256. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1257. if let page = pdf?.page(at: i) {
  1258. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1259. insertIndexSet.insert(index)
  1260. index += 1
  1261. }
  1262. }
  1263. self.insertPages(insertIndexSet, pageAt: index-1)
  1264. }
  1265. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1266. if let image = NSImage(contentsOfFile: url?.path ?? "") {
  1267. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1268. // [pdfView.document insertPage:page atIndex:index];
  1269. _ = self.pdfDocument()?.km_insert(image: image, at: UInt(index))
  1270. insertIndexSet.insert(index)
  1271. self.insertPages(insertIndexSet, pageAt: index-1)
  1272. }
  1273. }
  1274. result = true
  1275. } else {
  1276. result = false
  1277. }
  1278. }
  1279. return result == false
  1280. }
  1281. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1282. if tableView.isEqual(to: self.thumbnailTableView) {
  1283. let idx = rowIndexes.first ?? NSNotFound
  1284. if (idx != NSNotFound && self.isLocked() == false) {
  1285. let page = self.pdfDocument()?.page(at: UInt(idx))
  1286. var fileExt: String?
  1287. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.displayBox()) ?? .zero)
  1288. if self.allowsPrinting() {
  1289. // NSData *pdfData = [page dataRepresentation];
  1290. fileExt = "pdf"
  1291. // filenames
  1292. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1293. pboard.setData(tiffData, forType: .pdf)
  1294. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1295. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1296. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1297. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.pdfDocument()?.documentURL?.absoluteString)
  1298. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1299. var docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1300. // __block NSMutableString *pagesName = nil;
  1301. var pagesName = ""
  1302. if (rowIndexes.count > 1) {
  1303. pagesName = " pages"
  1304. } else {
  1305. pagesName = " page"
  1306. }
  1307. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1308. let pdf = CPDFDocument()
  1309. for idx in rowIndexes {
  1310. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1311. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1312. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1313. }
  1314. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1315. var cachesDir = paths.first ?? ""
  1316. docmentName = String(format: "%@%@", docmentName, tFileName)
  1317. if (docmentName.count > 50) {
  1318. docmentName = docmentName.substring(to: 50)
  1319. }
  1320. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1321. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1322. let success = pdf?.write(toFile: cachesDir) ?? false
  1323. if (success) {
  1324. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1325. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1326. } else{
  1327. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1328. pboard.setPropertyList([], forType: .fileURL)
  1329. }
  1330. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1331. } else {
  1332. fileExt = "tiff"
  1333. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1334. }
  1335. pboard.setData(tiffData, forType: .tiff)
  1336. // kPasteboardTypeFileURLPromise
  1337. pboard.setPropertyList([fileExt], forType: .filePromise)
  1338. return true
  1339. }
  1340. } else if self.snapshotTableView.isEqual(to: tableView) {
  1341. let idx = rowIndexes.first ?? NSNotFound
  1342. if (idx != NSNotFound) {
  1343. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1344. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1345. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1346. pboard.setData(data, forType: .tiff)
  1347. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1348. return true
  1349. }
  1350. }
  1351. }
  1352. return false
  1353. }
  1354. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
  1355. self.dragIn = true
  1356. }
  1357. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1358. self.dragIn = false
  1359. }
  1360. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1361. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1362. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1363. return
  1364. }
  1365. if aTableView.isEqual(to: self.snapshotTableView) {
  1366. var controllers: [KMSnapshotWindowController] = []
  1367. for i in rowIndexes {
  1368. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1369. if let winC = model?.windowC {
  1370. controllers.append(winC)
  1371. }
  1372. }
  1373. for c in controllers {
  1374. c.close()
  1375. }
  1376. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1377. guard let last = rowIndexes.last, last < self.pageCount() else {
  1378. return
  1379. }
  1380. //删除page时移除选中状态的annotation
  1381. self.listView?.activeAnnotations = []
  1382. for idx in rowIndexes {
  1383. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1384. // for anno in page.annotations {
  1385. // page.removeAnnotation(anno)
  1386. // }
  1387. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1388. // self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1389. self.deletePages_.insert(page)
  1390. }
  1391. }
  1392. self.pdfDocument()?.removePage(at: rowIndexes)
  1393. self.layoutDocumentView()
  1394. self.resetThumbnails()
  1395. let idx = rowIndexes.first ?? -1
  1396. let index = min(idx, self.pageCount()-1)
  1397. self.listView?.go(toPageIndex: index, animated: false)
  1398. }
  1399. }
  1400. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1401. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1402. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1403. return
  1404. }
  1405. if aTableView.isEqual(to: self.thumbnailTableView) {
  1406. self._copysPages.removeAll()
  1407. if self.isLocked() == false {
  1408. for idx in rowIndexes {
  1409. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1410. self._copysPages.append(page)
  1411. }
  1412. }
  1413. }
  1414. } else if aTableView.isEqual(to: self.findTableView) {
  1415. var string = ""
  1416. for idx in rowIndexes {
  1417. let match = self.searchResults[idx].selection
  1418. string.append("* ")
  1419. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1420. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1421. // [string appendFormat:@"", [[match contextString] string]];
  1422. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1423. }
  1424. let pboard = NSPasteboard.general
  1425. pboard.clearContents()
  1426. pboard.writeObjects([string as NSPasteboardWriting])
  1427. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1428. var string = ""
  1429. for idx in rowIndexes {
  1430. let result = self.groupSearchResults[idx]
  1431. let matches = result.datas
  1432. string.append("* ")
  1433. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1434. string.append(": ")
  1435. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1436. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1437. var tmpString = ""
  1438. for model in matches {
  1439. tmpString.append("\(model.selection.string() ?? "")")
  1440. }
  1441. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1442. }
  1443. let pboard = NSPasteboard.general
  1444. pboard.clearContents()
  1445. pboard.writeObjects([string as NSPasteboardWriting])
  1446. }
  1447. }
  1448. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1449. if self.thumbnailTableView.isEqual(to: tableView) {
  1450. var fileURLArray: [String] = []
  1451. if indexSet.count > 1 {
  1452. var docmentName = ""
  1453. let tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1454. let pdf = CPDFDocument()
  1455. for idx in indexSet {
  1456. if idx != NSNotFound && self.isLocked() == false {
  1457. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1458. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1459. }
  1460. }
  1461. let fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1462. docmentName = fileURL.path
  1463. let success = pdf?.write(toFile: docmentName) ?? false
  1464. if(success) {
  1465. fileURLArray.append(fileURL.lastPathComponent)
  1466. }
  1467. } else {
  1468. if let page = self.pdfDocument()?.page(at: UInt(indexSet.first ?? 0)) {
  1469. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1470. if self.allowsPrinting() {
  1471. fileURL = fileURL.appendingPathExtension("pdf").uniqueFileURL()
  1472. let pdf = CPDFDocument()
  1473. // let copyPage = page.copy() as? CPDFPage
  1474. let copyPage = page
  1475. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1476. let success = pdf?.write(toFile: fileURL.path) ?? false
  1477. if success {
  1478. fileURLArray.append(fileURL.lastPathComponent)
  1479. }
  1480. } else {
  1481. fileURL = fileURL.appendingPathExtension("tiff").uniqueFileURL()
  1482. let fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.displayBox()))
  1483. let success = (try?fileData?.write(to: fileURL)) != nil
  1484. if success {
  1485. fileURLArray.append(fileURL.lastPathComponent)
  1486. }
  1487. }
  1488. }
  1489. }
  1490. return fileURLArray
  1491. } else if self.snapshotTableView.isEqual(to: tableView) {
  1492. let idx = indexSet.first ?? NSNotFound
  1493. if (idx != NSNotFound) {
  1494. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1495. if let page = self.pdfDocument()?.page(at: snapshot.pageIndex()) {
  1496. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1497. fileURL = fileURL.uniqueFileURL()
  1498. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1499. return [fileURL.lastPathComponent]
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. return []
  1506. }
  1507. func tableViewColumnDidResize(_ notification: Notification) {
  1508. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1509. return
  1510. }
  1511. if column.identifier.rawValue == IMAGE_COLUMNID {
  1512. if self.thumbnailTableView.isEqual(to: notification.object) {
  1513. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1514. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1515. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1516. }
  1517. }
  1518. }
  1519. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1520. if tableView.isEqual(to: self.groupedFindTableView) {
  1521. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1522. }
  1523. }
  1524. /*
  1525. #pragma mark NSTableView delegate protocol
  1526. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1527. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1528. NSUInteger idx = [rowIndexes firstIndex];
  1529. if (idx != NSNotFound) {
  1530. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1531. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1532. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1533. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1534. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1535. [self fileWithPage:page atPath:filePath];
  1536. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1537. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1538. } else {
  1539. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1540. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1541. }
  1542. }
  1543. }
  1544. }
  1545. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1546. NSData *data = [page dataRepresentation];
  1547. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1548. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1549. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1550. if (success) {
  1551. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1552. NSURL *url = [NSURL fileURLWithPath:filePath];
  1553. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1554. }
  1555. [document release];
  1556. */
  1557. }
  1558. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1559. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1560. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1561. if outlineView.isEqual(to: self.tocOutlineView) {
  1562. if self.isLocked() {
  1563. return 0
  1564. }
  1565. if item == nil { // 第一层
  1566. let bks = self.bookmarks() ?? []
  1567. let bkNum = bks.isEmpty ? 0 : 1
  1568. guard let rootOL = self.outlineRoot() else {
  1569. if bkNum > 0 {
  1570. } else {
  1571. self.showOutlineEmptyView()
  1572. }
  1573. return 0 + bkNum
  1574. }
  1575. // 搜索按钮
  1576. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  1577. if self.isSearchOutlineMode { // 是否为搜索模块
  1578. if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  1579. self.showSearchOutlineBlankState(true)
  1580. return 0
  1581. }
  1582. self.showSearchOutlineBlankState(false)
  1583. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1584. return ols.count
  1585. }
  1586. if rootOL.numberOfChildren == 0 { // 没有数据
  1587. if bkNum > 0 {
  1588. } else {
  1589. self.showOutlineEmptyView()
  1590. }
  1591. return 0 + bkNum
  1592. }
  1593. // 有数据
  1594. self.hideOutlineEmptyView()
  1595. return Int(rootOL.numberOfChildren) + bkNum
  1596. } else { // 第二层 +
  1597. if item is CPDFBookmark { // 书签
  1598. return 0
  1599. }
  1600. if let data = item as? String, data == Self.kOutlineRootBookmarkItem { // 书签group
  1601. if self.isSearchOutlineMode {
  1602. return 0
  1603. }
  1604. return (self.bookmarks()?.count) ?? 0
  1605. }
  1606. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  1607. return 0
  1608. }
  1609. if self.isSearchOutlineMode == false {
  1610. return Int(ol.numberOfChildren)
  1611. }
  1612. // 搜索模式
  1613. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1614. return ols.count
  1615. }
  1616. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1617. if self.noteSearchMode {
  1618. return self.noteSearchArray.count
  1619. }
  1620. let count = self.annoListModel?.datas.count ?? 0
  1621. let hasAnno = self.allAnnotations.count >= 1
  1622. self.noteSearchButton.isEnabled = hasAnno
  1623. self.noteFilterButton.isEnabled = hasAnno
  1624. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1625. if count < 1 {
  1626. self.showNoteEmptyView()
  1627. } else {
  1628. self.hideNoteEmptyView()
  1629. }
  1630. return count
  1631. }
  1632. return 0
  1633. }
  1634. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1635. if outlineView.isEqual(to: self.tocOutlineView) {
  1636. if self.isLocked() {
  1637. return ""
  1638. }
  1639. let bks = self.bookmarks() ?? []
  1640. let bkNum = bks.isEmpty ? 0 : 1
  1641. if item == nil {
  1642. if self.isSearchOutlineMode {
  1643. guard let rootOL = self.outlineRoot(), rootOL.numberOfChildren > 0 else {
  1644. return ""
  1645. }
  1646. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1647. return ols.safe_element(for: index) as Any
  1648. }
  1649. if index == 0 && bkNum == 1 {
  1650. return Self.kOutlineRootBookmarkItem
  1651. }
  1652. let idx = bkNum == 1 ? index-1 : index
  1653. let rootOL = self.outlineRoot()
  1654. return rootOL?.child(at: UInt(idx)) as Any
  1655. } else {
  1656. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1657. return bks[index]
  1658. }
  1659. if item is CPDFBookmark {
  1660. return ""
  1661. }
  1662. if let ol = item as? CPDFOutline {
  1663. if self.isSearchOutlineMode == false {
  1664. return ol.child(at: UInt(index)) as Any
  1665. }
  1666. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1667. return ols.safe_element(for: index) as Any
  1668. }
  1669. }
  1670. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1671. if self.noteSearchMode {
  1672. return self.noteSearchArray[index]
  1673. }
  1674. return self.annoListModel?.datas[index] as Any
  1675. }
  1676. return item as Any
  1677. }
  1678. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1679. if outlineView.isEqual(to: self.tocOutlineView) {
  1680. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  1681. let columnId = tableColumn?.identifier.rawValue
  1682. var title = ""
  1683. var pageLabel = ""
  1684. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1685. title = NSLocalizedString("Bookmarks", comment: "")
  1686. } else if let ol = item as? CPDFOutline {
  1687. title = ol.label ?? ""
  1688. if ol.actionType == .page {
  1689. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  1690. }
  1691. } else if let bk = item as? CPDFBookmark {
  1692. title = bk.label ?? ""
  1693. pageLabel = "\(bk.pageIndex + 1)"
  1694. }
  1695. cell.pageLabel.stringValue = pageLabel
  1696. if columnId == kLabelColumnId.rawValue {
  1697. if self.isSearchOutlineMode {
  1698. let attriString = NSMutableAttributedString(string: title)
  1699. var searchString = self.outlineSearchField.stringValue
  1700. var roughString = title
  1701. if self.outlineIgnoreCaseFlag {
  1702. roughString = roughString.lowercased()
  1703. searchString = searchString.lowercased()
  1704. }
  1705. let ranges = roughString.ranges(of: searchString)
  1706. for range in ranges.nsRnage {
  1707. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  1708. }
  1709. cell.tocLabel.attributedStringValue = attriString
  1710. } else {
  1711. cell.tocLabel.stringValue = title
  1712. }
  1713. }
  1714. cell.tocLabel.textColor = KMAppearance.titleColor()
  1715. return cell
  1716. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1717. let model = item as? KMBotaAnnotationModel
  1718. let note = (item as? KMBotaAnnotationModel)?.anno
  1719. let cell = outlineView.makeView(withIdentifier: KMNoteTableViewCell.km_identifier, owner: self) as! KMNoteTableViewCell
  1720. cell.cellNote = note
  1721. cell.model = model
  1722. if let data = note {
  1723. if data.isKind(of: CPDFStampAnnotation.self) && data.isKind(of: KMSelfSignAnnotation.self) == false {
  1724. } else {
  1725. if data.isKind(of: CPDFMarkupAnnotation.self) {
  1726. if (!cell.isFold) {
  1727. // self.allFoldNotes.append(data)
  1728. } else {
  1729. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1730. }
  1731. } else {
  1732. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1733. }
  1734. }
  1735. }
  1736. cell.isUnFoldNote = { cellNote, isUnfold in
  1737. // 将折叠状态记录到模型
  1738. model?.foldType = isUnfold ? .unfold : .fold
  1739. }
  1740. return cell
  1741. }
  1742. return nil
  1743. }
  1744. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  1745. if outlineView.isEqual(self.noteOutlineView) {
  1746. if let model = item as? KMBotaAnnotationModel {
  1747. if model.foldType == .fold {
  1748. return model.foldH
  1749. }
  1750. if let anno = model.anno {
  1751. return KMBOTAAnnotationTool.fetchCellHeight(annotation: anno, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  1752. }
  1753. }
  1754. return 30
  1755. } else if outlineView.isEqual(self.tocOutlineView) {
  1756. if let ol = item as? CPDFOutline {
  1757. let string: NSString = ol.label as NSString
  1758. let ps = NSMutableParagraphStyle()
  1759. ps.lineHeightMultiple = 1.32
  1760. ps.alignment = .left
  1761. let attris = [NSAttributedString.Key.paragraphStyle : ps,
  1762. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  1763. let size = string.boundingRect(with: NSMakeSize(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attris)
  1764. return max(40, size.height + 16)
  1765. }
  1766. return 40
  1767. }
  1768. return outlineView.rowHeight
  1769. }
  1770. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  1771. if outlineView.isEqual(self.tocOutlineView) {
  1772. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1773. return true
  1774. }
  1775. if item is CPDFBookmark {
  1776. return false
  1777. }
  1778. guard let ol = item as? CPDFOutline else {
  1779. return false
  1780. }
  1781. if self.isSearchOutlineMode == false {
  1782. return ol.numberOfChildren > 0
  1783. }
  1784. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1785. return ols.count > 0
  1786. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1787. return false
  1788. }
  1789. return false
  1790. }
  1791. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  1792. if outlineView.isEqual(self.tocOutlineView) {
  1793. let itemView = KMBotaTableRowView()
  1794. return itemView
  1795. } else if outlineView.isEqual(self.noteOutlineView) {
  1796. let itemView = KMBotaTableRowView()
  1797. return itemView;
  1798. }
  1799. return nil
  1800. }
  1801. func outlineViewSelectionDidChange(_ notification: Notification) {
  1802. if self.tocOutlineView.isEqual(to: notification.object) {
  1803. if self.dragIn {
  1804. return
  1805. }
  1806. if self.updatingOutlineSelection == false {
  1807. self.updatingOutlineSelection = true
  1808. self.goToSelectedOutlineItem(nil)
  1809. self.updatingOutlineSelection = false
  1810. }
  1811. }
  1812. }
  1813. func outlineViewItemDidExpand(_ notification: Notification) {
  1814. // if self.tocOutlineView.isEqual(to: notification.object) {
  1815. // self.updateOutlineSelection()
  1816. // }
  1817. }
  1818. func outlineViewItemDidCollapse(_ notification: Notification) {
  1819. // if self.tocOutlineView.isEqual(to: notification.object) {
  1820. // self.updateOutlineSelection()
  1821. // }
  1822. }
  1823. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  1824. var dragOp = NSDragOperation(rawValue: 0)
  1825. if outlineView.isEqual(to: self.noteOutlineView) {
  1826. let pboard = info.draggingPasteboard
  1827. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) && index == NSOutlineViewDropOnItemIndex {
  1828. if let note = item as? CPDFAnnotation, note.type != nil {
  1829. dragOp = .every
  1830. }
  1831. }
  1832. } else if outlineView.isEqual(to: self.tocOutlineView) {
  1833. if (index == -1) {
  1834. dragOp = NSDragOperation(rawValue: 0)
  1835. } else {
  1836. dragOp = .move
  1837. }
  1838. }
  1839. return dragOp
  1840. }
  1841. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  1842. if outlineView.isEqual(to: self.tocOutlineView) {
  1843. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  1844. return false
  1845. }
  1846. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  1847. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  1848. self._dragPDFOutline = items.first as? CPDFOutline
  1849. let set = IndexSet(integer: 0)
  1850. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  1851. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  1852. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  1853. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1854. return true
  1855. }
  1856. return false
  1857. }
  1858. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  1859. if outlineView.isEqual(to: self.noteOutlineView) {
  1860. let pboard = info.draggingPasteboard
  1861. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) {
  1862. // [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  1863. let isShift = NSEvent.modifierFlags.contains(.shift)
  1864. let isAlt = NSEvent.modifierFlags.contains(.option)
  1865. guard let note = item as? CPDFAnnotation else {
  1866. NSSound.beep()
  1867. return false
  1868. }
  1869. if let color = NSColor(from: pboard) {
  1870. note.setColor(color, alternate: isAlt, updateDefaults: isShift)
  1871. return true
  1872. }
  1873. return false
  1874. }
  1875. } else if outlineView.isEqual(to: self.tocOutlineView) {
  1876. if (index < 0) {
  1877. return false
  1878. }
  1879. let outline = item as? CPDFOutline
  1880. guard let dragPDFOL = self._dragPDFOutline else {
  1881. return false
  1882. }
  1883. //root,drag item to root
  1884. if ((outline?.parent == nil)) {
  1885. //fetch root
  1886. var root = dragPDFOL
  1887. while (root.parent != nil) {
  1888. root = root.parent
  1889. }
  1890. if dragPDFOL.parent.isEqual(to: root) {
  1891. if dragPDFOL.index > index {
  1892. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1893. } else {
  1894. if let bks = self.bookmarks(), bks.count > 0 {
  1895. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1896. } else {
  1897. if index > 1 {
  1898. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-2, newParentOutline: root)
  1899. }
  1900. }
  1901. } else {
  1902. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  1903. }
  1904. }
  1905. } else {
  1906. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1907. }
  1908. } else {
  1909. //在同一个层级内移动
  1910. if dragPDFOL.parent.isEqual(to: item) {
  1911. if (dragPDFOL.index > 0) {
  1912. if dragPDFOL.index > index {
  1913. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1914. }else{
  1915. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  1916. }
  1917. } else {
  1918. return false
  1919. }
  1920. } else {
  1921. var tOutlline: CPDFOutline? = outline
  1922. var isContains = false
  1923. while (tOutlline != nil) {
  1924. if tOutlline!.isEqual(to: self._dragPDFOutline) {
  1925. isContains = true
  1926. break
  1927. }
  1928. tOutlline = tOutlline?.parent
  1929. }
  1930. if (!isContains) {
  1931. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1932. }
  1933. }
  1934. }
  1935. return true
  1936. }
  1937. return false
  1938. }
  1939. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  1940. if outlineView.isEqual(to: self.tocOutlineView) {
  1941. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  1942. (cell as? NSCell)?.backgroundStyle = .lowered
  1943. }
  1944. }
  1945. }
  1946. func outlineView(_ outlineView: NSOutlineView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, byItem item: Any?) {
  1947. if outlineView.isEqual(to: self.noteOutlineView) {
  1948. var note: CPDFAnnotation?
  1949. if let data = item as? CPDFAnnotation {
  1950. note = data
  1951. } else if let data = item as? KMBotaAnnotationModel {
  1952. note = data.anno
  1953. }
  1954. if let data = note?.type, data.isEmpty == false {
  1955. if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  1956. let string1 = (object as? String) ?? ""
  1957. let string2 = note?.string() ?? ""
  1958. if string1 != string2 {
  1959. note?.setString(string1)
  1960. }
  1961. } else if tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  1962. let string1 = (object as? String) ?? ""
  1963. let string2 = note?.userName() ?? ""
  1964. if string1 != string2 {
  1965. note?.setUserName(string1)
  1966. }
  1967. }
  1968. }
  1969. }
  1970. }
  1971. func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
  1972. if self.noteOutlineView.isEqual(to: outlineView) {
  1973. if tableColumn == nil {
  1974. if let anno = item as? CPDFAnnotation, anno.type == nil {
  1975. return outlineView.tableColumn(withIdentifier: self.noteColumnId)?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  1976. }
  1977. }
  1978. }
  1979. return tableColumn?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  1980. }
  1981. func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
  1982. if outlineView.isEqual(to: self.noteOutlineView) {
  1983. if (tableColumn == nil) {
  1984. if self.hideNotes() == false {
  1985. if let anno = item as? CPDFAnnotation, anno.isNote() {
  1986. // if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  1987. // PDFAnnotation *annotation = [(SKNoteText *)item note];
  1988. self.listView?.scrollAnnotationToVisible(anno)
  1989. self.listView?.updateActiveAnnotations([anno])
  1990. // [self showNote:annotation];
  1991. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  1992. // [[noteController window] makeFirstResponder:[noteController textView]];
  1993. // [[noteController textView] selectAll:nil];
  1994. }
  1995. }
  1996. return false
  1997. } else if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue || tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  1998. return true
  1999. }
  2000. }
  2001. return false
  2002. }
  2003. func outlineView(_ outlineView: NSOutlineView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, item: Any, mouseLocation: NSPoint) -> String {
  2004. if outlineView.isEqual(to: self.noteOutlineView) {
  2005. if tableColumn == nil || tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2006. return (item as? CPDFAnnotation)?.string() ?? ""
  2007. }
  2008. }
  2009. return ""
  2010. }
  2011. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
  2012. self.dragIn = true
  2013. }
  2014. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  2015. self.dragIn = false
  2016. }
  2017. /*
  2018. #pragma mark NSOutlineView delegate protocol
  2019. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  2020. if ([ov isEqual:rightSideController.noteOutlineView]) {
  2021. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  2022. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  2023. NSMutableArray *sortDescriptors = nil;
  2024. BOOL ascending = YES;
  2025. if ([oldTableColumn isEqual:newTableColumn]) {
  2026. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  2027. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  2028. ascending = [[sortDescriptors firstObject] ascending];
  2029. } else {
  2030. NSString *tcID = [newTableColumn identifier];
  2031. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  2032. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  2033. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  2034. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  2035. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  2036. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  2037. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  2038. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  2039. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2040. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  2041. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2042. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  2043. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  2044. }
  2045. if (oldTableColumn)
  2046. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  2047. [ov setHighlightedTableColumn:newTableColumn];
  2048. }
  2049. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  2050. if (newTableColumn)
  2051. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  2052. inTableColumn:newTableColumn];
  2053. [ov reloadData];
  2054. }
  2055. }
  2056. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  2057. if (mwcFlags.autoResizeNoteRows &&
  2058. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  2059. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  2060. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  2061. [rowHeights removeAllFloats];
  2062. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  2063. }
  2064. }
  2065. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  2066. {
  2067. NSInteger rowCount = [outlineView numberOfRows];
  2068. for (NSInteger i = 0; i < rowCount; i++){
  2069. CGFloat rowHeight = 0;
  2070. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  2071. if (!outline){
  2072. continue;
  2073. }
  2074. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2075. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2076. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  2077. [attributedString appendAttributedString:attr1];
  2078. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  2079. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  2080. // id cell = [tableColumn dataCell];
  2081. id cell = [tableColumn dataCellForRow:i];
  2082. [cell setObjectValue:attributedString];
  2083. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  2084. NSInteger num = [self getNum:outline];
  2085. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  2086. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  2087. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  2088. [rowHeights setFloat:rowHeight forKey:outline];
  2089. if (@available(macOS 10.13, *)) {
  2090. } else {
  2091. rowHeight = 40.0;
  2092. }
  2093. // CGRect fram = viewS.frame;
  2094. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  2095. }
  2096. [leftSideController.tocOutlineView reloadData];
  2097. }
  2098. */
  2099. func noteItems(_ items: NSArray) -> NSArray {
  2100. let noteItems = NSMutableArray()
  2101. for item in items {
  2102. guard let anno = (item as? KMBotaAnnotationModel)?.anno else {
  2103. continue
  2104. }
  2105. if anno.type == nil {
  2106. // item = [(SKNoteText *)item note];
  2107. }
  2108. if noteItems.contains(anno) == false {
  2109. noteItems.add(anno)
  2110. }
  2111. }
  2112. return noteItems
  2113. }
  2114. }
  2115. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  2116. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  2117. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  2118. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2119. return self.hideNotes() == false && items.count > 0
  2120. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2121. return items.count > 0
  2122. }
  2123. return false
  2124. }
  2125. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  2126. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2127. if (items.isEmpty) {
  2128. return
  2129. }
  2130. self.dataUpdating = true
  2131. for item in self.noteItems(items as NSArray) {
  2132. guard let anno = item as? CPDFAnnotation else {
  2133. continue
  2134. }
  2135. self.listView?.remove(anno)
  2136. }
  2137. self.dataUpdating = false
  2138. self.listView?.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  2139. self.note_refrshUIIfNeed()
  2140. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2141. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  2142. }
  2143. }
  2144. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  2145. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2146. if (items.count == 1) {
  2147. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  2148. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  2149. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  2150. // return NO;
  2151. // }
  2152. }
  2153. return items.count > 0
  2154. }
  2155. return false
  2156. }
  2157. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  2158. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  2159. // let pboard = NSPasteboard.general
  2160. // var copiedItems: [Any] = []
  2161. // var attrString = NSMutableAttributedString()
  2162. // var isAttributed = false
  2163. // var item: AnyObject?
  2164. // for (item in [self noteItems:items]) {
  2165. // if ([item isMovable])
  2166. // [copiedItems addObject:item];
  2167. // }
  2168. // for (item in items) {
  2169. // if ([attrString length])
  2170. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  2171. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  2172. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  2173. // isAttributed = YES;
  2174. // } else {
  2175. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  2176. // }
  2177. // }
  2178. //
  2179. // [pboard clearContents];
  2180. // if (isAttributed)
  2181. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  2182. // else
  2183. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  2184. // if ([copiedItems count] > 0)
  2185. // [pboard writeObjects:copiedItems];
  2186. }
  2187. }
  2188. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  2189. if self.noteOutlineView.isEqual(to: anOutlineView) {
  2190. let count = self.noteOutlineView.numberOfRows
  2191. let texts = NSMutableArray(capacity: count)
  2192. for i in 0 ..< count {
  2193. let item = self.noteOutlineView.item(atRow: i)
  2194. let string = (item as? CPDFAnnotation)?.string() ?? ""
  2195. texts.add(string)
  2196. }
  2197. return texts
  2198. } else if self.tocOutlineView.isEqual(to: anOutlineView) {
  2199. let count = self.tocOutlineView.numberOfRows
  2200. let array = NSMutableArray(capacity: count)
  2201. for i in 0 ..< count {
  2202. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  2203. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  2204. array.add(item?.label ?? "")
  2205. }
  2206. return array
  2207. }
  2208. return NSArray()
  2209. }
  2210. }
  2211. // MARK: - Other
  2212. extension KMLeftSideViewController {
  2213. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  2214. if tv.isEqual(to: self.thumbnailTableView) {
  2215. guard let document = self.pdfDocument() else {
  2216. return
  2217. }
  2218. let pages = NSMutableArray()
  2219. for idx in self.thumbnailTableView.selectedRowIndexes {
  2220. if (idx < document.pageCount) {
  2221. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  2222. pages.add(page)
  2223. }
  2224. }
  2225. }
  2226. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  2227. let saveAccessCtr = KMSavePanelAccessoryController()
  2228. let outputSavePanel = NSSavePanel()
  2229. outputSavePanel.allowedFileTypes = ["pdf"]
  2230. outputSavePanel.accessoryView = saveAccessCtr.view
  2231. outputSavePanel.nameFieldStringValue = fileName
  2232. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  2233. if (result == .OK) {
  2234. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  2235. let vc = KMProgressWindowController()
  2236. self.view.window?.beginSheet(vc.window!)
  2237. let saveFilePath = outputSavePanel.url?.path
  2238. DispatchQueue.global().async {
  2239. let pdf = CPDFDocument()
  2240. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  2241. DispatchQueue.main.async {
  2242. if (success) {
  2243. if (saveAccessCtr.openAutomaticButton.state == .on) {
  2244. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  2245. }
  2246. } else {
  2247. KMTools.viewFile(at: saveFilePath!)
  2248. }
  2249. }
  2250. NSApp.endSheet(vc.window!)
  2251. vc.close()
  2252. }
  2253. }
  2254. }
  2255. }
  2256. }
  2257. }
  2258. }
  2259. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  2260. var pagesName = ""
  2261. if (itemIndexes.count > 1) {
  2262. pagesName.append(" pages")
  2263. } else {
  2264. pagesName.append(" page")
  2265. }
  2266. let docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2267. let tFileName = String(format: "%@ %@", pagesName,KMTools.parseIndexSet(indexSet: itemIndexes))
  2268. return String(format: "%@%@", docmentName,tFileName)
  2269. }
  2270. func draggedFileName(for page: CPDFPage) -> String {
  2271. let pageIndex = "\(page.pageIndex() + 1)"
  2272. var fileName = ""
  2273. if let doc = self.view.window?.windowController?.document as? NSDocument {
  2274. // fileName = doc.displayName.deletingPathExtension
  2275. fileName = doc.fileURL?.deletingPathExtension().lastPathComponent ?? (MainBundle.nameSpaceName ?? "")
  2276. }
  2277. return "\(fileName)-Page \(pageIndex)"
  2278. }
  2279. func switchType(_ type: BotaType) {
  2280. if type == .Thumbnail {
  2281. self.leftView.segmentedControl.selectedSegment = 0
  2282. } else if type == .Outline {
  2283. self.leftView.segmentedControl.selectedSegment = 1
  2284. } else if type == .Annotation {
  2285. self.leftView.segmentedControl.selectedSegment = 2
  2286. } else if type == .snapshot {
  2287. self.leftView.segmentedControl.selectedSegment = 3
  2288. } else if type == .Search {
  2289. self.leftView.segmentedControl.selectedSegment = 4
  2290. }
  2291. }
  2292. func updateTableFont() {
  2293. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  2294. self.tocOutlineView.font = font
  2295. self.noteOutlineView.font = font
  2296. self.findTableView.font = font
  2297. self.groupedFindTableView.font = font
  2298. }
  2299. }