KMLeftSideViewController.swift 139 KB

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