KMLeftSideViewController.swift 157 KB

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