KMLeftSideViewController.swift 124 KB

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