KMLeftSideViewController.swift 163 KB

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