KMLeftSideViewController.swift 166 KB

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