KMLeftSideViewController.swift 141 KB

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