KMLeftSideViewController.swift 165 KB

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