KMLeftSideViewController.swift 116 KB

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