KMLeftSideViewController.swift 123 KB

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