KMLeftSideViewController.swift 116 KB

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