KMLeftSideViewController.swift 114 KB

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