KMLeftSideViewController.swift 116 KB

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