KMLeftSideViewController.swift 117 KB

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