KMLeftSideViewController.swift 119 KB

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