KMLeftSideViewController.swift 114 KB

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