KMLeftSideViewController.swift 119 KB

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