KMLeftSideViewController.swift 116 KB

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