KMLeftSideViewController.swift 117 KB

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