KMLeftSideViewController.swift 149 KB

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