KMLeftSideViewController.swift 171 KB

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