KMLeftSideViewController.swift 117 KB

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