KMLeftSideViewController.swift 116 KB

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