KMLeftSideViewController.swift 131 KB

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