KMLeftSideViewController.swift 170 KB

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