KMLeftSideViewController.swift 164 KB

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