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