KMLeftSideViewController.swift 150 KB

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