KMLeftSideViewController.swift 115 KB

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