KMLeftSideViewController.swift 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  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.isHidden = true
  920. }
  921. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  922. if (self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  923. cell.isSelectCell = true
  924. } else {
  925. cell.isSelectCell = false
  926. }
  927. return cell
  928. } else if (tableView.isEqual(to: self.findTableView)) {
  929. let cell = tableView.makeView(withIdentifier: KMFindTableviewCell.km_identifier, owner: self) as! KMFindTableviewCell
  930. let selection = searchResults[row]
  931. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  932. cell.resultLabel.attributedStringValue = selection.attributedString
  933. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  934. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  935. cell.resultLabel.stringValue = "\(Int(selection.selectionPageIndex) + 1)"
  936. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  937. }
  938. return cell
  939. } else if tableView.isEqual(to: self.snapshotTableView) {
  940. let cell = tableView.makeView(withIdentifier: KMSnapshotTableViewCell.km_identifier, owner: self) as! KMSnapshotTableViewCell
  941. var snapshot: KMSnapshotModel?
  942. if self.isSearchSnapshotMode {
  943. snapshot = self.searchSnapshots[row]
  944. } else {
  945. snapshot = self.snapshots[row]
  946. }
  947. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  948. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  949. if let data = snapshot?.windowC?.hasWindow, data {
  950. cell.snapshotImageView.isHidden = false
  951. } else {
  952. cell.snapshotImageView.isHidden = true
  953. }
  954. cell.isSelectCell = snapshot?.isSelected ?? false
  955. if (row == tableView.selectedRow) {
  956. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  957. } else {
  958. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  959. }
  960. return cell
  961. }
  962. return nil
  963. }
  964. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  965. if tableView.isEqual(to: self.thumbnailTableView) {
  966. let scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  967. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  968. let newScaling: CGFloat = scaling.cgFloat + 0.1
  969. let newThumbnailHeight = thumbnailSize.width * newScaling
  970. if (newThumbnailHeight > Self.kMinSidePaneWidth) {
  971. self.thumbnailZoomOutButton.isEnabled = false
  972. } else {
  973. self.thumbnailZoomOutButton.isEnabled = true
  974. }
  975. if ((scaling - 0.1) < 0.4) {
  976. self.thumbnailZoomInButton.isEnabled = false
  977. } else {
  978. self.thumbnailZoomInButton.isEnabled = true
  979. }
  980. var labelHeight = 0.0
  981. if (self.isDisplayPageSize) {
  982. labelHeight = 56.0
  983. } else {
  984. labelHeight = 41.5
  985. }
  986. let cellHeight = thumbnailSize.height + labelHeight
  987. var thumbSize: NSSize = .zero
  988. if (scaling > 0) {
  989. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  990. } else {
  991. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  992. }
  993. return thumbSize.height
  994. } else if tableView.isEqual(to: self.snapshotTableView) {
  995. let scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  996. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? CGSizeMake(120, 63)
  997. var newScaling = scaling + 0.1
  998. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat
  999. if (newSnapshotHeight > Self.kMinSidePaneWidth) {
  1000. self.snapshotNormalZoomInButton.isEnabled = false
  1001. } else {
  1002. self.snapshotNormalZoomInButton.isEnabled = true
  1003. }
  1004. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  1005. self.snapshotNormalZoomOutButton.isEnabled = false
  1006. } else {
  1007. self.snapshotNormalZoomOutButton.isEnabled = true
  1008. }
  1009. let cellHeight = snapshotSize.height + 24.0
  1010. var thumbSize: NSSize = .zero
  1011. if (scaling > 0) {
  1012. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1013. } else {
  1014. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  1015. }
  1016. return thumbSize.height
  1017. } else if (tableView.isEqual(to: self.findTableView)) {
  1018. return 40.0
  1019. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1020. return 16
  1021. }
  1022. return tableView.rowHeight
  1023. }
  1024. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1025. if (tableView.isEqual(to: self.findTableView)) {
  1026. let rowView = KMBotaTableRowView()
  1027. return rowView
  1028. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1029. let rowView = KMGroupFindTableRowView()
  1030. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1031. let model = self.groupSearchResults[row]
  1032. rowView.number = model.datas.count
  1033. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1034. return rowView
  1035. }
  1036. return nil
  1037. }
  1038. func tableViewSelectionIsChanging(_ notification: Notification) {
  1039. }
  1040. func tableViewSelectionDidChange(_ notification: Notification) {
  1041. self.delegate?.controller?(controller: self, listViewSelectionDidChange: notification.object, info: nil)
  1042. if self.findTableView.isEqual(to: notification.object) {
  1043. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1044. let row = self.findTableView.selectedRow
  1045. if row >= 0 {
  1046. let model = self.searchResults[row]
  1047. self.listView?.go(to: model.selection, animated: true)
  1048. self.listView?.setHighlightedSelection(model.selection, animated: true)
  1049. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  1050. }
  1051. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1052. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1053. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1054. self.thumbnailTableView.ks_reloadData()
  1055. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1056. let row = self.snapshotTableView.selectedRow
  1057. // 更新选中数据
  1058. for (i, model) in self.snapshots.enumerated() {
  1059. model.isSelected = i == row
  1060. }
  1061. if (row != -1) {
  1062. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1063. if let data = controller?.window?.isVisible, data {
  1064. controller?.window?.orderFront(self)
  1065. }
  1066. }
  1067. self.snapshotTableView.ks_reloadData()
  1068. }
  1069. }
  1070. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1071. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1072. return NSDragOperation(rawValue: 0)
  1073. }
  1074. let pboard = info.draggingPasteboard
  1075. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1076. return .move
  1077. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1078. guard let pbItems = pboard.pasteboardItems else {
  1079. return NSDragOperation(rawValue: 0)
  1080. }
  1081. var hasValidFile = false
  1082. for item in pbItems {
  1083. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1084. continue
  1085. }
  1086. let type = _url.pathExtension.lowercased()
  1087. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1088. hasValidFile = true
  1089. }
  1090. }
  1091. if (!hasValidFile) {
  1092. return NSDragOperation(rawValue: 0)
  1093. } else {
  1094. return .move
  1095. }
  1096. }
  1097. return NSDragOperation(rawValue: 0)
  1098. }
  1099. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1100. var result = false
  1101. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1102. return result
  1103. }
  1104. let pasteboard = info.draggingPasteboard
  1105. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1106. result = true
  1107. guard let rowData = pasteboard.data(forType: .localDraggedTypes) else {
  1108. return false
  1109. }
  1110. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet ?? IndexSet()
  1111. guard let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes) else {
  1112. return false
  1113. }
  1114. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData) as? String
  1115. if url != nil && url != self.pdfDocument()?.documentURL.absoluteString {
  1116. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1117. let fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1118. if (fileNames.count == 1) {
  1119. let path = fileNames.first ?? ""
  1120. let pathExtension = path.pathExtension.lowercased()
  1121. if pathExtension == "pdf" {
  1122. var index = row
  1123. var insertIndexSet = IndexSet()
  1124. let pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1125. if let data = pdf?.isEncrypted, data {
  1126. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path), type: .owner) { success, resultPassword in
  1127. if success && resultPassword.isEmpty == false {
  1128. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1129. if let page = pdf?.page(at: i).copy() as? CPDFPage {
  1130. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1131. insertIndexSet.insert(index)
  1132. index += 1
  1133. }
  1134. }
  1135. self.insertPages(insertIndexSet, pageAt: index-1)
  1136. }
  1137. }
  1138. } else {
  1139. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1140. let page = pdf?.page(at: i)
  1141. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1142. insertIndexSet.insert(index)
  1143. index += 1
  1144. }
  1145. self.insertPages(insertIndexSet, pageAt: index-1)
  1146. }
  1147. }
  1148. return true
  1149. }
  1150. }
  1151. }
  1152. var pageIndex = 0
  1153. var pages: [CPDFPage] = []
  1154. for idx in rowIndexes {
  1155. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1156. pages.append(page)
  1157. }
  1158. }
  1159. var toPage: CPDFPage?
  1160. if row < self.pageCount() {
  1161. toPage = self.pdfDocument()?.page(at: UInt(row))
  1162. }
  1163. var toPageIndex = 0
  1164. if (toPage != nil) {
  1165. toPageIndex = Int(self.pdfDocument()?.index(for: toPage) ?? 0)
  1166. } else {
  1167. toPageIndex = self.pageCount()
  1168. }
  1169. for i in 0 ..< pages.count {
  1170. let page = pages[i]
  1171. self.pdfDocument()?.insertPageObject(page, at: UInt(toPageIndex+i))
  1172. pageIndex += 1
  1173. self.listView?.go(toPageIndex: toPageIndex+i-1, animated: false)
  1174. }
  1175. self.layoutDocumentView()
  1176. var deletepages: [CPDFPage] = []
  1177. for idx in rowIndexes {
  1178. if idx < toPageIndex {
  1179. if((idx+pageIndex) < self.pageCount()) {
  1180. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1181. deletepages.append(page)
  1182. }
  1183. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1184. }
  1185. } else {
  1186. if((idx+pageIndex) < self.pageCount()) {
  1187. if let page = self.pdfDocument()?.page(at: UInt(idx+pageIndex)) {
  1188. deletepages.append(page)
  1189. }
  1190. self.pdfDocument()?.removePage(at: IndexSet(integer: idx+pageIndex))
  1191. }
  1192. }
  1193. }
  1194. self.layoutDocumentView()
  1195. self.resetThumbnails()
  1196. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1197. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1198. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1199. return false
  1200. }
  1201. let fileNames = pasteboard.propertyList(forType: .fileURL)
  1202. var insertIndexSet = IndexSet()
  1203. var index = row
  1204. // if (fileNames.count == 1) {
  1205. if fileNames != nil {
  1206. // var path = fileNames.first as? String ?? ""
  1207. let path = fileNames as? String ?? ""
  1208. let url = URL(string: path)
  1209. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1210. if pathExtension == "pdf" {
  1211. let pdf = CPDFDocument(url: url!)
  1212. if let data = pdf?.isEncrypted, data {
  1213. KMBaseWindowController.checkPassword(url: url!, type: .owner) { success, resultPassword in
  1214. if success && resultPassword.isEmpty == false {
  1215. pdf?.unlock(withPassword: resultPassword)
  1216. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1217. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1218. if let page = pdf?.page(at: i) {
  1219. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1220. insertIndexSet.insert(index)
  1221. index += 1
  1222. }
  1223. }
  1224. self.insertPages(insertIndexSet, pageAt: index-1)
  1225. }
  1226. }
  1227. } else {
  1228. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1229. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1230. if let page = pdf?.page(at: i) {
  1231. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1232. insertIndexSet.insert(index)
  1233. index += 1
  1234. }
  1235. }
  1236. self.insertPages(insertIndexSet, pageAt: index-1)
  1237. }
  1238. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1239. if let image = NSImage(contentsOfFile: url?.path ?? "") {
  1240. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1241. // [pdfView.document insertPage:page atIndex:index];
  1242. _ = self.pdfDocument()?.km_insert(image: image, at: UInt(index))
  1243. insertIndexSet.insert(index)
  1244. self.insertPages(insertIndexSet, pageAt: index-1)
  1245. }
  1246. }
  1247. result = true
  1248. } else {
  1249. result = false
  1250. }
  1251. }
  1252. return result == false
  1253. }
  1254. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1255. if tableView.isEqual(to: self.thumbnailTableView) {
  1256. let idx = rowIndexes.first ?? NSNotFound
  1257. if (idx != NSNotFound && self.isLocked() == false) {
  1258. let page = self.pdfDocument()?.page(at: UInt(idx))
  1259. var fileExt: String?
  1260. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.displayBox()) ?? .zero)
  1261. if self.allowsPrinting() {
  1262. // NSData *pdfData = [page dataRepresentation];
  1263. fileExt = "pdf"
  1264. // filenames
  1265. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1266. // let newDoc = CPDFDocument()
  1267. // newDoc?.insertPageObject(page, at: 0)
  1268. // let data = newDoc?.dataRepresentation()
  1269. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  1270. pboard.setData(tiffData, forType: .pdf)
  1271. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1272. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1273. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1274. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.pdfDocument()?.documentURL?.absoluteString)
  1275. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1276. var docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1277. // __block NSMutableString *pagesName = nil;
  1278. var pagesName = ""
  1279. if (rowIndexes.count > 1) {
  1280. pagesName = " pages"
  1281. } else {
  1282. pagesName = " page"
  1283. }
  1284. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1285. let pdf = CPDFDocument()
  1286. for idx in rowIndexes {
  1287. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1288. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1289. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1290. }
  1291. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1292. var cachesDir = paths.first ?? ""
  1293. docmentName = String(format: "%@%@", docmentName, tFileName)
  1294. if (docmentName.count > 50) {
  1295. docmentName = docmentName.substring(to: 50)
  1296. }
  1297. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1298. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1299. let success = pdf?.write(toFile: cachesDir) ?? false
  1300. if (success) {
  1301. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1302. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1303. } else{
  1304. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1305. pboard.setPropertyList([], forType: .fileURL)
  1306. }
  1307. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1308. } else {
  1309. fileExt = "tiff"
  1310. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1311. }
  1312. pboard.setData(tiffData, forType: .tiff)
  1313. // kPasteboardTypeFileURLPromise
  1314. pboard.setPropertyList([fileExt], forType: .filePromise)
  1315. return true
  1316. }
  1317. } else if self.snapshotTableView.isEqual(to: tableView) {
  1318. let idx = rowIndexes.first ?? NSNotFound
  1319. if (idx != NSNotFound) {
  1320. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1321. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1322. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1323. pboard.setData(data, forType: .tiff)
  1324. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1325. return true
  1326. }
  1327. }
  1328. }
  1329. return false
  1330. }
  1331. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
  1332. self.dragIn = true
  1333. }
  1334. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1335. self.dragIn = false
  1336. }
  1337. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1338. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1339. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1340. return
  1341. }
  1342. if aTableView.isEqual(to: self.snapshotTableView) {
  1343. var controllers: [KMSnapshotWindowController] = []
  1344. for i in rowIndexes {
  1345. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1346. if let winC = model?.windowC {
  1347. controllers.append(winC)
  1348. }
  1349. }
  1350. for c in controllers {
  1351. c.close()
  1352. }
  1353. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1354. guard let last = rowIndexes.last, last < self.pageCount() else {
  1355. return
  1356. }
  1357. for idx in rowIndexes {
  1358. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1359. for anno in page.annotations {
  1360. page.removeAnnotation(anno)
  1361. }
  1362. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1363. // self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1364. }
  1365. }
  1366. self.pdfDocument()?.removePage(at: rowIndexes)
  1367. self.layoutDocumentView()
  1368. self.resetThumbnails()
  1369. let idx = rowIndexes.first ?? -1
  1370. let index = min(idx, self.pageCount()-1)
  1371. self.listView?.go(toPageIndex: index, animated: false)
  1372. }
  1373. }
  1374. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1375. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1376. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1377. return
  1378. }
  1379. if aTableView.isEqual(to: self.thumbnailTableView) {
  1380. self._copysPages.removeAll()
  1381. if self.isLocked() == false {
  1382. for idx in rowIndexes {
  1383. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1384. self._copysPages.append(page)
  1385. }
  1386. }
  1387. }
  1388. } else if aTableView.isEqual(to: self.findTableView) {
  1389. var string = ""
  1390. for idx in rowIndexes {
  1391. let match = self.searchResults[idx].selection
  1392. string.append("* ")
  1393. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1394. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1395. // [string appendFormat:@"", [[match contextString] string]];
  1396. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1397. }
  1398. let pboard = NSPasteboard.general
  1399. pboard.clearContents()
  1400. pboard.writeObjects([string as NSPasteboardWriting])
  1401. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1402. var string = ""
  1403. for idx in rowIndexes {
  1404. let result = self.groupSearchResults[idx]
  1405. let matches = result.datas
  1406. string.append("* ")
  1407. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1408. string.append(": ")
  1409. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1410. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1411. var tmpString = ""
  1412. for model in matches {
  1413. tmpString.append("\(model.selection.string() ?? "")")
  1414. }
  1415. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1416. }
  1417. let pboard = NSPasteboard.general
  1418. pboard.clearContents()
  1419. pboard.writeObjects([string as NSPasteboardWriting])
  1420. }
  1421. }
  1422. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1423. if self.thumbnailTableView.isEqual(to: tableView) {
  1424. var fileURLArray: [String] = []
  1425. if indexSet.count > 1 {
  1426. var docmentName = ""
  1427. let tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1428. let pdf = CPDFDocument()
  1429. for idx in indexSet {
  1430. if idx != NSNotFound && self.isLocked() == false {
  1431. // let copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1432. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1433. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1434. }
  1435. }
  1436. let fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1437. docmentName = fileURL.path
  1438. let success = pdf?.write(toFile: docmentName) ?? false
  1439. if(success) {
  1440. fileURLArray.append(fileURL.lastPathComponent)
  1441. }
  1442. } else {
  1443. if let page = self.pdfDocument()?.page(at: UInt(indexSet.first ?? 0)) {
  1444. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1445. if self.allowsPrinting() {
  1446. fileURL = fileURL.appendingPathExtension("pdf").uniqueFileURL()
  1447. let pdf = CPDFDocument()
  1448. // let copyPage = page.copy() as? CPDFPage
  1449. let copyPage = page
  1450. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1451. let success = pdf?.write(toFile: fileURL.path) ?? false
  1452. if success {
  1453. fileURLArray.append(fileURL.lastPathComponent)
  1454. }
  1455. } else {
  1456. fileURL = fileURL.appendingPathExtension("tiff").uniqueFileURL()
  1457. let fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.displayBox()))
  1458. let success = (try?fileData?.write(to: fileURL)) != nil
  1459. if success {
  1460. fileURLArray.append(fileURL.lastPathComponent)
  1461. }
  1462. }
  1463. }
  1464. }
  1465. return fileURLArray
  1466. } else if self.snapshotTableView.isEqual(to: tableView) {
  1467. let idx = indexSet.first ?? NSNotFound
  1468. if (idx != NSNotFound) {
  1469. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1470. if let page = self.pdfDocument()?.page(at: snapshot.pageIndex()) {
  1471. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1472. fileURL = fileURL.uniqueFileURL()
  1473. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1474. return [fileURL.lastPathComponent]
  1475. }
  1476. }
  1477. }
  1478. }
  1479. }
  1480. return []
  1481. }
  1482. func tableViewColumnDidResize(_ notification: Notification) {
  1483. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1484. return
  1485. }
  1486. if column.identifier.rawValue == IMAGE_COLUMNID {
  1487. if self.thumbnailTableView.isEqual(to: notification.object) {
  1488. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1489. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1490. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1491. }
  1492. }
  1493. }
  1494. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1495. if tableView.isEqual(to: self.groupedFindTableView) {
  1496. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1497. }
  1498. }
  1499. /*
  1500. #pragma mark NSTableView delegate protocol
  1501. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1502. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1503. NSUInteger idx = [rowIndexes firstIndex];
  1504. if (idx != NSNotFound) {
  1505. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1506. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1507. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1508. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1509. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1510. [self fileWithPage:page atPath:filePath];
  1511. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1512. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1513. } else {
  1514. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1515. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1516. }
  1517. }
  1518. }
  1519. }
  1520. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1521. NSData *data = [page dataRepresentation];
  1522. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1523. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1524. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1525. if (success) {
  1526. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1527. NSURL *url = [NSURL fileURLWithPath:filePath];
  1528. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1529. }
  1530. [document release];
  1531. */
  1532. }
  1533. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1534. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1535. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1536. if outlineView.isEqual(to: self.tocOutlineView) {
  1537. if self.isLocked() {
  1538. return 0
  1539. }
  1540. if item == nil { // 第一层
  1541. let bks = self.bookmarks() ?? []
  1542. let bkNum = bks.isEmpty ? 0 : 1
  1543. guard let rootOL = self.outlineRoot() else {
  1544. if bkNum > 0 {
  1545. } else {
  1546. self.showOutlineEmptyView()
  1547. }
  1548. return 0 + bkNum
  1549. }
  1550. // 搜索按钮
  1551. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  1552. if self.isSearchOutlineMode { // 是否为搜索模块
  1553. if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  1554. self.showSearchOutlineBlankState(true)
  1555. return 0
  1556. }
  1557. self.showSearchOutlineBlankState(false)
  1558. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1559. return ols.count
  1560. }
  1561. if rootOL.numberOfChildren == 0 { // 没有数据
  1562. if bkNum > 0 {
  1563. } else {
  1564. self.showOutlineEmptyView()
  1565. }
  1566. return 0 + bkNum
  1567. }
  1568. // 有数据
  1569. self.hideOutlineEmptyView()
  1570. return Int(rootOL.numberOfChildren) + bkNum
  1571. } else { // 第二层 +
  1572. if item is CPDFBookmark { // 书签
  1573. return 0
  1574. }
  1575. if let data = item as? String, data == Self.kOutlineRootBookmarkItem { // 书签group
  1576. if self.isSearchOutlineMode {
  1577. return 0
  1578. }
  1579. return (self.bookmarks()?.count) ?? 0
  1580. }
  1581. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  1582. return 0
  1583. }
  1584. if self.isSearchOutlineMode == false {
  1585. return Int(ol.numberOfChildren)
  1586. }
  1587. // 搜索模式
  1588. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1589. return ols.count
  1590. }
  1591. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1592. if self.noteSearchMode {
  1593. return self.noteSearchArray.count
  1594. }
  1595. let count = self.annoListModel?.datas.count ?? 0
  1596. let hasAnno = self.allAnnotations.count >= 1
  1597. self.noteSearchButton.isEnabled = hasAnno
  1598. self.noteFilterButton.isEnabled = hasAnno
  1599. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1600. if count < 1 {
  1601. self.showNoteEmptyView()
  1602. } else {
  1603. self.hideNoteEmptyView()
  1604. }
  1605. return count
  1606. }
  1607. return 0
  1608. }
  1609. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1610. if outlineView.isEqual(to: self.tocOutlineView) {
  1611. if self.isLocked() {
  1612. return ""
  1613. }
  1614. let bks = self.bookmarks() ?? []
  1615. let bkNum = bks.isEmpty ? 0 : 1
  1616. if item == nil {
  1617. if self.isSearchOutlineMode {
  1618. guard let rootOL = self.outlineRoot(), rootOL.numberOfChildren > 0 else {
  1619. return ""
  1620. }
  1621. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1622. return ols.safe_element(for: index) as Any
  1623. }
  1624. if index == 0 && bkNum == 1 {
  1625. return Self.kOutlineRootBookmarkItem
  1626. }
  1627. let idx = bkNum == 1 ? index-1 : index
  1628. let rootOL = self.outlineRoot()
  1629. return rootOL?.child(at: UInt(idx)) as Any
  1630. } else {
  1631. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1632. return bks[index]
  1633. }
  1634. if item is CPDFBookmark {
  1635. return ""
  1636. }
  1637. if let ol = item as? CPDFOutline {
  1638. if self.isSearchOutlineMode == false {
  1639. return ol.child(at: UInt(index)) as Any
  1640. }
  1641. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1642. return ols.safe_element(for: index) as Any
  1643. }
  1644. }
  1645. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1646. if self.noteSearchMode {
  1647. return self.noteSearchArray[index]
  1648. }
  1649. return self.annoListModel?.datas[index] as Any
  1650. }
  1651. return item as Any
  1652. }
  1653. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1654. if outlineView.isEqual(to: self.tocOutlineView) {
  1655. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  1656. let columnId = tableColumn?.identifier.rawValue
  1657. var title = ""
  1658. var pageLabel = ""
  1659. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1660. title = NSLocalizedString("Bookmarks", comment: "")
  1661. } else if let ol = item as? CPDFOutline {
  1662. title = ol.label ?? ""
  1663. if ol.actionType == .page {
  1664. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  1665. }
  1666. } else if let bk = item as? CPDFBookmark {
  1667. title = bk.label ?? ""
  1668. pageLabel = "\(bk.pageIndex + 1)"
  1669. }
  1670. cell.pageLabel.stringValue = pageLabel
  1671. if columnId == kLabelColumnId.rawValue {
  1672. if self.isSearchOutlineMode {
  1673. let attriString = NSMutableAttributedString(string: title)
  1674. var searchString = self.outlineSearchField.stringValue
  1675. var roughString = title
  1676. if self.outlineIgnoreCaseFlag {
  1677. roughString = roughString.lowercased()
  1678. searchString = searchString.lowercased()
  1679. }
  1680. let ranges = roughString.ranges(of: searchString)
  1681. for range in ranges.nsRnage {
  1682. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  1683. }
  1684. cell.tocLabel.attributedStringValue = attriString
  1685. } else {
  1686. cell.tocLabel.stringValue = title
  1687. }
  1688. }
  1689. cell.tocLabel.textColor = KMAppearance.titleColor()
  1690. return cell
  1691. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1692. let model = item as? KMBotaAnnotationModel
  1693. let note = (item as? KMBotaAnnotationModel)?.anno
  1694. let cell = outlineView.makeView(withIdentifier: KMNoteTableViewCell.km_identifier, owner: self) as! KMNoteTableViewCell
  1695. cell.cellNote = note
  1696. cell.model = model
  1697. if let data = note {
  1698. if data.isKind(of: CPDFStampAnnotation.self) && data.isKind(of: KMSelfSignAnnotation.self) == false {
  1699. } else {
  1700. if data.isKind(of: CPDFMarkupAnnotation.self) {
  1701. if (!cell.isFold) {
  1702. // self.allFoldNotes.append(data)
  1703. } else {
  1704. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1705. }
  1706. } else {
  1707. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1708. }
  1709. }
  1710. }
  1711. cell.isUnFoldNote = { cellNote, isUnfold in
  1712. // 将折叠状态记录到模型
  1713. model?.foldType = isUnfold ? .unfold : .fold
  1714. }
  1715. return cell
  1716. }
  1717. return nil
  1718. }
  1719. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  1720. if outlineView.isEqual(self.noteOutlineView) {
  1721. if let model = item as? KMBotaAnnotationModel {
  1722. if model.foldType == .fold {
  1723. return model.foldH
  1724. }
  1725. if let anno = model.anno {
  1726. return KMBOTAAnnotationTool.fetchCellHeight(annotation: anno, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  1727. }
  1728. }
  1729. return 30
  1730. } else if outlineView.isEqual(self.tocOutlineView) {
  1731. if let ol = item as? CPDFOutline {
  1732. let string: NSString = ol.label as NSString
  1733. let ps = NSMutableParagraphStyle()
  1734. ps.lineHeightMultiple = 1.32
  1735. ps.alignment = .left
  1736. let attris = [NSAttributedString.Key.paragraphStyle : ps,
  1737. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  1738. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attris)
  1739. return max(40, size.height + 16)
  1740. }
  1741. return 40
  1742. }
  1743. return outlineView.rowHeight
  1744. }
  1745. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  1746. if outlineView.isEqual(self.tocOutlineView) {
  1747. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1748. return true
  1749. }
  1750. if item is CPDFBookmark {
  1751. return false
  1752. }
  1753. guard let ol = item as? CPDFOutline else {
  1754. return false
  1755. }
  1756. if self.isSearchOutlineMode == false {
  1757. return ol.numberOfChildren > 0
  1758. }
  1759. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1760. return ols.count > 0
  1761. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1762. return false
  1763. }
  1764. return false
  1765. }
  1766. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  1767. if outlineView.isEqual(self.tocOutlineView) {
  1768. let itemView = KMBotaTableRowView()
  1769. return itemView
  1770. } else if outlineView.isEqual(self.noteOutlineView) {
  1771. let itemView = KMBotaTableRowView()
  1772. return itemView;
  1773. }
  1774. return nil
  1775. }
  1776. func outlineViewSelectionDidChange(_ notification: Notification) {
  1777. if self.tocOutlineView.isEqual(to: notification.object) {
  1778. if self.dragIn {
  1779. return
  1780. }
  1781. if self.updatingOutlineSelection == false {
  1782. self.updatingOutlineSelection = true
  1783. self.goToSelectedOutlineItem(nil)
  1784. self.updatingOutlineSelection = false
  1785. }
  1786. }
  1787. }
  1788. func outlineViewItemDidExpand(_ notification: Notification) {
  1789. if self.tocOutlineView.isEqual(to: notification.object) {
  1790. self.updateOutlineSelection()
  1791. }
  1792. }
  1793. func outlineViewItemDidCollapse(_ notification: Notification) {
  1794. if self.tocOutlineView.isEqual(to: notification.object) {
  1795. self.updateOutlineSelection()
  1796. }
  1797. }
  1798. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  1799. var dragOp = NSDragOperation(rawValue: 0)
  1800. if outlineView.isEqual(to: self.noteOutlineView) {
  1801. let pboard = info.draggingPasteboard
  1802. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) && index == NSOutlineViewDropOnItemIndex {
  1803. if let note = item as? CPDFAnnotation, note.type != nil {
  1804. dragOp = .every
  1805. }
  1806. }
  1807. } else if outlineView.isEqual(to: self.tocOutlineView) {
  1808. if (index == -1) {
  1809. dragOp = NSDragOperation(rawValue: 0)
  1810. } else {
  1811. dragOp = .move
  1812. }
  1813. }
  1814. return dragOp
  1815. }
  1816. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  1817. if outlineView.isEqual(to: self.tocOutlineView) {
  1818. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  1819. return false
  1820. }
  1821. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  1822. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  1823. self._dragPDFOutline = items.first as? CPDFOutline
  1824. let set = IndexSet(integer: 0)
  1825. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  1826. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  1827. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  1828. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1829. return true
  1830. }
  1831. return false
  1832. }
  1833. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  1834. if outlineView.isEqual(to: self.noteOutlineView) {
  1835. let pboard = info.draggingPasteboard
  1836. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) {
  1837. // [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  1838. let isShift = NSEvent.modifierFlags.contains(.shift)
  1839. let isAlt = NSEvent.modifierFlags.contains(.option)
  1840. guard let note = item as? CPDFAnnotation else {
  1841. NSSound.beep()
  1842. return false
  1843. }
  1844. if let color = NSColor(from: pboard) {
  1845. note.setColor(color, alternate: isAlt, updateDefaults: isShift)
  1846. return true
  1847. }
  1848. return false
  1849. }
  1850. } else if outlineView.isEqual(to: self.tocOutlineView) {
  1851. if (index < 0) {
  1852. return false
  1853. }
  1854. let outline = item as? CPDFOutline
  1855. guard let dragPDFOL = self._dragPDFOutline else {
  1856. return false
  1857. }
  1858. //root,drag item to root
  1859. if ((outline?.parent == nil)) {
  1860. //fetch root
  1861. var root = dragPDFOL
  1862. while (root.parent != nil) {
  1863. root = root.parent
  1864. }
  1865. if dragPDFOL.parent.isEqual(to: root) {
  1866. if dragPDFOL.index > index {
  1867. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1868. } else {
  1869. if let bks = self.bookmarks(), bks.count > 0 {
  1870. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1871. } else {
  1872. if index > 1 {
  1873. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-2, newParentOutline: root)
  1874. }
  1875. }
  1876. } else {
  1877. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  1878. }
  1879. }
  1880. } else {
  1881. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1882. }
  1883. } else {
  1884. //在同一个层级内移动
  1885. if dragPDFOL.parent.isEqual(to: item) {
  1886. if (dragPDFOL.index > 0) {
  1887. if dragPDFOL.index > index {
  1888. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1889. }else{
  1890. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  1891. }
  1892. } else {
  1893. return false
  1894. }
  1895. } else {
  1896. var tOutlline: CPDFOutline? = outline
  1897. var isContains = false
  1898. while (tOutlline != nil) {
  1899. if tOutlline!.isEqual(to: self._dragPDFOutline) {
  1900. isContains = true
  1901. break
  1902. }
  1903. tOutlline = tOutlline?.parent
  1904. }
  1905. if (!isContains) {
  1906. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1907. }
  1908. }
  1909. }
  1910. return true
  1911. }
  1912. return false
  1913. }
  1914. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  1915. if outlineView.isEqual(to: self.tocOutlineView) {
  1916. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  1917. (cell as? NSCell)?.backgroundStyle = .lowered
  1918. }
  1919. }
  1920. }
  1921. func outlineView(_ outlineView: NSOutlineView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, byItem item: Any?) {
  1922. if outlineView.isEqual(to: self.noteOutlineView) {
  1923. var note: CPDFAnnotation?
  1924. if let data = item as? CPDFAnnotation {
  1925. note = data
  1926. } else if let data = item as? KMBotaAnnotationModel {
  1927. note = data.anno
  1928. }
  1929. if let data = note?.type, data.isEmpty == false {
  1930. if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  1931. let string1 = (object as? String) ?? ""
  1932. let string2 = note?.string() ?? ""
  1933. if string1 != string2 {
  1934. note?.setString(string1)
  1935. }
  1936. } else if tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  1937. let string1 = (object as? String) ?? ""
  1938. let string2 = note?.userName() ?? ""
  1939. if string1 != string2 {
  1940. note?.setUserName(string1)
  1941. }
  1942. }
  1943. }
  1944. }
  1945. }
  1946. func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
  1947. if self.noteOutlineView.isEqual(to: outlineView) {
  1948. if tableColumn == nil {
  1949. if let anno = item as? CPDFAnnotation, anno.type == nil {
  1950. return outlineView.tableColumn(withIdentifier: self.noteColumnId)?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  1951. }
  1952. }
  1953. }
  1954. return tableColumn?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  1955. }
  1956. func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
  1957. if outlineView.isEqual(to: self.noteOutlineView) {
  1958. if (tableColumn == nil) {
  1959. if self.hideNotes() == false {
  1960. if let anno = item as? CPDFAnnotation, anno.isNote() {
  1961. // if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  1962. // PDFAnnotation *annotation = [(SKNoteText *)item note];
  1963. self.listView?.scrollAnnotationToVisible(anno)
  1964. self.listView?.updateActiveAnnotations([anno])
  1965. // [self showNote:annotation];
  1966. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  1967. // [[noteController window] makeFirstResponder:[noteController textView]];
  1968. // [[noteController textView] selectAll:nil];
  1969. }
  1970. }
  1971. return false
  1972. } else if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue || tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  1973. return true
  1974. }
  1975. }
  1976. return false
  1977. }
  1978. func outlineView(_ outlineView: NSOutlineView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, item: Any, mouseLocation: NSPoint) -> String {
  1979. if outlineView.isEqual(to: self.noteOutlineView) {
  1980. if tableColumn == nil || tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  1981. return (item as? CPDFAnnotation)?.string() ?? ""
  1982. }
  1983. }
  1984. return ""
  1985. }
  1986. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
  1987. self.dragIn = true
  1988. }
  1989. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1990. self.dragIn = false
  1991. }
  1992. /*
  1993. #pragma mark NSOutlineView delegate protocol
  1994. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  1995. if ([ov isEqual:rightSideController.noteOutlineView]) {
  1996. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  1997. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  1998. NSMutableArray *sortDescriptors = nil;
  1999. BOOL ascending = YES;
  2000. if ([oldTableColumn isEqual:newTableColumn]) {
  2001. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  2002. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  2003. ascending = [[sortDescriptors firstObject] ascending];
  2004. } else {
  2005. NSString *tcID = [newTableColumn identifier];
  2006. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  2007. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  2008. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  2009. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  2010. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  2011. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  2012. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  2013. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  2014. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2015. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  2016. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2017. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  2018. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  2019. }
  2020. if (oldTableColumn)
  2021. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  2022. [ov setHighlightedTableColumn:newTableColumn];
  2023. }
  2024. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  2025. if (newTableColumn)
  2026. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  2027. inTableColumn:newTableColumn];
  2028. [ov reloadData];
  2029. }
  2030. }
  2031. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  2032. if (mwcFlags.autoResizeNoteRows &&
  2033. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  2034. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  2035. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  2036. [rowHeights removeAllFloats];
  2037. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  2038. }
  2039. }
  2040. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  2041. {
  2042. NSInteger rowCount = [outlineView numberOfRows];
  2043. for (NSInteger i = 0; i < rowCount; i++){
  2044. CGFloat rowHeight = 0;
  2045. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  2046. if (!outline){
  2047. continue;
  2048. }
  2049. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2050. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2051. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  2052. [attributedString appendAttributedString:attr1];
  2053. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  2054. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  2055. // id cell = [tableColumn dataCell];
  2056. id cell = [tableColumn dataCellForRow:i];
  2057. [cell setObjectValue:attributedString];
  2058. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  2059. NSInteger num = [self getNum:outline];
  2060. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  2061. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  2062. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  2063. [rowHeights setFloat:rowHeight forKey:outline];
  2064. if (@available(macOS 10.13, *)) {
  2065. } else {
  2066. rowHeight = 40.0;
  2067. }
  2068. // CGRect fram = viewS.frame;
  2069. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  2070. }
  2071. [leftSideController.tocOutlineView reloadData];
  2072. }
  2073. */
  2074. func noteItems(_ items: NSArray) -> NSArray {
  2075. let noteItems = NSMutableArray()
  2076. for item in items {
  2077. guard let anno = (item as? KMBotaAnnotationModel)?.anno else {
  2078. continue
  2079. }
  2080. if anno.type == nil {
  2081. // item = [(SKNoteText *)item note];
  2082. }
  2083. if noteItems.contains(anno) == false {
  2084. noteItems.add(anno)
  2085. }
  2086. }
  2087. return noteItems
  2088. }
  2089. }
  2090. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  2091. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  2092. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  2093. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2094. return self.hideNotes() == false && items.count > 0
  2095. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2096. return items.count > 0
  2097. }
  2098. return false
  2099. }
  2100. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  2101. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2102. if (items.isEmpty) {
  2103. return
  2104. }
  2105. self.dataUpdating = true
  2106. for item in self.noteItems(items as NSArray) {
  2107. guard let anno = item as? CPDFAnnotation else {
  2108. continue
  2109. }
  2110. self.listView?.remove(anno)
  2111. }
  2112. self.dataUpdating = false
  2113. self.listView?.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  2114. self.note_refrshUIIfNeed()
  2115. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2116. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  2117. }
  2118. }
  2119. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  2120. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2121. if (items.count == 1) {
  2122. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  2123. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  2124. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  2125. // return NO;
  2126. // }
  2127. }
  2128. return items.count > 0
  2129. }
  2130. return false
  2131. }
  2132. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  2133. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  2134. // let pboard = NSPasteboard.general
  2135. // var copiedItems: [Any] = []
  2136. // var attrString = NSMutableAttributedString()
  2137. // var isAttributed = false
  2138. // var item: AnyObject?
  2139. // for (item in [self noteItems:items]) {
  2140. // if ([item isMovable])
  2141. // [copiedItems addObject:item];
  2142. // }
  2143. // for (item in items) {
  2144. // if ([attrString length])
  2145. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  2146. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  2147. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  2148. // isAttributed = YES;
  2149. // } else {
  2150. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  2151. // }
  2152. // }
  2153. //
  2154. // [pboard clearContents];
  2155. // if (isAttributed)
  2156. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  2157. // else
  2158. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  2159. // if ([copiedItems count] > 0)
  2160. // [pboard writeObjects:copiedItems];
  2161. }
  2162. }
  2163. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  2164. if self.noteOutlineView.isEqual(to: anOutlineView) {
  2165. let count = self.noteOutlineView.numberOfRows
  2166. let texts = NSMutableArray(capacity: count)
  2167. for i in 0 ..< count {
  2168. let item = self.noteOutlineView.item(atRow: i)
  2169. let string = (item as? CPDFAnnotation)?.string() ?? ""
  2170. texts.add(string)
  2171. }
  2172. return texts
  2173. } else if self.tocOutlineView.isEqual(to: anOutlineView) {
  2174. let count = self.tocOutlineView.numberOfRows
  2175. let array = NSMutableArray(capacity: count)
  2176. for i in 0 ..< count {
  2177. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  2178. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  2179. array.add(item?.label ?? "")
  2180. }
  2181. return array
  2182. }
  2183. return NSArray()
  2184. }
  2185. }
  2186. // MARK: - Other
  2187. extension KMLeftSideViewController {
  2188. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  2189. if tv.isEqual(to: self.thumbnailTableView) {
  2190. guard let document = self.pdfDocument() else {
  2191. return
  2192. }
  2193. let pages = NSMutableArray()
  2194. for idx in self.thumbnailTableView.selectedRowIndexes {
  2195. if (idx < document.pageCount) {
  2196. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  2197. pages.add(page)
  2198. }
  2199. }
  2200. }
  2201. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  2202. let saveAccessCtr = KMSavePanelAccessoryController()
  2203. let outputSavePanel = NSSavePanel()
  2204. outputSavePanel.allowedFileTypes = ["pdf"]
  2205. outputSavePanel.accessoryView = saveAccessCtr.view
  2206. outputSavePanel.nameFieldStringValue = fileName
  2207. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  2208. if (result == .OK) {
  2209. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  2210. let vc = KMProgressWindowController()
  2211. self.view.window?.beginSheet(vc.window!)
  2212. let saveFilePath = outputSavePanel.url?.path
  2213. DispatchQueue.global().async {
  2214. let pdf = CPDFDocument()
  2215. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  2216. DispatchQueue.main.async {
  2217. if (success) {
  2218. if (saveAccessCtr.openAutomaticButton.state == .on) {
  2219. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  2220. }
  2221. } else {
  2222. KMTools.viewFile(at: saveFilePath!)
  2223. }
  2224. }
  2225. NSApp.endSheet(vc.window!)
  2226. vc.close()
  2227. }
  2228. }
  2229. }
  2230. }
  2231. }
  2232. }
  2233. }
  2234. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  2235. var pagesName = ""
  2236. if (itemIndexes.count > 1) {
  2237. pagesName.append(" pages")
  2238. } else {
  2239. pagesName.append(" page")
  2240. }
  2241. let docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2242. let tFileName = String(format: "%@ %@", pagesName,KMTools.parseIndexSet(indexSet: itemIndexes))
  2243. return String(format: "%@%@", docmentName,tFileName)
  2244. }
  2245. func draggedFileName(for page: CPDFPage) -> String {
  2246. let pageIndex = "\(page.pageIndex() + 1)"
  2247. var fileName = ""
  2248. if let doc = self.view.window?.windowController?.document as? NSDocument {
  2249. // fileName = doc.displayName.deletingPathExtension
  2250. fileName = doc.fileURL?.deletingPathExtension().lastPathComponent ?? (MainBundle.nameSpaceName ?? "")
  2251. }
  2252. return "\(fileName)-Page \(pageIndex)"
  2253. }
  2254. func switchType(_ type: BotaType) {
  2255. if type == .Thumbnail {
  2256. self.leftView.segmentedControl.selectedSegment = 0
  2257. } else if type == .Outline {
  2258. self.leftView.segmentedControl.selectedSegment = 1
  2259. } else if type == .Annotation {
  2260. self.leftView.segmentedControl.selectedSegment = 2
  2261. } else if type == .snapshot {
  2262. self.leftView.segmentedControl.selectedSegment = 3
  2263. } else if type == .Search {
  2264. self.leftView.segmentedControl.selectedSegment = 4
  2265. }
  2266. }
  2267. func updateTableFont() {
  2268. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  2269. self.tocOutlineView.font = font
  2270. self.noteOutlineView.font = font
  2271. self.findTableView.font = font
  2272. self.groupedFindTableView.font = font
  2273. }
  2274. }