KMLeftSideViewController.swift 166 KB

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