KMLeftSideViewController.swift 116 KB

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