KMLeftSideViewController.swift 120 KB

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