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