KMLeftSideViewController.swift 163 KB

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