KMLeftSideViewController.swift 139 KB

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