KMLeftSideViewController.swift 147 KB

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