KMLeftSideViewController.swift 116 KB

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