KMLeftSideViewController.swift 115 KB

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