KMLeftSideViewController.swift 163 KB

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