KMLeftSideViewController.swift 116 KB

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