KMLeftSideViewController.swift 164 KB

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