KMLeftSideViewController.swift 140 KB

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