KMLeftSideViewController.swift 117 KB

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