KMLeftSideViewController.swift 120 KB

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