KMLeftSideViewController.swift 114 KB

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