KMLeftSideViewController.swift 119 KB

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