KMLeftSideViewController.swift 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  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. // 快照
  135. var snapshotCacheSize: CGFloat = 32 * 3
  136. var isSearchSnapshotMode = false
  137. var snapshots: [KMSnapshotModel] = []
  138. var dirtySnapshots: [KMSnapshotWindowController] = []
  139. var searchSnapshots: [KMSnapshotModel] = []
  140. var dataUpdating = false
  141. // 搜索
  142. private var _findState: KMFindState = .none
  143. var findState: KMFindState {
  144. get {
  145. return self._findState
  146. }
  147. set {
  148. if self._findState != newValue {
  149. self._findState = newValue
  150. self.displayFindState()
  151. if self._findState == .content {
  152. self.search(self.searchField)
  153. } else if self.findState == .note {
  154. self.searchNotes(nil)
  155. } else if self.findState == .snapshot {
  156. self.searchNotes(self.searchField)
  157. }
  158. }
  159. }
  160. }
  161. var searchResults : [KMSearchMode] = [] {
  162. didSet {
  163. self.updataLeftSideFindView()
  164. }
  165. }
  166. var groupSearchResults: [KMSearchMode] = []
  167. var findPaneState: KMFindPaneState = .singular
  168. var searchResultIndex: Int = 0
  169. var leftMargin: CGFloat = 0
  170. private var _copysPages: [CPDFPage] = []
  171. var copyPages: [CPDFPage] {
  172. get {
  173. return self._copysPages
  174. }
  175. }
  176. var dragIn = false
  177. private let KPDFThumbnailDoucumentURLForDraggedTypes = NSPasteboard.PasteboardType("KPDFThumbnailDoucumentURLForDraggedTypes")
  178. deinit {
  179. KMPrint("KMLeftSideViewController deinit.")
  180. NotificationCenter.default.removeObserver(self)
  181. DistributedNotificationCenter.default().removeObserver(self)
  182. }
  183. override var nibName: NSNib.Name? {
  184. return "LeftSideView"
  185. }
  186. convenience init(type : KMLeftMethodMode) {
  187. self.init()
  188. self.type = type
  189. }
  190. override func viewDidLoad() {
  191. super.viewDidLoad()
  192. self.reloadThumbnailSize()
  193. self.reloadSnapshotSize()
  194. }
  195. func showPanelView(show: Bool) {
  196. self.isShowPanel = show
  197. if show {
  198. self.leftView.segmentedControl.selectedSegment = 0
  199. } else {
  200. self.leftView.segmentedControl.selectedSegment = UInt8.max
  201. self.type.methodType = .None
  202. self.delegate?.controlStateChange?(self, show: false)
  203. }
  204. }
  205. func refreshMethodType(methodType: BotaType) {
  206. let newType = KMLeftMethodMode()
  207. var show = true
  208. if self.type.methodType != methodType {
  209. newType.methodType = methodType
  210. }
  211. if self.type.methodType == methodType {
  212. show = false
  213. } else if methodType == .None {
  214. show = false
  215. }
  216. self.type = newType;
  217. self.delegate?.controlStateChange?(self,show:show)
  218. }
  219. override func loadView() {
  220. super.loadView()
  221. self.initSubView()
  222. self.initDefalutValue()
  223. self.searchViewController.loadView()
  224. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  225. self.searchField = self.searchViewController.searchField
  226. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  227. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  228. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  229. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  230. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  231. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  232. self.searchViewController.segmentedControl.selectedSegment = 0
  233. self.searchViewController.segmentedControl.block = { [unowned self] segIndex in
  234. if segIndex == 0 {
  235. self.findPaneState = .singular
  236. self.displayFindViewAnimating(false)
  237. } else {
  238. self.findPaneState = .grouped
  239. self.displayGroupedFindViewAnimating(false)
  240. }
  241. }
  242. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  243. self.toolButtonBox.isHidden = false
  244. self.toolButtonBoxLayoutConstraint.constant = 40.0
  245. if (segIndex == 0) {
  246. if self.type.methodType == .Thumbnail {
  247. self.leftView.segmentedControl.selectedSegment = UInt8.max
  248. self.refreshMethodType(methodType: .None)
  249. return
  250. }
  251. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Thumbnail"])
  252. self.refreshMethodType(methodType: .Thumbnail)
  253. DispatchQueue.main.async {
  254. self.toolButtonBox.contentView = self.thumbnailView
  255. self.displayThumbnailViewAnimating(false)
  256. }
  257. } else if (segIndex == 1) {
  258. if self.type.methodType == .Outline {
  259. self.leftView.segmentedControl.selectedSegment = UInt8.max
  260. self.refreshMethodType(methodType: .None)
  261. return
  262. }
  263. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Outline"])
  264. self.refreshMethodType(methodType: .Outline)
  265. DispatchQueue.main.async {
  266. self.toolButtonBox.contentView = self.outlineView
  267. self.displayTocViewAnimating(false)
  268. }
  269. } else if (segIndex == 2) {
  270. if self.type.methodType == .Annotation {
  271. self.leftView.segmentedControl.selectedSegment = UInt8.max
  272. self.refreshMethodType(methodType: .None)
  273. return
  274. }
  275. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Annotation"])
  276. self.refreshMethodType(methodType: .Annotation)
  277. DispatchQueue.main.async {
  278. self.toolButtonBox.contentView = self.noteView
  279. self.displayNoteViewAnimating(false)
  280. }
  281. } else if (segIndex == 3) {
  282. if self.type.methodType == .snapshot {
  283. self.leftView.segmentedControl.selectedSegment = UInt8.max
  284. self.refreshMethodType(methodType: .None)
  285. return
  286. }
  287. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Snapshot"])
  288. self.refreshMethodType(methodType: .snapshot)
  289. self.toolButtonBox.contentView = self.snapshotNormalView
  290. self.updateSnapshotFilterPredicate()
  291. self.displaySnapshotViewAnimating(false)
  292. self.updataLeftSideSnapView()
  293. } else if (segIndex == 4) {
  294. if self.type.methodType == .Search {
  295. self.leftView.segmentedControl.selectedSegment = UInt8.max
  296. self.refreshMethodType(methodType: .None)
  297. return
  298. }
  299. FMTrackEventManager.defaultManager.trackEvent(event: "LeftSidebar", withProperties: ["LeftSidebar_Btn": "Btn_LeftSidebar_Search"])
  300. self.refreshMethodType(methodType: .Search)
  301. DispatchQueue.main.async {
  302. self.toolButtonBox.isHidden = true
  303. self.toolButtonBoxLayoutConstraint.constant = 0
  304. self.displayFindViewAnimating(false)
  305. }
  306. }
  307. }
  308. let menu = NSMenu()
  309. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  310. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  311. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  312. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  313. self.searchField.action = #selector(search)
  314. self.searchField.target = self
  315. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  316. // //支持拖拽的文字类型
  317. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  318. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  319. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  320. if KMDataManager.ud_bool(forKey: Self.Key.disableTableToolTipsKey) == false {
  321. self.tocOutlineView.hasImageToolTips = true
  322. self.findTableView.hasImageToolTips = true
  323. self.groupedFindTableView.hasImageToolTips = true
  324. }
  325. self._updateViewColor()
  326. }
  327. func initSubView() {
  328. self.view.addSubview(self.leftView)
  329. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  330. self.leftView.autoresizingMask = [.height]
  331. self.thumb_initSubViews()
  332. self.outline_initSubViews()
  333. self.note_initSubViews()
  334. self.snapshot_initSubViews()
  335. self.search_initSubViews()
  336. }
  337. func initDefalutValue() {
  338. self.view.wantsLayer = true
  339. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  340. self.leftView.wantsLayer = true
  341. self.leftView.layer?.backgroundColor = .white
  342. self.leftListView.wantsLayer = true
  343. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  344. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  345. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  346. self.emptySearchBox.isHidden = true
  347. self.thumb_initDefalutValue()
  348. self.outline_initDefalutValue()
  349. self.note_initDefalutValue()
  350. self.snapshot_initDefalutValue()
  351. self.search_initDefalutValue()
  352. }
  353. func displayThumbnailViewAnimating(_ animate: Bool) {
  354. if let enclosingScrollView = self.thumbnailTableView.enclosingScrollView {
  355. self.replaceSideView(enclosingScrollView, animate: animate)
  356. }
  357. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  358. frame.origin.y = 0
  359. frame.origin.x = self.leftMargin
  360. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  361. self.thumbnailTableView.enclosingScrollView?.frame = frame
  362. self.resetThumbnails()
  363. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  364. frame.origin.y = 0
  365. frame.origin.x = self.leftMargin
  366. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  367. self.noteOutlineView.enclosingScrollView?.frame = frame
  368. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  369. frame.origin.y = 0
  370. frame.origin.x = self.leftMargin
  371. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  372. self.snapshotTableView.enclosingScrollView?.frame = frame
  373. self.updateThumbnailSelection()
  374. }
  375. func displayFindViewAnimating(_ animate: Bool) {
  376. self.replaceSideView(self.searchViewController.view, animate: animate)
  377. if (self.findState != .content) {
  378. self.findState = .content
  379. } else {
  380. self.displayFindState()
  381. }
  382. var frame = self.searchViewController.view.frame
  383. frame.origin.y = 0
  384. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  385. self.searchViewController.view.frame = frame
  386. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  387. frame.origin.y = 0
  388. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  389. self.noteOutlineView.enclosingScrollView?.frame = frame
  390. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  391. frame.origin.y = 0
  392. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  393. self.snapshotTableView.enclosingScrollView?.frame = frame
  394. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  395. self.updataLeftSideSnapView()
  396. }
  397. func displayFindState() {
  398. if (self.findState == .content) {
  399. self.displayFind()
  400. } else if (self.findState == .note) {
  401. self.displayNoteFind()
  402. } else if (self.findState == .snapshot) {
  403. self.displaySnapshotFind()
  404. }
  405. }
  406. func updataLeftSideFindView() {
  407. if (self.findState != .content) {
  408. return
  409. }
  410. if (self.searchResults.count > 0) {
  411. self.searchViewController.emptyBox.isHidden = true
  412. self.searchViewController.searchResultsView.isHidden = false
  413. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  414. } else {
  415. self.searchViewController.emptyBox.isHidden = false
  416. self.searchViewController.searchResultsView.isHidden = true
  417. }
  418. }
  419. func displayGroupedFindViewAnimating(_ animate: Bool) {
  420. self.replaceSideView(self.searchViewController.view , animate: animate)
  421. if (self.findState != .content) {
  422. self.findState = .content
  423. } else {
  424. self.displayFindState()
  425. }
  426. var frame = self.searchViewController.view.frame
  427. frame.origin.y = 0
  428. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  429. self.searchViewController.view.frame = frame
  430. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  431. frame.origin.y = 0
  432. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  433. self.noteOutlineView.enclosingScrollView?.frame = frame
  434. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  435. frame.origin.y = 0
  436. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  437. self.snapshotTableView.enclosingScrollView?.frame = frame
  438. self.updataLeftSideSnapView()
  439. }
  440. func displayNoteViewAnimating(_ animate: Bool) {
  441. self.searchViewController.contentView = nil
  442. if let data = self.noteOutlineView.enclosingScrollView {
  443. self.replaceSideView(data, animate: animate)
  444. }
  445. if (self.findState != .note) {
  446. self.findState = .note
  447. } else {
  448. self.displayFindState()
  449. }
  450. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  451. frame.origin.y = 0
  452. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  453. self.noteOutlineView.enclosingScrollView?.frame = frame
  454. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  455. frame.origin.y = 0
  456. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  457. self.noteOutlineView.enclosingScrollView?.frame = frame
  458. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  459. frame.origin.y = 0
  460. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  461. self.snapshotTableView.enclosingScrollView?.frame = frame
  462. let view = self.noteOutlineView.enclosingScrollView
  463. let viewFrame = view?.frame ?? .zero
  464. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  465. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  466. self.reloadAnnotation()
  467. }
  468. func displaySnapshotViewAnimating(_ animate: Bool) {
  469. self.searchViewController.contentView = nil
  470. if let data = self.snapshotTableView.enclosingScrollView {
  471. self.replaceSideView(data, animate: animate)
  472. }
  473. if (self.findState != .snapshot) {
  474. self.findState = .snapshot
  475. } else {
  476. self.displayFindState()
  477. }
  478. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  479. frame.origin.y = 0
  480. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  481. self.snapshotTableView.enclosingScrollView?.frame = frame
  482. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  483. frame.origin.y = 0
  484. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  485. self.noteOutlineView.enclosingScrollView?.frame = frame
  486. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  487. frame.origin.y = 0
  488. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  489. self.tocOutlineView.enclosingScrollView?.frame = frame
  490. Task { @MainActor in
  491. self.snapshotTableView.reloadData()
  492. }
  493. }
  494. func displayFind() {
  495. self.searchField = self.searchViewController.searchField
  496. let menu = NSMenu()
  497. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  498. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  499. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  500. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  501. self.searchViewController.searchField.action = #selector(search)
  502. self.searchViewController.searchField.target = self
  503. if (self.findPaneState == .singular) {
  504. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  505. self.findTableView.wantsLayer = true
  506. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  507. DispatchQueue.main.async {
  508. self.findTableView.reloadData()
  509. }
  510. } else if (self.findPaneState == .grouped) {
  511. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  512. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  513. array.sort(){$0.datas.count > $1.datas.count}
  514. self.groupSearchResults = array
  515. self.groupedFindTableView.reloadData()
  516. }
  517. }
  518. func displayTocViewAnimating(_ animate: Bool) {
  519. if let data = self.tocOutlineView.enclosingScrollView {
  520. self.replaceSideView(data, animate: animate)
  521. }
  522. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  523. frame.origin.y = 0
  524. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  525. self.tocOutlineView.enclosingScrollView?.frame = frame
  526. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  527. frame.origin.y = 0
  528. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  529. self.noteOutlineView.enclosingScrollView?.frame = frame
  530. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  531. frame.origin.y = 0
  532. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  533. self.snapshotTableView.enclosingScrollView?.frame = frame
  534. let view = self.tocOutlineView.enclosingScrollView
  535. let viewFrame = view?.frame ?? .zero
  536. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  537. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  538. DispatchQueue.main.async {
  539. self.tocOutlineView.reloadData()
  540. self.updateOutlineSelection()
  541. }
  542. }
  543. func displayNoteFind() {
  544. self.searchField = self.noteSearchField
  545. let menu = NSMenu()
  546. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  547. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  548. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  549. self.noteSearchField.action = #selector(searchNotes)
  550. self.noteSearchField.target = self
  551. }
  552. func displaySnapshotFind() {
  553. self.searchField = self.snapshotSearchField;
  554. let menu = NSMenu()
  555. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  556. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  557. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  558. self.snapshotSearchField.action = #selector(searchNotes)
  559. self.snapshotSearchField.target = self
  560. self.snapshotSearchField.delegate = self
  561. }
  562. func resetThumbnails(ks: Bool = true) {
  563. self.thumbnails.removeAll()
  564. let pageLabels = self.pdfDocument()?.pageLabels() ?? []
  565. if (pageLabels.isEmpty == false) {
  566. for (i, label) in pageLabels.enumerated() {
  567. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  568. thumbnail.dirty = true
  569. self.thumbnails.append(thumbnail)
  570. }
  571. }
  572. DispatchQueue.main.async {
  573. let ris = self.thumbnailTableView.selectedRowIndexes
  574. self.thumbnailTableView.reloadData()
  575. if ks {
  576. self.thumbnailTableView.km_safe_selectRowIndexes(ris, byExtendingSelection: false)
  577. }
  578. }
  579. }
  580. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  581. let button = sender as? NSButton
  582. let tag = button?.tag ?? 0
  583. if (tag == 310) {
  584. self.outlineSearchField.isHidden = true
  585. self.outlineDoneButton.isHidden = true
  586. self.outlineLabel.isHidden = false
  587. self.outlineSearchButton.isHidden = false
  588. self.outlineMoreButton.isHidden = false
  589. self.outlineAddButton.isHidden = false
  590. } else if (tag == 311) {
  591. self.noteSearchField.isHidden = true
  592. self.noteTitleLabel.isHidden = false
  593. self.noteSearchButton.isHidden = false
  594. self.noteDoneButton.isHidden = true
  595. self.noteFilterButton.isHidden = false
  596. self.noteMoreButton.isHidden = false
  597. } else if (tag == 312) {
  598. self.snapshotSearchField.isHidden = true
  599. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  600. self.snapshotNormalSearchButton.isHidden = false
  601. self.snapshotDoneButton.isHidden = true
  602. self.snapshotLabel.isHidden = false
  603. self.snapshotNormalZoomOutButton.isHidden = false
  604. self.snapshotNormalZoomInButton.isHidden = false
  605. }
  606. }
  607. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  608. let tag = sender.tag
  609. if (tag == 0 || tag == 1) {
  610. var scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  611. if (scaling <= 0) {
  612. scaling = 1
  613. }
  614. if (tag == 0) { // Zoom In
  615. scaling += self.scalingIncrement
  616. } else if (tag == 1) { // Zoom Out
  617. scaling -= self.scalingIncrement
  618. if scaling <= 0.4 {
  619. return
  620. }
  621. }
  622. KMDataManager.ud_set(scaling, forKey: Self.Key.thumbSizeScaling)
  623. let selectRow = self.thumbnailTableView.selectedRow
  624. self.thumbnailTableView.reloadData()
  625. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  626. } else if (tag == 2 || tag == 3) {
  627. var scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  628. if (scaling <= 0) {
  629. scaling = 1
  630. }
  631. if (tag == 2) { // Zoom In
  632. scaling += self.scalingIncrement
  633. } else if (tag == 3) { // Zoom Out
  634. scaling -= self.scalingIncrement
  635. }
  636. KMDataManager.ud_set(scaling, forKey: Self.Key.snapshotSizeScaling)
  637. let selectRow = self.snapshotTableView.selectedRow
  638. self.snapshotTableView.reloadData()
  639. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  640. }
  641. }
  642. func tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  643. if tv.isEqual(to: self.thumbnailTableView) {
  644. self._copysPages.removeAll()
  645. for idx in rowIndexes {
  646. if (idx != NSNotFound) {
  647. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  648. self._copysPages.append(page)
  649. }
  650. }
  651. }
  652. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  653. }
  654. }
  655. }
  656. // MARK: - KMBotaTableViewDelegate
  657. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  658. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  659. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  660. return rowIndexes.count > 0
  661. }
  662. return false
  663. }
  664. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  665. if aTableView.isEqual(to: self.thumbnailTableView) {
  666. if self._copysPages.count > 0 {
  667. return true
  668. }
  669. }
  670. return false
  671. }
  672. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  673. if aTableView.isEqual(to: self.snapshotTableView) {
  674. return rowIndexes.count > 0
  675. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  676. if self.pageCount() <= 1 {
  677. return false
  678. }
  679. return true
  680. }
  681. return false
  682. }
  683. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  684. if IAPProductsManager.default().isAvailableAllFunction() == false {
  685. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  686. return
  687. }
  688. if aTableView.isEqual(to: self.thumbnailTableView) {
  689. if self._copysPages.count > 0 {
  690. let index = self.currentPageIndex()
  691. if (index == NSNotFound) {
  692. return
  693. }
  694. let idx = index + 1
  695. for page in self._copysPages.reversed() {
  696. self.pdfDocument()?.insertPageObject(page, at: UInt(idx))
  697. self.layoutDocumentView()
  698. self.resetThumbnails()
  699. let pageIndex = min(idx, self.pageCount()-1)
  700. self.listView?.go(toPageIndex: Int(pageIndex), animated: true)
  701. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  702. }
  703. }
  704. }
  705. }
  706. func tableViewMoveLeft(_ aTableView: NSTableView) {
  707. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  708. self.updateFindResultHighlightsForDirection(.selectingPrevious)
  709. }
  710. }
  711. func tableViewMoveRight(_ aTableView: NSTableView) {
  712. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  713. self.updateFindResultHighlightsForDirection(.selectingNext)
  714. }
  715. }
  716. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  717. if aTableView.isEqual(to: self.findTableView) {
  718. if rowIndex >= self.searchResults.count {
  719. return nil
  720. }
  721. let model = self.searchResults[rowIndex]
  722. let selection = model.selection
  723. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  724. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  725. let point = NSPoint(x: x, y: y)
  726. return CPDFDestination(document: self.pdfDocument(), pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.scaleFactor().cgFloat)
  727. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  728. if rowIndex >= self.groupSearchResults.count {
  729. return nil
  730. }
  731. // let model = self.groupSearchResults[rowIndex]
  732. // let selection = model.selection
  733. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  734. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  735. }
  736. return nil
  737. }
  738. }
  739. // MARK: - 扩展
  740. extension KMLeftSideViewController {
  741. public func selectType(_ type: BotaType) {
  742. // 更新 type
  743. var show = true
  744. if (self.type.methodType == .None) {
  745. show = true
  746. } else {
  747. if (self.type.methodType == type) {
  748. show = false
  749. } else {
  750. show = true
  751. }
  752. }
  753. self.type = self.getMethodMode(show ? type : .None)
  754. // 将事件传递出去
  755. self.delegate?.controlStateChange?(self,show:show)
  756. }
  757. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  758. let mode = KMLeftMethodMode()
  759. mode.methodType = type
  760. switch type {
  761. case .None:
  762. mode.methodName = ""
  763. break
  764. case .Thumbnail:
  765. mode.methodName = thumbnailMethodKey
  766. break
  767. case .Outline:
  768. mode.methodName = outlineMethodKey
  769. break
  770. case .BookMark:
  771. mode.methodName = bookMarkMethodKey
  772. break
  773. case .Annotation:
  774. mode.methodName = anntationMethodKey
  775. break
  776. case .Search:
  777. mode.methodName = searchMethodKey
  778. break
  779. case .From:
  780. mode.methodName = formMethodKey
  781. break
  782. case .Signature:
  783. mode.methodName = signatureMethodKey
  784. break
  785. case .snapshot:
  786. mode.methodName = snapshotMethodKey
  787. }
  788. return mode
  789. }
  790. }
  791. //MARK: Cache
  792. extension KMLeftSideViewController {
  793. func clearNotification() {}
  794. }
  795. // MARK: - Private Methods
  796. extension KMLeftSideViewController {
  797. func updateViewColor() {
  798. self._updateViewColor()
  799. }
  800. private func _updateViewColor() {
  801. if(KMAppearance.isDarkMode()){
  802. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  803. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  804. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  805. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  806. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  807. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  808. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  809. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  810. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  811. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  812. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  813. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  814. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  815. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  816. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  817. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  818. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  819. } else {
  820. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  821. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  822. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  823. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  824. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  825. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  826. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  827. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  828. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  829. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  830. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  831. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  832. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  833. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  834. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  835. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  836. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  837. }
  838. }
  839. func hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  840. var label = outline.label ?? ""
  841. var searchLabel = searchString
  842. if self.outlineIgnoreCaseFlag {
  843. label = label.lowercased()
  844. searchLabel = searchLabel.lowercased()
  845. }
  846. if label.contains(searchLabel) {
  847. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  848. return true
  849. } else {
  850. var subHas = false
  851. for i in 0 ..< outline.numberOfChildren {
  852. if let subOutline = outline.child(at: i) {
  853. subHas = self.hasContainString(searchString, rootOutline: subOutline)
  854. } else {
  855. continue
  856. }
  857. if (subHas) {
  858. break
  859. }
  860. }
  861. return subHas
  862. }
  863. }
  864. }
  865. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  866. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  867. func numberOfRows(in tableView: NSTableView) -> Int {
  868. if tableView.isEqual(to: self.thumbnailTableView) {
  869. return self.thumbnails.count
  870. } else if tableView.isEqual(to: self.findTableView) {
  871. return self.searchResults.count
  872. } else if tableView.isEqual(to: self.groupedFindTableView) {
  873. return self.groupSearchResults.count
  874. } else if tableView.isEqual(to: self.snapshotTableView) {
  875. if self.isSearchSnapshotMode {
  876. return self.searchSnapshots.count
  877. }
  878. return self.snapshots.count
  879. }
  880. return 0
  881. }
  882. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  883. if tableView.isEqual(to: self.thumbnailTableView) {
  884. let cell = tableView.makeView(withIdentifier: KMThumbnailTableviewCell.km_identifier, owner: self) as! KMThumbnailTableviewCell
  885. let thumbnail = self.thumbnails[row]
  886. cell.pageNumLabel.stringValue = thumbnail.label
  887. cell.pageView.page = self.pdfDocument()?.page(at: UInt(row))
  888. if (self.isDisplayPageSize) {
  889. cell.sizeLabel.isHidden = false
  890. //获取Page的真实尺寸
  891. let page = self.pdfDocument()?.page(at: UInt(row))
  892. let rect = page?.bounds(for: .cropBox) ?? .zero
  893. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  894. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  895. if let data = page?.rotation, data == 90 || data == 270 {
  896. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  897. } else {
  898. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  899. }
  900. } else {
  901. cell.sizeLabel.isHidden = true
  902. }
  903. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  904. if (self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  905. cell.isSelectCell = true
  906. } else {
  907. cell.isSelectCell = false
  908. }
  909. return cell
  910. } else if (tableView.isEqual(to: self.findTableView)) {
  911. let cell = tableView.makeView(withIdentifier: KMFindTableviewCell.km_identifier, owner: self) as! KMFindTableviewCell
  912. let selection = searchResults[row]
  913. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  914. cell.resultLabel.attributedStringValue = selection.attributedString
  915. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  916. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  917. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  918. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  919. }
  920. return cell
  921. } else if tableView.isEqual(to: self.snapshotTableView) {
  922. let cell = tableView.makeView(withIdentifier: KMSnapshotTableViewCell.km_identifier, owner: self) as! KMSnapshotTableViewCell
  923. var snapshot: KMSnapshotModel?
  924. if self.isSearchSnapshotMode {
  925. snapshot = self.searchSnapshots[row]
  926. } else {
  927. snapshot = self.snapshots[row]
  928. }
  929. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  930. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  931. if let data = snapshot?.windowC?.hasWindow, data {
  932. cell.snapshotImageView.isHidden = false
  933. } else {
  934. cell.snapshotImageView.isHidden = true
  935. }
  936. cell.isSelectCell = snapshot?.isSelected ?? false
  937. if (row == tableView.selectedRow) {
  938. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  939. } else {
  940. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  941. }
  942. return cell
  943. }
  944. return nil
  945. }
  946. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  947. if tableView.isEqual(to: self.thumbnailTableView) {
  948. let scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  949. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  950. let newScaling: CGFloat = scaling.cgFloat + 0.1
  951. let newThumbnailHeight = thumbnailSize.width * newScaling
  952. if (newThumbnailHeight > Self.kMinSidePaneWidth) {
  953. self.thumbnailZoomOutButton.isEnabled = false
  954. } else {
  955. self.thumbnailZoomOutButton.isEnabled = true
  956. }
  957. if ((scaling - 0.1) < 0.4) {
  958. self.thumbnailZoomInButton.isEnabled = false
  959. } else {
  960. self.thumbnailZoomInButton.isEnabled = true
  961. }
  962. var labelHeight = 0.0
  963. if (self.isDisplayPageSize) {
  964. labelHeight = 56.0
  965. } else {
  966. labelHeight = 41.5
  967. }
  968. let cellHeight = thumbnailSize.height + labelHeight
  969. var thumbSize: NSSize = .zero
  970. if (scaling > 0) {
  971. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  972. } else {
  973. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  974. }
  975. return thumbSize.height
  976. } else if tableView.isEqual(to: self.snapshotTableView) {
  977. let scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  978. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? CGSizeMake(120, 63)
  979. var newScaling = scaling + 0.1
  980. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  981. if (newSnapshotHeight > Self.kMinSidePaneWidth) {
  982. self.snapshotNormalZoomInButton.isEnabled = false
  983. } else {
  984. self.snapshotNormalZoomInButton.isEnabled = true
  985. }
  986. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  987. self.snapshotNormalZoomOutButton.isEnabled = false
  988. } else {
  989. self.snapshotNormalZoomOutButton.isEnabled = true
  990. }
  991. let cellHeight = snapshotSize.height + 24.0
  992. var thumbSize: NSSize = .zero
  993. if (scaling > 0) {
  994. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  995. } else {
  996. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  997. }
  998. return thumbSize.height
  999. } else if (tableView.isEqual(to: self.findTableView)) {
  1000. return 40.0
  1001. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1002. return 16
  1003. }
  1004. return tableView.rowHeight
  1005. }
  1006. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1007. if (tableView.isEqual(to: self.findTableView)) {
  1008. let rowView = KMBotaTableRowView()
  1009. return rowView
  1010. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1011. let rowView = KMGroupFindTableRowView()
  1012. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1013. let model = self.groupSearchResults[row]
  1014. rowView.number = model.datas.count
  1015. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1016. return rowView
  1017. }
  1018. return nil
  1019. }
  1020. func tableViewSelectionIsChanging(_ notification: Notification) {
  1021. }
  1022. func tableViewSelectionDidChange(_ notification: Notification) {
  1023. self.delegate?.controller?(controller: self, listViewSelectionDidChange: notification.object, info: nil)
  1024. if self.findTableView.isEqual(to: notification.object) {
  1025. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1026. let row = self.findTableView.selectedRow
  1027. if row >= 0 {
  1028. let model = self.searchResults[row]
  1029. self.listView?.go(to: model.selection, animated: true)
  1030. self.listView?.setHighlightedSelection(model.selection, animated: true)
  1031. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  1032. }
  1033. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1034. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1035. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1036. self.thumbnailTableView.ks_reloadData()
  1037. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1038. let row = self.snapshotTableView.selectedRow
  1039. // 更新选中数据
  1040. for (i, model) in self.snapshots.enumerated() {
  1041. model.isSelected = i == row
  1042. }
  1043. if (row != -1) {
  1044. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1045. if let data = controller?.window?.isVisible, data {
  1046. controller?.window?.orderFront(self)
  1047. }
  1048. }
  1049. self.snapshotTableView.ks_reloadData()
  1050. }
  1051. }
  1052. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1053. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1054. return NSDragOperation(rawValue: 0)
  1055. }
  1056. let pboard = info.draggingPasteboard
  1057. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1058. return .move
  1059. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1060. guard let pbItems = pboard.pasteboardItems else {
  1061. return NSDragOperation(rawValue: 0)
  1062. }
  1063. var hasValidFile = false
  1064. for item in pbItems {
  1065. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1066. continue
  1067. }
  1068. let type = _url.pathExtension.lowercased()
  1069. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1070. hasValidFile = true
  1071. }
  1072. }
  1073. if (!hasValidFile) {
  1074. return NSDragOperation(rawValue: 0)
  1075. } else {
  1076. return .move
  1077. }
  1078. }
  1079. return NSDragOperation(rawValue: 0)
  1080. }
  1081. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1082. var result = false
  1083. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1084. return result
  1085. }
  1086. let pasteboard = info.draggingPasteboard
  1087. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1088. result = true
  1089. guard let rowData = pasteboard.data(forType: .localDraggedTypes) else {
  1090. return false
  1091. }
  1092. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet ?? IndexSet()
  1093. guard let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes) else {
  1094. return false
  1095. }
  1096. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData) as? String
  1097. if url != nil && url != self.pdfDocument()?.documentURL.absoluteString {
  1098. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1099. let fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1100. if (fileNames.count == 1) {
  1101. let path = fileNames.first ?? ""
  1102. let pathExtension = path.pathExtension.lowercased()
  1103. if pathExtension == "pdf" {
  1104. var index = row
  1105. var insertIndexSet = IndexSet()
  1106. let pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1107. if let data = pdf?.isEncrypted, data {
  1108. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path), type: .owner) { success, resultPassword in
  1109. if success && resultPassword.isEmpty == false {
  1110. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1111. if let page = pdf?.page(at: i).copy() as? CPDFPage {
  1112. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1113. insertIndexSet.insert(index)
  1114. index += 1
  1115. }
  1116. }
  1117. self.insertPages(insertIndexSet, pageAt: index-1)
  1118. }
  1119. }
  1120. } else {
  1121. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1122. let page = pdf?.page(at: i)
  1123. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1124. insertIndexSet.insert(index)
  1125. index += 1
  1126. }
  1127. self.insertPages(insertIndexSet, pageAt: index-1)
  1128. }
  1129. }
  1130. return true
  1131. }
  1132. }
  1133. }
  1134. var pageIndex = 0
  1135. var pages: [CPDFPage] = []
  1136. for idx in rowIndexes {
  1137. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1138. pages.append(page)
  1139. }
  1140. }
  1141. var toPage: CPDFPage?
  1142. if row < self.pageCount() {
  1143. toPage = self.pdfDocument()?.page(at: UInt(row))
  1144. }
  1145. var toPageIndex = 0
  1146. if (toPage != nil) {
  1147. toPageIndex = Int(self.pdfDocument()?.index(for: toPage) ?? 0)
  1148. } else {
  1149. toPageIndex = self.pageCount()
  1150. }
  1151. for i in 0 ..< pages.count {
  1152. let page = pages[i]
  1153. self.pdfDocument()?.insertPageObject(page, at: UInt(toPageIndex+i))
  1154. pageIndex += 1
  1155. self.listView?.go(toPageIndex: toPageIndex+i, animated: false)
  1156. }
  1157. self.layoutDocumentView()
  1158. var deletepages: [CPDFPage] = []
  1159. for idx in rowIndexes {
  1160. if idx < toPageIndex {
  1161. if((idx+pageIndex) < self.pageCount()) {
  1162. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1163. deletepages.append(page)
  1164. }
  1165. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1166. }
  1167. } else {
  1168. if((idx+pageIndex) < self.pageCount()) {
  1169. if let page = self.pdfDocument()?.page(at: UInt(idx+pageIndex)) {
  1170. deletepages.append(page)
  1171. }
  1172. self.pdfDocument()?.removePage(at: IndexSet(integer: idx+pageIndex))
  1173. }
  1174. }
  1175. }
  1176. self.layoutDocumentView()
  1177. self.resetThumbnails()
  1178. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1179. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1180. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1181. return false
  1182. }
  1183. let fileNames = pasteboard.propertyList(forType: .fileURL)
  1184. var insertIndexSet = IndexSet()
  1185. var index = row
  1186. // if (fileNames.count == 1) {
  1187. if fileNames != nil {
  1188. // var path = fileNames.first as? String ?? ""
  1189. let path = fileNames as? String ?? ""
  1190. let url = URL(string: path)
  1191. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1192. if pathExtension == "pdf" {
  1193. let pdf = CPDFDocument(url: url!)
  1194. if let data = pdf?.isEncrypted, data {
  1195. KMBaseWindowController.checkPassword(url: url!, type: .owner) { success, resultPassword in
  1196. if success && resultPassword.isEmpty == false {
  1197. pdf?.unlock(withPassword: resultPassword)
  1198. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1199. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1200. if let page = pdf?.page(at: i) {
  1201. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1202. insertIndexSet.insert(index)
  1203. index += 1
  1204. }
  1205. }
  1206. self.insertPages(insertIndexSet, pageAt: index-1)
  1207. }
  1208. }
  1209. } else {
  1210. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1211. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1212. if let page = pdf?.page(at: i) {
  1213. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1214. insertIndexSet.insert(index)
  1215. index += 1
  1216. }
  1217. }
  1218. self.insertPages(insertIndexSet, pageAt: index-1)
  1219. }
  1220. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1221. if let image = NSImage(contentsOfFile: url?.path ?? "") {
  1222. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1223. // [pdfView.document insertPage:page atIndex:index];
  1224. _ = self.pdfDocument()?.km_insert(image: image, at: UInt(index))
  1225. insertIndexSet.insert(index)
  1226. self.insertPages(insertIndexSet, pageAt: index-1)
  1227. }
  1228. }
  1229. result = true
  1230. } else {
  1231. result = false
  1232. }
  1233. }
  1234. return result == false
  1235. }
  1236. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1237. if tableView.isEqual(to: self.thumbnailTableView) {
  1238. let idx = rowIndexes.first ?? NSNotFound
  1239. if (idx != NSNotFound && self.isLocked()) {
  1240. let page = self.pdfDocument()?.page(at: UInt(idx))
  1241. var fileExt: String?
  1242. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.displayBox()) ?? .zero)
  1243. if self.allowsPrinting() {
  1244. // NSData *pdfData = [page dataRepresentation];
  1245. fileExt = "pdf"
  1246. // filenames
  1247. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1248. // let newDoc = CPDFDocument()
  1249. // newDoc?.insertPageObject(page, at: 0)
  1250. // let data = newDoc?.dataRepresentation()
  1251. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  1252. pboard.setData(tiffData, forType: .pdf)
  1253. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1254. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1255. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1256. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.pdfDocument()?.documentURL?.absoluteString)
  1257. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1258. var docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1259. // __block NSMutableString *pagesName = nil;
  1260. var pagesName = ""
  1261. if (rowIndexes.count > 1) {
  1262. pagesName = " pages"
  1263. } else {
  1264. pagesName = " page"
  1265. }
  1266. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1267. let pdf = CPDFDocument()
  1268. for idx in rowIndexes {
  1269. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1270. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1271. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1272. }
  1273. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1274. var cachesDir = paths.first ?? ""
  1275. docmentName = String(format: "%@%@", docmentName, tFileName)
  1276. if (docmentName.count > 50) {
  1277. docmentName = docmentName.substring(to: 50)
  1278. }
  1279. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1280. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1281. let success = pdf?.write(toFile: cachesDir) ?? false
  1282. if (success) {
  1283. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1284. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1285. } else{
  1286. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1287. pboard.setPropertyList([], forType: .fileURL)
  1288. }
  1289. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1290. } else {
  1291. fileExt = "tiff"
  1292. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1293. }
  1294. pboard.setData(tiffData, forType: .tiff)
  1295. // kPasteboardTypeFileURLPromise
  1296. pboard.setPropertyList([fileExt], forType: .filePromise)
  1297. return true
  1298. }
  1299. } else if self.snapshotTableView.isEqual(to: tableView) {
  1300. let idx = rowIndexes.first ?? NSNotFound
  1301. if (idx != NSNotFound) {
  1302. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1303. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1304. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1305. pboard.setData(data, forType: .tiff)
  1306. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1307. return true
  1308. }
  1309. }
  1310. }
  1311. return false
  1312. }
  1313. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
  1314. self.dragIn = true
  1315. }
  1316. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1317. self.dragIn = false
  1318. }
  1319. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1320. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1321. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1322. return
  1323. }
  1324. if aTableView.isEqual(to: self.snapshotTableView) {
  1325. var controllers: [KMSnapshotWindowController] = []
  1326. for i in rowIndexes {
  1327. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1328. if let winC = model?.windowC {
  1329. controllers.append(winC)
  1330. }
  1331. }
  1332. for c in controllers {
  1333. c.close()
  1334. }
  1335. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1336. for idx in rowIndexes {
  1337. if idx >= self.pageCount() {
  1338. return
  1339. }
  1340. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1341. for anno in page.annotations {
  1342. page.removeAnnotation(anno)
  1343. }
  1344. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1345. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1346. }
  1347. }
  1348. if rowIndexes.isEmpty == false {
  1349. self.layoutDocumentView()
  1350. self.resetThumbnails()
  1351. let idx = rowIndexes.first ?? -1
  1352. let index = min(idx, self.pageCount()-1)
  1353. self.listView?.go(toPageIndex: index, animated: false)
  1354. }
  1355. }
  1356. }
  1357. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1358. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1359. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1360. return
  1361. }
  1362. if aTableView.isEqual(to: self.thumbnailTableView) {
  1363. self._copysPages.removeAll()
  1364. if self.isLocked() == false {
  1365. for idx in rowIndexes {
  1366. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1367. self._copysPages.append(page)
  1368. }
  1369. }
  1370. }
  1371. } else if aTableView.isEqual(to: self.findTableView) {
  1372. var string = ""
  1373. for idx in rowIndexes {
  1374. let match = self.searchResults[idx].selection
  1375. string.append("* ")
  1376. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1377. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1378. // [string appendFormat:@"", [[match contextString] string]];
  1379. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1380. }
  1381. let pboard = NSPasteboard.general
  1382. pboard.clearContents()
  1383. pboard.writeObjects([string as NSPasteboardWriting])
  1384. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1385. var string = ""
  1386. for idx in rowIndexes {
  1387. let result = self.groupSearchResults[idx]
  1388. let matches = result.datas
  1389. string.append("* ")
  1390. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1391. string.append(": ")
  1392. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1393. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1394. var tmpString = ""
  1395. for model in matches {
  1396. tmpString.append("\(model.selection.string() ?? "")")
  1397. }
  1398. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1399. }
  1400. let pboard = NSPasteboard.general
  1401. pboard.clearContents()
  1402. pboard.writeObjects([string as NSPasteboardWriting])
  1403. }
  1404. }
  1405. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1406. if self.thumbnailTableView.isEqual(to: tableView) {
  1407. var fileURLArray: [String] = []
  1408. if indexSet.count > 1 {
  1409. var docmentName = ""
  1410. let tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1411. let pdf = CPDFDocument()
  1412. for idx in indexSet {
  1413. if idx != NSNotFound && self.isLocked() == false {
  1414. // let copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1415. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1416. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1417. }
  1418. }
  1419. let fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1420. docmentName = fileURL.path
  1421. let success = pdf?.write(toFile: docmentName) ?? false
  1422. if(success) {
  1423. fileURLArray.append(fileURL.lastPathComponent)
  1424. }
  1425. } else {
  1426. if let page = self.pdfDocument()?.page(at: UInt(indexSet.first ?? 0)) {
  1427. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1428. if self.allowsPrinting() {
  1429. fileURL = fileURL.appendingPathExtension("pdf").uniqueFileURL()
  1430. let pdf = CPDFDocument()
  1431. // let copyPage = page.copy() as? CPDFPage
  1432. let copyPage = page
  1433. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1434. let success = pdf?.write(toFile: fileURL.path) ?? false
  1435. if success {
  1436. fileURLArray.append(fileURL.lastPathComponent)
  1437. }
  1438. } else {
  1439. fileURL = fileURL.appendingPathExtension("tiff").uniqueFileURL()
  1440. let fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.displayBox()))
  1441. let success = (try?fileData?.write(to: fileURL)) != nil
  1442. if success {
  1443. fileURLArray.append(fileURL.lastPathComponent)
  1444. }
  1445. }
  1446. }
  1447. }
  1448. return fileURLArray
  1449. } else if self.snapshotTableView.isEqual(to: tableView) {
  1450. let idx = indexSet.first ?? NSNotFound
  1451. if (idx != NSNotFound) {
  1452. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1453. if let page = self.pdfDocument()?.page(at: snapshot.pageIndex()) {
  1454. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1455. fileURL = fileURL.uniqueFileURL()
  1456. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1457. return [fileURL.lastPathComponent]
  1458. }
  1459. }
  1460. }
  1461. }
  1462. }
  1463. return []
  1464. }
  1465. func tableViewColumnDidResize(_ notification: Notification) {
  1466. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1467. return
  1468. }
  1469. if column.identifier.rawValue == IMAGE_COLUMNID {
  1470. if self.thumbnailTableView.isEqual(to: notification.object) {
  1471. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1472. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1473. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1474. }
  1475. }
  1476. }
  1477. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1478. if tableView.isEqual(to: self.groupedFindTableView) {
  1479. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1480. }
  1481. }
  1482. /*
  1483. #pragma mark NSTableView delegate protocol
  1484. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1485. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1486. NSUInteger idx = [rowIndexes firstIndex];
  1487. if (idx != NSNotFound) {
  1488. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1489. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1490. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1491. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1492. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1493. [self fileWithPage:page atPath:filePath];
  1494. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1495. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1496. } else {
  1497. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1498. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1499. }
  1500. }
  1501. }
  1502. }
  1503. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1504. NSData *data = [page dataRepresentation];
  1505. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1506. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1507. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1508. if (success) {
  1509. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1510. NSURL *url = [NSURL fileURLWithPath:filePath];
  1511. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1512. }
  1513. [document release];
  1514. */
  1515. }
  1516. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1517. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1518. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1519. if outlineView.isEqual(to: self.tocOutlineView) {
  1520. if self.isLocked() {
  1521. return 0
  1522. }
  1523. if item == nil { // 第一层
  1524. guard let rootOL = self.outlineRoot() else {
  1525. self.showOutlineEmptyView()
  1526. return 0
  1527. }
  1528. // 搜索按钮
  1529. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  1530. if self.isSearchOutlineMode { // 是否为搜索模块
  1531. if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  1532. self.showSearchOutlineBlankState(true)
  1533. return 0
  1534. }
  1535. self.showSearchOutlineBlankState(false)
  1536. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1537. return ols.count
  1538. }
  1539. if rootOL.numberOfChildren == 0 { // 没有数据
  1540. self.showOutlineEmptyView()
  1541. return 0
  1542. }
  1543. // 有数据
  1544. self.hideOutlineEmptyView()
  1545. let bks = self.bookmarks() ?? []
  1546. let bkNum = bks.isEmpty ? 0 : 1
  1547. return Int(rootOL.numberOfChildren) + bkNum
  1548. } else { // 第二层 +
  1549. if item is CPDFBookmark { // 书签
  1550. return 0
  1551. }
  1552. if let data = item as? String, data == Self.kOutlineRootBookmarkItem { // 书签group
  1553. if self.isSearchOutlineMode {
  1554. return 0
  1555. }
  1556. return (self.bookmarks()?.count) ?? 0
  1557. }
  1558. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  1559. return 0
  1560. }
  1561. if self.isSearchOutlineMode == false {
  1562. return Int(ol.numberOfChildren)
  1563. }
  1564. // 搜索模式
  1565. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1566. return ols.count
  1567. }
  1568. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1569. if self.noteSearchMode {
  1570. return self.noteSearchArray.count
  1571. }
  1572. let count = self.annoListModel?.datas.count ?? 0
  1573. let hasAnno = self.allAnnotations.count >= 1
  1574. self.noteSearchButton.isEnabled = hasAnno
  1575. self.noteFilterButton.isEnabled = hasAnno
  1576. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1577. if count < 1 {
  1578. self.showNoteEmptyView()
  1579. } else {
  1580. self.hideNoteEmptyView()
  1581. }
  1582. return count
  1583. }
  1584. return 0
  1585. }
  1586. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1587. if outlineView.isEqual(to: self.tocOutlineView) {
  1588. if self.isLocked() {
  1589. return ""
  1590. }
  1591. let bks = self.bookmarks() ?? []
  1592. let bkNum = bks.isEmpty ? 0 : 1
  1593. if item == nil {
  1594. if self.isSearchOutlineMode {
  1595. guard let rootOL = self.outlineRoot(), rootOL.numberOfChildren > 0 else {
  1596. return ""
  1597. }
  1598. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1599. return ols.safe_element(for: index) as Any
  1600. }
  1601. if index == 0 && bkNum == 1 {
  1602. return Self.kOutlineRootBookmarkItem
  1603. }
  1604. let idx = bkNum == 1 ? index-1 : index
  1605. let rootOL = self.outlineRoot()
  1606. return rootOL?.child(at: UInt(idx)) as Any
  1607. } else {
  1608. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1609. return bks[index]
  1610. }
  1611. if item is CPDFBookmark {
  1612. return ""
  1613. }
  1614. if let ol = item as? CPDFOutline {
  1615. if self.isSearchOutlineMode == false {
  1616. return ol.child(at: UInt(index)) as Any
  1617. }
  1618. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1619. return ols.safe_element(for: index) as Any
  1620. }
  1621. }
  1622. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1623. if self.noteSearchMode {
  1624. return self.noteSearchArray[index]
  1625. }
  1626. return self.annoListModel?.datas[index] as Any
  1627. }
  1628. return item as Any
  1629. }
  1630. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1631. if outlineView.isEqual(to: self.tocOutlineView) {
  1632. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  1633. let columnId = tableColumn?.identifier.rawValue
  1634. var title = ""
  1635. var pageLabel = ""
  1636. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1637. title = NSLocalizedString("Bookmarks", comment: "")
  1638. } else if let ol = item as? CPDFOutline {
  1639. title = ol.label
  1640. if ol.actionType == .page {
  1641. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  1642. }
  1643. } else if let bk = item as? CPDFBookmark {
  1644. title = bk.label
  1645. pageLabel = "\(bk.pageIndex + 1)"
  1646. }
  1647. cell.pageLabel.stringValue = pageLabel
  1648. if columnId == kLabelColumnId.rawValue {
  1649. if self.isSearchOutlineMode {
  1650. let attriString = NSMutableAttributedString(string: title)
  1651. var searchString = self.outlineSearchField.stringValue
  1652. var roughString = title
  1653. if self.outlineIgnoreCaseFlag {
  1654. roughString = roughString.lowercased()
  1655. searchString = searchString.lowercased()
  1656. }
  1657. let ranges = roughString.ranges(of: searchString)
  1658. for range in ranges.nsRnage {
  1659. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  1660. }
  1661. cell.tocLabel.attributedStringValue = attriString
  1662. } else {
  1663. cell.tocLabel.stringValue = title
  1664. }
  1665. }
  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. }