KMLeftSideViewController.swift 116 KB

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