KMLeftSideViewController.swift 166 KB

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