KMLeftSideViewController.swift 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848
  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 allFoldNotes: [CPDFAnnotation] = []
  124. var canFoldNotes: [CPDFAnnotation] = []
  125. var isRenameNoteOutline = false
  126. // 注释列表数据源
  127. var annotations: [KMBOTAAnnotationSection] = []
  128. // 所有注释
  129. var allAnnotations: [CPDFAnnotation] = []
  130. // 注释搜索模式标记
  131. var noteSearchMode = false
  132. // 注释搜索数组
  133. var noteSearchArray: [CPDFAnnotation] = []
  134. // 注释搜索 忽略大小写标识
  135. var caseInsensitiveNoteSearch = false
  136. // 快照
  137. var snapshotCacheSize: CGFloat = 32 * 3
  138. var isSearchSnapshotMode = false
  139. var snapshots: [KMSnapshotModel] = []
  140. var dirtySnapshots: [KMSnapshotWindowController] = []
  141. var searchSnapshots: [KMSnapshotModel] = []
  142. // 搜索
  143. private var _findState: KMFindState = .none
  144. var findState: KMFindState {
  145. get {
  146. return self._findState
  147. }
  148. set {
  149. if self._findState != newValue {
  150. self._findState = newValue
  151. self.displayFindState()
  152. if self._findState == .content {
  153. self.search(self.searchField)
  154. } else if self.findState == .note {
  155. self.searchNotes(nil)
  156. } else if self.findState == .snapshot {
  157. self.searchNotes(self.searchField)
  158. }
  159. }
  160. }
  161. }
  162. var searchResults : [KMSearchMode] = [] {
  163. didSet {
  164. self.updataLeftSideFindView()
  165. }
  166. }
  167. var groupSearchResults: [KMSearchMode] = []
  168. var findPaneState: KMFindPaneState = .singular
  169. var searchResultIndex: Int = 0
  170. var foldType: KMFoldAllAnnotationType = .none
  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.reloadAnnotation()
  444. self.searchViewController.contentView = nil
  445. if let data = self.noteOutlineView.enclosingScrollView {
  446. self.replaceSideView(data, animate: animate)
  447. }
  448. if (self.findState != .note) {
  449. self.findState = .note
  450. } else {
  451. self.displayFindState()
  452. }
  453. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  454. frame.origin.y = 0
  455. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  456. self.noteOutlineView.enclosingScrollView?.frame = frame
  457. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  458. frame.origin.y = 0
  459. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  460. self.noteOutlineView.enclosingScrollView?.frame = frame
  461. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  462. frame.origin.y = 0
  463. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  464. self.snapshotTableView.enclosingScrollView?.frame = frame
  465. let view = self.noteOutlineView.enclosingScrollView
  466. let viewFrame = view?.frame ?? .zero
  467. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  468. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  469. DispatchQueue.main.async {
  470. self.noteOutlineView.reloadData()
  471. }
  472. }
  473. func displaySnapshotViewAnimating(_ animate: Bool) {
  474. self.searchViewController.contentView = nil
  475. if let data = self.snapshotTableView.enclosingScrollView {
  476. self.replaceSideView(data, animate: animate)
  477. }
  478. if (self.findState != .snapshot) {
  479. self.findState = .snapshot
  480. } else {
  481. self.displayFindState()
  482. }
  483. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  484. frame.origin.y = 0
  485. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  486. self.snapshotTableView.enclosingScrollView?.frame = frame
  487. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  488. frame.origin.y = 0
  489. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  490. self.noteOutlineView.enclosingScrollView?.frame = frame
  491. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  492. frame.origin.y = 0
  493. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  494. self.tocOutlineView.enclosingScrollView?.frame = frame
  495. Task { @MainActor in
  496. self.snapshotTableView.reloadData()
  497. }
  498. }
  499. func displayFind() {
  500. self.searchField = self.searchViewController.searchField
  501. let menu = NSMenu()
  502. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  503. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  504. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  505. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  506. self.searchViewController.searchField.action = #selector(search)
  507. self.searchViewController.searchField.target = self
  508. if (self.findPaneState == .singular) {
  509. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  510. self.findTableView.wantsLayer = true
  511. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  512. DispatchQueue.main.async {
  513. self.findTableView.reloadData()
  514. }
  515. } else if (self.findPaneState == .grouped) {
  516. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  517. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  518. array.sort(){$0.datas.count > $1.datas.count}
  519. self.groupSearchResults = array
  520. self.groupedFindTableView.reloadData()
  521. }
  522. }
  523. func displayTocViewAnimating(_ animate: Bool) {
  524. if let data = self.tocOutlineView.enclosingScrollView {
  525. self.replaceSideView(data, animate: animate)
  526. }
  527. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  528. frame.origin.y = 0
  529. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  530. self.tocOutlineView.enclosingScrollView?.frame = frame
  531. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  532. frame.origin.y = 0
  533. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  534. self.noteOutlineView.enclosingScrollView?.frame = frame
  535. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  536. frame.origin.y = 0
  537. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  538. self.snapshotTableView.enclosingScrollView?.frame = frame
  539. let view = self.tocOutlineView.enclosingScrollView
  540. let viewFrame = view?.frame ?? .zero
  541. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  542. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  543. DispatchQueue.main.async {
  544. self.tocOutlineView.reloadData()
  545. self.updateOutlineSelection()
  546. }
  547. }
  548. func displayNoteFind() {
  549. self.searchField = self.noteSearchField
  550. let menu = NSMenu()
  551. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  552. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  553. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  554. self.noteSearchField.action = #selector(searchNotes)
  555. self.noteSearchField.target = self
  556. }
  557. func displaySnapshotFind() {
  558. self.searchField = self.snapshotSearchField;
  559. let menu = NSMenu()
  560. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  561. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  562. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  563. self.snapshotSearchField.action = #selector(searchNotes)
  564. self.snapshotSearchField.target = self
  565. self.snapshotSearchField.delegate = self
  566. }
  567. func resetThumbnails(ks: Bool = true) {
  568. self.thumbnails.removeAll()
  569. let pageLabels = self.pdfDocument()?.pageLabels() ?? []
  570. if (pageLabels.isEmpty == false) {
  571. for (i, label) in pageLabels.enumerated() {
  572. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  573. thumbnail.dirty = true
  574. self.thumbnails.append(thumbnail)
  575. }
  576. }
  577. DispatchQueue.main.async {
  578. let ris = self.thumbnailTableView.selectedRowIndexes
  579. self.thumbnailTableView.reloadData()
  580. if ks {
  581. self.thumbnailTableView.km_safe_selectRowIndexes(ris, byExtendingSelection: false)
  582. }
  583. }
  584. }
  585. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  586. let button = sender as? NSButton
  587. let tag = button?.tag ?? 0
  588. if (tag == 310) {
  589. self.outlineSearchField.isHidden = true
  590. self.outlineDoneButton.isHidden = true
  591. self.outlineLabel.isHidden = false
  592. self.outlineSearchButton.isHidden = false
  593. self.outlineMoreButton.isHidden = false
  594. self.outlineAddButton.isHidden = false
  595. } else if (tag == 311) {
  596. self.noteSearchField.isHidden = true
  597. self.noteTitleLabel.isHidden = false
  598. self.noteSearchButton.isHidden = false
  599. self.noteDoneButton.isHidden = true
  600. self.noteFilterButton.isHidden = false
  601. self.noteMoreButton.isHidden = false
  602. } else if (tag == 312) {
  603. self.snapshotSearchField.isHidden = true
  604. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  605. self.snapshotNormalSearchButton.isHidden = false
  606. self.snapshotDoneButton.isHidden = true
  607. self.snapshotLabel.isHidden = false
  608. self.snapshotNormalZoomOutButton.isHidden = false
  609. self.snapshotNormalZoomInButton.isHidden = false
  610. }
  611. }
  612. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  613. let tag = sender.tag
  614. if (tag == 0 || tag == 1) {
  615. var scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  616. if (scaling <= 0) {
  617. scaling = 1
  618. }
  619. if (tag == 0) { // Zoom In
  620. scaling += self.scalingIncrement
  621. } else if (tag == 1) { // Zoom Out
  622. scaling -= self.scalingIncrement
  623. if scaling <= 0.4 {
  624. return
  625. }
  626. }
  627. KMDataManager.ud_set(scaling, forKey: Self.Key.thumbSizeScaling)
  628. let selectRow = self.thumbnailTableView.selectedRow
  629. self.thumbnailTableView.reloadData()
  630. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  631. } else if (tag == 2 || tag == 3) {
  632. var scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  633. if (scaling <= 0) {
  634. scaling = 1
  635. }
  636. if (tag == 2) { // Zoom In
  637. scaling += self.scalingIncrement
  638. } else if (tag == 3) { // Zoom Out
  639. scaling -= self.scalingIncrement
  640. }
  641. KMDataManager.ud_set(scaling, forKey: Self.Key.snapshotSizeScaling)
  642. let selectRow = self.snapshotTableView.selectedRow
  643. self.snapshotTableView.reloadData()
  644. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  645. }
  646. }
  647. func tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  648. if tv.isEqual(to: self.thumbnailTableView) {
  649. self._copysPages.removeAll()
  650. for idx in rowIndexes {
  651. if (idx != NSNotFound) {
  652. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  653. self._copysPages.append(page)
  654. }
  655. }
  656. }
  657. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  658. }
  659. }
  660. }
  661. // MARK: - KMBotaTableViewDelegate
  662. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  663. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  664. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  665. return rowIndexes.count > 0
  666. }
  667. return false
  668. }
  669. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  670. if aTableView.isEqual(to: self.thumbnailTableView) {
  671. if self._copysPages.count > 0 {
  672. return true
  673. }
  674. }
  675. return false
  676. }
  677. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  678. if aTableView.isEqual(to: self.snapshotTableView) {
  679. return rowIndexes.count > 0
  680. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  681. if self.pageCount() <= 1 {
  682. return false
  683. }
  684. return true
  685. }
  686. return false
  687. }
  688. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  689. if IAPProductsManager.default().isAvailableAllFunction() == false {
  690. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  691. return
  692. }
  693. if aTableView.isEqual(to: self.thumbnailTableView) {
  694. if self._copysPages.count > 0 {
  695. let index = self.currentPageIndex()
  696. if (index == NSNotFound) {
  697. return
  698. }
  699. let idx = index + 1
  700. for page in self._copysPages.reversed() {
  701. self.pdfDocument()?.insertPageObject(page, at: UInt(idx))
  702. self.layoutDocumentView()
  703. self.resetThumbnails()
  704. let pageIndex = min(idx, self.pageCount()-1)
  705. self.listView?.go(toPageIndex: Int(pageIndex), animated: true)
  706. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  707. }
  708. }
  709. }
  710. }
  711. func tableViewMoveLeft(_ aTableView: NSTableView) {
  712. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  713. // [self updateFindResultHighlightsForDirection:NSSelectingPrevious];
  714. }
  715. }
  716. func tableViewMoveRight(_ aTableView: NSTableView) {
  717. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  718. // [self updateFindResultHighlightsForDirection:NSSelectingNext];
  719. }
  720. }
  721. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  722. if aTableView.isEqual(to: self.findTableView) {
  723. if rowIndex >= self.searchResults.count {
  724. return nil
  725. }
  726. let model = self.searchResults[rowIndex]
  727. let selection = model.selection
  728. let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  729. return CPDFDestination(document: self.pdfDocument(), pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.scaleFactor().cgFloat)
  730. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  731. if rowIndex >= self.groupSearchResults.count {
  732. return nil
  733. }
  734. // let model = self.groupSearchResults[rowIndex]
  735. // let selection = model.selection
  736. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  737. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  738. }
  739. return nil
  740. }
  741. }
  742. // MARK: - 扩展
  743. extension KMLeftSideViewController {
  744. public func selectType(_ type: BotaType) {
  745. // 更新 type
  746. var show = true
  747. if (self.type.methodType == .None) {
  748. show = true
  749. } else {
  750. if (self.type.methodType == type) {
  751. show = false
  752. } else {
  753. show = true
  754. }
  755. }
  756. self.type = self.getMethodMode(show ? type : .None)
  757. // 将事件传递出去
  758. self.delegate?.controlStateChange?(self,show:show)
  759. }
  760. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  761. let mode = KMLeftMethodMode()
  762. mode.methodType = type
  763. switch type {
  764. case .None:
  765. mode.methodName = ""
  766. break
  767. case .Thumbnail:
  768. mode.methodName = thumbnailMethodKey
  769. break
  770. case .Outline:
  771. mode.methodName = outlineMethodKey
  772. break
  773. case .BookMark:
  774. mode.methodName = bookMarkMethodKey
  775. break
  776. case .Annotation:
  777. mode.methodName = anntationMethodKey
  778. break
  779. case .Search:
  780. mode.methodName = searchMethodKey
  781. break
  782. case .From:
  783. mode.methodName = formMethodKey
  784. break
  785. case .Signature:
  786. mode.methodName = signatureMethodKey
  787. break
  788. case .snapshot:
  789. mode.methodName = snapshotMethodKey
  790. }
  791. return mode
  792. }
  793. }
  794. //MARK: Cache
  795. extension KMLeftSideViewController {
  796. func clearNotification() {}
  797. }
  798. // MARK: - Private Methods
  799. extension KMLeftSideViewController {
  800. func updateViewColor() {
  801. self._updateViewColor()
  802. }
  803. private func _updateViewColor() {
  804. if(KMAppearance.isDarkMode()){
  805. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  806. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  807. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  808. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  809. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  810. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  811. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  812. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  813. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  814. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  815. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  816. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  817. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  818. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  819. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  820. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  821. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  822. } else {
  823. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  824. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  825. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  826. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  827. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  828. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  829. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  830. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  831. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  832. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  833. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  834. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  835. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  836. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  837. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  838. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  839. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  840. }
  841. }
  842. func hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  843. var label = outline.label ?? ""
  844. var searchLabel = searchString
  845. if self.outlineIgnoreCaseFlag {
  846. label = label.lowercased()
  847. searchLabel = searchLabel.lowercased()
  848. }
  849. if label.contains(searchLabel) {
  850. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  851. return true
  852. } else {
  853. var subHas = false
  854. for i in 0 ..< outline.numberOfChildren {
  855. if let subOutline = outline.child(at: i) {
  856. subHas = self.hasContainString(searchString, rootOutline: subOutline)
  857. } else {
  858. continue
  859. }
  860. if (subHas) {
  861. break
  862. }
  863. }
  864. return subHas
  865. }
  866. }
  867. }
  868. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  869. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  870. func numberOfRows(in tableView: NSTableView) -> Int {
  871. if tableView.isEqual(to: self.thumbnailTableView) {
  872. return self.thumbnails.count
  873. } else if tableView.isEqual(to: self.findTableView) {
  874. return self.searchResults.count
  875. } else if tableView.isEqual(to: self.groupedFindTableView) {
  876. return self.groupSearchResults.count
  877. } else if tableView.isEqual(to: self.snapshotTableView) {
  878. if self.isSearchSnapshotMode {
  879. return self.searchSnapshots.count
  880. }
  881. return self.snapshots.count
  882. }
  883. return 0
  884. }
  885. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  886. if tableView.isEqual(to: self.thumbnailTableView) {
  887. let cell = tableView.makeView(withIdentifier: KMThumbnailTableviewCell.km_identifier, owner: self) as! KMThumbnailTableviewCell
  888. let thumbnail = self.thumbnails[row]
  889. cell.pageNumLabel.stringValue = thumbnail.label
  890. // cell.thumImage.image = thumbnail.image
  891. cell.pageView.page = self.pdfDocument()?.page(at: UInt(row))
  892. // if let _image = thumbnail.image {
  893. // let multiplierHToW = _image.size.height / (_image.size.width == 0 ? 1 : _image.size.width)
  894. // let multiplierWToH = _image.size.width / (_image.size.height == 0 ? 1 : _image.size.height)
  895. // if (_image.size.height > _image.size.width) {
  896. // NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  897. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .height, relatedBy: .equal, toItem: cell.thumImage, attribute: .width, multiplier: multiplierHToW, constant: 0)
  898. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  899. // } else {
  900. // NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  901. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .width, relatedBy: .equal, toItem: cell.thumImage, attribute: .height, multiplier: multiplierWToH, constant: 0)
  902. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  903. // }
  904. // }
  905. if (self.isDisplayPageSize) {
  906. cell.sizeLabel.isHidden = false
  907. //获取Page的真实尺寸
  908. let page = self.pdfDocument()?.page(at: UInt(row))
  909. let rect = page?.bounds(for: .cropBox) ?? .zero
  910. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  911. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  912. if let data = page?.rotation, data == 90 || data == 270 {
  913. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  914. } else {
  915. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  916. }
  917. } else {
  918. cell.sizeLabel.isHidden = true
  919. }
  920. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  921. if (self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  922. cell.isSelectCell = true
  923. } else {
  924. cell.isSelectCell = false
  925. }
  926. return cell
  927. } else if (tableView.isEqual(to: self.findTableView)) {
  928. let cell = tableView.makeView(withIdentifier: KMFindTableviewCell.km_identifier, owner: self) as! KMFindTableviewCell
  929. let selection = searchResults[row]
  930. if let data = tableColumn?.identifier.rawValue, data == kResultsColumnId.rawValue {
  931. cell.resultLabel.attributedStringValue = selection.attributedString
  932. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  933. } else if let data = tableColumn?.identifier.rawValue, data == kPageColumnId.rawValue {
  934. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  935. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  936. }
  937. return cell
  938. } else if tableView.isEqual(to: self.snapshotTableView) {
  939. let cell = tableView.makeView(withIdentifier: KMSnapshotTableViewCell.km_identifier, owner: self) as! KMSnapshotTableViewCell
  940. var snapshot: KMSnapshotModel?
  941. if self.isSearchSnapshotMode {
  942. snapshot = self.searchSnapshots[row]
  943. } else {
  944. snapshot = self.snapshots[row]
  945. }
  946. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  947. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  948. if let data = snapshot?.windowC?.hasWindow, data {
  949. cell.snapshotImageView.isHidden = false
  950. } else {
  951. cell.snapshotImageView.isHidden = true
  952. }
  953. cell.isSelectCell = snapshot?.isSelected ?? false
  954. if (row == tableView.selectedRow) {
  955. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  956. } else {
  957. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  958. }
  959. return cell
  960. }
  961. return nil
  962. }
  963. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  964. if tableView.isEqual(to: self.thumbnailTableView) {
  965. let scaling = KMDataManager.ud_float(forKey: Self.Key.thumbSizeScaling)
  966. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  967. let newScaling: CGFloat = scaling.cgFloat + 0.1
  968. let newThumbnailHeight = thumbnailSize.width * newScaling
  969. if (newThumbnailHeight > Self.kMinSidePaneWidth) {
  970. self.thumbnailZoomOutButton.isEnabled = false
  971. } else {
  972. self.thumbnailZoomOutButton.isEnabled = true
  973. }
  974. if ((scaling - 0.1) < 0.4) {
  975. self.thumbnailZoomInButton.isEnabled = false
  976. } else {
  977. self.thumbnailZoomInButton.isEnabled = true
  978. }
  979. var labelHeight = 0.0
  980. if (self.isDisplayPageSize) {
  981. labelHeight = 56.0
  982. } else {
  983. labelHeight = 41.5
  984. }
  985. let cellHeight = thumbnailSize.height + labelHeight
  986. var thumbSize: NSSize = .zero
  987. if (scaling > 0) {
  988. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  989. } else {
  990. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  991. }
  992. return thumbSize.height
  993. } else if tableView.isEqual(to: self.snapshotTableView) {
  994. let scaling = KMDataManager.ud_float(forKey: Self.Key.snapshotSizeScaling)
  995. let snapshotSize = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC?.thumbnail?.size ?? CGSizeMake(120, 63)
  996. var newScaling = scaling + 0.1
  997. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  998. if (newSnapshotHeight > Self.kMinSidePaneWidth) {
  999. self.snapshotNormalZoomInButton.isEnabled = false
  1000. } else {
  1001. self.snapshotNormalZoomInButton.isEnabled = true
  1002. }
  1003. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  1004. self.snapshotNormalZoomOutButton.isEnabled = false
  1005. } else {
  1006. self.snapshotNormalZoomOutButton.isEnabled = true
  1007. }
  1008. let cellHeight = snapshotSize.height + 24.0
  1009. var thumbSize: NSSize = .zero
  1010. if (scaling > 0) {
  1011. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  1012. } else {
  1013. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  1014. }
  1015. return thumbSize.height
  1016. } else if (tableView.isEqual(to: self.findTableView)) {
  1017. return 40.0
  1018. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1019. return 16
  1020. }
  1021. return tableView.rowHeight
  1022. }
  1023. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  1024. if (tableView.isEqual(to: self.findTableView)) {
  1025. let rowView = KMBotaTableRowView()
  1026. return rowView
  1027. } else if tableView.isEqual(to: self.groupedFindTableView) {
  1028. let rowView = KMGroupFindTableRowView()
  1029. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  1030. let model = self.groupSearchResults[row]
  1031. rowView.number = model.datas.count
  1032. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  1033. return rowView
  1034. }
  1035. return nil
  1036. }
  1037. func tableViewSelectionIsChanging(_ notification: Notification) {
  1038. }
  1039. func tableViewSelectionDidChange(_ notification: Notification) {
  1040. self.delegate?.controller?(controller: self, listViewSelectionDidChange: notification.object, info: nil)
  1041. if self.findTableView.isEqual(to: notification.object) {
  1042. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1043. let row = self.findTableView.selectedRow
  1044. if row >= 0 {
  1045. let model = self.searchResults[row]
  1046. self.listView?.go(to: model.selection, animated: true)
  1047. self.listView?.setHighlightedSelection(model.selection, animated: true)
  1048. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  1049. }
  1050. } else if self.groupedFindTableView.isEqual(to: notification.object) {
  1051. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  1052. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  1053. self.thumbnailTableView.ks_reloadData()
  1054. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1055. let row = self.snapshotTableView.selectedRow
  1056. // 更新选中数据
  1057. for (i, model) in self.snapshots.enumerated() {
  1058. model.isSelected = i == row
  1059. }
  1060. if (row != -1) {
  1061. let controller = (self.snapshots.safe_element(for: row) as? KMSnapshotModel)?.windowC
  1062. if let data = controller?.window?.isVisible, data {
  1063. controller?.window?.orderFront(self)
  1064. }
  1065. }
  1066. self.snapshotTableView.ks_reloadData()
  1067. }
  1068. }
  1069. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  1070. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  1071. return NSDragOperation(rawValue: 0)
  1072. }
  1073. let pboard = info.draggingPasteboard
  1074. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  1075. return .move
  1076. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  1077. guard let pbItems = pboard.pasteboardItems else {
  1078. return NSDragOperation(rawValue: 0)
  1079. }
  1080. var hasValidFile = false
  1081. for item in pbItems {
  1082. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  1083. continue
  1084. }
  1085. let type = _url.pathExtension.lowercased()
  1086. if type == "pdf" || KMImageToPDFMethod.supportedImageTypes().contains(type) {
  1087. hasValidFile = true
  1088. }
  1089. }
  1090. if (!hasValidFile) {
  1091. return NSDragOperation(rawValue: 0)
  1092. } else {
  1093. return .move
  1094. }
  1095. }
  1096. return NSDragOperation(rawValue: 0)
  1097. }
  1098. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  1099. var result = false
  1100. if tableView.isEqual(to: self.thumbnailTableView) == false {
  1101. return result
  1102. }
  1103. let pasteboard = info.draggingPasteboard
  1104. if (pasteboard.availableType(from: [.localDraggedTypes]) != nil) {
  1105. result = true
  1106. guard let rowData = pasteboard.data(forType: .localDraggedTypes) else {
  1107. return false
  1108. }
  1109. let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData) as? IndexSet ?? IndexSet()
  1110. guard let urlData = pasteboard.data(forType: KPDFThumbnailDoucumentURLForDraggedTypes) else {
  1111. return false
  1112. }
  1113. let url = NSKeyedUnarchiver.unarchiveObject(with: urlData) as? String
  1114. if url != nil && url != self.pdfDocument()?.documentURL.absoluteString {
  1115. if (pasteboard.availableType(from: [.fileURL]) != nil) {
  1116. let fileNames = pasteboard.propertyList(forType: .fileURL) as? [String] ?? []
  1117. if (fileNames.count == 1) {
  1118. let path = fileNames.first ?? ""
  1119. let pathExtension = path.pathExtension.lowercased()
  1120. if pathExtension == "pdf" {
  1121. var index = row
  1122. var insertIndexSet = IndexSet()
  1123. let pdf = CPDFDocument(url: URL(fileURLWithPath: path))
  1124. if let data = pdf?.isEncrypted, data {
  1125. KMBaseWindowController.checkPassword(url: URL(fileURLWithPath: path), type: .owner) { success, resultPassword in
  1126. if success && resultPassword.isEmpty == false {
  1127. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1128. if let page = pdf?.page(at: i).copy() as? CPDFPage {
  1129. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1130. insertIndexSet.insert(index)
  1131. index += 1
  1132. }
  1133. }
  1134. self.insertPages(insertIndexSet, pageAt: index-1)
  1135. }
  1136. }
  1137. } else {
  1138. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1139. let page = pdf?.page(at: i)
  1140. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1141. insertIndexSet.insert(index)
  1142. index += 1
  1143. }
  1144. self.insertPages(insertIndexSet, pageAt: index-1)
  1145. }
  1146. }
  1147. return true
  1148. }
  1149. }
  1150. }
  1151. var pageIndex = 0
  1152. var pages: [CPDFPage] = []
  1153. for idx in rowIndexes {
  1154. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1155. pages.append(page)
  1156. }
  1157. }
  1158. var toPage: CPDFPage?
  1159. if row < self.pageCount() {
  1160. toPage = self.pdfDocument()?.page(at: UInt(row))
  1161. }
  1162. var toPageIndex = 0
  1163. if (toPage != nil) {
  1164. toPageIndex = Int(self.pdfDocument()?.index(for: toPage) ?? 0)
  1165. } else {
  1166. toPageIndex = self.pageCount()
  1167. }
  1168. for i in 0 ..< pages.count {
  1169. let page = pages[i]
  1170. self.pdfDocument()?.insertPageObject(page, at: UInt(toPageIndex+i))
  1171. pageIndex += 1
  1172. self.listView?.go(toPageIndex: toPageIndex+i, animated: false)
  1173. }
  1174. self.layoutDocumentView()
  1175. var deletepages: [CPDFPage] = []
  1176. for idx in rowIndexes {
  1177. if idx < toPageIndex {
  1178. if((idx+pageIndex) < self.pageCount()) {
  1179. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1180. deletepages.append(page)
  1181. }
  1182. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1183. }
  1184. } else {
  1185. if((idx+pageIndex) < self.pageCount()) {
  1186. if let page = self.pdfDocument()?.page(at: UInt(idx+pageIndex)) {
  1187. deletepages.append(page)
  1188. }
  1189. self.pdfDocument()?.removePage(at: IndexSet(integer: idx+pageIndex))
  1190. }
  1191. }
  1192. }
  1193. self.layoutDocumentView()
  1194. self.resetThumbnails()
  1195. } else if pasteboard.availableType(from: [.fileURL]) != nil && tableView.isEqual(to: self.thumbnailTableView) {
  1196. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1197. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1198. return false
  1199. }
  1200. let fileNames = pasteboard.propertyList(forType: .fileURL)
  1201. var insertIndexSet = IndexSet()
  1202. var index = row
  1203. // if (fileNames.count == 1) {
  1204. if fileNames != nil {
  1205. // var path = fileNames.first as? String ?? ""
  1206. let path = fileNames as? String ?? ""
  1207. let url = URL(string: path)
  1208. let pathExtension = url?.pathExtension.lowercased() ?? ""
  1209. if pathExtension == "pdf" {
  1210. let pdf = CPDFDocument(url: url!)
  1211. if let data = pdf?.isEncrypted, data {
  1212. KMBaseWindowController.checkPassword(url: url!, type: .owner) { success, resultPassword in
  1213. if success && resultPassword.isEmpty == false {
  1214. pdf?.unlock(withPassword: resultPassword)
  1215. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1216. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1217. if let page = pdf?.page(at: i) {
  1218. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1219. insertIndexSet.insert(index)
  1220. index += 1
  1221. }
  1222. }
  1223. self.insertPages(insertIndexSet, pageAt: index-1)
  1224. }
  1225. }
  1226. } else {
  1227. for i in 0 ..< (pdf?.pageCount ?? 0) {
  1228. // let page = pdf?.page(at: i).copy() as? CPDFPage
  1229. if let page = pdf?.page(at: i) {
  1230. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  1231. insertIndexSet.insert(index)
  1232. index += 1
  1233. }
  1234. }
  1235. self.insertPages(insertIndexSet, pageAt: index-1)
  1236. }
  1237. } else if KMImageToPDFMethod.supportedImageTypes().contains(pathExtension) {
  1238. if let image = NSImage(contentsOfFile: url?.path ?? "") {
  1239. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  1240. // [pdfView.document insertPage:page atIndex:index];
  1241. _ = self.pdfDocument()?.km_insert(image: image, at: UInt(index))
  1242. insertIndexSet.insert(index)
  1243. self.insertPages(insertIndexSet, pageAt: index-1)
  1244. }
  1245. }
  1246. result = true
  1247. } else {
  1248. result = false
  1249. }
  1250. }
  1251. return result == false
  1252. }
  1253. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  1254. if tableView.isEqual(to: self.thumbnailTableView) {
  1255. let idx = rowIndexes.first ?? NSNotFound
  1256. if (idx != NSNotFound && self.isLocked()) {
  1257. let page = self.pdfDocument()?.page(at: UInt(idx))
  1258. var fileExt: String?
  1259. let tiffData = page?.PDFListViewTIFFData(for: page?.bounds(for: self.displayBox()) ?? .zero)
  1260. if self.allowsPrinting() {
  1261. // NSData *pdfData = [page dataRepresentation];
  1262. fileExt = "pdf"
  1263. // filenames
  1264. pboard.declareTypes([.pdf, .tiff, .fileURL, .filePromise, .localDraggedTypes, KPDFThumbnailDoucumentURLForDraggedTypes], owner: self)
  1265. // let newDoc = CPDFDocument()
  1266. // newDoc?.insertPageObject(page, at: 0)
  1267. // let data = newDoc?.dataRepresentation()
  1268. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  1269. pboard.setData(tiffData, forType: .pdf)
  1270. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  1271. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: rowIndexes)
  1272. pboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  1273. let documentURL = NSKeyedArchiver.archivedData(withRootObject: self.pdfDocument()?.documentURL?.absoluteString)
  1274. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  1275. var docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1276. // __block NSMutableString *pagesName = nil;
  1277. var pagesName = ""
  1278. if (rowIndexes.count > 1) {
  1279. pagesName = " pages"
  1280. } else {
  1281. pagesName = " page"
  1282. }
  1283. let tFileName = String(format: "%@ %@", pagesName, self.fileNameWithSelectedPages(rowIndexes))
  1284. let pdf = CPDFDocument()
  1285. for idx in rowIndexes {
  1286. // var copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1287. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1288. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1289. }
  1290. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  1291. var cachesDir = paths.first ?? ""
  1292. docmentName = String(format: "%@%@", docmentName, tFileName)
  1293. if (docmentName.count > 50) {
  1294. docmentName = docmentName.substring(to: 50)
  1295. }
  1296. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  1297. cachesDir = "\(cachesDir)/\(docmentName).pdf"
  1298. let success = pdf?.write(toFile: cachesDir) ?? false
  1299. if (success) {
  1300. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  1301. pboard.setPropertyList([cachesDir], forType: .fileURL)
  1302. } else{
  1303. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  1304. pboard.setPropertyList([], forType: .fileURL)
  1305. }
  1306. pboard.setData(documentURL, forType: KPDFThumbnailDoucumentURLForDraggedTypes)
  1307. } else {
  1308. fileExt = "tiff"
  1309. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1310. }
  1311. pboard.setData(tiffData, forType: .tiff)
  1312. // kPasteboardTypeFileURLPromise
  1313. pboard.setPropertyList([fileExt], forType: .filePromise)
  1314. return true
  1315. }
  1316. } else if self.snapshotTableView.isEqual(to: tableView) {
  1317. let idx = rowIndexes.first ?? NSNotFound
  1318. if (idx != NSNotFound) {
  1319. let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC
  1320. if let data = snapshot?.thumbnailWithSize(0)?.tiffRepresentation {
  1321. pboard.declareTypes([.tiff, .filePromise], owner: self)
  1322. pboard.setData(data, forType: .tiff)
  1323. pboard.setPropertyList(["tiff"], forType: .filePromise)
  1324. return true
  1325. }
  1326. }
  1327. }
  1328. return false
  1329. }
  1330. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forRowIndexes rowIndexes: IndexSet) {
  1331. self.dragIn = true
  1332. }
  1333. func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1334. self.dragIn = false
  1335. }
  1336. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  1337. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1338. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1339. return
  1340. }
  1341. if aTableView.isEqual(to: self.snapshotTableView) {
  1342. var controllers: [KMSnapshotWindowController] = []
  1343. for i in rowIndexes {
  1344. let model: KMSnapshotModel? = self.snapshots.safe_element(for: i) as? KMSnapshotModel
  1345. if let winC = model?.windowC {
  1346. controllers.append(winC)
  1347. }
  1348. }
  1349. for c in controllers {
  1350. c.close()
  1351. }
  1352. } else if aTableView.isEqual(to: self.thumbnailTableView) {
  1353. for idx in rowIndexes {
  1354. if idx >= self.pageCount() {
  1355. return
  1356. }
  1357. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  1358. for anno in page.annotations {
  1359. page.removeAnnotation(anno)
  1360. }
  1361. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  1362. self.pdfDocument()?.removePage(at: IndexSet(integer: idx))
  1363. }
  1364. }
  1365. if rowIndexes.isEmpty == false {
  1366. self.layoutDocumentView()
  1367. self.resetThumbnails()
  1368. let idx = rowIndexes.first ?? -1
  1369. let index = min(idx, self.pageCount()-1)
  1370. self.listView?.go(toPageIndex: index, animated: false)
  1371. }
  1372. }
  1373. }
  1374. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  1375. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1376. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1377. return
  1378. }
  1379. if aTableView.isEqual(to: self.thumbnailTableView) {
  1380. self._copysPages.removeAll()
  1381. if self.isLocked() == false {
  1382. for idx in rowIndexes {
  1383. if let page = self.pdfDocument()?.page(at: UInt(idx))?.copy() as? CPDFPage {
  1384. self._copysPages.append(page)
  1385. }
  1386. }
  1387. }
  1388. } else if aTableView.isEqual(to: self.findTableView) {
  1389. var string = ""
  1390. for idx in rowIndexes {
  1391. let match = self.searchResults[idx].selection
  1392. string.append("* ")
  1393. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  1394. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  1395. // [string appendFormat:@"", [[match contextString] string]];
  1396. string = string.appendingFormat(": %@\n", match.string() ?? "")
  1397. }
  1398. let pboard = NSPasteboard.general
  1399. pboard.clearContents()
  1400. pboard.writeObjects([string as NSPasteboardWriting])
  1401. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1402. var string = ""
  1403. for idx in rowIndexes {
  1404. let result = self.groupSearchResults[idx]
  1405. let matches = result.datas
  1406. string.append("* ")
  1407. string = string.appendingFormat(KMLocalizedString("Page %@", ""), "\(result.selectionPageIndex)")
  1408. string.append(": ")
  1409. string = string.appendingFormat(KMLocalizedString("%ld Results", ""), matches.count)
  1410. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  1411. var tmpString = ""
  1412. for model in matches {
  1413. tmpString.append("\(model.selection.string() ?? "")")
  1414. }
  1415. string = string.appendingFormat(":\n\t%@\n", tmpString)
  1416. }
  1417. let pboard = NSPasteboard.general
  1418. pboard.clearContents()
  1419. pboard.writeObjects([string as NSPasteboardWriting])
  1420. }
  1421. }
  1422. func tableView(_ tableView: NSTableView, namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedRowsWith indexSet: IndexSet) -> [String] {
  1423. if self.thumbnailTableView.isEqual(to: tableView) {
  1424. var fileURLArray: [String] = []
  1425. if indexSet.count > 1 {
  1426. var docmentName = ""
  1427. let tFileName = String(format: "%@", self.fileNameWithSelectedPages(indexSet))
  1428. let pdf = CPDFDocument()
  1429. for idx in indexSet {
  1430. if idx != NSNotFound && self.isLocked() == false {
  1431. // let copyPage = self.listView.document.page(at: UInt(idx)).copy() as? CPDFPage
  1432. let copyPage = self.pdfDocument()?.page(at: UInt(idx))
  1433. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1434. }
  1435. }
  1436. let fileURL = dropDestination.appendingPathComponent(tFileName).appendingPathExtension("pdf").uniqueFileURL()
  1437. docmentName = fileURL.path
  1438. let success = pdf?.write(toFile: docmentName) ?? false
  1439. if(success) {
  1440. fileURLArray.append(fileURL.lastPathComponent)
  1441. }
  1442. } else {
  1443. if let page = self.pdfDocument()?.page(at: UInt(indexSet.first ?? 0)) {
  1444. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page))
  1445. if self.allowsPrinting() {
  1446. fileURL = fileURL.appendingPathExtension("pdf").uniqueFileURL()
  1447. let pdf = CPDFDocument()
  1448. // let copyPage = page.copy() as? CPDFPage
  1449. let copyPage = page
  1450. pdf?.insertPageObject(copyPage, at: pdf?.pageCount ?? 0)
  1451. let success = pdf?.write(toFile: fileURL.path) ?? false
  1452. if success {
  1453. fileURLArray.append(fileURL.lastPathComponent)
  1454. }
  1455. } else {
  1456. fileURL = fileURL.appendingPathExtension("tiff").uniqueFileURL()
  1457. let fileData = page.PDFListViewTIFFData(for: page.bounds(for: self.displayBox()))
  1458. let success = (try?fileData?.write(to: fileURL)) != nil
  1459. if success {
  1460. fileURLArray.append(fileURL.lastPathComponent)
  1461. }
  1462. }
  1463. }
  1464. }
  1465. return fileURLArray
  1466. } else if self.snapshotTableView.isEqual(to: tableView) {
  1467. let idx = indexSet.first ?? NSNotFound
  1468. if (idx != NSNotFound) {
  1469. if let snapshot = (self.snapshots.safe_element(for: idx) as? KMSnapshotModel)?.windowC {
  1470. if let page = self.pdfDocument()?.page(at: snapshot.pageIndex()) {
  1471. var fileURL = dropDestination.appendingPathComponent(self.draggedFileName(for: page)).appendingPathExtension("tiff")
  1472. fileURL = fileURL.uniqueFileURL()
  1473. if ((try?snapshot.thumbnailWithSize(0)?.tiffRepresentation?.write(to: fileURL)) != nil) {
  1474. return [fileURL.lastPathComponent]
  1475. }
  1476. }
  1477. }
  1478. }
  1479. }
  1480. return []
  1481. }
  1482. func tableViewColumnDidResize(_ notification: Notification) {
  1483. guard let column = notification.userInfo?["NSTableColumn"] as? NSTableColumn else {
  1484. return
  1485. }
  1486. if column.identifier.rawValue == IMAGE_COLUMNID {
  1487. if self.thumbnailTableView.isEqual(to: notification.object) {
  1488. self.thumbnailTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.thumbnailTableView.numberOfRows)) as IndexSet)
  1489. } else if self.snapshotTableView.isEqual(to: notification.object) {
  1490. self.snapshotTableView.noteHeightOfRows(withIndexesChanged: NSIndexSet(indexesIn: NSMakeRange(0, self.snapshotTableView.numberOfRows)) as IndexSet)
  1491. }
  1492. }
  1493. }
  1494. func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
  1495. if tableView.isEqual(to: self.groupedFindTableView) {
  1496. // [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  1497. }
  1498. }
  1499. /*
  1500. #pragma mark NSTableView delegate protocol
  1501. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  1502. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1503. NSUInteger idx = [rowIndexes firstIndex];
  1504. if (idx != NSNotFound) {
  1505. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  1506. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  1507. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1508. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  1509. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  1510. [self fileWithPage:page atPath:filePath];
  1511. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  1512. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  1513. } else {
  1514. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  1515. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  1516. }
  1517. }
  1518. }
  1519. }
  1520. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  1521. NSData *data = [page dataRepresentation];
  1522. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  1523. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  1524. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  1525. if (success) {
  1526. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  1527. NSURL *url = [NSURL fileURLWithPath:filePath];
  1528. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  1529. }
  1530. [document release];
  1531. */
  1532. }
  1533. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  1534. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  1535. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  1536. if outlineView.isEqual(to: self.tocOutlineView) {
  1537. if self.isLocked() {
  1538. return 0
  1539. }
  1540. if item == nil { // 第一层
  1541. guard let rootOL = self.outlineRoot() else {
  1542. self.showOutlineEmptyView()
  1543. return 0
  1544. }
  1545. // 搜索按钮
  1546. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  1547. if self.isSearchOutlineMode { // 是否为搜索模块
  1548. if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  1549. self.showSearchOutlineBlankState(true)
  1550. return 0
  1551. }
  1552. self.showSearchOutlineBlankState(false)
  1553. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1554. return ols.count
  1555. }
  1556. if rootOL.numberOfChildren == 0 { // 没有数据
  1557. self.showOutlineEmptyView()
  1558. return 0
  1559. }
  1560. // 有数据
  1561. self.hideOutlineEmptyView()
  1562. let bks = self.bookmarks() ?? []
  1563. let bkNum = bks.isEmpty ? 0 : 1
  1564. return Int(rootOL.numberOfChildren) + bkNum
  1565. } else { // 第二层 +
  1566. if item is CPDFBookmark { // 书签
  1567. return 0
  1568. }
  1569. if let data = item as? String, data == Self.kOutlineRootBookmarkItem { // 书签group
  1570. if self.isSearchOutlineMode {
  1571. return 0
  1572. }
  1573. return (self.bookmarks()?.count) ?? 0
  1574. }
  1575. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  1576. return 0
  1577. }
  1578. if self.isSearchOutlineMode == false {
  1579. return Int(ol.numberOfChildren)
  1580. }
  1581. // 搜索模式
  1582. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1583. return ols.count
  1584. }
  1585. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1586. if self.noteSearchMode {
  1587. return self.noteSearchArray.count
  1588. }
  1589. var count = 0
  1590. for section in self.annotations {
  1591. if let cnt = section.annotations?.count {
  1592. count += cnt
  1593. }
  1594. }
  1595. if (self.allAnnotations.count < 1) {
  1596. self.noteSearchButton.isEnabled = false
  1597. self.noteFilterButton.isEnabled = false
  1598. } else {
  1599. self.noteSearchButton.isEnabled = true
  1600. self.noteFilterButton.isEnabled = true
  1601. }
  1602. if count < 1 {
  1603. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1604. let view = self.noteOutlineView.enclosingScrollView
  1605. let viewFrame = view?.frame ?? .zero
  1606. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  1607. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  1608. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1609. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  1610. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  1611. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  1612. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  1613. self.noteHeaderView.isHidden = true
  1614. self.toolButtonBoxLayoutConstraint.constant = 40.0
  1615. }
  1616. } else {
  1617. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  1618. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  1619. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  1620. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  1621. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  1622. self.noteHeaderView.isHidden = false
  1623. self.toolButtonBoxLayoutConstraint.constant = 64.0
  1624. }
  1625. }
  1626. return count
  1627. }
  1628. return 0
  1629. }
  1630. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  1631. if outlineView.isEqual(to: self.tocOutlineView) {
  1632. if self.isLocked() {
  1633. return ""
  1634. }
  1635. let bks = self.bookmarks() ?? []
  1636. let bkNum = bks.isEmpty ? 0 : 1
  1637. if item == nil {
  1638. if self.isSearchOutlineMode {
  1639. guard let rootOL = self.outlineRoot(), rootOL.numberOfChildren > 0 else {
  1640. return ""
  1641. }
  1642. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  1643. return ols.safe_element(for: index) as Any
  1644. }
  1645. if index == 0 && bkNum == 1 {
  1646. return Self.kOutlineRootBookmarkItem
  1647. }
  1648. let idx = bkNum == 1 ? index-1 : index
  1649. let rootOL = self.outlineRoot()
  1650. return rootOL?.child(at: UInt(idx)) as Any
  1651. } else {
  1652. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1653. return bks[index]
  1654. }
  1655. if item is CPDFBookmark {
  1656. return ""
  1657. }
  1658. if let ol = item as? CPDFOutline {
  1659. if self.isSearchOutlineMode == false {
  1660. return ol.child(at: UInt(index)) as Any
  1661. }
  1662. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  1663. return ols.safe_element(for: index) as Any
  1664. }
  1665. }
  1666. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1667. if self.noteSearchMode {
  1668. return self.noteSearchArray[index]
  1669. }
  1670. var tempArray: [KMBOTAAnnotationItem] = []
  1671. for secion in self.annotations {
  1672. if secion.annotations?.count != 0 {
  1673. for _item in secion.annotations! {
  1674. tempArray.append(_item)
  1675. }
  1676. }
  1677. }
  1678. return tempArray[index] as Any
  1679. }
  1680. return item as Any
  1681. }
  1682. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  1683. if outlineView.isEqual(to: self.tocOutlineView) {
  1684. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  1685. let columnId = tableColumn?.identifier.rawValue
  1686. var title = ""
  1687. var pageLabel = ""
  1688. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1689. title = NSLocalizedString("Bookmarks", comment: "")
  1690. } else if let ol = item as? CPDFOutline {
  1691. title = ol.label
  1692. if ol.actionType == .page {
  1693. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  1694. }
  1695. } else if let bk = item as? CPDFBookmark {
  1696. title = bk.label
  1697. pageLabel = "\(bk.pageIndex + 1)"
  1698. }
  1699. cell.pageLabel.stringValue = pageLabel
  1700. if columnId == kLabelColumnId.rawValue {
  1701. if self.isSearchOutlineMode {
  1702. let attriString = NSMutableAttributedString(string: title)
  1703. var searchString = self.outlineSearchField.stringValue
  1704. var roughString = title
  1705. if self.outlineIgnoreCaseFlag {
  1706. roughString = roughString.lowercased()
  1707. searchString = searchString.lowercased()
  1708. }
  1709. let ranges = roughString.ranges(of: searchString)
  1710. for range in ranges.nsRnage {
  1711. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  1712. }
  1713. cell.tocLabel.attributedStringValue = attriString
  1714. } else {
  1715. cell.tocLabel.stringValue = title
  1716. }
  1717. }
  1718. return cell
  1719. } else if outlineView.isEqual(to: self.noteOutlineView) {
  1720. let model = item as? KMBOTAAnnotationItem
  1721. var note: CPDFAnnotation?
  1722. if self.noteSearchMode {
  1723. note = item as? CPDFAnnotation
  1724. } else {
  1725. note = (item as? KMBOTAAnnotationItem)?.annotation
  1726. }
  1727. let cell = outlineView.makeView(withIdentifier: KMNoteTableViewCell.km_identifier, owner: self) as! KMNoteTableViewCell
  1728. cell.cellNote = note
  1729. let noteColor = note?.color
  1730. var noteType = note?.type ?? ""
  1731. var noteString = ""
  1732. if let data = note {
  1733. noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: data)
  1734. }
  1735. let pageString = "\((note?.page?.pageIndex() ?? 0) + 1)"
  1736. var dateString = ""
  1737. if let date = note?.modificationDate() {
  1738. dateString = KMTools.timeString(timeDate: date)
  1739. }
  1740. let authorString = note?.userName() ?? ""
  1741. let noteTextString = note?.string() ?? ""
  1742. // if([noteType isEqualToString:@"Redact"]) {
  1743. // noteString = @"Redact";
  1744. // }
  1745. //
  1746. let timeKey = self.noteTypeDict[Self.Key.noteFilterTime] as? Bool
  1747. if timeKey == nil || timeKey == false {
  1748. cell.timeLabel.stringValue = dateString
  1749. cell.timeLabel.isHidden = false
  1750. } else {
  1751. cell.timeLabel.isHidden = true
  1752. }
  1753. let pageKey = self.noteTypeDict[Self.Key.noteFilterPage] as? Bool
  1754. if pageKey == nil || pageKey == false {
  1755. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  1756. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  1757. cell.pageLabel.stringValue = pageString
  1758. cell.pageLabel.isHidden = false
  1759. } else {
  1760. cell.pageLabel.isHidden = true
  1761. }
  1762. let autherKey = self.noteTypeDict[Self.Key.noteFilterAuther] as? Bool
  1763. if autherKey == nil || autherKey == false {
  1764. cell.autherLabel.stringValue = authorString
  1765. cell.autherLabel.isHidden = false
  1766. } else {
  1767. cell.autherLabel.isHidden = true
  1768. }
  1769. let imageView = KMNoteTypeImageView()
  1770. if let data = note {
  1771. if data.isKind(of: CPDFStampAnnotation.self) {
  1772. let annotation_stamp = data as! CPDFStampAnnotation
  1773. if (annotation_stamp.stampImage() != nil) {
  1774. noteType = SKNStampString
  1775. }
  1776. } else if data.isKind(of: CPDFLineAnnotation.self) {
  1777. let annotation_line = data as! CPDFLineAnnotation
  1778. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  1779. noteType = SKNLine_NoneString
  1780. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  1781. noteType = SKNLine_OpenArrowString
  1782. } else {
  1783. noteType = SKNLine_NoneString
  1784. }
  1785. } else if data.isKind(of: CPDFButtonWidgetAnnotation.self) {
  1786. let buttonWidget = data as! CPDFButtonWidgetAnnotation
  1787. if buttonWidget.controlType() == .radioButtonControl {
  1788. noteType = KMAnnotationFormRadioButtonKey
  1789. } else if buttonWidget.controlType() == .checkBoxControl {
  1790. noteType = KMAnnotationFormCheckBoxKey
  1791. } else if buttonWidget.controlType() == .pushButtonControl {
  1792. noteType = KMAnnotationFormActionButtonKey
  1793. }
  1794. } else if data.isKind(of: CPDFTextWidgetAnnotation.self) {
  1795. noteType = KMAnnotationFormTextFieldKey
  1796. } else if data.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  1797. let choiceWidget = data as! CPDFChoiceWidgetAnnotation
  1798. if choiceWidget.isListChoice {
  1799. noteType = KMAnnotationFormListMenuKey
  1800. } else {
  1801. noteType = KMAnnotationFormComboBoxKey
  1802. }
  1803. } else if data.isKind(of: KMTableAnnotation.self) {
  1804. noteType = "Ink_Table"
  1805. } else if data.isKind(of: KMSelfSignAnnotation.self) {
  1806. let selfSignNote = data as! KMSelfSignAnnotation
  1807. if selfSignNote.annotationType == .signFalse {
  1808. noteType = "KMSelfSignTypeFalseActionButtonKey"
  1809. } else if (selfSignNote.annotationType == .signature) {
  1810. noteType = "KMSelfSignTypeTureActionButtonKey"
  1811. } else if (selfSignNote.annotationType == .signCircle) {
  1812. noteType = "KMSelfSignTypeCircleActionButtonKey"
  1813. } else if (selfSignNote.annotationType == .signLine) {
  1814. noteType = "KMSelfSignTypeLineActionButtonKey"
  1815. } else if (selfSignNote.annotationType == .signDot) {
  1816. noteType = "KMSelfSignTypeDotActionButtonKey"
  1817. } else if (selfSignNote.annotationType == .signText) {
  1818. noteType = "KMSelfSignTypeTextActionButtonKey"
  1819. }
  1820. } else if data.isKind(of: CPDFSquareAnnotation.self) {
  1821. noteType = SKNSquareString
  1822. } else if data.isKind(of: CPDFTextAnnotation.self) {
  1823. noteType = SKNNoteString
  1824. } else if data.isKind(of: CPDFFreeTextAnnotation.self) {
  1825. noteType = SKNFreeTextString
  1826. } else if data.isKind(of: CPDFCircleAnnotation.self) {
  1827. noteType = SKNCircleString
  1828. } else if data.isKind(of: CPDFSignatureAnnotation.self) {
  1829. noteType = SKNSignatureString
  1830. } else if data.isKind(of: CPDFInkAnnotation.self) {
  1831. noteType = SKNInkString
  1832. } else if data.isKind(of: CPDFMarkupAnnotation.self) {
  1833. let anno = data as! CPDFMarkupAnnotation
  1834. if anno.markupType() == .highlight {
  1835. noteType = SKNHighlightString
  1836. } else if anno.markupType() == .underline {
  1837. noteType = SKNUnderlineString
  1838. } else if anno.markupType() == .strikeOut {
  1839. noteType = SKNStrikeOutString
  1840. }
  1841. }
  1842. }
  1843. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  1844. cell.typeImageView.isHidden = false
  1845. if note is CPDFMarkupAnnotation {
  1846. cell.isFold = true
  1847. }
  1848. cell.noteContentBox.isHidden = true
  1849. cell.noteImageView.isHidden = true
  1850. cell.foldButton.isHidden = true
  1851. cell.annotationContentLabel.isHidden = false
  1852. cell.noteContentLabel.stringValue = noteString
  1853. cell.contentView.isHidden = false
  1854. cell.contentViewHidden(false)
  1855. if let data = note {
  1856. if data.isKind(of: CPDFMarkupAnnotation.self) {
  1857. let markup = data as! CPDFMarkupAnnotation
  1858. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent())
  1859. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  1860. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  1861. cell.noteContentLabel.stringValue = contentString
  1862. if(contentString.isEmpty == false) {
  1863. cell.foldButton.isHidden = false
  1864. }
  1865. let attributeStr = NSMutableAttributedString(string: contentString)
  1866. if (markup.markupType() == .highlight) {
  1867. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  1868. } else if (markup.markupType() == .strikeOut) {
  1869. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  1870. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  1871. } else if (markup.markupType() == .underline) {
  1872. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  1873. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  1874. }
  1875. cell.annotationContentLabel.attributedStringValue = attributeStr
  1876. if self.foldType == .unfold {
  1877. // if let data = model?.foldType, data == .unfold { // 全部展开
  1878. cell.isFold = false
  1879. } else if self.foldType == .fold {
  1880. // else if let data = model?.foldType, data == .fold { // 全部折叠
  1881. cell.isFold = true
  1882. } else { // 混合
  1883. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(data) {
  1884. cell.isFold = false
  1885. } else {
  1886. cell.isFold = true
  1887. }
  1888. }
  1889. // noteString.isEmpty == false &&
  1890. if (contentString.isEmpty == false) {
  1891. cell.contentViewHidden(false)
  1892. } else {
  1893. cell.contentViewHidden(true)
  1894. }
  1895. } else if data.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  1896. noteString = data.page?.string(for: data.bounds) ?? ""
  1897. cell.annotationContentLabel.stringValue = noteString
  1898. if (noteString.isEmpty == false) {
  1899. cell.contentViewHidden(false)
  1900. } else {
  1901. cell.contentViewHidden(true)
  1902. }
  1903. } else if data.isKind(of: CPDFStampAnnotation.self) {
  1904. if data.isKind(of: KMSelfSignAnnotation.self) {
  1905. let newAnnotation = note as! KMSelfSignAnnotation
  1906. let type = newAnnotation.annotationType
  1907. var returnString = ""
  1908. if (type == .signFalse) {
  1909. returnString = KMLocalizedString("X", nil)
  1910. } else if (type == .signature) {
  1911. returnString = KMLocalizedString("Check mark", nil)
  1912. } else if (type == .signCircle) {
  1913. returnString = KMLocalizedString("Circle", nil)
  1914. } else if (type == .signLine) {
  1915. returnString = KMLocalizedString("Line", nil)
  1916. } else if (type == .signDot) {
  1917. returnString = KMLocalizedString("Dot", nil)
  1918. } else if (type == .signText) {
  1919. returnString = KMLocalizedString("Text", nil)
  1920. }
  1921. cell.annotationContentLabel.stringValue = returnString
  1922. } else {
  1923. cell.annotationContentLabel.isHidden = true
  1924. cell.noteImageView.isHidden = false
  1925. let anno = note as! CPDFStampAnnotation
  1926. cell.noteImageView.image = anno.stampImage()
  1927. }
  1928. } else if data.isKind(of: CPDFTextAnnotation.self) {
  1929. cell.foldButton.isHidden = false
  1930. if noteString.isEmpty {
  1931. cell.annotationContentLabel.stringValue = noteTextString
  1932. }else{
  1933. cell.annotationContentLabel.stringValue = noteString
  1934. cell.noteContentLabel.stringValue = noteTextString
  1935. }
  1936. if (self.foldType == .unfold) {
  1937. cell.isFold = false
  1938. } else if (self.foldType == .fold) {
  1939. cell.isFold = true
  1940. } else {
  1941. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(data) {
  1942. cell.isFold = false
  1943. } else {
  1944. cell.isFold = true
  1945. }
  1946. }
  1947. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  1948. cell.contentView.isHidden = false
  1949. } else {
  1950. cell.contentView.isHidden = true
  1951. cell.contentViewHidden(true)
  1952. }
  1953. // noteString.isEmpty == false &&
  1954. if (noteTextString.isEmpty == false) {
  1955. cell.foldButton.isHidden = false
  1956. }else{
  1957. cell.foldButton.isHidden = true
  1958. }
  1959. } else {
  1960. cell.annotationContentLabel.stringValue = noteString
  1961. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  1962. if (noteString.isEmpty == false) {
  1963. cell.contentViewHidden(false)
  1964. } else {
  1965. cell.contentViewHidden(true)
  1966. }
  1967. }
  1968. }
  1969. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  1970. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  1971. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  1972. if let data = note {
  1973. if data.isKind(of: CPDFStampAnnotation.self) && data.isKind(of: KMSelfSignAnnotation.self) == false {
  1974. } else {
  1975. if data.isKind(of: CPDFMarkupAnnotation.self) {
  1976. if (!cell.isFold) {
  1977. self.allFoldNotes.append(data)
  1978. } else {
  1979. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1980. }
  1981. } else {
  1982. cell.imageViewHeightConstraint.constant = 18.0 + 8
  1983. }
  1984. }
  1985. }
  1986. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  1987. model?.foldType = isUnfold ? .unfold : .fold
  1988. // let COLUMN_INDENTATION: CGFloat = 16
  1989. // if let _cell = tableColumn?.dataCell as? NSCell {
  1990. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  1991. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  1992. // let height = _cell.cellSize(forBounds: bound).height
  1993. // KMPrint(height)
  1994. // }
  1995. if cellNote is CPDFMarkupAnnotation {
  1996. // let content = cell.annotationContentLabel.attributedStringValue
  1997. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  1998. // KMPrint(bound)
  1999. // 154 34 273
  2000. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  2001. model?.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  2002. }
  2003. if (isUnfold) {
  2004. if let data = note {
  2005. if (self.allFoldNotes.contains(data)) {
  2006. self.allFoldNotes.removeObject(data)
  2007. }
  2008. }
  2009. if (self.allFoldNotes.count == 0) {
  2010. self.foldType = .fold
  2011. } else {
  2012. self.foldType = .none
  2013. }
  2014. } else {
  2015. if let data = note {
  2016. if self.allFoldNotes.contains(data) == false {
  2017. self.allFoldNotes.append(data)
  2018. }
  2019. }
  2020. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  2021. self.foldType = .unfold
  2022. // } else {
  2023. // self.foldType = KMFoldAllAnnotationType_None;
  2024. // }
  2025. }
  2026. }
  2027. return cell
  2028. }
  2029. return nil
  2030. }
  2031. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2032. if outlineView.isEqual(self.noteOutlineView) {
  2033. if let model = item as? KMBOTAAnnotationItem {
  2034. if model.foldType == .fold {
  2035. return model.foldH
  2036. }
  2037. if let anno = model.annotation {
  2038. return KMBOTAAnnotationTool.fetchCellHeight(annotation: anno, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  2039. }
  2040. }
  2041. return 30
  2042. } else if outlineView.isEqual(self.tocOutlineView) {
  2043. if let ol = item as? CPDFOutline {
  2044. let string: NSString = ol.label as NSString
  2045. let ps = NSMutableParagraphStyle()
  2046. ps.lineHeightMultiple = 1.32
  2047. ps.alignment = .left
  2048. let attris = [NSAttributedString.Key.paragraphStyle : ps,
  2049. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  2050. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attris)
  2051. return max(40, size.height + 16)
  2052. }
  2053. return 40
  2054. }
  2055. return outlineView.rowHeight
  2056. }
  2057. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2058. if outlineView.isEqual(self.tocOutlineView) {
  2059. if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  2060. return true
  2061. }
  2062. if item is CPDFBookmark {
  2063. return false
  2064. }
  2065. guard let ol = item as? CPDFOutline else {
  2066. return false
  2067. }
  2068. if self.isSearchOutlineMode == false {
  2069. return ol.numberOfChildren > 0
  2070. }
  2071. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  2072. return ols.count > 0
  2073. } else if outlineView.isEqual(to: self.noteOutlineView) {
  2074. // return [item hasNoteText];
  2075. return false
  2076. }
  2077. return false
  2078. }
  2079. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2080. if outlineView.isEqual(self.tocOutlineView) {
  2081. let itemView = KMBotaTableRowView()
  2082. return itemView
  2083. } else if outlineView.isEqual(self.noteOutlineView) {
  2084. let itemView = KMBotaTableRowView()
  2085. return itemView;
  2086. }
  2087. return nil
  2088. }
  2089. func outlineViewSelectionDidChange(_ notification: Notification) {
  2090. if self.tocOutlineView.isEqual(to: notification.object) {
  2091. if self.dragIn {
  2092. return
  2093. }
  2094. if self.updatingOutlineSelection == false {
  2095. self.updatingOutlineSelection = true
  2096. self.goToSelectedOutlineItem(nil)
  2097. self.updatingOutlineSelection = false
  2098. }
  2099. }
  2100. }
  2101. func outlineViewItemDidExpand(_ notification: Notification) {
  2102. if self.tocOutlineView.isEqual(to: notification.object) {
  2103. self.updateOutlineSelection()
  2104. }
  2105. }
  2106. func outlineViewItemDidCollapse(_ notification: Notification) {
  2107. if self.tocOutlineView.isEqual(to: notification.object) {
  2108. self.updateOutlineSelection()
  2109. }
  2110. }
  2111. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  2112. var dragOp = NSDragOperation(rawValue: 0)
  2113. if outlineView.isEqual(to: self.noteOutlineView) {
  2114. let pboard = info.draggingPasteboard
  2115. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) && index == NSOutlineViewDropOnItemIndex {
  2116. if let note = item as? CPDFAnnotation, note.type != nil {
  2117. dragOp = .every
  2118. }
  2119. }
  2120. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2121. if (index == -1) {
  2122. dragOp = NSDragOperation(rawValue: 0)
  2123. } else {
  2124. dragOp = .move
  2125. }
  2126. }
  2127. return dragOp
  2128. }
  2129. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  2130. if outlineView.isEqual(to: self.tocOutlineView) {
  2131. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  2132. return false
  2133. }
  2134. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  2135. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  2136. self._dragPDFOutline = items.first as? CPDFOutline
  2137. let set = IndexSet(integer: 0)
  2138. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  2139. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  2140. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  2141. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  2142. return true
  2143. }
  2144. return false
  2145. }
  2146. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  2147. if outlineView.isEqual(to: self.noteOutlineView) {
  2148. let pboard = info.draggingPasteboard
  2149. if pboard.canReadObject(forClasses: [NSColor.self], options: [:]) {
  2150. // [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  2151. let isShift = NSEvent.modifierFlags.contains(.shift)
  2152. let isAlt = NSEvent.modifierFlags.contains(.option)
  2153. guard let note = item as? CPDFAnnotation else {
  2154. NSSound.beep()
  2155. return false
  2156. }
  2157. if let color = NSColor(from: pboard) {
  2158. note.setColor(color, alternate: isAlt, updateDefaults: isShift)
  2159. return true
  2160. }
  2161. return false
  2162. }
  2163. } else if outlineView.isEqual(to: self.tocOutlineView) {
  2164. if (index < 0) {
  2165. return false
  2166. }
  2167. // guard let outline = item as? CPDFOutline else {
  2168. // return false
  2169. // }
  2170. let outline = item as? CPDFOutline
  2171. guard let dragPDFOL = self._dragPDFOutline else {
  2172. return false
  2173. }
  2174. //root,drag item to root
  2175. if ((outline?.parent == nil)) {
  2176. //fetch root
  2177. var root = dragPDFOL
  2178. while (root.parent != nil) {
  2179. root = root.parent
  2180. }
  2181. if dragPDFOL.parent.isEqual(to: root) {
  2182. if dragPDFOL.index > index {
  2183. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2184. } else {
  2185. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  2186. }
  2187. } else {
  2188. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  2189. }
  2190. } else {
  2191. //在同一个层级内移动
  2192. if dragPDFOL.parent.isEqual(to: item) {
  2193. if (dragPDFOL.index > 0) {
  2194. if dragPDFOL.index > index {
  2195. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2196. }else{
  2197. self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  2198. }
  2199. } else {
  2200. return false
  2201. }
  2202. } else {
  2203. var tOutlline: CPDFOutline? = outline
  2204. var isContains = false
  2205. while (tOutlline != nil) {
  2206. if tOutlline!.isEqual(to: self._dragPDFOutline) {
  2207. isContains = true
  2208. break
  2209. }
  2210. tOutlline = tOutlline?.parent
  2211. }
  2212. if (!isContains) {
  2213. self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  2214. }
  2215. }
  2216. }
  2217. return true
  2218. }
  2219. return false
  2220. }
  2221. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  2222. if outlineView.isEqual(to: self.tocOutlineView) {
  2223. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  2224. (cell as? NSCell)?.backgroundStyle = .lowered
  2225. }
  2226. }
  2227. }
  2228. func outlineView(_ outlineView: NSOutlineView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, byItem item: Any?) {
  2229. if outlineView.isEqual(to: self.noteOutlineView) {
  2230. // PDFAnnotation *note = item;
  2231. var note: CPDFAnnotation?
  2232. = item as? CPDFAnnotation
  2233. if let data = item as? CPDFAnnotation {
  2234. note = data
  2235. } else if let data = note as? KMBOTAAnnotationItem {
  2236. note = data.annotation
  2237. }
  2238. if let data = note?.type, data.isEmpty == false {
  2239. if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2240. let string1 = (object as? String) ?? ""
  2241. let string2 = note?.string() ?? ""
  2242. if string1 != string2 {
  2243. note?.setString(string1)
  2244. }
  2245. } else if tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2246. let string1 = (object as? String) ?? ""
  2247. let string2 = note?.userName() ?? ""
  2248. if string1 != string2 {
  2249. note?.setUserName(string1)
  2250. }
  2251. }
  2252. }
  2253. }
  2254. }
  2255. func outlineView(_ outlineView: NSOutlineView, dataCellFor tableColumn: NSTableColumn?, item: Any) -> NSCell? {
  2256. if self.noteOutlineView.isEqual(to: outlineView) {
  2257. if tableColumn == nil {
  2258. if let anno = item as? CPDFAnnotation, anno.type == nil {
  2259. return outlineView.tableColumn(withIdentifier: self.noteColumnId)?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2260. }
  2261. }
  2262. }
  2263. return tableColumn?.dataCell(forRow: outlineView.row(forItem: item)) as? NSCell
  2264. }
  2265. func outlineView(_ outlineView: NSOutlineView, shouldEdit tableColumn: NSTableColumn?, item: Any) -> Bool {
  2266. if outlineView.isEqual(to: self.noteOutlineView) {
  2267. if (tableColumn == nil) {
  2268. if self.hideNotes() == false {
  2269. if let anno = item as? CPDFAnnotation, anno.isNote() {
  2270. // if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  2271. // PDFAnnotation *annotation = [(SKNoteText *)item note];
  2272. self.listView?.scrollAnnotationToVisible(anno)
  2273. self.listView?.updateActiveAnnotations([anno])
  2274. // [self showNote:annotation];
  2275. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  2276. // [[noteController window] makeFirstResponder:[noteController textView]];
  2277. // [[noteController textView] selectAll:nil];
  2278. }
  2279. }
  2280. return false
  2281. } else if tableColumn?.identifier.rawValue == self.noteColumnId.rawValue || tableColumn?.identifier.rawValue == self.authorColumnId.rawValue {
  2282. return true
  2283. }
  2284. }
  2285. return false
  2286. }
  2287. func outlineView(_ outlineView: NSOutlineView, toolTipFor cell: NSCell, rect: NSRectPointer, tableColumn: NSTableColumn?, item: Any, mouseLocation: NSPoint) -> String {
  2288. if outlineView.isEqual(to: self.noteOutlineView) {
  2289. if tableColumn == nil || tableColumn?.identifier.rawValue == self.noteColumnId.rawValue {
  2290. return (item as? CPDFAnnotation)?.string() ?? ""
  2291. }
  2292. }
  2293. return ""
  2294. }
  2295. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
  2296. self.dragIn = true
  2297. }
  2298. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  2299. self.dragIn = false
  2300. }
  2301. /*
  2302. #pragma mark NSOutlineView delegate protocol
  2303. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  2304. if ([ov isEqual:rightSideController.noteOutlineView]) {
  2305. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  2306. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  2307. NSMutableArray *sortDescriptors = nil;
  2308. BOOL ascending = YES;
  2309. if ([oldTableColumn isEqual:newTableColumn]) {
  2310. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  2311. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  2312. ascending = [[sortDescriptors firstObject] ascending];
  2313. } else {
  2314. NSString *tcID = [newTableColumn identifier];
  2315. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  2316. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  2317. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  2318. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  2319. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  2320. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  2321. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  2322. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  2323. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2324. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  2325. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  2326. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  2327. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  2328. }
  2329. if (oldTableColumn)
  2330. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  2331. [ov setHighlightedTableColumn:newTableColumn];
  2332. }
  2333. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  2334. if (newTableColumn)
  2335. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  2336. inTableColumn:newTableColumn];
  2337. [ov reloadData];
  2338. }
  2339. }
  2340. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  2341. if (mwcFlags.autoResizeNoteRows &&
  2342. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  2343. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  2344. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  2345. [rowHeights removeAllFloats];
  2346. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  2347. }
  2348. }
  2349. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  2350. {
  2351. NSInteger rowCount = [outlineView numberOfRows];
  2352. for (NSInteger i = 0; i < rowCount; i++){
  2353. CGFloat rowHeight = 0;
  2354. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  2355. if (!outline){
  2356. continue;
  2357. }
  2358. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  2359. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  2360. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  2361. [attributedString appendAttributedString:attr1];
  2362. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  2363. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  2364. // id cell = [tableColumn dataCell];
  2365. id cell = [tableColumn dataCellForRow:i];
  2366. [cell setObjectValue:attributedString];
  2367. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  2368. NSInteger num = [self getNum:outline];
  2369. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  2370. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  2371. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  2372. [rowHeights setFloat:rowHeight forKey:outline];
  2373. if (@available(macOS 10.13, *)) {
  2374. } else {
  2375. rowHeight = 40.0;
  2376. }
  2377. // CGRect fram = viewS.frame;
  2378. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  2379. }
  2380. [leftSideController.tocOutlineView reloadData];
  2381. }
  2382. */
  2383. func noteItems(_ items: NSArray) -> NSArray {
  2384. let noteItems = NSMutableArray()
  2385. for item in items {
  2386. guard let anno = (item as? KMBOTAAnnotationItem)?.annotation else {
  2387. continue
  2388. }
  2389. if anno.type == nil {
  2390. // item = [(SKNoteText *)item note];
  2391. }
  2392. if noteItems.contains(anno) == false {
  2393. noteItems.add(anno)
  2394. }
  2395. }
  2396. return noteItems
  2397. }
  2398. }
  2399. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  2400. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  2401. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  2402. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2403. return self.hideNotes() == false && items.count > 0
  2404. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2405. return items.count > 0
  2406. }
  2407. return false
  2408. }
  2409. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  2410. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2411. if (items.isEmpty) {
  2412. return
  2413. }
  2414. for item in self.noteItems(items as NSArray) {
  2415. guard let anno = item as? CPDFAnnotation else {
  2416. continue
  2417. }
  2418. self.listView?.remove(anno)
  2419. }
  2420. self.listView?.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  2421. self.reloadAnnotation()
  2422. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  2423. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  2424. }
  2425. }
  2426. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  2427. if anOutlineView.isEqual(to: self.noteOutlineView) {
  2428. if (items.count == 1) {
  2429. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  2430. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  2431. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  2432. // return NO;
  2433. // }
  2434. }
  2435. return items.count > 0
  2436. }
  2437. return false
  2438. }
  2439. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  2440. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  2441. // let pboard = NSPasteboard.general
  2442. // var copiedItems: [Any] = []
  2443. // var attrString = NSMutableAttributedString()
  2444. // var isAttributed = false
  2445. // var item: AnyObject?
  2446. // for (item in [self noteItems:items]) {
  2447. // if ([item isMovable])
  2448. // [copiedItems addObject:item];
  2449. // }
  2450. // for (item in items) {
  2451. // if ([attrString length])
  2452. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  2453. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  2454. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  2455. // isAttributed = YES;
  2456. // } else {
  2457. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  2458. // }
  2459. // }
  2460. //
  2461. // [pboard clearContents];
  2462. // if (isAttributed)
  2463. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  2464. // else
  2465. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  2466. // if ([copiedItems count] > 0)
  2467. // [pboard writeObjects:copiedItems];
  2468. }
  2469. }
  2470. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  2471. if self.noteOutlineView.isEqual(to: anOutlineView) {
  2472. let count = self.noteOutlineView.numberOfRows
  2473. let texts = NSMutableArray(capacity: count)
  2474. for i in 0 ..< count {
  2475. let item = self.noteOutlineView.item(atRow: i)
  2476. let string = (item as? CPDFAnnotation)?.string() ?? ""
  2477. texts.add(string)
  2478. }
  2479. return texts
  2480. } else if self.tocOutlineView.isEqual(to: anOutlineView) {
  2481. let count = self.tocOutlineView.numberOfRows
  2482. let array = NSMutableArray(capacity: count)
  2483. for i in 0 ..< count {
  2484. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  2485. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  2486. array.add(item?.label ?? "")
  2487. }
  2488. return array
  2489. }
  2490. return NSArray()
  2491. }
  2492. }
  2493. // MARK: - Other
  2494. extension KMLeftSideViewController {
  2495. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  2496. if tv.isEqual(to: self.thumbnailTableView) {
  2497. guard let document = self.pdfDocument() else {
  2498. return
  2499. }
  2500. let pages = NSMutableArray()
  2501. for idx in self.thumbnailTableView.selectedRowIndexes {
  2502. if (idx < document.pageCount) {
  2503. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  2504. pages.add(page)
  2505. }
  2506. }
  2507. }
  2508. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  2509. let saveAccessCtr = KMSavePanelAccessoryController()
  2510. let outputSavePanel = NSSavePanel()
  2511. outputSavePanel.allowedFileTypes = ["pdf"]
  2512. outputSavePanel.accessoryView = saveAccessCtr.view
  2513. outputSavePanel.nameFieldStringValue = fileName
  2514. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  2515. if (result == .OK) {
  2516. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  2517. let vc = KMProgressWindowController()
  2518. self.view.window?.beginSheet(vc.window!)
  2519. let saveFilePath = outputSavePanel.url?.path
  2520. DispatchQueue.global().async {
  2521. let pdf = CPDFDocument()
  2522. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  2523. DispatchQueue.main.async {
  2524. if (success) {
  2525. if (saveAccessCtr.openAutomaticButton.state == .on) {
  2526. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  2527. }
  2528. } else {
  2529. KMTools.viewFile(at: saveFilePath!)
  2530. }
  2531. }
  2532. NSApp.endSheet(vc.window!)
  2533. vc.close()
  2534. }
  2535. }
  2536. }
  2537. }
  2538. }
  2539. }
  2540. }
  2541. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  2542. var pagesName = ""
  2543. if (itemIndexes.count > 1) {
  2544. pagesName.append(" pages")
  2545. } else {
  2546. pagesName.append(" page")
  2547. }
  2548. let docmentName = self.pdfDocument()?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2549. let tFileName = String(format: "%@ %@", pagesName,KMTools.parseIndexSet(indexSet: itemIndexes))
  2550. return String(format: "%@%@", docmentName,tFileName)
  2551. }
  2552. func draggedFileName(for page: CPDFPage) -> String {
  2553. let pageIndex = "\(page.pageIndex() + 1)"
  2554. var fileName = ""
  2555. if let doc = self.view.window?.windowController?.document as? NSDocument {
  2556. // fileName = doc.displayName.deletingPathExtension
  2557. fileName = doc.fileURL?.deletingPathExtension().lastPathComponent ?? (MainBundle.nameSpaceName ?? "")
  2558. }
  2559. return "\(fileName)-Page \(pageIndex)"
  2560. }
  2561. func switchType(_ type: BotaType) {
  2562. if type == .Thumbnail {
  2563. self.leftView.segmentedControl.selectedSegment = 0
  2564. } else if type == .Outline {
  2565. self.leftView.segmentedControl.selectedSegment = 1
  2566. } else if type == .Annotation {
  2567. self.leftView.segmentedControl.selectedSegment = 2
  2568. } else if type == .snapshot {
  2569. self.leftView.segmentedControl.selectedSegment = 3
  2570. } else if type == .Search {
  2571. self.leftView.segmentedControl.selectedSegment = 4
  2572. }
  2573. }
  2574. func updateTableFont() {
  2575. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  2576. self.tocOutlineView.font = font
  2577. self.noteOutlineView.font = font
  2578. self.findTableView.font = font
  2579. self.groupedFindTableView.font = font
  2580. }
  2581. }