KMLeftSideViewController.swift 120 KB

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