KMLeftSideViewController.swift 114 KB

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