KMLeftSideViewController.swift 134 KB

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