KMLeftSideViewController.swift 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348
  1. //
  2. // KMLeftSideViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. @objc protocol KMLeftSideViewControllerDelegate {
  9. @objc optional func controlStateChange(_ obj: KMLeftSideViewController,show:Bool)
  10. @objc optional func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int])
  11. @objc optional func searchAction(searchString:String, isCase:Bool)
  12. @objc optional func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType)
  13. @objc optional func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  14. @objc optional func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem])
  15. @objc optional func controller(controller: KMLeftSideViewController, rotateType: KMRotateType)
  16. }
  17. class KMLeftSideViewController: KMSideViewController {
  18. var dataSource : [KMLeftMethodMode] = [KMLeftMethodMode]()
  19. var type : KMLeftMethodMode = KMLeftMethodMode()
  20. var isShowPanel : Bool = false
  21. var norImage : [String] = []
  22. var selectImage : [String] = []
  23. var mainVC: KMMainViewController?
  24. var selectPages: [Int]?
  25. open weak var delegate: KMLeftSideViewControllerDelegate?
  26. deinit {
  27. KMPrint("KMLeftSideViewController deinit.")
  28. NotificationCenter.default.removeObserver(self)
  29. }
  30. override var nibName: NSNib.Name? {
  31. return "LeftSideView"
  32. }
  33. convenience init(type : KMLeftMethodMode) {
  34. self.init()
  35. self.type = type
  36. }
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. self.reloadThumbnailSize()
  40. self.reloadSnapshotSize()
  41. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  42. self.isDisplayPageSize = UserDefaults.standard.bool(forKey: "kKMThumbnailDisplayPageSizeKey")
  43. }
  44. func showPanelView(show: Bool) {
  45. self.isShowPanel = show
  46. if show {
  47. self.leftView.segmentedControl.selectedSegment = 0
  48. } else {
  49. self.leftView.segmentedControl.selectedSegment = UInt8.max
  50. self.delegate?.controlStateChange?(self, show: false)
  51. }
  52. }
  53. func refreshMethodType(methodType: BotaType) {
  54. let newType = KMLeftMethodMode()
  55. var show = true
  56. if self.type.methodType != methodType {
  57. newType.methodType = methodType
  58. }
  59. if self.type.methodType == methodType {
  60. show = false
  61. } else if methodType == .None {
  62. show = false
  63. }
  64. self.type = newType;
  65. self.delegate?.controlStateChange?(self,show:show)
  66. }
  67. // MARK: - New
  68. /*
  69. NSArrayController *findArrayController;
  70. NSArrayController *groupedFindArrayController;
  71. }
  72. - (void)applySearchTableHeader:(NSString *)message;
  73. */
  74. @IBOutlet var segmentedControl: KMSegmentedControl!
  75. @IBOutlet var thumbnailTableView: KMThumbnailTableView!
  76. @IBOutlet var tocOutlineView: KMTocOutlineView!
  77. @IBOutlet var noteOutlineView: KMNoteOutlineView!
  78. @IBOutlet var findTableView: KMBotaTableView!
  79. @IBOutlet var groupedFindTableView: KMBotaTableView!
  80. @IBOutlet var snapshotTableView: KMBotaTableView!
  81. @IBOutlet weak var leftListView: NSView!
  82. @IBOutlet var searchViewController: KMBotaSearchViewController!
  83. @IBOutlet weak var toolButtonBox: NSBox!
  84. @IBOutlet weak var toolButtonBoxLayoutConstraint: NSLayoutConstraint!
  85. @IBOutlet weak var snapshotNormalView: NSView!
  86. @IBOutlet weak var snapshotLabel: NSTextField!
  87. @IBOutlet weak var snapshotNormalMoreButton: NSButton!
  88. @IBOutlet weak var snapshotNormalSearchButton: NSButton!
  89. @IBOutlet weak var snapshotNormalZoomOutButton: NSButton!
  90. @IBOutlet weak var snapshotNormalZoomInButton: NSButton!
  91. @IBOutlet weak var snapshotSearchZoomOutButton: NSButton!
  92. @IBOutlet weak var snapshotSearchZoomInButton: NSButton!
  93. @IBOutlet weak var snapshotSearchField: KMLeftSideViewSearchField!
  94. @IBOutlet weak var snapshotDoneButton: NSButton!
  95. @IBOutlet weak var outlineView: NSView!
  96. @IBOutlet weak var outlineMoreButton: NSButton!
  97. @IBOutlet weak var outlineAddButton: NSButton!
  98. @IBOutlet weak var outlineSearchButton: NSButton!
  99. @IBOutlet weak var outlineLabel: NSTextField!
  100. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  101. @IBOutlet weak var outlineDoneButton: NSButton!
  102. @IBOutlet weak var noteView: NSView!
  103. @IBOutlet weak var noteMoreButton: NSButton!
  104. @IBOutlet weak var noteFilterButton: NSButton!
  105. @IBOutlet weak var noteSearchButton: NSButton!
  106. @IBOutlet weak var noteSearchField: KMLeftSideViewSearchField!
  107. @IBOutlet weak var noteTitleLabel: NSTextField!
  108. @IBOutlet weak var noteHeaderView: NSView!
  109. @IBOutlet weak var sortTypeBox: KMBox!
  110. @IBOutlet weak var sortTypeLabel: NSTextField!
  111. @IBOutlet weak var noteSortButton: NSButton!
  112. @IBOutlet weak var noteDoneButton: NSButton!
  113. @IBOutlet weak var thumbnailView: NSView!
  114. @IBOutlet weak var thumbnailZoomOutButton: NSButton!
  115. @IBOutlet weak var thumbnailZoomInButton: NSButton!
  116. @IBOutlet weak var thumbnailTitleLabel: NSTextField!
  117. @IBOutlet weak var emptySearchBox: NSBox!
  118. @IBOutlet weak var emptySearchLabel: NSTextField!
  119. var filterButtonLayer: NSView?
  120. var moreButtonLayer: KMButtonLayer?
  121. var thumbnails: [KMThumbnail] = []
  122. var isDisplayPageSize = false
  123. var thumbnailCacheSize: CGFloat = 32 * 3
  124. var snapshotCacheSize: CGFloat = 32 * 3
  125. private var _findState: KMFindState = .none
  126. var findState: KMFindState {
  127. get {
  128. return self._findState
  129. }
  130. set {
  131. if self._findState != newValue {
  132. self._findState = newValue
  133. self.displayFindState()
  134. if self._findState == .content {
  135. self.search(self.searchField)
  136. } else if self.findState == .note {
  137. // self.searchNotes(self.searchField)
  138. self.searchNotes(nil)
  139. } else if self.findState == .snapshot {
  140. self.searchNotes(self.searchField)
  141. }
  142. }
  143. }
  144. }
  145. var searchResults : [KMSearchMode] = [] {
  146. didSet {
  147. self.updataLeftSideFindView()
  148. }
  149. }
  150. var groupSearchResults: [KMSearchMode] = []
  151. var findPaneState: KMFindPaneState = .singular
  152. var isSearchOutlineMode = false
  153. var isSearchSnapshotMode = false
  154. var outlineIgnoreCaseFlag = false
  155. var noteTypeDict: [String : Any] = [:]
  156. private let MIN_SIDE_PANE_WIDTH: CGFloat = 270
  157. private let LABEL_COLUMNID = "label"
  158. var foldType: KMFoldAllAnnotationType = .none
  159. private let KMLeftSideViewNoteSortTypeKey = "KMLeftSideViewNoteSortTypeKey"
  160. private let KMLeftSideViewAscendSortBoolKey = "KMLeftSideViewAscendSortBoolKey"
  161. private let SKDisableTableToolTipsKey = "SKDisableTableToolTips"
  162. var tocType: KMFoldType = .none
  163. var snapshots: [KMSnapshotModel] = []
  164. var searchSnapshots: [KMSnapshotModel] = []
  165. private var _noteSortType: KMNoteSortType = .none
  166. var noteSortType: KMNoteSortType {
  167. get {
  168. return self._noteSortType
  169. }
  170. set {
  171. self._noteSortType = newValue
  172. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  173. }
  174. }
  175. var isAscendSort = false {
  176. didSet {
  177. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMAnnotationSortTypeKeyNotification"), object: self)
  178. }
  179. }
  180. lazy var leftSideEmptyVC: KMLeftSideEmptyFileViewController = {
  181. let vc = KMLeftSideEmptyFileViewController(nibName: "KMLeftSideEmptyFileViewController", bundle: nil)
  182. vc.view.wantsLayer = true
  183. return vc
  184. }()
  185. var preThumbnailRow: Int = 0
  186. var leftMargin: CGFloat = 0
  187. lazy var leftView: KMBotaLeftView = {
  188. let view = KMBotaLeftView()
  189. return view
  190. }()
  191. private var _copysPages: [CPDFPage] = []
  192. var copyPages: [CPDFPage] {
  193. get {
  194. return self._copysPages
  195. }
  196. }
  197. private var _annotations: [KMBOTAAnnotationSection] = []
  198. private var _allAnnotations: [CPDFAnnotation] = []
  199. var allAnnotations: [CPDFAnnotation] {
  200. get {
  201. return self._allAnnotations
  202. }
  203. }
  204. private let kKMPDFViewOutlineDragDataType = "kKMPDFViewOutlineDragDataType"
  205. private let KPDFThumbnailDoucumentURLForDraggedTypes = "KPDFThumbnailDoucumentURLForDraggedTypes"
  206. var renamePDFOutline: CPDFOutline?
  207. var renamePDFOutlineTextField: NSTextField?
  208. var allFoldNotes: [CPDFAnnotation] = []
  209. var notes: [CPDFAnnotation] = []
  210. var canFoldNotes: [CPDFAnnotation] = []
  211. var isRenameNoteOutline = false
  212. var caseInsensitiveNoteSearch = false
  213. var noteSearchArray: [CPDFAnnotation] = []
  214. var noteSearchMode = false
  215. var mwcFlags: MwcFlags = MwcFlags()
  216. override func loadView() {
  217. super.loadView()
  218. self.view.wantsLayer = true
  219. self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  220. self.view.addSubview(self.leftView)
  221. self.leftView.frame = NSMakeRect(0, 0, 44, NSHeight(self.view.frame))
  222. self.leftView.autoresizingMask = [.height]
  223. self.leftView.wantsLayer = true
  224. self.leftView.layer?.backgroundColor = .white
  225. self.outlineView.wantsLayer = true
  226. self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  227. self.noteView.wantsLayer = true
  228. self.noteView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  229. self.thumbnailView.wantsLayer = true
  230. self.thumbnailView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  231. self.snapshotNormalView.wantsLayer = true
  232. self.snapshotNormalView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  233. self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  234. self.noteOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  235. self.findTableView.backgroundColor = KMAppearance.Layout.l0Color()
  236. self.groupedFindTableView.backgroundColor = KMAppearance.Layout.l0Color()
  237. self.snapshotTableView.backgroundColor = KMAppearance.Layout.l0Color()
  238. self.thumbnailTableView.backgroundColor = KMAppearance.Layout.l0Color()
  239. self.leftListView.wantsLayer = true
  240. self.leftListView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  241. self.emptySearchLabel.stringValue = KMLocalizedString("No Results",nil)
  242. self.emptySearchLabel.textColor = KMAppearance.Layout.h0Color()
  243. self.emptySearchBox.isHidden = true
  244. self.thumbnailTitleLabel.stringValue = KMLocalizedString("Thumbnails", nil)
  245. self.thumbnailTitleLabel.textColor = KMAppearance.Layout.h0Color()
  246. self.thumbnailZoomInButton.action = #selector(thumbnailSizeScaling)
  247. self.thumbnailZoomInButton.target = self
  248. self.thumbnailZoomInButton.tag = 1
  249. self.thumbnailZoomOutButton.action = #selector(thumbnailSizeScaling)
  250. self.thumbnailZoomOutButton.target = self
  251. self.thumbnailZoomOutButton.tag = 0
  252. self.snapshotTableView.delegate = self
  253. self.snapshotTableView.dataSource = self
  254. self.snapshotTableView.menu = NSMenu()
  255. self.snapshotTableView.menu?.delegate = self
  256. self.snapshotTableView.doubleAction = #selector(toggleSelectedSnapshots)
  257. self.snapshotTableView.target = self
  258. self.snapshotTableView.backgroundColor = .clear
  259. // [snapshotTableView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
  260. self.snapshotLabel.stringValue = KMLocalizedString("Snapshots", nil)
  261. self.snapshotLabel.textColor = KMAppearance.Layout.h0Color()
  262. self.snapshotNormalZoomInButton.action = #selector(thumbnailSizeScaling)
  263. self.snapshotNormalZoomInButton.target = self
  264. self.snapshotNormalZoomInButton.tag = 2
  265. self.snapshotNormalZoomOutButton.action = #selector(thumbnailSizeScaling)
  266. self.snapshotNormalZoomOutButton.target = self
  267. self.snapshotNormalZoomOutButton.tag = 3
  268. self.snapshotNormalSearchButton.toolTip = KMLocalizedString("Search", nil)
  269. self.snapshotNormalMoreButton.action = #selector(leftSideViewMoreButtonAction)
  270. self.snapshotNormalMoreButton.target = self
  271. self.snapshotNormalMoreButton.tag = 300
  272. self.snapshotSearchZoomInButton.action = #selector(thumbnailSizeScaling)
  273. self.snapshotSearchZoomInButton.target = self
  274. self.snapshotSearchZoomInButton.tag = 2
  275. self.snapshotSearchZoomOutButton.action = #selector(thumbnailSizeScaling)
  276. self.snapshotSearchZoomOutButton.target = self
  277. self.snapshotSearchZoomOutButton.tag = 3
  278. self.snapshotDoneButton.title = KMLocalizedString("Done", nil)
  279. self.snapshotDoneButton.toolTip = KMLocalizedString("Done", nil)
  280. self.snapshotDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  281. self.snapshotDoneButton.wantsLayer = true
  282. self.snapshotDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  283. self.snapshotDoneButton.layer?.cornerRadius = 4.0
  284. self.snapshotDoneButton.action = #selector(leftSideViewDoneButtonAction)
  285. self.snapshotDoneButton.target = self
  286. self.snapshotDoneButton.tag = 312
  287. self.snapshotDoneButton.isHidden = true
  288. self.noteOutlineView.autoresizesOutlineColumn = false
  289. self.noteOutlineView.delegate = self
  290. self.noteOutlineView.dataSource = self
  291. self.noteOutlineView.botaDelegate = self
  292. self.noteOutlineView.botaDataSource = self
  293. self.noteOutlineView.noteDelegate = self
  294. self.noteOutlineView.menu = NSMenu()
  295. self.noteOutlineView.menu?.delegate = self
  296. // [noteOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  297. self.noteOutlineView.indentationPerLevel = 0
  298. // [noteOutlineView registerForDraggedTypes:[NSColor readableTypesForPasteboard:[NSPasteboard pasteboardWithName:NSDragPboard]]];
  299. self.noteOutlineView.target = self
  300. self.noteOutlineView.doubleAction = #selector(selectSelectedNote)
  301. self.tocOutlineView.menu = NSMenu()
  302. self.tocOutlineView.menu?.delegate = self
  303. self.outlineSearchField.delegate = self
  304. self.snapshotSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  305. self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  306. self.noteSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  307. self.snapshotSearchField.wantsLayer = true
  308. self.outlineSearchField.wantsLayer = true
  309. self.noteSearchField.wantsLayer = true
  310. self.snapshotSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  311. self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  312. self.noteSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  313. self.snapshotSearchField.layer?.borderWidth = 1.0
  314. self.outlineSearchField.layer?.borderWidth = 1.0
  315. self.noteSearchField.layer?.borderWidth = 1.0
  316. self.snapshotSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  317. self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  318. self.noteSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  319. // __block typeof(self) blockSelf = self;
  320. // _snapshotSearchField.changeCallBack = ^(NSString *changeContent) {
  321. // NSString *editContent = @"";
  322. // if (changeContent) {
  323. // editContent = changeContent;
  324. // }
  325. // [blockSelf.mainController searchFieldChangeAction:editContent];
  326. // };
  327. self.snapshotSearchField.isHidden = true
  328. self.snapshotSearchZoomOutButton.isHidden = true
  329. self.snapshotSearchZoomInButton.isHidden = true
  330. // _snapshotSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  331. // if (isEndEdit/* && searchViewController.segmentedControl.segmentCount == 3*/) {
  332. // _snapshotSearchField.hidden = YES;
  333. // _snapshotSearchZoomOutButton.hidden = YES;
  334. // _snapshotSearchZoomInButton.hidden = YES;
  335. // _snapshotLabel.hidden = NO;
  336. // _snapshotNormalZoomOutButton.hidden = NO;
  337. // _snapshotNormalZoomInButton.hidden = NO;
  338. // }
  339. // };
  340. self.thumbnailZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  341. self.snapshotNormalZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  342. self.snapshotSearchZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  343. self.thumbnailZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  344. self.snapshotNormalZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  345. self.snapshotSearchZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  346. self.outlineLabel.stringValue = KMLocalizedString("Outline", nil);
  347. self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  348. self.outlineAddButton.toolTip = KMLocalizedString("Add Item", nil)
  349. self.outlineAddButton.action = #selector(outlineContextMenuItemClicked_AddEntry)
  350. self.outlineAddButton.target = self
  351. self.outlineSearchButton.toolTip = KMLocalizedString("Search", nil)
  352. self.outlineMoreButton.action = #selector(leftSideViewMoreButtonAction)
  353. self.outlineMoreButton.target = self
  354. self.outlineMoreButton.tag = 302
  355. self.outlineDoneButton.title = KMLocalizedString("Done", nil);
  356. self.outlineDoneButton.toolTip = KMLocalizedString("Done", nil);
  357. self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  358. self.outlineDoneButton.wantsLayer = true
  359. self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  360. self.outlineDoneButton.layer?.cornerRadius = 4.0
  361. self.outlineDoneButton.action = #selector(leftSideViewDoneButtonAction)
  362. self.outlineDoneButton.target = self
  363. self.outlineDoneButton.tag = 310
  364. self.outlineDoneButton.isHidden = true
  365. self.outlineSearchField.isHidden = true
  366. // _outlineSearchField.endEditCallBack = ^(BOOL isEndEdit) {
  367. // if (isEndEdit) {
  368. // _outlineSearchField.hidden = YES;
  369. // _outlineLabel.hidden = NO;
  370. // _outlineSearchButton.hidden = NO;
  371. // }
  372. // };
  373. let menuOutline = NSMenu()
  374. menuOutline.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleOutlineCaseInsensitiveSearch), target: self)
  375. (self.outlineSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menuOutline
  376. (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline", nil)
  377. self.outlineSearchField.target = self
  378. let sud = UserDefaults.standard
  379. self.noteTitleLabel.stringValue = KMLocalizedString("Notes", nil);
  380. self.noteTitleLabel.textColor = KMAppearance.Layout.h0Color()
  381. self.noteMoreButton.action = #selector(leftSideViewMoreButtonAction)
  382. self.noteMoreButton.target = self
  383. self.noteMoreButton.tag = 304
  384. self.noteMoreButton.wantsLayer = true
  385. self.moreButtonLayer = KMButtonLayer()
  386. self.noteMoreButton.layer?.addSublayer(self.moreButtonLayer!)
  387. self.moreButtonLayer?.frame = CGRectMake(0, 0, CGRectGetWidth(self.noteMoreButton.bounds), CGRectGetHeight(self.noteMoreButton.bounds))
  388. self.moreButtonLayer?.layerType = .none
  389. self.moreButtonLayer?.isHidden = true
  390. self.noteFilterButton.action = #selector(noteFilterAction)
  391. self.noteFilterButton.target = self
  392. self.noteFilterButton.toolTip = KMLocalizedString("Sort", nil)
  393. self.noteFilterButton.wantsLayer = true
  394. self.filterButtonLayer = NSView()
  395. self.noteFilterButton.addSubview(self.filterButtonLayer!)
  396. self.filterButtonLayer?.frame = CGRectMake(14, 2, 8, 8)
  397. self.filterButtonLayer?.isHidden = true
  398. self.filterButtonLayer?.wantsLayer = true
  399. self.filterButtonLayer?.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  400. self.filterButtonLayer?.layer?.cornerRadius = 4.0
  401. self.noteDoneButton.title = KMLocalizedString("Done", nil)
  402. self.noteDoneButton.toolTip = KMLocalizedString("Done", nil)
  403. self.noteDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  404. self.noteDoneButton.wantsLayer = true
  405. self.noteDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  406. self.noteDoneButton.layer?.cornerRadius = 4.0
  407. self.noteDoneButton.action = #selector(leftSideViewDoneButtonAction)
  408. self.noteDoneButton.target = self
  409. self.noteDoneButton.tag = 311
  410. self.noteDoneButton.isHidden = true
  411. self.noteSearchButton.toolTip = KMLocalizedString("Search", nil)
  412. self.noteSearchField.delegate = self
  413. self.noteSearchField.isHidden = true
  414. self.noteSearchField.endEditCallBack = { [unowned self] isEndEdit in
  415. if (isEndEdit) {
  416. self.noteSearchField.isHidden = true
  417. self.noteSearchButton.isHidden = false
  418. self.noteTitleLabel.isHidden = false
  419. }
  420. };
  421. self.noteHeaderView.wantsLayer = true
  422. self.noteHeaderView.layer?.backgroundColor = KMAppearance.Else.textTagColor().cgColor
  423. self.noteHeaderView.layer?.cornerRadius = 1.0
  424. let sortType = sud.integer(forKey: KMLeftSideViewNoteSortTypeKey)
  425. if (sortType == 1) {
  426. self.noteSortType = KMNoteSortType(rawValue: sortType)!
  427. if (self.noteSortType == .time) {
  428. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  429. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  430. } else if (self._noteSortType == .page) {
  431. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  432. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  433. }
  434. } else {
  435. self.noteSortType = .time
  436. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  437. }
  438. self.sortTypeLabel.textColor = KMAppearance.Layout.h1Color()
  439. self.isAscendSort = sud.bool(forKey: KMLeftSideViewAscendSortBoolKey)
  440. if (self.isAscendSort) {
  441. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  442. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  443. } else {
  444. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  445. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  446. }
  447. self.sortTypeBox.downCallback = { [unowned self] downEntered, mouseBox, _ in
  448. if (downEntered) {
  449. let menu = NSMenu()
  450. let timeItem = menu.addItem(title: KMLocalizedString("Time", nil), action: #selector(sortTypeAction), target: self)
  451. timeItem?.representedObject = self
  452. timeItem?.tag = 0
  453. let pageItem = menu.addItem(title: KMLocalizedString("Page", nil), action: #selector(sortTypeAction), target: self)
  454. pageItem?.representedObject = self
  455. timeItem?.tag = 1
  456. if (self.noteSortType == .time) {
  457. timeItem?.state = .on
  458. pageItem?.state = .off
  459. } else if (self.noteSortType == .page) {
  460. timeItem?.state = .off
  461. pageItem?.state = .on
  462. }
  463. menu.popUp(positioning: nil, at: CGPointMake(-10, 0), in: self.sortTypeBox)
  464. }
  465. }
  466. self.searchViewController.loadView()
  467. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  468. self.searchField = self.searchViewController.searchField
  469. self.searchViewController.segmentedControl.setSegmentCount(2, with: 25)
  470. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarListNor)!, for: 0)
  471. self.searchViewController.segmentedControl.setImage(NSImage(named: KMImageNameUXIconBtnSidebarPageNor)!, for: 1)
  472. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Separate search results", nil), for: 0)
  473. self.searchViewController.segmentedControl.setToolTip(KMLocalizedString("Group search results by page", nil), for: 1)
  474. self.searchViewController.segmentedControl.isBackgroundHighlighted = true
  475. self.searchViewController.segmentedControl.selectedSegment = 0
  476. self.searchViewController.segmentedControl.block = { [unowned self] segIndex in
  477. if segIndex == 0 {
  478. self.findPaneState = .singular
  479. self.displayFindViewAnimating(false)
  480. } else {
  481. self.findPaneState = .grouped
  482. self.displayGroupedFindViewAnimating(false)
  483. }
  484. }
  485. self.leftView.segmentedControl.block = { [unowned self] segIndex in
  486. self.toolButtonBox.isHidden = false
  487. self.toolButtonBoxLayoutConstraint.constant = 40.0
  488. if (segIndex == 0) {
  489. if self.type.methodType == .Thumbnail {
  490. self.leftView.segmentedControl.selectedSegment = UInt8.max
  491. self.refreshMethodType(methodType: .None)
  492. return
  493. }
  494. self.refreshMethodType(methodType: .Thumbnail)
  495. DispatchQueue.main.async {
  496. self.toolButtonBox.contentView = self.thumbnailView
  497. self.displayThumbnailViewAnimating(false)
  498. }
  499. } else if (segIndex == 1) {
  500. if self.type.methodType == .Outline {
  501. self.leftView.segmentedControl.selectedSegment = UInt8.max
  502. self.refreshMethodType(methodType: .None)
  503. return
  504. }
  505. self.refreshMethodType(methodType: .Outline)
  506. DispatchQueue.main.async {
  507. self.toolButtonBox.contentView = self.outlineView
  508. self.displayTocViewAnimating(false)
  509. }
  510. } else if (segIndex == 2) {
  511. if self.type.methodType == .Annotation {
  512. self.leftView.segmentedControl.selectedSegment = UInt8.max
  513. self.refreshMethodType(methodType: .None)
  514. return
  515. }
  516. self.refreshMethodType(methodType: .Annotation)
  517. DispatchQueue.main.async {
  518. self.toolButtonBox.contentView = self.noteView
  519. self.displayNoteViewAnimating(false)
  520. }
  521. } else if (segIndex == 3) {
  522. self.toolButtonBox.contentView = self.snapshotNormalView
  523. self.updateSnapshotFilterPredicate()
  524. self.displaySnapshotViewAnimating(false)
  525. self.updataLeftSideSnapView()
  526. } else if (segIndex == 4) {
  527. if self.type.methodType == .Search {
  528. self.leftView.segmentedControl.selectedSegment = UInt8.max
  529. self.refreshMethodType(methodType: .None)
  530. return
  531. }
  532. self.refreshMethodType(methodType: .Search)
  533. DispatchQueue.main.async {
  534. self.toolButtonBox.isHidden = true
  535. self.toolButtonBoxLayoutConstraint.constant = 0
  536. self.displayFindViewAnimating(false)
  537. }
  538. }
  539. }
  540. // self.button.setHelp(KMLocalizedString("View Thumbnails", "Tool tip message"), for: KMLeftSidePaneState.thumbnail.rawValue)
  541. // self.button.setHelp(KMLocalizedString("View Outline", "Tool tip message"), for: KMLeftSidePaneState.outline.rawValue)
  542. // self.alternateButton.setHelp(KMLocalizedString("Separate search results", "Tool tip message"), for: KMFindPaneState.singular.rawValue)
  543. // self.alternateButton.setHelp(KMLocalizedString("Group search results by page", "Tool tip message"), for: KMFindPaneState.grouped.rawValue)
  544. let menu = NSMenu()
  545. menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  546. menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  547. (self.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  548. (self.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  549. self.searchField.action = #selector(search)
  550. self.searchField.target = self
  551. self.tocOutlineView.autoresizesOutlineColumn = false
  552. self.tocOutlineView.allowsMultipleSelection = true
  553. self.tocOutlineView.allowsEmptySelection = true
  554. self.tocOutlineView.delegate = self
  555. self.tocOutlineView.dataSource = self
  556. self.tocOutlineView.botaDelegate = self
  557. self.tocOutlineView.botaDataSource = self
  558. self.tocOutlineView.tocDelegate = self
  559. self.thumbnailTableView.delegate = self
  560. self.thumbnailTableView.dataSource = self
  561. self.thumbnailTableView.thumbDelegate = self
  562. self.thumbnailTableView.allowsMultipleSelection = true
  563. self.findTableView.delegate = self
  564. self.findTableView.dataSource = self
  565. self.findTableView.botaDelegate = self
  566. self.groupedFindTableView.delegate = self
  567. self.groupedFindTableView.dataSource = self
  568. self.groupedFindTableView.botaDelegate = self
  569. self.thumbnailTableView.menu?.delegate = self
  570. self.findTableView.menu?.delegate = self
  571. self.groupedFindTableView.menu?.delegate = self
  572. self.tocOutlineView.doubleAction = #selector(goToSelectedOutlineItem)
  573. self.tocOutlineView.target = self
  574. self.findTableView.doubleAction = #selector(goToSelectedFindResults)
  575. self.findTableView.target = self
  576. self.groupedFindTableView.doubleAction = #selector(goToSelectedFindResults)
  577. self.groupedFindTableView.target = self
  578. // [thumbnailTableView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKFullStringMatch]];
  579. // //支持拖拽的文字类型
  580. // [thumbnailTableView registerForDraggedTypes:@[KPDFThumbnailLocalForDraggedTypes,NSFilenamesPboardType]];
  581. // self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL])
  582. self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL,.string,.pdf])
  583. // self.thumbnailTableView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  584. // self.thumbnailTableView.setDraggingSourceOperationMask([.copy, .delete], forLocal: true)
  585. // [tocOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
  586. // [tocOutlineView registerForDraggedTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType]];
  587. // [[[findTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  588. // [[[groupedFindTableView tableColumnWithIdentifier:PAGE_COLUMNID] headerCell] setTitle:NSLocalizedString(@"Page", @"Table header title")];
  589. // [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] dataCell] setEnabled:NO];
  590. self.thumbnailTableView.selectionHighlightStyle = .none
  591. // NSSortDescriptor *countDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKGroupedSearchResultCountKey ascending:NO] autorelease];
  592. // [groupedFindArrayController setSortDescriptors:[NSArray arrayWithObjects:countDescriptor, nil]];
  593. //
  594. // self.thumbnailTableView.setDraggingSourceOperationMask(.every, forLocal: false)
  595. if UserDefaults.standard.bool(forKey: SKDisableTableToolTipsKey) == false {
  596. self.tocOutlineView.hasImageToolTips = true
  597. self.findTableView.hasImageToolTips = true
  598. self.groupedFindTableView.hasImageToolTips = true
  599. }
  600. self._updateViewColor()
  601. self.mwcFlags.wholeWordSearch = UserDefaults.standard.integer(forKey: SKWholeWordSearchKey)
  602. self.mwcFlags.caseInsensitiveSearch = UserDefaults.standard.integer(forKey: SKCaseInsensitiveSearchKey)
  603. }
  604. func displayThumbnailViewAnimating(_ animate: Bool) {
  605. self.replaceSideView(self.thumbnailTableView.enclosingScrollView!, animate: animate)
  606. var frame = self.thumbnailTableView.enclosingScrollView?.frame ?? .zero
  607. frame.origin.y = 0
  608. frame.origin.x = self.leftMargin
  609. frame.size.height = self.thumbnailTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  610. self.thumbnailTableView.enclosingScrollView?.frame = frame
  611. self.resetThumbnails()
  612. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  613. frame.origin.y = 0
  614. frame.origin.x = self.leftMargin
  615. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  616. self.noteOutlineView.enclosingScrollView?.frame = frame
  617. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  618. frame.origin.y = 0
  619. frame.origin.x = self.leftMargin
  620. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  621. self.snapshotTableView.enclosingScrollView?.frame = frame
  622. // [self updateThumbnailSelection];
  623. }
  624. func displayFindViewAnimating(_ animate: Bool) {
  625. self.replaceSideView(self.searchViewController.view, animate: animate)
  626. if (self.findState != .content) {
  627. self.findState = .content
  628. } else {
  629. self.displayFindState()
  630. }
  631. var frame = self.searchViewController.view.frame
  632. frame.origin.y = 0
  633. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? .zero
  634. self.searchViewController.view.frame = frame
  635. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  636. frame.origin.y = 0
  637. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  638. self.noteOutlineView.enclosingScrollView?.frame = frame
  639. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  640. frame.origin.y = 0
  641. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  642. self.snapshotTableView.enclosingScrollView?.frame = frame
  643. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  644. self.updataLeftSideSnapView()
  645. }
  646. func displayFindState() {
  647. if (self.findState == .content) {
  648. self.displayFind()
  649. } else if (self.findState == .note) {
  650. self.displayNoteFind()
  651. } else if (self.findState == .snapshot) {
  652. self.displaySnapshotFind()
  653. }
  654. }
  655. func updataLeftSideSnapView() {
  656. if (snapshots.count < 1) {
  657. self.snapshotNormalSearchButton.isEnabled = false
  658. // leftSideController.snapshotSearchZoomOutButton.enabled = NO;
  659. self.snapshotNormalZoomOutButton.isEnabled = false
  660. // leftSideController.snapshotSearchZoomInButton.enabled = NO;
  661. self.snapshotNormalZoomInButton.isEnabled = false
  662. self.snapshotNormalMoreButton.isEnabled = false
  663. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = false
  664. self.leftSideEmptyVC.exportSnapBtn.isEnabled = false
  665. self.leftSideEmptyVC.printSnapBtn.isEnabled = false
  666. self.snapshotTableView.usesAlternatingRowBackgroundColors = false
  667. let view = self.snapshotTableView.enclosingScrollView!
  668. let emptyVcSize = self.leftSideEmptyVC.emptySnapView.frame.size
  669. self.leftSideEmptyVC.emptySnapView.frame = NSMakeRect((view.frame.size.width-emptyVcSize.width)/2.0,(view.frame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height);
  670. self.leftSideEmptyVC.emptySnapView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  671. self.snapshotTableView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptySnapView)
  672. } else {
  673. self.snapshotNormalSearchButton.isEnabled = true
  674. // leftSideController.snapshotSearchZoomOutButton.enabled = YES;
  675. self.snapshotNormalZoomOutButton.isEnabled = true
  676. // leftSideController.snapshotSearchZoomInButton.enabled = YES;
  677. self.snapshotNormalZoomInButton.isEnabled = true
  678. self.snapshotNormalMoreButton.isEnabled = true
  679. self.leftSideEmptyVC.emptySnapView.removeFromSuperview()
  680. self.leftSideEmptyVC.deleteSnapBtn.isEnabled = true
  681. self.leftSideEmptyVC.exportSnapBtn.isEnabled = true
  682. self.leftSideEmptyVC.printSnapBtn.isEnabled = true
  683. }
  684. }
  685. func updataLeftSideFindView() {
  686. if (self.findState != .content) {
  687. return
  688. }
  689. if (self.searchResults.count > 0) {
  690. self.searchViewController.emptyBox.isHidden = true
  691. self.searchViewController.searchResultsView.isHidden = false
  692. self.searchViewController.searchResultsLabel.stringValue = String(format: KMLocalizedString("%ld Results", "Message in search table header"), self.searchResults.count)
  693. } else {
  694. self.searchViewController.emptyBox.isHidden = false
  695. self.searchViewController.searchResultsView.isHidden = true
  696. }
  697. }
  698. func displayGroupedFindViewAnimating(_ animate: Bool) {
  699. self.replaceSideView(self.searchViewController.view , animate: animate)
  700. if (self.findState != .content) {
  701. self.findState = .content
  702. } else {
  703. self.displayFindState()
  704. }
  705. var frame = self.searchViewController.view.frame
  706. frame.origin.y = 0
  707. frame.size.height = self.searchViewController.view.superview?.frame.size.height ?? 0
  708. self.searchViewController.view.frame = frame
  709. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  710. frame.origin.y = 0
  711. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  712. self.noteOutlineView.enclosingScrollView?.frame = frame
  713. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  714. frame.origin.y = 0
  715. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  716. self.snapshotTableView.enclosingScrollView?.frame = frame
  717. self.updataLeftSideSnapView()
  718. }
  719. func displayNoteViewAnimating(_ animate: Bool) {
  720. self.reloadAnnotation()
  721. self.annotationSort(sortArray: [])
  722. self.searchViewController.contentView = nil
  723. self.replaceSideView(self.noteOutlineView.enclosingScrollView!, animate: animate)
  724. if (self.findState != .note) {
  725. self.findState = .note
  726. } else {
  727. self.displayFindState()
  728. }
  729. var frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  730. frame.origin.y = 0
  731. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  732. self.noteOutlineView.enclosingScrollView?.frame = frame
  733. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  734. frame.origin.y = 0
  735. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  736. self.noteOutlineView.enclosingScrollView?.frame = frame
  737. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  738. frame.origin.y = 0
  739. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  740. self.snapshotTableView.enclosingScrollView?.frame = frame
  741. let view = self.noteOutlineView.enclosingScrollView!
  742. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  743. 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)
  744. DispatchQueue.main.async {
  745. self.noteOutlineView.reloadData()
  746. }
  747. }
  748. func displaySnapshotViewAnimating(_ animate: Bool) {
  749. self.searchViewController.contentView = nil
  750. self.replaceSideView(self.snapshotTableView.enclosingScrollView!, animate: animate)
  751. if (self.findState != .snapshot) {
  752. self.findState = .snapshot
  753. } else {
  754. self.displayFindState()
  755. }
  756. var frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  757. frame.origin.y = 0
  758. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  759. self.snapshotTableView.enclosingScrollView?.frame = frame
  760. // frame = rightSideController.noteOutlineView.enclosingScrollView.frame;
  761. // frame.origin.y = 0;
  762. // frame.size.height = rightSideController.noteOutlineView.enclosingScrollView.superview.frame.size.height;
  763. // rightSideController.noteOutlineView.enclosingScrollView.frame = frame;
  764. frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  765. frame.origin.y = 0
  766. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  767. self.tocOutlineView.enclosingScrollView?.frame = frame
  768. // [self updateSnapshotsIfNeeded];
  769. Task { @MainActor in
  770. self.snapshotTableView.reloadData()
  771. }
  772. }
  773. func displayFind() {
  774. self.searchField = self.searchViewController.searchField
  775. let menu = NSMenu()
  776. _ = menu.addItem(title: KMLocalizedString("Whole Words Only", "Menu item title"), action: #selector(toggleWholeWordSearch), target: self)
  777. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveSearch), target: self)
  778. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  779. (self.searchViewController.searchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search PDF", "placeholder")
  780. self.searchViewController.searchField.action = #selector(search)
  781. self.searchViewController.searchField.target = self
  782. if (self.findPaneState == .singular) {
  783. self.searchViewController.contentView = self.findTableView.enclosingScrollView
  784. self.findTableView.wantsLayer = true
  785. self.findTableView.layer?.backgroundColor = NSColor.red.cgColor
  786. DispatchQueue.main.async {
  787. self.findTableView.reloadData()
  788. }
  789. } else if (self.findPaneState == .grouped) {
  790. self.searchViewController.contentView = self.groupedFindTableView.enclosingScrollView
  791. var array = KMSearchMode.sortSearchResult(results: self.searchResults)
  792. array.sort(){$0.datas.count > $1.datas.count}
  793. self.groupSearchResults = array
  794. self.groupedFindTableView.reloadData()
  795. }
  796. }
  797. func displayTocViewAnimating(_ animate: Bool) {
  798. self.replaceSideView(self.tocOutlineView.enclosingScrollView!, animate: animate)
  799. var frame = self.tocOutlineView.enclosingScrollView?.frame ?? .zero
  800. frame.origin.y = 0
  801. frame.size.height = self.tocOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  802. self.tocOutlineView.enclosingScrollView?.frame = frame
  803. frame = self.noteOutlineView.enclosingScrollView?.frame ?? .zero
  804. frame.origin.y = 0
  805. frame.size.height = self.noteOutlineView.enclosingScrollView?.superview?.frame.size.height ?? 0
  806. self.noteOutlineView.enclosingScrollView?.frame = frame
  807. frame = self.snapshotTableView.enclosingScrollView?.frame ?? .zero
  808. frame.origin.y = 0
  809. frame.size.height = self.snapshotTableView.enclosingScrollView?.superview?.frame.size.height ?? 0
  810. self.snapshotTableView.enclosingScrollView?.frame = frame
  811. let view = self.tocOutlineView.enclosingScrollView!
  812. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  813. 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);
  814. DispatchQueue.main.async {
  815. self.tocOutlineView.reloadData()
  816. self.updateOutlineSelection()
  817. }
  818. }
  819. override func requiresAlternateButton(forView aview: NSView?) -> Bool {
  820. return false
  821. }
  822. func displayNoteFind() {
  823. self.searchField = self.noteSearchField
  824. let menu = NSMenu()
  825. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  826. (self.noteSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  827. (self.noteSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Notes", "placeholder")
  828. self.noteSearchField.action = #selector(searchNotes)
  829. self.noteSearchField.target = self
  830. }
  831. func displaySnapshotFind() {
  832. self.searchField = self.snapshotSearchField;
  833. let menu = NSMenu()
  834. _ = menu.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleCaseInsensitiveNoteSearch), target: self)
  835. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menu
  836. (self.snapshotSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Snapshots", "placeholder")
  837. self.snapshotSearchField.action = #selector(searchNotes)
  838. self.snapshotSearchField.target = self
  839. self.snapshotSearchField.delegate = self
  840. }
  841. /*
  842. - (void)applySearchTableHeader:(NSString *)message {
  843. [[[findTableView tableColumnWithIdentifier:RESULTS_COLUMNID] headerCell] setStringValue:message];
  844. [[findTableView headerView] setNeedsDisplay:YES];
  845. [[[groupedFindTableView tableColumnWithIdentifier:RELEVANCE_COLUMNID] headerCell] setStringValue:message];
  846. [[groupedFindTableView headerView] setNeedsDisplay:YES];
  847. }
  848. */
  849. @IBAction func search(_ sender: NSSearchField) {
  850. self.delegate?.searchAction?(searchString: sender.stringValue, isCase: self.mwcFlags.caseInsensitiveSearch == 1)
  851. }
  852. @IBAction func snapshotNormalSearchButtonAction(_ sender: NSButton) {
  853. self.snapshotSearchField.isHidden = false
  854. // _snapshotSearchZoomOutButton.hidden = YES;
  855. self.snapshotSearchZoomInButton.isHidden = true
  856. self.snapshotNormalSearchButton.isHidden = true
  857. self.snapshotDoneButton.isHidden = false
  858. self.snapshotLabel.isHidden = true
  859. self.snapshotNormalZoomOutButton.isHidden = true
  860. self.snapshotNormalZoomInButton.isHidden = true
  861. self.snapshotSearchField.becomeFirstResponder()
  862. }
  863. func resetThumbnails() {
  864. // [self willChangeValueForKey:THUMBNAILS_KEY];
  865. // self.thumbnailCacheSize = 160
  866. self.thumbnails.removeAll()
  867. let pageLabels = self.listView.document.pageLabels()
  868. if (pageLabels.isEmpty == false) {
  869. let isLocked = self.listView.document.isLocked
  870. let firstPage = self.listView.document.page(at: 0)
  871. let emptyPage = CPDFPage()
  872. let firstFrame = firstPage?.bounds(for: .cropBox) ?? .zero
  873. let firstFrame2 = firstPage?.bounds(for: .mediaBox) ?? .zero
  874. emptyPage.setBounds(firstFrame, for: .cropBox)
  875. emptyPage.setBounds(firstFrame2, for: .mediaBox)
  876. emptyPage.rotation = firstPage?.rotation ?? 0
  877. let pageImage = firstPage!.thumbnail(of: NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize))
  878. // NSImage * = [emptyPage thumbnailWithSize:thumbnailCacheSize forBox:[pdfView displayBox]];
  879. var rect: NSRect = .zero
  880. rect.size = pageImage?.size ?? .zero
  881. let width = 1.2 * fmin(NSWidth(rect), NSHeight(rect))
  882. rect = NSInsetRect(rect, 0.5 * (NSWidth(rect) - width), 0.5 * (NSHeight(rect) - width));
  883. pageImage?.lockFocus()
  884. // NSImage(named: NSImage.applicationIconName)?.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  885. if (isLocked) {
  886. NSWorkspace.shared.icon(forFileType: NSFileTypeForHFSTypeCode(OSType(kLockedBadgeIcon))).draw(in: rect, from: .zero, operation: .sourceOver, fraction: 0.5)
  887. // [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kLockedBadgeIcon)] drawInRect:rect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:0.5];
  888. }
  889. pageImage?.unlockFocus()
  890. for (i, label) in pageLabels.enumerated() {
  891. let firstPage = self.listView.document.page(at: UInt(i))
  892. let size = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  893. // let pageImage = firstPage!.thumbnail(of: size)
  894. let thumbnail = KMThumbnail(image: nil, label: label, pageIndex: i)
  895. // thumbnail.delegate = self
  896. thumbnail.dirty = true
  897. self.thumbnails.append(thumbnail)
  898. }
  899. }
  900. // [self didChangeValueForKey:THUMBNAILS_KEY];
  901. // [self allThumbnailsNeedUpdate];
  902. DispatchQueue.main.async {
  903. self.thumbnailTableView.reloadData()
  904. }
  905. }
  906. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  907. let item = sender
  908. let tag = item.tag
  909. if (item.state == .on) {
  910. item.state = .off
  911. } else {
  912. item.state = .on
  913. }
  914. if (tag == 0) {
  915. self.noteSortType = .page
  916. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  917. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  918. } else if (tag == 1) {
  919. self.noteSortType = .time
  920. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  921. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  922. }
  923. UserDefaults.standard.set(self.noteSortType.rawValue, forKey: KMLeftSideViewNoteSortTypeKey)
  924. UserDefaults.standard.synchronize()
  925. self.annotationSort(sortArray: [])
  926. }
  927. @IBAction func noteSortAction(_ sender: AnyObject?) {
  928. if (self.isAscendSort) {
  929. self.isAscendSort = false
  930. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  931. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  932. } else {
  933. self.isAscendSort = true
  934. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  935. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  936. }
  937. UserDefaults.standard.setValue(self.isAscendSort, forKey: KMLeftSideViewAscendSortBoolKey)
  938. UserDefaults.standard.synchronize()
  939. self.annotationSort(sortArray: [])
  940. }
  941. @IBAction func noteSearchAction(_ sender: NSButton) {
  942. self.noteSearchField.isHidden = false
  943. self.noteTitleLabel.isHidden = true
  944. self.noteSearchButton.isHidden = true
  945. self.noteDoneButton.isHidden = false
  946. self.noteFilterButton.isHidden = true
  947. self.noteMoreButton.isHidden = true
  948. self.noteSearchField.becomeFirstResponder()
  949. }
  950. @IBAction func leftSideViewDoneButtonAction(_ sender: AnyObject?) {
  951. let button = sender as? NSButton
  952. let tag = button?.tag ?? 0
  953. if (tag == 310) {
  954. self.outlineSearchField.isHidden = true
  955. self.outlineDoneButton.isHidden = true
  956. self.outlineLabel.isHidden = false
  957. self.outlineSearchButton.isHidden = false
  958. self.outlineMoreButton.isHidden = false
  959. self.outlineAddButton.isHidden = false
  960. } else if (tag == 311) {
  961. self.noteSearchField.isHidden = true
  962. self.noteTitleLabel.isHidden = false
  963. self.noteSearchButton.isHidden = false
  964. self.noteDoneButton.isHidden = true
  965. self.noteFilterButton.isHidden = false
  966. self.noteMoreButton.isHidden = false
  967. } else if (tag == 312) {
  968. self.snapshotSearchField.isHidden = true
  969. // leftSideController.snapshotSearchZoomOutButton.hidden = YES;
  970. // leftSideController.snapshotSearchZoomInButton.hidden = YES;
  971. self.snapshotNormalSearchButton.isHidden = false
  972. self.snapshotDoneButton.isHidden = true
  973. self.snapshotLabel.isHidden = false
  974. self.snapshotNormalZoomOutButton.isHidden = false
  975. self.snapshotNormalZoomInButton.isHidden = false
  976. }
  977. }
  978. @IBAction func leftSideViewMoreButtonAction(_ sender: AnyObject?) {
  979. let button = sender as? NSButton
  980. let tag = button?.tag ?? 0
  981. if (tag == 300) {
  982. var selectedRow = 0
  983. if (self.snapshotTableView.selectedRow >= 0) {
  984. selectedRow = self.snapshotTableView.selectedRow;
  985. } else {
  986. return
  987. }
  988. let model = self.snapshots[selectedRow]
  989. let controller = model.windowC
  990. let menu = NSMenu()
  991. let itemExport = menu.addItem(title: KMLocalizedString("Export", "Menu item title"), action: nil, target: self)
  992. let subMenu = NSMenu()
  993. var t = subMenu.addItem(title: KMLocalizedString("PNG", "Menu item title"), action: #selector(menuItemClick_ExportPNG), target: self)
  994. t?.representedObject = controller
  995. t = subMenu.addItem(title: KMLocalizedString("JPG", "Menu item title"), action: #selector(menuItemClick_ExportJPG), target: self)
  996. t?.representedObject = controller
  997. t = subMenu.addItem(title: KMLocalizedString("PDF", "Menu item title"), action: #selector(menuItemClick_ExportPDF), target: self)
  998. t?.representedObject = controller
  999. itemExport?.submenu = subMenu
  1000. let itemPrint = menu.addItem(title: KMLocalizedString("Print", "Menu item title"), action: #selector(menuItemClick_Print), target: self)
  1001. itemPrint?.representedObject = controller
  1002. menu.addItem(.separator())
  1003. let itemSelectAll = menu.addItem(title: KMLocalizedString("Select All", "Menu item title"), action: #selector(menuItemClick_SelectAll), target: self)
  1004. itemSelectAll?.representedObject = controller
  1005. menu.addItem(.separator())
  1006. let itemDeleteAllSnapshot = menu.addItem(title: KMLocalizedString("Delete All Snapshots", "Menu item title"), action: #selector(deleteAllSnapshot), target: self)
  1007. itemDeleteAllSnapshot?.representedObject = controller
  1008. //
  1009. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  1010. } else if (tag == 302) {
  1011. let menu = NSMenu()
  1012. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(toc_expandAllComments), target: self)
  1013. expandAllCommentsItem?.representedObject = self.tocOutlineView
  1014. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(toc_foldAllComments), target: self)
  1015. expandAllCommentsItem?.representedObject = self.tocOutlineView
  1016. let item = self.listView.document.outlineRoot()
  1017. var num = 0
  1018. for i in 0 ..< Int(item?.numberOfChildren ?? 0) {
  1019. let outline = item?.child(at: UInt(i))
  1020. if self.tocOutlineView.isItemExpanded(outline) {
  1021. num += 1
  1022. }
  1023. }
  1024. if let cnt = item?.numberOfChildren, cnt > 0 && num == 0 {
  1025. self.tocType = .fold
  1026. } else if let cnt = item?.numberOfChildren, cnt > 0 && num == cnt {
  1027. self.tocType = .unfold
  1028. } else {
  1029. self.tocType = .none
  1030. }
  1031. if (self.tocType == .unfold) {
  1032. expandAllCommentsItem?.state = .on
  1033. foldAllCommentsItem?.state = .off
  1034. } else if (self.tocType == .fold) {
  1035. expandAllCommentsItem?.state = .off
  1036. foldAllCommentsItem?.state = .on
  1037. } else {
  1038. expandAllCommentsItem?.state = .off
  1039. foldAllCommentsItem?.state = .off
  1040. }
  1041. let removeEntryItem = menu.addItem(title: KMLocalizedString("Remove All Outlines", nil), action: #selector(leftSideEmptyAnnotationClick_DeleteOutline), target: self)
  1042. removeEntryItem?.representedObject = self.tocOutlineView
  1043. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender as! NSButton)
  1044. } else if (tag == 304) {
  1045. let menu = NSMenu()
  1046. let object = KMPopupMenuObject()
  1047. object.menuTag = 1001
  1048. menu.delegate = object
  1049. object.enterControllerCallback = { [weak self] isEnter in
  1050. if (isEnter) {
  1051. self?.moreButtonLayer?.isHidden = false
  1052. } else {
  1053. self?.moreButtonLayer?.isHidden = true
  1054. }
  1055. }
  1056. let expandAllCommentsItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(note_expandAllComments), target: self)
  1057. expandAllCommentsItem?.representedObject = self.noteOutlineView
  1058. let foldAllCommentsItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(note_foldAllComments), target: self)
  1059. foldAllCommentsItem?.representedObject = self.noteOutlineView
  1060. if (self.foldType == .unfold) {
  1061. expandAllCommentsItem?.state = .on
  1062. foldAllCommentsItem?.state = .off
  1063. } else if (self.foldType == .fold) {
  1064. expandAllCommentsItem?.state = .off
  1065. foldAllCommentsItem?.state = .on
  1066. } else {
  1067. expandAllCommentsItem?.state = .off
  1068. foldAllCommentsItem?.state = .off
  1069. }
  1070. let showAnnotationItem = menu.addItem(title: KMLocalizedString("Show Note", nil), action: nil, target: self)
  1071. let subMenu = NSMenu()
  1072. var t = subMenu.addItem(title: KMLocalizedString("Page", nil), action: #selector(noteShowNoteAction), target: self)
  1073. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool ?? false
  1074. if pageKey {
  1075. t?.state = .off
  1076. } else {
  1077. t?.state = .on
  1078. }
  1079. t?.representedObject = self.noteOutlineView
  1080. t?.tag = 101
  1081. t = subMenu.addItem(title: KMLocalizedString("Time", nil) , action: #selector(noteShowNoteAction), target: self)
  1082. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool ?? false
  1083. if timeKey {
  1084. t?.state = .off
  1085. } else {
  1086. t?.state = .on
  1087. }
  1088. t?.representedObject = self.noteOutlineView
  1089. t?.tag = 102
  1090. t = subMenu.addItem(title: KMLocalizedString("Author", nil) , action: #selector(noteShowNoteAction), target: self)
  1091. let authorKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool ?? false
  1092. if authorKey {
  1093. t?.state = .off
  1094. } else {
  1095. t?.state = .on
  1096. }
  1097. t?.representedObject = self.noteOutlineView
  1098. t?.tag = 103
  1099. showAnnotationItem?.submenu = subMenu
  1100. menu.addItem(.separator())
  1101. let exportAnnotationsItem = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "MainMenu", comment: ""), action: nil, target: self)
  1102. let subMenu2 = NSMenu()
  1103. var t2 = subMenu2.addItem(title: NSLocalizedString("PDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1104. t2?.representedObject = self.noteOutlineView
  1105. t2?.tag = 0
  1106. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Bundle", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1107. t2?.representedObject = self.noteOutlineView
  1108. t2?.tag = 1
  1109. t2 = subMenu2.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1110. t2?.representedObject = self.noteOutlineView
  1111. t2?.tag = 2
  1112. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as Text", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1113. t2?.representedObject = self.noteOutlineView
  1114. t2?.tag = 3
  1115. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1116. t2?.representedObject = self.noteOutlineView
  1117. t2?.tag = 4
  1118. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1119. t2?.representedObject = self.noteOutlineView
  1120. t2?.tag = 5
  1121. t2 = subMenu2.addItem(title: NSLocalizedString("Notes as FDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  1122. t2?.representedObject = self.noteOutlineView
  1123. t2?.tag = 6
  1124. exportAnnotationsItem?.submenu = subMenu2
  1125. menu.addItem(.separator())
  1126. let removeAllAnnotationsItem = menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "MainMenu", comment: ""), action: #selector(leftSideEmptyAnnotationClick_DeleteAnnotation), target: self)
  1127. removeAllAnnotationsItem?.representedObject = self.noteOutlineView
  1128. NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: button!, with: nil)
  1129. }
  1130. }
  1131. @IBAction func noteFilterAction(_ sender: AnyObject?) {
  1132. let button = sender as? NSButton
  1133. let menu = NSMenu()
  1134. let filterViewController = KMNoteOutlineFilterViewController()
  1135. filterViewController.listView = self.listView
  1136. filterViewController.view.layer?.backgroundColor = .clear
  1137. var notes = NSMutableArray()
  1138. // for section in self._annotations {
  1139. // if section.annotations?.count != 0 {
  1140. // for item in section.annotations! {
  1141. // notes.add(item.annotation!)
  1142. // }
  1143. // }
  1144. // }
  1145. filterViewController.setNotesArray(self.allAnnotations as NSArray)
  1146. filterViewController.applyFilterCallback = { [weak self] typeArr, colorArr, authorArr, isEmpty in
  1147. menu.cancelTracking()
  1148. if (isEmpty) {
  1149. self?.filterButtonLayer?.isHidden = true
  1150. } else {
  1151. self?.filterButtonLayer?.isHidden = false
  1152. }
  1153. self?.annotationSort(sortArray: [])
  1154. }
  1155. filterViewController.cancelCallback = { isCancel in
  1156. if (isCancel) {
  1157. menu.cancelTracking()
  1158. }
  1159. }
  1160. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  1161. item.target = self
  1162. item.representedObject = filterViewController
  1163. item.view = filterViewController.view
  1164. menu.popUp(positioning: nil, at: CGPointMake(-130, 30), in: button)
  1165. }
  1166. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  1167. self.outlineSearchField.isHidden = false
  1168. self.outlineDoneButton.isHidden = false
  1169. self.outlineLabel.isHidden = true
  1170. self.outlineSearchButton.isHidden = true
  1171. self.outlineMoreButton.isHidden = true
  1172. self.outlineAddButton.isHidden = true
  1173. self.outlineSearchField.becomeFirstResponder()
  1174. }
  1175. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  1176. if (self.tocType == .unfold) {
  1177. return
  1178. }
  1179. self.tocType = .unfold
  1180. self.tocOutlineView.reloadData()
  1181. self.tocOutlineView.expandItem(nil, expandChildren: true)
  1182. }
  1183. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  1184. if (self.tocType == .fold) {
  1185. return
  1186. }
  1187. self.tocType = .fold
  1188. self.tocOutlineView.reloadData()
  1189. self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  1190. }
  1191. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  1192. let alert = NSAlert()
  1193. alert.alertStyle = .critical
  1194. alert.messageText = ""
  1195. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?", nil)
  1196. alert.addButton(withTitle: KMLocalizedString("Yes", nil))
  1197. alert.addButton(withTitle: KMLocalizedString("No", nil))
  1198. let response = alert.runModal()
  1199. if response == .alertFirstButtonReturn {
  1200. if let item = self.listView.document.outlineRoot() {
  1201. self.removeAllOutline(item)
  1202. }
  1203. }
  1204. }
  1205. @IBAction func thumbnailSizeScaling(_ sender: NSButton) {
  1206. let sud = UserDefaults.standard
  1207. let tag = sender.tag
  1208. if (tag == 0 || tag == 1) {
  1209. var scaling = sud.float(forKey: "KMThumbnailSizeScalingKey")
  1210. if (scaling <= 0) {
  1211. scaling = 1
  1212. }
  1213. if (tag == 0) { // thumbnail Zoom In
  1214. scaling += 0.1
  1215. if scaling >= 2.2 {
  1216. return
  1217. }
  1218. } else if (tag == 1) { // thumbnail Zoom Out
  1219. scaling -= 0.1
  1220. if scaling <= 0.4 {
  1221. return
  1222. }
  1223. }
  1224. sud.setValue(scaling, forKey: "KMThumbnailSizeScalingKey")
  1225. let selectRow = self.thumbnailTableView.selectedRow
  1226. self.thumbnailTableView.reloadData()
  1227. self.thumbnailTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1228. } else if (tag == 2 || tag == 3) {
  1229. var scaling = sud.float(forKey: "KMSnapshotSizeScalingKey")
  1230. if (scaling <= 0) {
  1231. scaling = 1
  1232. }
  1233. if (tag == 2) { // snapshot Zoom In
  1234. scaling += 0.1
  1235. } else if (tag == 3) { // snapshot Zoom Out
  1236. scaling -= 0.1
  1237. }
  1238. sud.setValue(scaling, forKey: "KMSnapshotSizeScalingKey")
  1239. let selectRow = self.snapshotTableView.selectedRow
  1240. self.snapshotTableView.reloadData()
  1241. self.snapshotTableView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  1242. }
  1243. }
  1244. func reloadAnnotation() {
  1245. if self.listView != nil {
  1246. var dataArray: [KMBOTAAnnotationSection] = []
  1247. var annotationArray: [CPDFAnnotation] = []
  1248. var allAnnotation: [CPDFAnnotation] = []
  1249. for i in 0 ..< self.listView.document.pageCount {
  1250. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1251. let page = self.listView.document.page(at: i)
  1252. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  1253. var pageAnnotations: [CPDFAnnotation] = KMOCToolClass.filterAnnotation(annotations: page!.annotations,types: types) as! [CPDFAnnotation]
  1254. //添加签名注释
  1255. for annotation in page!.annotations {
  1256. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  1257. pageAnnotations.append(annotation)
  1258. }
  1259. }
  1260. for annotation in pageAnnotations {
  1261. if annotation.annotationShouldDisplay() == false {
  1262. pageAnnotations.removeObject(annotation)
  1263. }
  1264. }
  1265. //转换所有annotation类型
  1266. let section = KMBOTAAnnotationSection()
  1267. for annotation in pageAnnotations {
  1268. let item = KMBOTAAnnotationItem()
  1269. item.section = section
  1270. item.annotation = annotation
  1271. item.index = Int(annotation.page.pageIndex())
  1272. annotationItemArray.append(item)
  1273. allAnnotation.append(annotation)
  1274. }
  1275. if annotationItemArray.count != 0 {
  1276. section.annotations = annotationItemArray
  1277. section.page = page
  1278. section.isItemExpanded = true
  1279. dataArray.append(section)
  1280. }
  1281. //添加所有annotation 用于筛选
  1282. annotationArray += pageAnnotations
  1283. }
  1284. if self.noteSortType == .page {
  1285. /// 根据id进行排序(升序)
  1286. if self.isAscendSort {
  1287. dataArray.sort { $0.page!.pageIndex() > $1.page!.pageIndex()}
  1288. } else {
  1289. dataArray.sort { $0.page!.pageIndex() <= $1.page!.pageIndex()}
  1290. }
  1291. self._annotations = dataArray
  1292. } else if self.noteSortType == .time {
  1293. var datas: [KMBOTAAnnotationSection] = []
  1294. /// 根据id进行排序(升序)
  1295. if self.isAscendSort {
  1296. allAnnotation.sort { $0.modificationDate() > $1.modificationDate() }
  1297. } else {
  1298. allAnnotation.sort { $0.modificationDate() <= $1.modificationDate() }
  1299. }
  1300. for anno in allAnnotation {
  1301. let section = KMBOTAAnnotationSection()
  1302. let item = KMBOTAAnnotationItem()
  1303. item.section = section
  1304. item.annotation = anno
  1305. item.index = Int(anno.pageIndex())
  1306. section.annotations = [item]
  1307. section.page = anno.page
  1308. section.isItemExpanded = true
  1309. datas.append(section)
  1310. }
  1311. self._annotations = datas
  1312. }
  1313. //转换对象,用于数据显示
  1314. // self._annotations = dataArray
  1315. self._allAnnotations = annotationArray
  1316. // if self.annotations.count < 1 {
  1317. // self.filtrateButton.isEnabled = false
  1318. // } else {
  1319. // self.filtrateButton.isEnabled = true
  1320. // }
  1321. }
  1322. }
  1323. func annotationSort(sortArray:[[Any]]) {
  1324. if self.listView != nil {
  1325. var typeArr: [Any] = []
  1326. var colorArr: [Any] = []
  1327. var authorArr: [Any] = []
  1328. let sud = UserDefaults.standard
  1329. let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type" + self.listView.document.documentURL.path) as? Data
  1330. // let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type") as? Data
  1331. if typeData != nil {
  1332. typeArr = NSKeyedUnarchiver.unarchiveObject(with: typeData!) as! [Any]
  1333. }
  1334. let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color" + self.listView.document.documentURL.path) as? Data
  1335. // let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color") as? Data
  1336. if colorData != nil {
  1337. colorArr = NSKeyedUnarchiver.unarchiveObject(with: colorData!) as! [Any]
  1338. }
  1339. let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author" + self.listView.document.documentURL.path) as? Data
  1340. // let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author") as? Data
  1341. if authorData != nil {
  1342. authorArr = NSKeyedUnarchiver.unarchiveObject(with: authorData!) as! [Any]
  1343. }
  1344. var colorMutableArray = NSMutableArray()
  1345. var typeMutableArray = NSMutableArray()
  1346. var authorMutableArray = NSMutableArray()
  1347. for annotation in self.allAnnotations {
  1348. if annotation.isKind(of: CPDFInkAnnotation.self) == false &&
  1349. annotation.isKind(of: CPDFTextWidgetAnnotation.self) == false &&
  1350. annotation.isKind(of: CPDFButtonWidgetAnnotation.self) == false &&
  1351. annotation.isKind(of: CPDFChoiceWidgetAnnotation.self) == false
  1352. // ![annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature] &&
  1353. // ![annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeText] &&
  1354. // ![annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeButton] &&
  1355. // ![annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeChoice])
  1356. {
  1357. let noteColor = annotation.color ?? .clear
  1358. let noteType = annotation.type ?? ""
  1359. let authorString = annotation.userName() ?? ""
  1360. if (noteColor != nil) {
  1361. if (colorMutableArray.count > 0) {
  1362. if colorMutableArray.contains(noteColor) == false {
  1363. colorMutableArray.add(noteColor)
  1364. }
  1365. } else {
  1366. colorMutableArray.add(noteColor)
  1367. }
  1368. }
  1369. if noteType.isEmpty == false {
  1370. if (typeMutableArray.count > 0) {
  1371. if typeMutableArray.contains(noteType) == false {
  1372. typeMutableArray.add(noteType)
  1373. }
  1374. } else {
  1375. typeMutableArray.add(noteType)
  1376. }
  1377. }
  1378. if authorString.isEmpty == false {
  1379. if (authorMutableArray.count > 0) {
  1380. if authorMutableArray.contains(authorString) == false {
  1381. authorMutableArray.add(authorString)
  1382. }
  1383. } else {
  1384. authorMutableArray.add(authorString)
  1385. }
  1386. }
  1387. }
  1388. }
  1389. // var temporaryArr1 = NSMutableArray()
  1390. // var temporaryArr2 = NSMutableArray()
  1391. // var temporaryArr3 = NSMutableArray()
  1392. // if typeArr.isEmpty == false {
  1393. // for type in typeArr {
  1394. // if typeMutableArray.contains(type) == false {
  1395. // temporaryArr1.add(type)
  1396. // }
  1397. // }
  1398. // }
  1399. // if colorArr.isEmpty == false {
  1400. // for color in colorArr {
  1401. // if colorMutableArray.contains(color) == false {
  1402. // temporaryArr2.add(type)
  1403. // }
  1404. // }
  1405. // }
  1406. // if authorArr.isEmpty == false {
  1407. // for author in authorArr {
  1408. // if authorMutableArray.contains(author) == false {
  1409. // temporaryArr3.add(type)
  1410. // }
  1411. // }
  1412. // }
  1413. // if (temporaryArr1.count > 0) {
  1414. // for type in temporaryArr1 {
  1415. // guard let typeS = type as? String else {
  1416. // continue
  1417. // }
  1418. //// [typeArr removeObject:type];
  1419. //
  1420. // var flag = -1
  1421. // for (i, data) in typeArr.enumerated() {
  1422. // if data as! String == typeS {
  1423. // flag = i
  1424. // }
  1425. // }
  1426. // if flag != -1 {
  1427. // typeArr.remove(at: flag)
  1428. // }
  1429. // }
  1430. // }
  1431. // if (temporaryArr2.count > 0) {
  1432. // for (NSColor *color in temporaryArr2) {
  1433. // [colorArr removeObject:color];
  1434. // }
  1435. // }
  1436. // for color in temporaryArr2 {
  1437. // guard let colorT = color as? NSColor else {
  1438. // continue
  1439. // }
  1440. //// [typeArr removeObject:type];
  1441. //
  1442. // var flag = -1
  1443. // for (i, data) in colorArr.enumerated() {
  1444. // if data as! NSColor == colorT {
  1445. // flag = i
  1446. // }
  1447. // }
  1448. // if flag != -1 {
  1449. // colorArr.remove(at: flag)
  1450. // }
  1451. // }
  1452. // if (temporaryArr3.count > 0) {
  1453. // for (NSColor *author in temporaryArr3) {
  1454. // [authorArr removeObject:author];
  1455. // }
  1456. // }
  1457. // for author in temporaryArr3 {
  1458. // guard let authorS = author as? String else {
  1459. // continue
  1460. // }
  1461. //// [typeArr removeObject:type];
  1462. //
  1463. // var flag = -1
  1464. // for (i, data) in authorArr.enumerated() {
  1465. // if data as! String == authorS {
  1466. // flag = i
  1467. // }
  1468. // }
  1469. // if flag != -1 {
  1470. // authorArr.remove(at: flag)
  1471. // }
  1472. // }
  1473. // let data1 = NSKeyedArchiver.archivedData(withRootObject: NSArray(array: typeArr))
  1474. // let data2 = NSKeyedArchiver.archivedData(withRootObject: NSArray(array: colorArr))
  1475. // let data3 = NSKeyedArchiver.archivedData(withRootObject: NSArray(array: authorArr))
  1476. // let sud = UserDefaults.standard
  1477. // sud.set(data1, forKey: "KMNoteOutlineFilterSelectArray_Type")
  1478. // sud.set(data2, forKey: "KMNoteOutlineFilterSelectArray_Color")
  1479. // sud.set(data3, forKey: "KMNoteOutlineFilterSelectArray_Author")
  1480. // sud.synchronize()
  1481. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  1482. // self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  1483. self.reloadAnnotation()
  1484. } else {
  1485. // self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")
  1486. var dataArray: [KMBOTAAnnotationSection] = []
  1487. var allAnnotation: [CPDFAnnotation] = []
  1488. for i in 0 ..< self.listView.document.pageCount {
  1489. var annotationItemArray: [KMBOTAAnnotationItem] = []
  1490. let page = self.listView.document.page(at: i)
  1491. if page!.annotations.count > 0 {
  1492. var filterAnnotations: [CPDFAnnotation] = page!.annotations
  1493. if typeArr.count > 0 {
  1494. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations, types: typeArr) as! [CPDFAnnotation])
  1495. }
  1496. if (colorArr.count > 0) {
  1497. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,colors: colorArr) as! [CPDFAnnotation])
  1498. }
  1499. if (authorArr.count > 0) {
  1500. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,authors: authorArr) as! [CPDFAnnotation])
  1501. }
  1502. let section = KMBOTAAnnotationSection()
  1503. for annotation in filterAnnotations {
  1504. let item = KMBOTAAnnotationItem()
  1505. item.section = section
  1506. item.annotation = annotation
  1507. item.index = Int(page!.pageIndex())
  1508. annotationItemArray.append(item)
  1509. allAnnotation.append(annotation)
  1510. }
  1511. if annotationItemArray.count != 0 {
  1512. section.annotations = annotationItemArray
  1513. section.page = page
  1514. section.isItemExpanded = true
  1515. dataArray.append(section)
  1516. }
  1517. }
  1518. }
  1519. if self.noteSortType == .page {
  1520. /// 根据id进行排序(升序)
  1521. if self.isAscendSort {
  1522. dataArray.sort { $0.page!.pageIndex() > $1.page!.pageIndex()}
  1523. } else {
  1524. dataArray.sort { $0.page!.pageIndex() <= $1.page!.pageIndex()}
  1525. }
  1526. self._annotations = dataArray
  1527. } else if self.noteSortType == .time {
  1528. var datas: [KMBOTAAnnotationSection] = []
  1529. /// 根据id进行排序(升序)
  1530. if self.isAscendSort {
  1531. allAnnotation.sort { $0.modificationDate() > $1.modificationDate() }
  1532. } else {
  1533. allAnnotation.sort { $0.modificationDate() <= $1.modificationDate() }
  1534. }
  1535. for anno in allAnnotation {
  1536. let section = KMBOTAAnnotationSection()
  1537. let item = KMBOTAAnnotationItem()
  1538. item.section = section
  1539. item.annotation = anno
  1540. item.index = Int(anno.pageIndex())
  1541. section.annotations = [item]
  1542. section.page = anno.page
  1543. section.isItemExpanded = true
  1544. datas.append(section)
  1545. }
  1546. self._annotations = datas
  1547. }
  1548. }
  1549. Task { @MainActor in
  1550. self.noteOutlineView.reloadData()
  1551. }
  1552. }
  1553. }
  1554. func showSearchOutlineBlankState(_ toShowState: Bool) {
  1555. if (toShowState) {
  1556. self.leftSideEmptyVC.outlineSearchView.frame = CGRectMake((self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.width - self.leftSideEmptyVC.outlineSearchView.bounds.size.width)/2.0, (self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.height - self.leftSideEmptyVC.outlineSearchView.bounds.size.height)/2.0, self.leftSideEmptyVC.outlineSearchView.bounds.size.width, self.leftSideEmptyVC.outlineSearchView.bounds.size.height);
  1557. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  1558. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  1559. } else {
  1560. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  1561. }
  1562. }
  1563. // func allRangeOfRoughString(_ roughString: String, searchString: String) -> [NSRange] {
  1564. //
  1565. // }
  1566. func removeAllOutline(_ outline: CPDFOutline) {
  1567. self.listView.document.setNewOutlineRoot()
  1568. for i in 0 ..< self.listView.document.pageCount {
  1569. self.listView.document.removeBookmark(forPageIndex: i)
  1570. }
  1571. self.listView.layoutDocumentView()
  1572. DispatchQueue.main.async {
  1573. self.tocOutlineView.reloadData()
  1574. }
  1575. }
  1576. func updateNoteFilterPredicate() {
  1577. //注释筛选
  1578. // [rightSideController.noteArrayController setFilterPredicate:[noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch]];
  1579. let stringValue = self.noteSearchField.stringValue
  1580. // NSPredicate *predicate = [noteTypeSheetController filterPredicateForSearchString:[rightSideController.searchField stringValue] caseInsensitive:mwcFlags.caseInsensitiveNoteSearch];
  1581. // [self loadAnnotationSortData:[NSArray arrayWithObjects:predicate, nil]];
  1582. self.noteSearchArray.removeAll()
  1583. if stringValue.isEmpty {
  1584. self.noteSearchArray = self.allAnnotations
  1585. } else {
  1586. for note in self.allAnnotations {
  1587. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  1588. if let anno = note as? CPDFMarkupAnnotation {
  1589. noteString = anno.markupContent()
  1590. }
  1591. if noteString.contains(stringValue) {
  1592. self.noteSearchArray.append(note)
  1593. }
  1594. }
  1595. }
  1596. Task { @MainActor in
  1597. self.noteOutlineView.reloadData()
  1598. }
  1599. }
  1600. @objc func selectSelectedNote(_ sender: AnyObject?) {
  1601. if self.listView.hideNotes == false {
  1602. let selectedNotes = self.selectedNotes()
  1603. if selectedNotes.count == 1 {
  1604. let annotation = selectedNotes.last!
  1605. self.listView.go(to: annotation.bounds, on: annotation.page, animated: true)
  1606. // [pdfView scrollAnnotationToVisible:annotation];
  1607. // [pdfView setActiveAnnotation:annotation];
  1608. self.listView.updateActiveAnnotations([annotation])
  1609. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  1610. // }
  1611. }
  1612. // NSInteger column = [sender clickedColumn];
  1613. // if (column != -1) {
  1614. // NSString *colID = [[[sender tableColumns] objectAtIndex:column] identifier];
  1615. //
  1616. // if ([colID isEqualToString:@"color"]){
  1617. // for (PDFAnnotation *annotation in self.pdfView.activeAnnotations) {
  1618. // if (![annotation isKindOfClass:[PDFAnnotationChoiceWidget class]] &&
  1619. // ![annotation isKindOfClass:[PDFAnnotationButtonWidget class]] &&
  1620. // ![annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  1621. // [[NSColorPanel sharedColorPanel] orderFront:nil];
  1622. // break;
  1623. // }
  1624. //
  1625. // }
  1626. // }
  1627. // }
  1628. }
  1629. }
  1630. func selectedNotes() -> [CPDFAnnotation] {
  1631. var selectedNotes: [CPDFAnnotation] = []
  1632. let rowIndexes = self.noteOutlineView.selectedRowIndexes
  1633. for row in rowIndexes {
  1634. let item = self.noteOutlineView.item(atRow: row)
  1635. if item is KMBOTAAnnotationItem {
  1636. if let anno = (item as! KMBOTAAnnotationItem).annotation {
  1637. // if anno.type == nil {
  1638. // item = [(SKNoteText *)item note];
  1639. // }
  1640. if selectedNotes.contains(anno) == false {
  1641. selectedNotes.append(anno)
  1642. }
  1643. }
  1644. }
  1645. }
  1646. return selectedNotes
  1647. }
  1648. }
  1649. // MARK: - Note
  1650. extension KMLeftSideViewController {
  1651. func loadAnnotationSortData(_ morePredicates: NSArray) {
  1652. var isLink = false
  1653. var typeMutableArr = NSMutableArray()
  1654. if self.allAnnotations.count > 0 {
  1655. for annotation in self.allAnnotations {
  1656. if annotation is CPDFLinkAnnotation || annotation is CPDFTextWidgetAnnotation || annotation is CPDFButtonWidgetAnnotation || annotation is CPDFChoiceWidgetAnnotation {
  1657. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature] ||
  1658. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeText] ||
  1659. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeButton] ||
  1660. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeChoice]) {
  1661. isLink = true
  1662. } else {
  1663. if typeMutableArr.contains(annotation.type) == false {
  1664. typeMutableArr.add(annotation.type)
  1665. }
  1666. }
  1667. }
  1668. }
  1669. var colorMutableArray = NSMutableArray()
  1670. var typeMutableArray = NSMutableArray()
  1671. var authorMutableArray = NSMutableArray()
  1672. for annotation in self.allAnnotations {
  1673. if annotation is CPDFLinkAnnotation || annotation is CPDFTextWidgetAnnotation || annotation is CPDFButtonWidgetAnnotation || annotation is CPDFChoiceWidgetAnnotation {
  1674. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature] ||
  1675. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeText] ||
  1676. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeButton] ||
  1677. // [annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeChoice]) {
  1678. let noteColor = annotation.color ?? .clear
  1679. let noteType = annotation.type ?? ""
  1680. let authorString = annotation.userName() ?? ""
  1681. if (noteColor != nil) {
  1682. if (colorMutableArray.count > 0) {
  1683. if colorMutableArray.contains(noteColor) == false {
  1684. colorMutableArray.add(noteColor)
  1685. }
  1686. } else {
  1687. colorMutableArray.add(noteColor)
  1688. }
  1689. }
  1690. if noteType.isEmpty == false {
  1691. if typeMutableArray.count > 0 {
  1692. if typeMutableArray.contains(noteType) == false {
  1693. typeMutableArray.add(noteType)
  1694. }
  1695. } else {
  1696. typeMutableArray.add(noteType)
  1697. }
  1698. }
  1699. if authorString.isEmpty == false {
  1700. if authorString.count > 0 {
  1701. if authorMutableArray.contains(authorString) == false {
  1702. authorMutableArray.add(authorString)
  1703. }
  1704. } else {
  1705. authorMutableArray.add(authorString)
  1706. }
  1707. }
  1708. } else {
  1709. if typeMutableArr.contains(annotation.type) == false {
  1710. typeMutableArr.add(annotation.type)
  1711. }
  1712. }
  1713. }
  1714. let sud = UserDefaults.standard
  1715. var typeArr = NSMutableArray()
  1716. if let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type") as? Data {
  1717. if let data = NSKeyedUnarchiver.unarchiveObject(with: typeData) as? NSArray {
  1718. typeArr = NSMutableArray(array: data)
  1719. }
  1720. }
  1721. var colorArr = NSMutableArray()
  1722. if let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color") as? Data {
  1723. if let data = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? NSArray {
  1724. colorArr = NSMutableArray(array: data)
  1725. }
  1726. }
  1727. var authorArr = NSMutableArray()
  1728. if let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author") as? Data {
  1729. if let data = NSKeyedUnarchiver.unarchiveObject(with: authorData) as? NSArray {
  1730. authorArr = NSMutableArray(array: data)
  1731. }
  1732. }
  1733. var temporaryArr1 = NSMutableArray()
  1734. var temporaryArr2 = NSMutableArray()
  1735. var temporaryArr3 = NSMutableArray()
  1736. if (typeArr.count > 0) {
  1737. for type in typeArr {
  1738. if typeMutableArray.contains(type) == false {
  1739. temporaryArr1.add(type)
  1740. }
  1741. }
  1742. }
  1743. if (colorArr.count > 0) {
  1744. for color in colorArr {
  1745. if colorMutableArray.contains(color) == false {
  1746. temporaryArr2.add(color)
  1747. }
  1748. }
  1749. }
  1750. if (authorArr.count > 0) {
  1751. for author in authorArr {
  1752. if authorMutableArray.contains(author) == false {
  1753. temporaryArr3.add(author)
  1754. }
  1755. }
  1756. }
  1757. if (temporaryArr1.count > 0) {
  1758. for type in temporaryArr1 {
  1759. typeArr.remove(type)
  1760. }
  1761. }
  1762. if (temporaryArr2.count > 0) {
  1763. for color in temporaryArr2 {
  1764. colorArr.remove(color)
  1765. }
  1766. }
  1767. if (temporaryArr3.count > 0) {
  1768. for author in temporaryArr3 {
  1769. authorArr.remove(author)
  1770. }
  1771. }
  1772. var predicateMutableArr = NSMutableArray()
  1773. // predicateMutableArr.add
  1774. }
  1775. }
  1776. // MARK: - KMBotaTableViewDelegate
  1777. extension KMLeftSideViewController: KMBotaTableViewDelegate {
  1778. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1779. if aTableView.isEqual(to: self.thumbnailTableView) || aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1780. return rowIndexes.count > 0
  1781. }
  1782. return false
  1783. }
  1784. func tableView(_ aTableView: NSTableView, canPasteFromPasteboard pboard: NSPasteboard) -> Bool {
  1785. if aTableView.isEqual(to: self.thumbnailTableView) {
  1786. if self._copysPages.count > 0 {
  1787. return true
  1788. }
  1789. }
  1790. return false
  1791. }
  1792. func tableView(_ aTableView: NSTableView, canDeleteRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  1793. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  1794. // return [rowIndexes count] > 0;
  1795. // } else
  1796. if aTableView.isEqual(to: self.thumbnailTableView) {
  1797. if self.listView.document.pageCount <= 1 {
  1798. return false
  1799. }
  1800. return true
  1801. }
  1802. return false
  1803. }
  1804. func tableView(_ aTableView: NSTableView, pasteFromPasteboard pboard: NSPasteboard?) {
  1805. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  1806. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1807. // return;
  1808. // }
  1809. if aTableView.isEqual(to: self.thumbnailTableView) {
  1810. if self._copysPages.count > 0 {
  1811. let index = self.listView.document.index(for: self.listView.currentPage()) + 1
  1812. if (index == NSNotFound) {
  1813. return
  1814. }
  1815. for page in self._copysPages.reversed() {
  1816. // if let newPage = page.copy() as? CPDFPage {
  1817. self.listView.document.insertPageObject(page, at: index)
  1818. // }
  1819. self.listView.layoutDocumentView()
  1820. // [pageLabels setArray:[[pdfView document] pageLabels]];
  1821. self.resetThumbnails()
  1822. let pageIndex = min(index, self.listView.document.pageCount-1)
  1823. self.listView.go(toPageIndex: Int(pageIndex), animated: true)
  1824. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: IndexSet.Element(index)))
  1825. }
  1826. }
  1827. }
  1828. }
  1829. func tableViewMoveLeft(_ aTableView: NSTableView) {
  1830. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1831. // [self updateFindResultHighlightsForDirection:NSSelectingPrevious];
  1832. }
  1833. }
  1834. func tableViewMoveRight(_ aTableView: NSTableView) {
  1835. if aTableView.isEqual(to: self.findTableView) || aTableView.isEqual(to: self.groupedFindTableView) {
  1836. // [self updateFindResultHighlightsForDirection:NSSelectingNext];
  1837. }
  1838. }
  1839. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  1840. if aTableView.isEqual(to: self.findTableView) {
  1841. if rowIndex >= self.searchResults.count {
  1842. return nil
  1843. }
  1844. let model = self.searchResults[rowIndex]
  1845. let selection = model.selection
  1846. let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1847. return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1848. } else if aTableView.isEqual(to: self.groupedFindTableView) {
  1849. if rowIndex >= self.groupSearchResults.count {
  1850. return nil
  1851. }
  1852. // let model = self.groupSearchResults[rowIndex]
  1853. // let selection = model.selection
  1854. // let point = NSPoint(x: NSWidth(selection.bounds) * 0.5, y: NSHeight(selection.bounds) * 0.5)
  1855. // return CPDFDestination(document: self.listView.document, pageIndex: Int(selection.page.pageIndex()), at: point, zoom: self.listView.scaleFactor)
  1856. }
  1857. return nil
  1858. }
  1859. /*
  1860. - (NSArray *)tableView:(NSTableView *)tv typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  1861. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1862. return pageLabels;
  1863. }
  1864. return nil;
  1865. }
  1866. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  1867. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1868. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  1869. }
  1870. }
  1871. - (void)tableView:(NSTableView *)tv typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  1872. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  1873. if (searchString.length > 0)
  1874. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  1875. else
  1876. [self updateLeftStatus];
  1877. }
  1878. }
  1879. */
  1880. }
  1881. // MARK: - KMThumbnailTableViewDelegate
  1882. extension KMLeftSideViewController: KMThumbnailTableViewDelegate {
  1883. func tableView(_ tableView: NSTableView, highlightLevelForRow row: Int) -> UInt {
  1884. if tableView.isEqual(to: self.thumbnailTableView) {
  1885. // NSUInteger i, iMax = [lastViewedPages count];
  1886. // for (i = 0; i < iMax; i++) {
  1887. // if (row == (NSInteger)[lastViewedPages pointerAtIndex:i])
  1888. // return i;
  1889. // }
  1890. }
  1891. return UInt.max
  1892. }
  1893. func tableView(_ tableView: NSTableView, commandSelectRow rowIndex: Int) -> Bool {
  1894. if tableView.isEqual(to: self.thumbnailTableView) {
  1895. // NSRect rect = [[[pdfView document] pageAtIndex:row] boundsForBox:kPDFDisplayBoxCropBox];
  1896. //
  1897. // rect.origin.y = NSMidY(rect) - 0.5 * SNAPSHOT_HEIGHT;
  1898. // rect.size.height = SNAPSHOT_HEIGHT;
  1899. // [self showSnapshotAtPageNumber:row forRect:rect scaleFactor:[pdfView scaleFactor] autoFits:NO];
  1900. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1901. thumbailTabCell?.isSelectCell = true
  1902. var rowIndexSet = IndexSet()
  1903. for i in self.thumbnailTableView.selectedRowIndexes {
  1904. rowIndexSet.insert(i)
  1905. }
  1906. rowIndexSet.insert(rowIndex)
  1907. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1908. return true
  1909. }
  1910. return false
  1911. }
  1912. func tableView(_ tableView: NSTableView, shiftSelectRow rowIndex: Int) -> Bool {
  1913. if tableView.isEqual(to: self.thumbnailTableView) {
  1914. if (self.thumbnailTableView.selectedRowIndexes.count == 0) {
  1915. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  1916. thumbailTabCell?.isSelectCell = true
  1917. var rowIndexSet = IndexSet()
  1918. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1919. return true
  1920. } else if (self.thumbnailTableView.selectedRowIndexes.count == 1 && self.thumbnailTableView.selectedRowIndexes.first == rowIndex) {
  1921. return false
  1922. } else {
  1923. var fristIndex = self.thumbnailTableView.selectedRowIndexes.first ?? Int.min
  1924. var lastIndex = self.thumbnailTableView.selectedRowIndexes.last ?? Int.max
  1925. for idx in self.thumbnailTableView.selectedRowIndexes {
  1926. // [leftSideController.thumbnailTableView.selectedRowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  1927. if(idx < fristIndex) {
  1928. fristIndex = idx
  1929. }
  1930. if(idx > lastIndex) {
  1931. lastIndex = idx
  1932. }
  1933. }
  1934. if(rowIndex < fristIndex) {
  1935. fristIndex = rowIndex
  1936. } else if (rowIndex > lastIndex) {
  1937. lastIndex = rowIndex
  1938. }
  1939. var rowIndexSet = IndexSet()
  1940. for i in fristIndex ... lastIndex {
  1941. rowIndexSet.insert(i)
  1942. }
  1943. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  1944. return true
  1945. }
  1946. }
  1947. return false
  1948. }
  1949. }
  1950. // MARK: - 扩展
  1951. extension KMLeftSideViewController {
  1952. public func selectType(_ type: BotaType) {
  1953. // 更新 type
  1954. var show = true
  1955. if (self.type.methodType == .None) {
  1956. show = true
  1957. } else {
  1958. if (self.type.methodType == type) {
  1959. show = false
  1960. } else {
  1961. show = true
  1962. }
  1963. }
  1964. var index: Int = NSNotFound
  1965. switch type {
  1966. case .None:
  1967. index = NSNotFound
  1968. break
  1969. case .Thumbnail:
  1970. index = 0
  1971. break
  1972. case .Outline:
  1973. index = 1
  1974. break
  1975. case .BookMark:
  1976. index = 2
  1977. break
  1978. case .Annotation:
  1979. index = 3
  1980. break
  1981. case .Search:
  1982. index = 4
  1983. break
  1984. case .From:
  1985. index = 5
  1986. break
  1987. case .Signature:
  1988. index = 6
  1989. break
  1990. case .snapshot:
  1991. index = 7
  1992. break
  1993. }
  1994. self.type = self.getMethodMode(show ? type : .None)
  1995. // 更新按钮状态
  1996. // self.updateViewButtonState()
  1997. // 将事件传递出去
  1998. self.delegate?.controlStateChange?(self,show:show)
  1999. if (index != NSNotFound) {
  2000. // 记录当前选中
  2001. UserDefaults.standard.set(index, forKey: "KMBOTASelectedIndexKey")
  2002. UserDefaults.standard.synchronize()
  2003. }
  2004. }
  2005. private func getMethodMode(_ type: BotaType) -> KMLeftMethodMode {
  2006. let mode = KMLeftMethodMode()
  2007. mode.methodType = type
  2008. switch type {
  2009. case .None:
  2010. mode.methodName = ""
  2011. break
  2012. case .Thumbnail:
  2013. mode.methodName = thumbnailMethodKey
  2014. break
  2015. case .Outline:
  2016. mode.methodName = outlineMethodKey
  2017. break
  2018. case .BookMark:
  2019. mode.methodName = bookMarkMethodKey
  2020. break
  2021. case .Annotation:
  2022. mode.methodName = anntationMethodKey
  2023. break
  2024. case .Search:
  2025. mode.methodName = searchMethodKey
  2026. break
  2027. case .From:
  2028. mode.methodName = formMethodKey
  2029. break
  2030. case .Signature:
  2031. mode.methodName = signatureMethodKey
  2032. break
  2033. case .snapshot:
  2034. mode.methodName = snapshotMethodKey
  2035. }
  2036. return mode
  2037. }
  2038. }
  2039. //MARK: Cache
  2040. extension KMLeftSideViewController {
  2041. func clearAnnotationFilterData() {
  2042. if let _key = self.listView?.document?.documentURL?.path {
  2043. let userDefaults = UserDefaults.standard
  2044. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  2045. userDefaults.set(typeData, forKey: "KMNoteOutlineFilterSelectArray_Type" + _key)
  2046. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  2047. userDefaults.set(colorData, forKey: "KMNoteOutlineFilterSelectArray_Color" + _key)
  2048. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  2049. userDefaults.set(authorData, forKey: "KMNoteOutlineFilterSelectArray_Author" + _key)
  2050. userDefaults.synchronize()
  2051. }
  2052. }
  2053. func clearNotification() {
  2054. }
  2055. }
  2056. // MARK: - Analytics (埋点)
  2057. extension KMLeftSideViewController {
  2058. func trackEvent(type: BotaType) -> Void {
  2059. if (type == .Thumbnail) {
  2060. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Thumbnail", parameters: [
  2061. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  2062. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  2063. } else if (type == .Outline) {
  2064. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Outline", parameters: [
  2065. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  2066. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  2067. } else if (type == .BookMark) {
  2068. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_BookMark", parameters: [
  2069. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  2070. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  2071. } else if (type == .Annotation) {
  2072. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Annotation", parameters: [
  2073. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  2074. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  2075. } else if (type == .Search) {
  2076. KMAnalytics.trackEvent(eventName: "Btn_LeftSideBar_Search", parameters: [
  2077. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.leftSideBar,
  2078. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.leftSideBar_Btn], platform: .AppCenter, appTarget: .all)
  2079. }
  2080. }
  2081. }
  2082. // MARK: - Private Methods
  2083. extension KMLeftSideViewController {
  2084. @objc private func _themeChanged(_ notification: NSNotification) {
  2085. DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {
  2086. self._updateViewColor()
  2087. }
  2088. }
  2089. private func _updateViewColor() {
  2090. if(KMAppearance.isDarkMode()){
  2091. self.leftListView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2092. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2093. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2094. self.noteView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2095. self.outlineView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2096. self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  2097. self.thumbnailTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  2098. self.groupedFindTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  2099. self.tocOutlineView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  2100. self.findTableView.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  2101. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  2102. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  2103. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  2104. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1).cgColor
  2105. self.snapshotSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  2106. self.outlineSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  2107. self.noteSearchField.backgroundColor = NSColor(red: 0.224, green: 0.235, blue: 0.243, alpha: 1)
  2108. } else {
  2109. self.leftListView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2110. self.snapshotNormalView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2111. self.thumbnailView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2112. self.noteView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2113. self.outlineView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2114. self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  2115. self.thumbnailTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  2116. self.groupedFindTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  2117. self.tocOutlineView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  2118. self.findTableView.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1)
  2119. self.snapshotSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  2120. self.outlineSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  2121. self.noteSearchField.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  2122. self.segmentedControl.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
  2123. self.snapshotSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  2124. self.outlineSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  2125. self.noteSearchField.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1)
  2126. }
  2127. }
  2128. private func _hasContainString(_ searchString: String, rootOutline outline: CPDFOutline) -> Bool {
  2129. var label = outline.label ?? ""
  2130. var searchLabel = searchString
  2131. if self.outlineIgnoreCaseFlag {
  2132. label = label.lowercased()
  2133. searchLabel = searchLabel.lowercased()
  2134. }
  2135. if label.contains(searchLabel) {
  2136. // if ([outline.label rangeOfString:searchString options:self.outlineIgnoreCaseFlag?NSCaseInsensitiveSearch:0].location != NSNotFound){
  2137. return true
  2138. } else {
  2139. var subHas = false
  2140. for i in 0 ..< outline.numberOfChildren {
  2141. if let subOutline = outline.child(at: i) {
  2142. subHas = self._hasContainString(searchString, rootOutline: subOutline)
  2143. } else {
  2144. continue
  2145. }
  2146. if (subHas) {
  2147. break
  2148. }
  2149. }
  2150. return subHas
  2151. }
  2152. return false
  2153. }
  2154. }
  2155. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  2156. extension KMLeftSideViewController: NSTableViewDelegate, NSTableViewDataSource {
  2157. func numberOfRows(in tableView: NSTableView) -> Int {
  2158. if tableView.isEqual(to: self.thumbnailTableView) {
  2159. return self.thumbnails.count
  2160. } else if tableView.isEqual(to: self.findTableView) {
  2161. return self.searchResults.count
  2162. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2163. return self.groupSearchResults.count
  2164. } else if tableView.isEqual(to: self.snapshotTableView) {
  2165. if self.isSearchSnapshotMode {
  2166. return self.searchSnapshots.count
  2167. }
  2168. return self.snapshots.count
  2169. }
  2170. return 0
  2171. }
  2172. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  2173. if tableView.isEqual(to: self.thumbnailTableView) {
  2174. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMThumbnailTableviewCell"), owner: self) as! KMThumbnailTableviewCell
  2175. let thumbnail = self.thumbnails[row]
  2176. cell.pageNumLabel.stringValue = thumbnail.label
  2177. // cell.thumImage.image = thumbnail.image
  2178. cell.pageView.page = self.listView.document.page(at: UInt(row))
  2179. if let _image = thumbnail.image {
  2180. let multiplierHToW = _image.size.height / (_image.size.width == 0 ? 1 : _image.size.width)
  2181. let multiplierWToH = _image.size.width / (_image.size.height == 0 ? 1 : _image.size.height)
  2182. if (_image.size.height > _image.size.width) {
  2183. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  2184. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .height, relatedBy: .equal, toItem: cell.thumImage, attribute: .width, multiplier: multiplierHToW, constant: 0)
  2185. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  2186. } else {
  2187. NSLayoutConstraint.deactivate([cell.imageAspectRatioLayout])
  2188. // cell.imageAspectRatioLayout = NSLayoutConstraint(item: cell.thumImage, attribute: .width, relatedBy: .equal, toItem: cell.thumImage, attribute: .height, multiplier: multiplierWToH, constant: 0)
  2189. // NSLayoutConstraint.activate([cell.imageAspectRatioLayout])
  2190. }
  2191. }
  2192. if (self.isDisplayPageSize) {
  2193. cell.sizeLabel.isHidden = false
  2194. //获取Page的真实尺寸
  2195. let page = self.listView.document.page(at: UInt(row))
  2196. let rect = page?.bounds(for: .cropBox) ?? .zero
  2197. let w = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetWidth(rect)/595 * 210))
  2198. let h = KMPageSizeTool.conversion(withUnit: "mm", value: (CGRectGetHeight(rect)/842 * 297))
  2199. if let data = page?.rotation, data == 90 || data == 270 {
  2200. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", h.stringToCGFloat(), w.stringToCGFloat(), KMLocalizedString("mm", nil))
  2201. } else {
  2202. cell.sizeLabel.stringValue = String(format: "%.f × %.f %@", w.stringToCGFloat(), h.stringToCGFloat(), KMLocalizedString("mm", nil))
  2203. }
  2204. } else {
  2205. cell.sizeLabel.isHidden = true
  2206. }
  2207. cell.sizeTopConstant.constant = cell.sizeLabel.isHidden ? -cell.sizeLabel.frame.size.height : 0
  2208. if(self.thumbnailTableView.selectedRowIndexes.contains(row)) {
  2209. cell.isSelectCell = true
  2210. } else {
  2211. cell.isSelectCell = false
  2212. }
  2213. return cell
  2214. } else if (tableView.isEqual(to: self.findTableView)) {
  2215. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMFindTableviewCell"), owner: self) as! KMFindTableviewCell
  2216. let selection = searchResults[row]
  2217. if let data = tableColumn?.identifier.rawValue, data == "results" {
  2218. cell.resultLabel.attributedStringValue = selection.attributedString
  2219. cell.resultLabel.textColor = KMAppearance.Layout.h0Color()
  2220. } else if let data = tableColumn?.identifier.rawValue, data == "page" {
  2221. cell.resultLabel.stringValue = "\(Int(selection.selection.page?.pageIndex() ?? 0) + 1)"
  2222. cell.resultLabel.textColor = KMAppearance.Layout.h2Color()
  2223. }
  2224. return cell
  2225. } else if tableView.isEqual(to: self.snapshotTableView) {
  2226. let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMSnapshotTableViewCell"), owner: self) as! KMSnapshotTableViewCell
  2227. var snapshot: KMSnapshotModel?
  2228. if self.isSearchSnapshotMode {
  2229. snapshot = self.searchSnapshots[row]
  2230. } else {
  2231. snapshot = self.snapshots[row]
  2232. }
  2233. cell.snapshotImage.image = snapshot?.windowC?.thumbnail
  2234. cell.snapshotLabel.stringValue = snapshot?.windowC?.pageLabel ?? ""
  2235. if let data = snapshot?.windowC?.hasWindow, data {
  2236. cell.snapshotImageView.isHidden = false
  2237. } else {
  2238. cell.snapshotImageView.isHidden = true
  2239. }
  2240. cell.isSelectCell = snapshot?.isSelected ?? false
  2241. if (row == tableView.selectedRow) {
  2242. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowSel)
  2243. } else {
  2244. cell.snapshotImageView.image = NSImage(named: KMImageNameUXIconSidebarSnapshotWindowNor)
  2245. }
  2246. return cell
  2247. }
  2248. return nil
  2249. }
  2250. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  2251. if tableView.isEqual(to: self.thumbnailTableView) {
  2252. let scaling = UserDefaults.standard.float(forKey: "KMThumbnailSizeScalingKey")
  2253. // let thumbnailSize = self.thumbnails[row].size
  2254. let thumbnailSize = NSMakeSize(self.thumbnailCacheSize, self.thumbnailCacheSize)
  2255. let newScaling: CGFloat = scaling.cgFloat + 0.1
  2256. let newThumbnailHeight = thumbnailSize.width * newScaling
  2257. if (newThumbnailHeight > MIN_SIDE_PANE_WIDTH) {
  2258. self.thumbnailZoomOutButton.isEnabled = false
  2259. } else {
  2260. self.thumbnailZoomOutButton.isEnabled = true
  2261. }
  2262. if ((scaling - 0.1) < 0.3) {
  2263. self.thumbnailZoomInButton.isEnabled = false
  2264. } else {
  2265. self.thumbnailZoomInButton.isEnabled = true
  2266. }
  2267. var labelHeight = 0.0
  2268. if (self.isDisplayPageSize) {
  2269. labelHeight = 56.0
  2270. } else {
  2271. labelHeight = 41.5
  2272. }
  2273. let cellHeight = thumbnailSize.height + labelHeight
  2274. var thumbSize: NSSize = .zero
  2275. if (scaling != nil && scaling > 0) {
  2276. thumbSize = NSMakeSize(thumbnailSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  2277. } else {
  2278. thumbSize = NSMakeSize(thumbnailSize.width, cellHeight)
  2279. }
  2280. return thumbSize.height
  2281. // NSSize cellSize = NSMakeSize([[tv tableColumnWithIdentifier:IMAGE_COLUMNID] width], fmin(thumbSize.height, roundedThumbnailSize));
  2282. // if (thumbSize.height < [tv rowHeight])
  2283. // return [tv rowHeight];
  2284. // else if (thumbSize.width / thumbSize.height < cellSize.width / cellSize.height)
  2285. // return cellSize.height;
  2286. // else
  2287. // return fmax([tv rowHeight], fmin(cellSize.width, thumbSize.width) * thumbSize.height / thumbSize.width);
  2288. } else if tableView.isEqual(to: self.snapshotTableView) {
  2289. let scaling = UserDefaults.standard.float(forKey: "KMSnapshotSizeScalingKey")
  2290. // NSSize snapshotSize = [[[[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row] thumbnail] size];
  2291. let snapshotSize = CGSizeMake(120, 63)
  2292. var newScaling = scaling + 0.1
  2293. let newSnapshotHeight = snapshotSize.width * newScaling.cgFloat;
  2294. if (newSnapshotHeight > MIN_SIDE_PANE_WIDTH) {
  2295. self.snapshotNormalZoomInButton.isEnabled = false
  2296. } else {
  2297. self.snapshotNormalZoomInButton.isEnabled = true
  2298. }
  2299. if ((scaling - 0.1) < 0.3 || (newSnapshotHeight < 150.0)) {
  2300. self.snapshotNormalZoomOutButton.isEnabled = false
  2301. } else {
  2302. self.snapshotNormalZoomOutButton.isEnabled = true
  2303. }
  2304. let cellHeight = snapshotSize.height + 24.0
  2305. var thumbSize: NSSize = .zero
  2306. if (scaling > 0) {
  2307. thumbSize = NSMakeSize(snapshotSize.width * scaling.cgFloat, cellHeight * scaling.cgFloat)
  2308. } else {
  2309. thumbSize = NSMakeSize(snapshotSize.width, cellHeight)
  2310. }
  2311. return thumbSize.height
  2312. } else if (tableView.isEqual(to: self.findTableView)) {
  2313. return 40.0
  2314. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2315. return 16
  2316. }
  2317. return tableView.rowHeight
  2318. }
  2319. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  2320. if (tableView.isEqual(to: self.findTableView)) {
  2321. let rowView = KMBotaTableRowView()
  2322. return rowView
  2323. } else if tableView.isEqual(to: self.groupedFindTableView) {
  2324. let rowView = KMGroupFindTableRowView()
  2325. rowView.totalNumber = self.groupSearchResults.first?.datas.count ?? 0
  2326. let model = self.groupSearchResults[row]
  2327. rowView.number = model.datas.count
  2328. rowView.pageIndex = Int(model.selectionPageIndex) + 1
  2329. return rowView
  2330. }
  2331. return nil
  2332. }
  2333. func tableViewSelectionIsChanging(_ notification: Notification) {
  2334. }
  2335. func tableViewSelectionDidChange(_ notification: Notification) {
  2336. // if ([[aNotification object] isEqual:leftSideController.findTableView] || [[aNotification object] isEqual:leftSideController.groupedFindTableView]) {
  2337. // [self updateFindResultHighlightsForDirection:NSDirectSelection];
  2338. //
  2339. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2340. // [self hideLeftSideWindow];
  2341. // } else
  2342. if self.findTableView.isEqual(to: notification.object) {
  2343. let row = self.findTableView.selectedRow
  2344. if row >= 0 {
  2345. let model = self.searchResults[row]
  2346. if model.selection != nil {
  2347. self.listView.go(to: model.selection, animated: true)
  2348. self.listView.setHighlightedSelection(model.selection, animated: true)
  2349. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2350. }
  2351. }
  2352. } else if self.thumbnailTableView.isEqual(to: notification.object) {
  2353. // if (mwcFlags.updatingThumbnailSelection == 0) {
  2354. let row = self.thumbnailTableView.selectedRow
  2355. let curPage = self.listView.document.index(for: self.listView.currentPage())
  2356. if (row != -1 && row != curPage) {
  2357. // [pdfView goToPage:[[pdfView document] pageAtIndex:row]];
  2358. self.listView.go(toPageIndex: row, animated: true)
  2359. }
  2360. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  2361. // [self hideLeftSideWindow];
  2362. // thumbnailSelectCount = row;
  2363. // var rowIndexSet = IndexSet()
  2364. // for i in 0 ..< self.thumbnailTableView.numberOfRows {
  2365. // rowIndexSet.insert(i)
  2366. // }
  2367. // self.thumbnailTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: IndexSet(integer: 0))
  2368. // }
  2369. let view = self.thumbnailTableView.view(atColumn: 0, row: self.preThumbnailRow, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2370. view?.isSelectCell = false
  2371. let view2 = self.thumbnailTableView.view(atColumn: 0, row: row, makeIfNecessary: false) as? KMThumbnailTableviewCell
  2372. view2?.isSelectCell = true
  2373. self.preThumbnailRow = row
  2374. }
  2375. // else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2376. // NSInteger row = [rightSideController.snapshotTableView selectedRow];
  2377. // [selectCellList removeAllObjects];
  2378. // [selectCellList addObject:[NSString stringWithFormat:@"%ld",row]];
  2379. // if (row != -1) {
  2380. // SKSnapshotWindowController *controller = [[rightSideController.snapshotArrayController arrangedObjects] objectAtIndex:row];
  2381. // if ([[controller window] isVisible])
  2382. // [[controller window] orderFront:self];
  2383. // }
  2384. // NSMutableIndexSet *rowIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2385. // for (NSInteger i = 0; i < rightSideController.snapshotTableView.numberOfRows; i ++) {
  2386. // [rowIndexSet addIndex:i];
  2387. // }
  2388. // NSMutableIndexSet *columnIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2389. // [columnIndexSet addIndex:0];
  2390. // [rightSideController.snapshotTableView reloadDataForRowIndexes:rowIndexSet columnIndexes:columnIndexSet];
  2391. //
  2392. // }
  2393. }
  2394. func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
  2395. if dropOperation == .on || tableView.isEqual(to: self.thumbnailTableView) == false {
  2396. return NSDragOperation(rawValue: 0)
  2397. }
  2398. let pboard = info.draggingPasteboard
  2399. if (pboard.availableType(from: [.localDraggedTypes]) != nil) {
  2400. return .move
  2401. } else if (pboard.availableType(from: [.fileURL]) != nil) && tableView.isEqual(to: self.thumbnailTableView) {
  2402. guard let pbItems = pboard.pasteboardItems else {
  2403. return NSDragOperation(rawValue: 0)
  2404. }
  2405. // guard let _allowedFileTypes = self.kmAllowedFileTypes else {
  2406. // return .generic
  2407. // }
  2408. var hasValidFile = false
  2409. for item in pbItems {
  2410. guard let data = item.string(forType: .fileURL), let _url = URL(string: data) else {
  2411. continue
  2412. }
  2413. let type = _url.pathExtension.lowercased()
  2414. // if (_allowedFileTypes.contains(type)) {
  2415. hasValidFile = true
  2416. // break
  2417. // }
  2418. }
  2419. if (!hasValidFile) {
  2420. return NSDragOperation(rawValue: 0)
  2421. }
  2422. }
  2423. return NSDragOperation(rawValue: 0)
  2424. }
  2425. func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
  2426. var result = false
  2427. if tableView.isEqual(to: self.thumbnailTableView) == false {
  2428. return result
  2429. }
  2430. // let pasteboard = info.draggingPasteboard
  2431. //
  2432. // if pasteboard.availableType(from: [.localDraggedTypes]) {
  2433. // result = true
  2434. // let rowData = pasteboard.data(forType: .localDraggedTypes)
  2435. // let rowIndexes = NSKeyedUnarchiver.unarchiveObject(with: rowData!)
  2436. // NSData *urlData = [pasteboard dataForType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2437. // NSString *url = [NSKeyedUnarchiver unarchiveObjectWithData:urlData];
  2438. // if(![url isEqualToString:[pdfView document].documentURL.absoluteString] && url) {
  2439. // if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]]){
  2440. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2441. // if (fileNames.count == 1) {
  2442. // NSString *path = fileNames.firstObject;
  2443. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2444. // if ([pathExtension isEqualToString:@"pdf"]) {
  2445. // __block NSInteger index = row;
  2446. // __block NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2447. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]] autorelease];
  2448. // if ([pdf isEncrypted]) {
  2449. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2450. // vc.filePath = url;
  2451. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2452. // if (password) {
  2453. // [pdf unlockWithPassword:password];
  2454. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2455. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2456. // [self.pdfView.document insertPage:page atIndex:index];
  2457. // [insertIndexSet addIndex:index];
  2458. // index++;
  2459. // [page release];
  2460. // }
  2461. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2462. // }
  2463. // }];
  2464. // [vc release];
  2465. // } else {
  2466. // for(NSUInteger i=0; i<pdf.pageCount;i++) {
  2467. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2468. // [self.pdfView.document insertPage:page atIndex:index];
  2469. // [insertIndexSet addIndex:index];
  2470. // index++;
  2471. // [page release];
  2472. // }
  2473. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2474. // }
  2475. // return YES;
  2476. // }
  2477. // }
  2478. // }
  2479. // }
  2480. // __block NSInteger pageIndex = 0;
  2481. // __block NSMutableArray *pages = [NSMutableArray array];
  2482. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2483. // PDFPage *page = [[[pdfView document] pageAtIndex:idx] copy];
  2484. // [pages addObject:page];
  2485. // [page release];
  2486. // }];
  2487. // PDFPage *toPage = nil;
  2488. // if (row < (NSInteger)pdfView.document.pageCount) {
  2489. // toPage = [pdfView.document pageAtIndex:row];
  2490. // }
  2491. // __block NSInteger toPageIndex = 0;
  2492. // if (toPage) {
  2493. // toPageIndex = [pdfView.document indexForPage:toPage];
  2494. // } else {
  2495. // toPageIndex = pdfView.document.pageCount;
  2496. // }
  2497. // for(NSUInteger i = 0;i<pages.count;i++) {
  2498. // PDFPage *page = pages[i];
  2499. // [pdfView.document insertPage:page atIndex:toPageIndex+i];
  2500. // pageIndex += 1;
  2501. // [self.pdfView goToPage:page];
  2502. // }
  2503. // [self.pdfView layoutDocumentView];
  2504. // __block NSMutableArray *deletepages = [NSMutableArray array];
  2505. // [rowIndexes enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2506. // if((NSInteger)idx < toPageIndex) {
  2507. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2508. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2509. // [deletepages addObject:page];
  2510. // [pdfView.document removePageAtIndex:idx];
  2511. // }
  2512. // } else {
  2513. // if((idx+pageIndex) < pdfView.document.pageCount) {
  2514. // PDFPage *page = [[pdfView document] pageAtIndex:idx+pageIndex];
  2515. // [deletepages addObject:page];
  2516. // [pdfView.document removePageAtIndex:idx+pageIndex];
  2517. // }
  2518. // }
  2519. // }];
  2520. // [[[[self document] undoManager] prepareWithInvocationTarget:self] undoClick];
  2521. // [self.pageLabels setArray:[[self.pdfView document] pageLabels]];
  2522. // [self.pdfView layoutDocumentView];
  2523. // [self resetThumbnails];
  2524. //
  2525. // } else if ([pasteboard availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]] && [tableView isEqual:leftSideController.thumbnailTableView]) {
  2526. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2527. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2528. //
  2529. // return NO;
  2530. // }
  2531. //
  2532. // NSArray *fileNames = [pasteboard propertyListForType:NSFilenamesPboardType];
  2533. // NSMutableIndexSet *insertIndexSet = [[[NSMutableIndexSet alloc] init] autorelease];
  2534. // __block NSInteger index = row;
  2535. //
  2536. // if (fileNames.count == 1) {
  2537. // NSString *path = fileNames.firstObject;
  2538. // NSString *pathExtension = [path.pathExtension lowercaseString];
  2539. // if ([pathExtension isEqualToString:@"pdf"]) {
  2540. // PDFDocument *pdf = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]]autorelease];
  2541. // if ([pdf isEncrypted]) {
  2542. // KMDecryptWindowController *vc = [[KMDecryptWindowController alloc] init];
  2543. // vc.filePath = path;
  2544. // [vc beginSheetModalForWindow:self.window completionHandler:^(NSString *password) {
  2545. // if (password) {
  2546. // [pdf unlockWithPassword:password];
  2547. // for (NSUInteger i = 0; i< pdf.pageCount; i++) {
  2548. // PDFPage *page = [[pdf pageAtIndex:i] copy];
  2549. // [self.pdfView.document insertPage:page atIndex:index];
  2550. // [insertIndexSet addIndex:index];
  2551. // index++;
  2552. // [page release];
  2553. // }
  2554. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2555. // }
  2556. // }];
  2557. // [vc release];
  2558. // } else {
  2559. // for (NSUInteger i = 0; i < pdf.pageCount; i++) {
  2560. // PDFPage * page = [[pdf pageAtIndex:i] copy];
  2561. // [self.pdfView.document insertPage:page atIndex:index];
  2562. // [insertIndexSet addIndex:index];
  2563. // index++;
  2564. // [page release];
  2565. // }
  2566. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2567. //
  2568. // }
  2569. // } else if ([[KMImageToPDFMethod supportedImageTypes] containsObject:pathExtension]) {
  2570. // NSImage *image = [[[NSImage alloc] initWithContentsOfFile:path] autorelease];
  2571. // PDFPage * page = [[[PDFPage alloc] initWithImage:image] autorelease];
  2572. // [pdfView.document insertPage:page atIndex:index];
  2573. // [insertIndexSet addIndex:index];
  2574. // [self insertPages:insertIndexSet pageAtIndex:(index-1)];
  2575. // }
  2576. // result = YES;
  2577. // } else {
  2578. // result = NO;
  2579. // }
  2580. // }
  2581. return result == false
  2582. }
  2583. func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
  2584. if tableView.isEqual(to: self.thumbnailTableView) {
  2585. // let idx = rowIndexes.first
  2586. // if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2587. // PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2588. // NSString *fileExt = nil;
  2589. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2590. //
  2591. // if ([[pdfView document] allowsPrinting]) {
  2592. // NSData *pdfData = [page dataRepresentation];
  2593. // fileExt = @"pdf";
  2594. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypePDF, NSPasteboardTypeTIFF,NSFilenamesPboardType, NSFilesPromisePboardType, KPDFThumbnailLocalForDraggedTypes,KPDFThumbnailDoucumentURLForDraggedTypes,nil] owner:self];
  2595. // [pboard setData:pdfData forType:NSPasteboardTypePDF];
  2596. // NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
  2597. // [pboard setData:zNSIndexSetData forType:KPDFThumbnailLocalForDraggedTypes];
  2598. // NSData *documentURL = [NSKeyedArchiver archivedDataWithRootObject:[[pdfView document].documentURL absoluteString]];
  2599. // NSString *docmentName = [[[pdfView.document.documentURL path] lastPathComponent] stringByDeletingPathExtension];
  2600. // __block NSMutableString *pagesName = nil;
  2601. // if (rowIndexes.count > 1) {
  2602. // pagesName = [NSMutableString stringWithString:@" pages"];
  2603. //
  2604. // } else {
  2605. // pagesName = [NSMutableString stringWithString:@" page"];
  2606. //
  2607. // }
  2608. // NSString * tFileName = [NSString stringWithFormat:@"%@ %@",pagesName,[self fileNameWithSelectedPages:rowIndexes]];
  2609. // PDFDocument * pdf = [[[PDFDocument alloc] init] autorelease];
  2610. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2611. // PDFPage *copyPage = [[pdfView.document pageAtIndex:idx] copy];
  2612. // [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2613. // [copyPage release];
  2614. // }];
  2615. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  2616. // NSString *cachesDir = [paths objectAtIndex:0];
  2617. // docmentName = [NSString stringWithFormat:@"%@%@",docmentName,tFileName];
  2618. // if (docmentName.length > 50) {
  2619. // [docmentName substringWithRange:NSMakeRange(0, 50)];
  2620. // }
  2621. // cachesDir = [[cachesDir stringByAppendingPathComponent:docmentName] stringByAppendingPathExtension:@"pdf"];
  2622. //
  2623. // BOOL success = [pdf writeToFile:cachesDir];
  2624. // if (success) {
  2625. // [pboard setPropertyList:@[cachesDir] forType:NSFilenamesPboardType];
  2626. // }else{
  2627. // [pboard setPropertyList:@[@""] forType:NSFilenamesPboardType];
  2628. // }
  2629. // [pboard setData:documentURL forType:KPDFThumbnailDoucumentURLForDraggedTypes];
  2630. // } else {
  2631. // fileExt = @"tiff";
  2632. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2633. // }
  2634. // [pboard setData:tiffData forType:NSPasteboardTypeTIFF];
  2635. // [pboard setPropertyList:[NSArray arrayWithObject:fileExt] forType:NSFilesPromisePboardType];
  2636. let data: Data = try! NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: true)
  2637. pboard.declareTypes([.localDraggedTypes], owner: self)
  2638. pboard.setData(data, forType: .localDraggedTypes)
  2639. return true
  2640. // }
  2641. }
  2642. // else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2643. // NSUInteger idx = [rowIndexes firstIndex];
  2644. // if (idx != NSNotFound) {
  2645. // SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2646. // [pboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSFilesPromisePboardType, nil] owner:self];
  2647. // [pboard setData:[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] forType:NSPasteboardTypeTIFF];
  2648. // [pboard setPropertyList:[NSArray arrayWithObject:@"tiff"] forType:NSFilesPromisePboardType];
  2649. // return YES;
  2650. // }
  2651. // }
  2652. return false
  2653. }
  2654. @objc dynamic func tableView(_ aTableView: NSTableView, deleteRowsWithIndexes rowIndexes: IndexSet) {
  2655. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  2656. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2657. // return;
  2658. // }
  2659. // if ([tv isEqual:rightSideController.snapshotTableView]) {
  2660. // NSArray *controllers = [[rightSideController.snapshotArrayController arrangedObjects] objectsAtIndexes:rowIndexes];
  2661. // [controllers makeObjectsPerformSelector:@selector(close)];
  2662. // } else
  2663. if aTableView.isEqual(to: self.thumbnailTableView) {
  2664. for idx in rowIndexes {
  2665. if idx >= self.listView.document.pageCount {
  2666. return
  2667. }
  2668. if let page = self.listView.document.page(at: UInt(idx)) {
  2669. for anno in page.annotations {
  2670. page.removeAnnotation(anno)
  2671. }
  2672. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPage(page, pageAt: idx)
  2673. self.listView.document.removePage(at: IndexSet(integer: idx))
  2674. }
  2675. }
  2676. self.listView.layoutDocumentView()
  2677. // [pageLabels setArray:[[pdfView document] pageLabels]];
  2678. self.resetThumbnails()
  2679. let idx = rowIndexes.first ?? -1
  2680. let index = min(idx, Int(self.listView.document.pageCount)-1)
  2681. self.listView.go(toPageIndex: index, animated: false)
  2682. }
  2683. }
  2684. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  2685. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  2686. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  2687. // return;
  2688. // }
  2689. if aTableView.isEqual(to: self.thumbnailTableView) {
  2690. self._copysPages.removeAll()
  2691. if self.listView.document.isLocked == false {
  2692. for idx in rowIndexes {
  2693. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  2694. self._copysPages.append(page)
  2695. }
  2696. }
  2697. // NSData *tiffData = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2698. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2699. // NSPasteboardItem *pboardItem = [[[NSPasteboardItem alloc] init] autorelease];
  2700. // if ([[pdfView document] allowsPrinting])
  2701. // [pboardItem setData:[page dataRepresentation] forType:NSPasteboardTypePDF];
  2702. // [pboardItem setData:tiffData forType:NSPasteboardTypeTIFF];
  2703. // [pboard clearContents];
  2704. // [pboard writeObjects:[NSArray arrayWithObjects:pboardItem, nil]];
  2705. }
  2706. }
  2707. // else if ([tv isEqual:leftSideController.findTableView]) {
  2708. // NSMutableString *string = [NSMutableString string];
  2709. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2710. // PDFSelection *match = [searchResults objectAtIndex:idx];
  2711. // [string appendString:@"* "];
  2712. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  2713. // [string appendFormat:@": %@\n", [[match contextString] string]];
  2714. // }];
  2715. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2716. // [pboard clearContents];
  2717. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2718. // } else if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2719. // NSMutableString *string = [NSMutableString string];
  2720. // [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  2721. // SKGroupedSearchResult *result = [groupedSearchResults objectAtIndex:idx];
  2722. // NSArray *matches = [result matches];
  2723. // [string appendString:@"* "];
  2724. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [[result page] displayLabel]];
  2725. // [string appendString:@": "];
  2726. // [string appendFormat:NSLocalizedString(@"%ld Results", @""), (long)[matches count]];
  2727. // [string appendFormat:@":\n\t%@\n", [[matches valueForKeyPath:@"contextString.string"] componentsJoinedByString:@"\n\t"]];
  2728. // }];
  2729. // NSPasteboard *pboard = [NSPasteboard generalPasteboard];
  2730. // [pboard clearContents];
  2731. // [pboard writeObjects:[NSArray arrayWithObjects:string, nil]];
  2732. // }
  2733. }
  2734. /*
  2735. #pragma mark dragging
  2736. - (NSArray *)tableView:(NSTableView *)tv namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2737. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2738. __block NSMutableArray *fileURLArray = [NSMutableArray array];
  2739. if (rowIndexes.count > 1) {
  2740. NSString *docmentName = @"";
  2741. NSString * tFileName = [NSString stringWithFormat:@"%@",[self fileNameWithSelectedPages:rowIndexes]];
  2742. PDFDocument *pdf = [[[PDFDocument alloc] init] autorelease];
  2743. [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
  2744. if (idx != NSNotFound && [[pdfView document] isLocked] == NO) {
  2745. PDFPage *copyPage = [[[pdfView document] pageAtIndex:idx] copy];
  2746. [pdf insertPage:copyPage atIndex:pdf.pageCount];
  2747. [copyPage release];
  2748. }
  2749. }];
  2750. NSURL *fileURL = [[[dropDestination URLByAppendingPathComponent:tFileName] URLByAppendingPathExtension:@"pdf"] uniqueFileURL];
  2751. docmentName = fileURL.path;
  2752. BOOL success = [pdf writeToFile:docmentName];
  2753. if(success) {
  2754. [fileURLArray addObject:[fileURL lastPathComponent]];
  2755. }
  2756. } else {
  2757. PDFPage *page = [[pdfView document] pageAtIndex:rowIndexes.firstIndex];
  2758. NSURL *fileURL = [dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]];
  2759. NSString *pathExt = nil;
  2760. NSData *data = nil;
  2761. if ([[pdfView document] allowsPrinting]) {
  2762. pathExt = @"pdf";
  2763. data = [page dataRepresentation];
  2764. } else {
  2765. pathExt = @"tiff";
  2766. data = [page TIFFDataForRect:[page boundsForBox:[pdfView displayBox]]];
  2767. }
  2768. fileURL = [[fileURL URLByAppendingPathExtension:pathExt] uniqueFileURL];
  2769. if ([data writeToURL:fileURL atomically:YES]) {
  2770. [fileURLArray addObject:[fileURL lastPathComponent]];
  2771. }
  2772. }
  2773. return fileURLArray;
  2774. } else if ([tv isEqual:rightSideController.snapshotTableView]) {
  2775. NSUInteger idx = [rowIndexes firstIndex];
  2776. if (idx != NSNotFound) {
  2777. SKSnapshotWindowController *snapshot = [self objectInSnapshotsAtIndex:idx];
  2778. PDFPage *page = [[pdfView document] pageAtIndex:[snapshot pageIndex]];
  2779. NSURL *fileURL = [[dropDestination URLByAppendingPathComponent:[self draggedFileNameForPage:page]] URLByAppendingPathExtension:@"tiff"];
  2780. fileURL = [fileURL uniqueFileURL];
  2781. if ([[[snapshot thumbnailWithSize:0.0] TIFFRepresentation] writeToURL:fileURL atomically:YES])
  2782. return [NSArray arrayWithObjects:[fileURL lastPathComponent], nil];
  2783. }
  2784. }
  2785. return [NSArray array];
  2786. }
  2787. - (void)tableView:(NSTableView *)tv sortDescriptorsDidChange:(NSArray *)oldDescriptors {
  2788. if ([tv isEqual:leftSideController.groupedFindTableView]) {
  2789. [leftSideController.groupedFindArrayController setSortDescriptors:[tv sortDescriptors]];
  2790. }
  2791. }
  2792. #pragma mark NSTableView delegate protocol
  2793. - (void)tableViewColumnDidResize:(NSNotification *)aNotification {
  2794. if ([[[[aNotification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:IMAGE_COLUMNID]) {
  2795. if ([[aNotification object] isEqual:leftSideController.thumbnailTableView]) {
  2796. [leftSideController.thumbnailTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [leftSideController.thumbnailTableView numberOfRows])]];
  2797. } else if ([[aNotification object] isEqual:rightSideController.snapshotTableView]) {
  2798. [rightSideController.snapshotTableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.snapshotTableView numberOfRows])]];
  2799. }
  2800. }
  2801. }
  2802. - (void)tableView:(NSTableView *)tv shareRowsWithIndexes:(NSIndexSet *)rowIndexes {
  2803. if ([tv isEqual:leftSideController.thumbnailTableView]) {
  2804. NSUInteger idx = [rowIndexes firstIndex];
  2805. if (idx != NSNotFound) {
  2806. PDFPage *page = [[pdfView document] pageAtIndex:idx];
  2807. NSString *fileName = [[[pdfView document] documentURL] lastPathComponent];
  2808. NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  2809. NSString *filePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Untitled"]];
  2810. filePath = [filePath stringByAppendingPathExtension:[fileName pathExtension]];
  2811. [self fileWithPage:page atPath:filePath];
  2812. if (rint(NSAppKitVersionNumber) < NSAppKitVersionNumber10_8) {
  2813. [KMMailHelper sendFileWithPaths:[NSArray arrayWithObject:filePath]];
  2814. } else {
  2815. NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
  2816. [service performWithItems:[NSArray arrayWithObject:[NSURL fileURLWithPath:filePath]]];
  2817. }
  2818. }
  2819. }
  2820. }
  2821. - (void)fileWithPage:(PDFPage *)page atPath:(NSString *)filePath {
  2822. NSData *data = [page dataRepresentation];
  2823. PDFDocument *document = [[PDFDocument alloc] initWithData:data];
  2824. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  2825. BOOL success = [document writeToURL:[NSURL fileURLWithPath:filePath]];
  2826. if (success) {
  2827. NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  2828. NSURL *url = [NSURL fileURLWithPath:filePath];
  2829. [workspace activateFileViewerSelectingURLs:[NSArray arrayWithObject:url]];
  2830. }
  2831. [document release];
  2832. */
  2833. }
  2834. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  2835. /*
  2836. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  2837. if item is KMBOTAAnnotationSection {
  2838. let section = item as? KMBOTAAnnotationSection
  2839. return section!.annotations?[index] as Any
  2840. } else if item is KMBOTAAnnotationItem {
  2841. return item as Any
  2842. } else {
  2843. var tempArray: [KMBOTAAnnotationSection] = []
  2844. for temp in self.data {
  2845. if temp.annotations?.count != 0 {
  2846. tempArray.append(temp)
  2847. }
  2848. }
  2849. let section = tempArray[index]
  2850. return section as Any
  2851. }
  2852. }
  2853. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  2854. if item is KMBOTAAnnotationItem {
  2855. let cell : KMAnnotationOutlineCellView = KMAnnotationOutlineCellView.init()
  2856. cell.delegate = self
  2857. cell.model = item as? KMBOTAAnnotationItem
  2858. return cell
  2859. } else if item is KMBOTAAnnotationSection {
  2860. let section = item as? KMBOTAAnnotationSection
  2861. let cell : KMAnnotationOutlineSectionView = KMAnnotationOutlineSectionView.init()
  2862. cell.model = section
  2863. return cell
  2864. }
  2865. return NSTableCellView()
  2866. }
  2867. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  2868. let rowView = KMAnnotationOutlineRowView()
  2869. if item is KMBOTAAnnotationItem {
  2870. rowView.model = (item as? KMBOTAAnnotationItem)
  2871. } else if item is KMBOTAAnnotationSection {
  2872. rowView.section = (item as? KMBOTAAnnotationSection)
  2873. }
  2874. rowView.mouseDownAction = { [unowned self] view, event in
  2875. if rowView.section != nil {
  2876. let expanded = outlineView.isItemExpanded(outlineView.item(atRow: outlineView.selectedRow))
  2877. if expanded {
  2878. outlineView.collapseItem(outlineView.item(atRow: outlineView.selectedRow), collapseChildren: true)
  2879. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2880. } else {
  2881. outlineView.expandItem(outlineView.item(atRow: outlineView.selectedRow), expandChildren: true)
  2882. outlineView.reloadItem(outlineView.item(atRow: outlineView.selectedRow))
  2883. }
  2884. } else if rowView.model != nil {
  2885. self.didSelectItem(view: rowView, event: event)
  2886. }
  2887. }
  2888. rowView.rightMouseDownAction = { [unowned self] view, event in
  2889. if rowView.section != nil {
  2890. } else if rowView.model != nil {
  2891. if !KMOCToolClass.arrayContains(array: self.selectItems, annotation: item) ||
  2892. self.selectItems.count == 1 {
  2893. self.selectItem(item: item as! KMBOTAAnnotationItem)
  2894. }
  2895. DispatchQueue.main.async {
  2896. self.delegate?.annotationOutlineView(self, rightMouseDownDidSelectView: view, evnet: event)
  2897. }
  2898. }
  2899. }
  2900. rowView.hoverCallback = { [unowned self] (mouseEntered, mouseBox) in
  2901. self.outlineView.enumerateAvailableRowViews { view, row in
  2902. if view is KMAnnotationOutlineRowView {
  2903. (view as? KMAnnotationOutlineRowView)?.model?.hover = false
  2904. (view as? KMAnnotationOutlineRowView)?.reloadData()
  2905. }
  2906. }
  2907. if mouseEntered {
  2908. rowView.model?.hover = true
  2909. } else {
  2910. rowView.model?.hover = false
  2911. }
  2912. }
  2913. return rowView
  2914. }
  2915. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  2916. if item is KMBOTAAnnotationItem {
  2917. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: self.maxWidth - 16, height: 1000))
  2918. } else if item is KMBOTAAnnotationSection {
  2919. return 40
  2920. } else {
  2921. return 30
  2922. }
  2923. }
  2924. func outlineViewSelectionDidChange(_ notification: Notification) {
  2925. if self.outlineView.selectedRow == -1 {
  2926. self.cancelSelect()
  2927. }
  2928. }
  2929. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  2930. if item is KMBOTAAnnotationItem {
  2931. return false
  2932. } else if item is KMBOTAAnnotationSection {
  2933. let section = item as? KMBOTAAnnotationSection
  2934. return section!.annotations?.count ?? 0 > 0
  2935. }
  2936. return false
  2937. }
  2938. func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
  2939. if let item = item as? KMBOTAAnnotationSection {
  2940. if !item.isItemExpanded {
  2941. item.isItemExpanded = true
  2942. outlineView.animator().expandItem(item, expandChildren: true)
  2943. return false
  2944. }
  2945. }
  2946. return true
  2947. }
  2948. func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
  2949. if let item = item as? KMBOTAAnnotationSection {
  2950. if item.isItemExpanded {
  2951. item.isItemExpanded = false
  2952. outlineView.animator().collapseItem(item, collapseChildren: true)
  2953. return false
  2954. }
  2955. }
  2956. return true
  2957. }
  2958. */
  2959. extension KMLeftSideViewController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  2960. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  2961. if outlineView.isEqual(to: self.tocOutlineView) {
  2962. let isLocked = self.listView.document?.isLocked ?? true
  2963. if isLocked { // 文档不存在 或 已加锁
  2964. return 0
  2965. }
  2966. if item == nil { // 第一层
  2967. // 获取根
  2968. guard let outline = self.listView.document.outlineRoot() else {
  2969. let view = self.tocOutlineView.enclosingScrollView!
  2970. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2971. //
  2972. 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)
  2973. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2974. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2975. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  2976. return 0
  2977. }
  2978. if outline.numberOfChildren == 0 {
  2979. // return 0
  2980. }
  2981. if self.isSearchOutlineMode { // 是否为搜索模块
  2982. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: outline) {
  2983. self.showSearchOutlineBlankState(false)
  2984. } else {
  2985. self.showSearchOutlineBlankState(true)
  2986. return 0
  2987. }
  2988. } else {
  2989. if outline.numberOfChildren > 0 { // 有数据
  2990. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  2991. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  2992. } else { // 没有数据
  2993. let view = self.tocOutlineView.enclosingScrollView!
  2994. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  2995. //
  2996. 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)
  2997. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  2998. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  2999. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  3000. return 0
  3001. }
  3002. }
  3003. // 搜索按钮
  3004. if outline.numberOfChildren > 0 {
  3005. self.outlineSearchButton.isEnabled = true
  3006. } else {
  3007. self.outlineSearchButton.isEnabled = false
  3008. }
  3009. if (self.isSearchOutlineMode) {
  3010. var num = 0
  3011. for i in 0 ..< outline.numberOfChildren {
  3012. if let child = outline.child(at: i) {
  3013. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  3014. num += 1
  3015. }
  3016. }
  3017. }
  3018. return num
  3019. } else {
  3020. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  3021. var bookmarkNum = 0
  3022. if array.isEmpty == false {
  3023. bookmarkNum = 1
  3024. }
  3025. return Int(outline.numberOfChildren) + bookmarkNum
  3026. }
  3027. } else { // 第二层 +
  3028. if self.isSearchOutlineMode {
  3029. if let data = item as? String, data == "Bookmarks" { // 书签group
  3030. return 0
  3031. } else if item is CPDFOutline { // 大纲
  3032. let child = item as! CPDFOutline
  3033. if child.numberOfChildren == 0 {
  3034. return 0
  3035. }
  3036. var num = 0
  3037. for i in 0 ..< child.numberOfChildren {
  3038. if let _child = child.child(at: i) {
  3039. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: _child) {
  3040. num += 1
  3041. }
  3042. }
  3043. }
  3044. return num
  3045. } else if item is CPDFBookmark { // 书签
  3046. return 0
  3047. }
  3048. } else {
  3049. if let data = item as? String, data == "Bookmarks" { // 书签group
  3050. return (self.listView.document?.bookmarks().count) ?? 0
  3051. } else if item is CPDFOutline { // 大纲
  3052. return Int((item as? CPDFOutline)?.numberOfChildren ?? 0)
  3053. } else if item is CPDFBookmark { // 书签
  3054. return 0
  3055. }
  3056. }
  3057. }
  3058. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3059. if self.noteSearchMode {
  3060. return self.noteSearchArray.count
  3061. }
  3062. var count = 0
  3063. for section in self._annotations {
  3064. if section.annotations?.count != 0 {
  3065. count += section.annotations!.count
  3066. }
  3067. }
  3068. // if (item == nil){
  3069. // NSInteger count = [[rightSideController.noteArrayController arrangedObjects] count];
  3070. if (count < 1) {
  3071. // if (notes.count < 1) {
  3072. self.noteSearchButton.isEnabled = false
  3073. self.noteFilterButton.isEnabled = false
  3074. // }
  3075. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  3076. let view = self.noteOutlineView.enclosingScrollView!
  3077. var emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  3078. 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)
  3079. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  3080. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  3081. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  3082. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  3083. //
  3084. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  3085. self.noteHeaderView.isHidden = true
  3086. self.toolButtonBoxLayoutConstraint.constant = 40.0
  3087. }
  3088. } else {
  3089. self.noteSearchButton.isEnabled = true
  3090. self.noteFilterButton.isEnabled = true
  3091. self.noteOutlineView.usesAlternatingRowBackgroundColors = false
  3092. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  3093. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  3094. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  3095. //
  3096. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  3097. self.noteHeaderView.isHidden = false
  3098. self.toolButtonBoxLayoutConstraint.constant = 64.0
  3099. }
  3100. }
  3101. return count
  3102. // } else {
  3103. // return [item hasNoteText];
  3104. // }
  3105. }
  3106. return 0
  3107. }
  3108. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  3109. if outlineView.isEqual(to: self.tocOutlineView) {
  3110. let isLocked = self.listView.document?.isLocked ?? true
  3111. if isLocked { // 文档不存在 或 已加锁
  3112. return ""
  3113. }
  3114. let array = self.listView.document.bookmarks() ?? [CPDFBookmark]()
  3115. var bookmarkNum = 0
  3116. if array.isEmpty == false {
  3117. bookmarkNum = 1
  3118. }
  3119. if item == nil {
  3120. if self.isSearchOutlineMode {
  3121. guard let outline = self.listView.document.outlineRoot() else {
  3122. return ""
  3123. }
  3124. if outline.numberOfChildren == 0 {
  3125. return ""
  3126. }
  3127. var array: [CPDFOutline] = []
  3128. for i in 0 ..< outline.numberOfChildren {
  3129. if let child = outline.child(at: i) {
  3130. if self._hasContainString(self.outlineSearchField.stringValue, rootOutline: child) {
  3131. array.append(child)
  3132. }
  3133. }
  3134. }
  3135. if index < array.count {
  3136. return array[index]
  3137. }
  3138. return ""
  3139. } else {
  3140. if index == 0 && bookmarkNum == 1 {
  3141. return "Bookmarks"
  3142. } else {
  3143. var _index = bookmarkNum == 1 ? index-1 : index
  3144. let outline = self.listView.document.outlineRoot()
  3145. var obj = outline?.child(at: UInt(_index))
  3146. return obj as Any
  3147. }
  3148. }
  3149. } else {
  3150. if let data = item as? String, data == "Bookmarks" {
  3151. return array[index]
  3152. } else if item is CPDFOutline {
  3153. return (item as! CPDFOutline).child(at: UInt(index))
  3154. } else if item is CPDFBookmark {
  3155. return ""
  3156. }
  3157. }
  3158. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3159. // if (item == nil)
  3160. // {
  3161. // return [[rightSideController.noteArrayController arrangedObjects] objectAtIndex:anIndex];
  3162. // // return [self.notes objectAtIndex:anIndex];
  3163. // }
  3164. // else
  3165. // return [item noteText];
  3166. if self.noteSearchMode {
  3167. return self.noteSearchArray[index]
  3168. }
  3169. var tempArray: [KMBOTAAnnotationItem] = []
  3170. for secion in self._annotations {
  3171. if secion.annotations?.count != 0 {
  3172. for _item in secion.annotations! {
  3173. tempArray.append(_item)
  3174. }
  3175. }
  3176. }
  3177. return tempArray[index] as Any
  3178. }
  3179. return item
  3180. }
  3181. func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
  3182. if outlineView.isEqual(to: self.tocOutlineView) {
  3183. // let tcID = tableColumn?.identifier.rawValue ?? ""
  3184. // var ol = item as? CPDFOutline
  3185. // if(tcID == LABEL_COLUMNID) {
  3186. // if (self.isSearchOutlineMode) {
  3187. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  3188. //// NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  3189. //// NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  3190. //// for (NSUInteger i = 0; i <arr.count ; i++) {
  3191. //// NSValue * rangeValue = arr[i];
  3192. //// NSRange range = rangeValue.rangeValue;
  3193. //// range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  3194. //// [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  3195. //// }
  3196. //// [attributeString addAttribute:NSForegroundColorAttributeName value:[KMAppearance KMColor_Layout_H0] range:NSMakeRange(0, roughString.length)];
  3197. //// return attributeString;
  3198. // } else {
  3199. // var attributedString = NSMutableAttributedString()
  3200. //// attributedString
  3201. // attributedString.append(.init(string: ol?.label ?? "", attributes: [.foregroundColor : KMAppearance.Layout.h0Color()]))
  3202. //// NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines]? : @"";
  3203. //// NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3204. //// NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  3205. //// [attributedString appendAttributedString:attr1];
  3206. //
  3207. // return attributedString
  3208. // }
  3209. //
  3210. // }
  3211. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3212. // NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3213. // NSString *roughString = [ol pageLabel]? : @"";
  3214. // NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3215. // NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:roughString attributes:dictAttr1];
  3216. // [attributedString appendAttributedString:attr1];
  3217. //
  3218. // return attributedString;
  3219. // }
  3220. }
  3221. // else if ([ov isEqual:rightSideController.noteOutlineView]) {
  3222. // NSString *tcID = [tableColumn identifier];
  3223. // PDFAnnotation *note = item;
  3224. // if (tableColumn == nil || [tcID isEqualToString:NOTE_COLUMNID])
  3225. // return [note objectValue];
  3226. // else if([tcID isEqualToString:TYPE_COLUMNID]){
  3227. // NSString *noteType = [note type];
  3228. // if ([note isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  3229. // PDFAnnotationButtonWidget *buttonWidget = (PDFAnnotationButtonWidget *)note;
  3230. // if (buttonWidget.controlType == kPDFWidgetRadioButtonControl) {
  3231. // noteType = SKAnnotationFormRadioButtonKey;
  3232. // } else if (buttonWidget.controlType == kPDFWidgetCheckBoxControl){
  3233. // noteType = SKAnnotationFormCheckBoxKey;
  3234. // } else if (buttonWidget.controlType == kPDFWidgetPushButtonControl){
  3235. // noteType = SKAnnotationFormActionButtonKey;
  3236. // }
  3237. // } else if ([note isKindOfClass:[PDFAnnotationTextWidget class]]){
  3238. // noteType = SKAnnotationFormTextFieldKey;
  3239. // } else if ([note isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  3240. // PDFAnnotationChoiceWidget *choiceWidget = (PDFAnnotationChoiceWidget *)note;
  3241. // if (choiceWidget.isListChoice) {
  3242. // noteType = SKAnnotationFormListMenuKey;
  3243. // } else {
  3244. // noteType = SKAnnotationFormComboBoxKey;
  3245. // }
  3246. //
  3247. // }
  3248. // return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:note == [pdfView activeAnnotation]], SKAnnotationTypeImageCellActiveKey, noteType, SKAnnotationTypeImageCellTypeKey,[note color],SKAnnotationTypeImageCellColorKey, nil];
  3249. // }
  3250. // else if([tcID isEqualToString:COLOR_COLUMNID])
  3251. // return [note type] ? [note color] : nil;
  3252. // else if([tcID isEqualToString:PAGE_COLUMNID])
  3253. // return [[note page] displayLabel];
  3254. // else if([tcID isEqualToString:AUTHOR_COLUMNID])
  3255. // return [note type] ? [note userName] : nil;
  3256. // else if([tcID isEqualToString:DATE_COLUMNID])
  3257. // return [note type] ? [note modificationDate] : nil;
  3258. // }
  3259. return nil
  3260. }
  3261. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  3262. if outlineView.isEqual(to: self.tocOutlineView) {
  3263. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMTocTableCellView"), owner: self) as! KMTocTableCellView
  3264. let tcID = tableColumn?.identifier.rawValue
  3265. var title = ""
  3266. var pageLabel = ""
  3267. if let data = item as? String, data == "Bookmarks" {
  3268. title = NSLocalizedString("Bookmarks", comment: "")
  3269. } else if item is CPDFOutline {
  3270. title = (item as! CPDFOutline).label
  3271. pageLabel = "\(((item as! CPDFOutline).destination?.pageIndex ?? 0) + 1)"
  3272. } else if item is CPDFBookmark {
  3273. title = (item as! CPDFBookmark).label
  3274. pageLabel = "\((item as! CPDFBookmark).pageIndex + 1)"
  3275. }
  3276. if tcID == LABEL_COLUMNID {
  3277. if (self.isSearchOutlineMode) {
  3278. // NSString *roughString = [[ol label] stringByCollapsingWhitespaceAndNewlinesAndRemovingSurroundingWhitespaceAndNewlines];
  3279. let roughString = title
  3280. // NSArray *arr = [self allRangeOfRoughString:roughString searchString:self.leftSideController.outlineSearchField.stringValue];
  3281. // NSMutableAttributedString *attributeString = [[[NSMutableAttributedString alloc] initWithString:roughString] autorelease];
  3282. //
  3283. // for (NSUInteger i = 0; i <arr.count ; i++) {
  3284. // NSValue * rangeValue = arr[i];
  3285. // NSRange range = rangeValue.rangeValue;
  3286. // range.location += i * self.leftSideController.outlineSearchField.stringValue.length;
  3287. // [attributeString addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:13] range:range];
  3288. // }
  3289. // cell.tocLabel.attributedStringValue = attributeString;
  3290. cell.tocLabel.stringValue = title
  3291. } else {
  3292. cell.tocLabel.stringValue = title
  3293. }
  3294. cell.pageLabel.stringValue = pageLabel
  3295. }
  3296. // else if([tcID isEqualToString:PAGE_COLUMNID]) {
  3297. // cell.pageLabel.stringValue = [ol pageLabel];
  3298. // }
  3299. return cell
  3300. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3301. let model = item as? KMBOTAAnnotationItem
  3302. var note: CPDFAnnotation!
  3303. if self.noteSearchMode {
  3304. note = item as! CPDFAnnotation
  3305. } else {
  3306. note = (item as! KMBOTAAnnotationItem).annotation!
  3307. }
  3308. let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMNoteTableViewCell"), owner: self) as! KMNoteTableViewCell
  3309. cell.cellNote = note
  3310. let noteColor = note.color
  3311. var noteType = note.type ?? ""
  3312. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  3313. // NSString *pageString = [[note page] displayLabel] ? : @"";
  3314. var pageString = "\((note.page?.pageIndex() ?? 0) + 1)"
  3315. let formatter = DateFormatter()
  3316. formatter.dateFormat = "hh:mm"
  3317. var dateString = ""
  3318. if let date = note.modificationDate() {
  3319. dateString = formatter.string(from: date)
  3320. }
  3321. var authorString = note.userName() ?? ""
  3322. // NSString *noteTextString = [note noteText].string ? : @"";
  3323. var noteTextString = note.string() ?? ""
  3324. //
  3325. // if([noteType isEqualToString:@"Redact"]) {
  3326. // noteString = @"Redact";
  3327. // }
  3328. //
  3329. let timeKey = self.noteTypeDict["kKMNoteFilterAnnotationTimeKey"] as? Bool
  3330. if timeKey == nil || timeKey == false {
  3331. // if (date != nil) {
  3332. cell.timeLabel.stringValue = dateString
  3333. //
  3334. // } else {
  3335. // cell.timeLabel.stringValue = ""
  3336. // }
  3337. cell.timeLabel.isHidden = false
  3338. } else {
  3339. cell.timeLabel.isHidden = true
  3340. }
  3341. let pageKey = self.noteTypeDict["kKMNoteFilterAnnotationPageKey"] as? Bool
  3342. if pageKey == nil || pageKey == false {
  3343. let labelsize = cell.pageLabel.stringValue.boundingRect(with: CGSizeMake(CGFloat(MAXFLOAT),CGRectGetHeight(cell.pageLabel.bounds)), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font : NSFont.systemFont(ofSize: 12)])
  3344. cell.pageLabelWidthConstraint.constant = labelsize.size.width + 5
  3345. cell.pageLabel.stringValue = pageString
  3346. cell.pageLabel.isHidden = false
  3347. } else {
  3348. cell.pageLabel.isHidden = true
  3349. }
  3350. let autherKey = self.noteTypeDict["kKMNoteFilterAnnotationAutherKey"] as? Bool
  3351. if pageKey == nil || pageKey == false {
  3352. cell.autherLabel.stringValue = authorString
  3353. cell.autherLabel.isHidden = false
  3354. } else {
  3355. cell.autherLabel.isHidden = true
  3356. }
  3357. let imageView = KMNoteTypeImageView()
  3358. if note.isKind(of: CPDFStampAnnotation.self) {
  3359. let annotation_stamp = note as! CPDFStampAnnotation
  3360. if (annotation_stamp.stampImage() != nil) {
  3361. noteType = SKNStampString
  3362. }
  3363. } else if note.isKind(of: CPDFLineAnnotation.self) {
  3364. let annotation_line = note as! CPDFLineAnnotation
  3365. if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .none {
  3366. noteType = SKNLine_NoneString
  3367. } else if annotation_line.startLineStyle == .none && annotation_line.endLineStyle == .openArrow {
  3368. noteType = SKNLine_OpenArrowString
  3369. } else {
  3370. noteType = SKNLine_NoneString
  3371. }
  3372. } else if note.isKind(of: CPDFButtonWidgetAnnotation.self) {
  3373. let buttonWidget = note as! CPDFButtonWidgetAnnotation
  3374. if buttonWidget.controlType() == .radioButtonControl {
  3375. noteType = KMAnnotationFormRadioButtonKey
  3376. } else if buttonWidget.controlType() == .checkBoxControl {
  3377. noteType = KMAnnotationFormCheckBoxKey
  3378. } else if buttonWidget.controlType() == .pushButtonControl {
  3379. noteType = KMAnnotationFormActionButtonKey
  3380. }
  3381. } else if note.isKind(of: CPDFTextWidgetAnnotation.self) {
  3382. noteType = KMAnnotationFormTextFieldKey
  3383. } else if note.isKind(of: CPDFChoiceWidgetAnnotation.self) {
  3384. let choiceWidget = note as! CPDFChoiceWidgetAnnotation
  3385. if choiceWidget.isListChoice {
  3386. noteType = KMAnnotationFormListMenuKey
  3387. } else {
  3388. noteType = KMAnnotationFormComboBoxKey
  3389. }
  3390. } else if note.isKind(of: KMTableAnnotation.self) {
  3391. noteType = "Ink_Table"
  3392. } else if note.isKind(of: KMSelfSignAnnotation.self) {
  3393. let selfSignNote = note as! KMSelfSignAnnotation
  3394. if selfSignNote.annotationType == .signFalse {
  3395. noteType = "KMSelfSignTypeFalseActionButtonKey"
  3396. } else if (selfSignNote.annotationType == .signature) {
  3397. noteType = "KMSelfSignTypeTureActionButtonKey"
  3398. } else if (selfSignNote.annotationType == .signCircle) {
  3399. noteType = "KMSelfSignTypeCircleActionButtonKey"
  3400. } else if (selfSignNote.annotationType == .signLine) {
  3401. noteType = "KMSelfSignTypeLineActionButtonKey"
  3402. } else if (selfSignNote.annotationType == .signDot) {
  3403. noteType = "KMSelfSignTypeDotActionButtonKey"
  3404. } else if (selfSignNote.annotationType == .signText) {
  3405. noteType = "KMSelfSignTypeTextActionButtonKey"
  3406. }
  3407. } else if note.isKind(of: CPDFSquareAnnotation.self) {
  3408. noteType = SKNSquareString
  3409. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3410. noteType = SKNNoteString
  3411. } else if note.isKind(of: CPDFFreeTextAnnotation.self) {
  3412. noteType = SKNFreeTextString
  3413. } else if note.isKind(of: CPDFCircleAnnotation.self) {
  3414. noteType = SKNCircleString
  3415. } else if note.isKind(of: CPDFSignatureAnnotation.self) {
  3416. noteType = SKNSignatureString
  3417. } else if note.isKind(of: CPDFInkAnnotation.self) {
  3418. noteType = SKNInkString
  3419. } else if note.isKind(of: CPDFMarkupAnnotation.self) {
  3420. let anno = note as! CPDFMarkupAnnotation
  3421. if anno.markupType() == .highlight {
  3422. noteType = SKNHighlightString
  3423. } else if anno.markupType() == .underline {
  3424. noteType = SKNUnderlineString
  3425. } else if anno.markupType() == .strikeOut {
  3426. noteType = SKNStrikeOutString
  3427. }
  3428. }
  3429. cell.typeImageView.image = imageView.noteTypeImage(withType: noteType, color: noteColor ?? .red)
  3430. cell.typeImageView.isHidden = false
  3431. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3432. cell.isFold = true
  3433. }
  3434. cell.noteContentBox.isHidden = true
  3435. cell.noteImageView.isHidden = true
  3436. cell.foldButton.isHidden = true
  3437. cell.annotationContentLabel.isHidden = false
  3438. cell.noteContentLabel.stringValue = noteString
  3439. cell.contentView.isHidden = false
  3440. cell.contentViewHidden(false)
  3441. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3442. let markup = note as! CPDFMarkupAnnotation
  3443. var contentString = KMBOTAAnnotationTool.fetchText(text: markup.markupContent() ?? "")
  3444. contentString = contentString.replacingOccurrences(of: "\r", with: "")
  3445. contentString = contentString.replacingOccurrences(of: "\n", with: "")
  3446. cell.noteContentLabel.stringValue = contentString
  3447. if(contentString.isEmpty == false) {
  3448. cell.foldButton.isHidden = false
  3449. }
  3450. var attributeStr = NSMutableAttributedString(string: contentString)
  3451. if (markup.markupType() == .highlight) {
  3452. attributeStr.addAttribute(.backgroundColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3453. } else if (markup.markupType() == .strikeOut) {
  3454. attributeStr.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3455. attributeStr.addAttribute(.strikethroughColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3456. } else if (markup.markupType() == .underline) {
  3457. attributeStr.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, contentString.count))
  3458. attributeStr.addAttribute(.underlineColor, value: noteColor as Any, range: NSMakeRange(0, contentString.count))
  3459. }
  3460. cell.annotationContentLabel.attributedStringValue = attributeStr
  3461. if let data = model?.foldType, data == .unfold {
  3462. cell.isFold = false
  3463. } else if let data = model?.foldType, data == .fold {
  3464. cell.isFold = true
  3465. } else {
  3466. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3467. cell.isFold = false
  3468. } else {
  3469. cell.isFold = true
  3470. }
  3471. }
  3472. // noteString.isEmpty == false &&
  3473. if (contentString.isEmpty == false) {
  3474. cell.contentViewHidden(false)
  3475. } else {
  3476. cell.contentViewHidden(true)
  3477. }
  3478. } else if note.isKind(of: CPDFLineAnnotation.self) || noteType == SKNSquareString || noteType == SKNCircleString || noteType == SKNInkString {
  3479. cell.annotationContentLabel.stringValue = noteString
  3480. if (noteString.isEmpty == false) {
  3481. cell.contentViewHidden(false)
  3482. } else {
  3483. cell.contentViewHidden(true)
  3484. }
  3485. } else if note.isKind(of: CPDFStampAnnotation.self) {
  3486. if note.isKind(of: KMSelfSignAnnotation.self) {
  3487. let newAnnotation = note as! KMSelfSignAnnotation
  3488. let type = newAnnotation.annotationType
  3489. var returnString = ""
  3490. if (type == .signFalse) {
  3491. returnString = KMLocalizedString("X", nil)
  3492. } else if (type == .signature) {
  3493. returnString = KMLocalizedString("Check mark", nil)
  3494. } else if (type == .signCircle) {
  3495. returnString = KMLocalizedString("Circle", nil)
  3496. } else if (type == .signLine) {
  3497. returnString = KMLocalizedString("Line", nil)
  3498. } else if (type == .signDot) {
  3499. returnString = KMLocalizedString("Dot", nil)
  3500. } else if (type == .signText) {
  3501. returnString = KMLocalizedString("Text", nil)
  3502. }
  3503. cell.annotationContentLabel.stringValue = returnString
  3504. } else {
  3505. cell.annotationContentLabel.isHidden = true
  3506. cell.noteImageView.isHidden = false
  3507. let anno = note as! CPDFStampAnnotation
  3508. cell.noteImageView.image = anno.stampImage()
  3509. }
  3510. } else if note.isKind(of: CPDFTextAnnotation.self) {
  3511. cell.foldButton.isHidden = false
  3512. if noteString.isEmpty {
  3513. cell.annotationContentLabel.stringValue = noteTextString
  3514. }else{
  3515. cell.annotationContentLabel.stringValue = noteString
  3516. cell.noteContentLabel.stringValue = noteTextString
  3517. }
  3518. if (self.foldType == .unfold) {
  3519. cell.isFold = false
  3520. } else if (self.foldType == .fold) {
  3521. cell.isFold = true
  3522. } else {
  3523. if self.allFoldNotes.isEmpty == false && self.allFoldNotes.contains(note) {
  3524. cell.isFold = false
  3525. } else {
  3526. cell.isFold = true
  3527. }
  3528. }
  3529. if (noteString.isEmpty == false || noteTextString.isEmpty == false) {
  3530. cell.contentView.isHidden = false
  3531. } else {
  3532. cell.contentView.isHidden = true
  3533. cell.contentViewHidden(true)
  3534. }
  3535. // noteString.isEmpty == false &&
  3536. if (noteTextString.isEmpty == false) {
  3537. cell.foldButton.isHidden = false
  3538. }else{
  3539. cell.foldButton.isHidden = true
  3540. }
  3541. } else {
  3542. cell.annotationContentLabel.stringValue = noteString
  3543. cell.imageViewHeightConstraint.constant = cell.contentView.frame.size.height
  3544. if (noteString.isEmpty == false) {
  3545. cell.contentViewHidden(false)
  3546. } else {
  3547. cell.contentViewHidden(true)
  3548. }
  3549. }
  3550. cell.autherLayoutConstraint.constant = cell.autherLabel.isHidden ? -(cell.autherLabel.bounds.size.width) + 10.0 : 10.0
  3551. cell.typeImageViewLayoutConstraint.constant = cell.typeImageView.isHidden ? -(cell.typeImageView.bounds.size.width) : 0.0
  3552. cell.contentBoxLayoutConstraint.constant = cell.noteContentBox.isHidden ? -(cell.noteContentBox.bounds.size.height+8.0) : 8.0
  3553. if note.isKind(of: CPDFStampAnnotation.self) && note.isKind(of: KMSelfSignAnnotation.self) == false {
  3554. } else {
  3555. if note.isKind(of: CPDFMarkupAnnotation.self) {
  3556. if (!cell.isFold) {
  3557. self.allFoldNotes.append(note)
  3558. } else {
  3559. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3560. }
  3561. } else {
  3562. cell.imageViewHeightConstraint.constant = 18.0 + 8
  3563. }
  3564. }
  3565. cell.isUnFoldNote = { [unowned self] cellNote, isUnfold in
  3566. model?.foldType = isUnfold ? .unfold : .fold
  3567. // let COLUMN_INDENTATION: CGFloat = 16
  3568. // if let _cell = tableColumn?.dataCell as? NSCell {
  3569. // _cell.objectValue = cell.annotationContentLabel.attributedStringValue
  3570. // let bound = NSMakeRect(0.0, 0.0, fmax(10.0, NSWidth(outlineView.frame) - COLUMN_INDENTATION - outlineView.indentationPerLevel-40), CGFLOAT_MAX)
  3571. // let height = _cell.cellSize(forBounds: bound).height
  3572. // KMPrint(height)
  3573. // }
  3574. if cellNote is CPDFMarkupAnnotation {
  3575. // let content = cell.annotationContentLabel.attributedStringValue
  3576. // let bound = content.string.boundingRect(with: NSMakeSize(150, CGFLOAT_MAX), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: nil)
  3577. // KMPrint(bound)
  3578. // 154 34 273
  3579. // 273 - 188 = 85 noteContentHeightConstraint maltlineLabelLayoutConstraint
  3580. model?.foldH = isUnfold ? 30 : (cell.noteContentHeightConstraint.constant + cell.maltlineLabelLayoutConstraint.constant + 85)
  3581. }
  3582. if (isUnfold) {
  3583. if (self.allFoldNotes.contains(note)) {
  3584. self.allFoldNotes.removeObject(note)
  3585. }
  3586. if (self.allFoldNotes.count == 0) {
  3587. self.foldType = .fold
  3588. } else {
  3589. self.foldType = .none
  3590. }
  3591. } else {
  3592. if self.allFoldNotes.contains(note) == false {
  3593. self.allFoldNotes.append(note)
  3594. }
  3595. // if (rightSideController.allFoldNotes.count == rightSideController.canFoldNotes.count) {
  3596. self.foldType = .unfold
  3597. // } else {
  3598. // self.foldType = KMFoldAllAnnotationType_None;
  3599. // }
  3600. }
  3601. }
  3602. return cell
  3603. }
  3604. return nil
  3605. }
  3606. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  3607. if outlineView.isEqual(self.noteOutlineView) {
  3608. if item is KMBOTAAnnotationItem {
  3609. let model = item as! KMBOTAAnnotationItem
  3610. if model.foldType == .fold {
  3611. return model.foldH
  3612. }
  3613. return KMBOTAAnnotationTool.fetchCellHeight(annotation: (item as? KMBOTAAnnotationItem)!.annotation!, maxSize: CGSize(width: 260+40 - 16, height: 1000))
  3614. }
  3615. return 30
  3616. } else if outlineView.isEqual(self.tocOutlineView) {
  3617. if item is CPDFOutline {
  3618. let tempItem = item as! CPDFOutline
  3619. let string: NSString = tempItem.label as NSString
  3620. let paragraphStyle = NSMutableParagraphStyle()
  3621. paragraphStyle.lineHeightMultiple = 1.32
  3622. paragraphStyle.alignment = .left
  3623. let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
  3624. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  3625. let size = string.boundingRect(with: CGSizeMake(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attributes)
  3626. return max(40, size.height + 16)
  3627. }
  3628. return 40
  3629. }
  3630. return outlineView.rowHeight
  3631. }
  3632. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  3633. if outlineView.isEqual(self.tocOutlineView) {
  3634. // var _item: CPDFOutline?
  3635. // if item == nil && self.listView.document.isLocked == false {
  3636. // _item = self.listView.document.outlineRoot()
  3637. // }
  3638. if let data = item as? String, data == "Bookmarks" {
  3639. return true
  3640. } else if item is CPDFOutline {
  3641. return ((item as! CPDFOutline).numberOfChildren ?? 0) != 0
  3642. } else if item is CPDFBookmark {
  3643. return false
  3644. }
  3645. if (self.isSearchOutlineMode) {
  3646. // return [self subOutLineContainString:self.leftSideController.outlineSearchField.stringValue rootOutline:(PDFOutline *)item];
  3647. } else {
  3648. // return ((_item?.numberOfChildren ?? 0) != 0)
  3649. }
  3650. } else if outlineView.isEqual(to: self.noteOutlineView) {
  3651. // return [item hasNoteText];
  3652. return false
  3653. }
  3654. return false
  3655. }
  3656. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  3657. if outlineView.isEqual(self.tocOutlineView) {
  3658. let itemView = KMBotaTableRowView()
  3659. return itemView
  3660. } else if outlineView.isEqual(self.noteOutlineView) {
  3661. let itemView = KMBotaTableRowView()
  3662. return itemView;
  3663. }
  3664. return nil
  3665. }
  3666. func outlineViewSelectionDidChange(_ notification: Notification) {
  3667. if self.tocOutlineView.isEqual(to: notification.object) {
  3668. // if ([[notification object] isEqual:leftSideController.tocOutlineView] && (mwcFlags.updatingOutlineSelection == 0)){
  3669. // mwcFlags.updatingOutlineSelection = 1;
  3670. self.goToSelectedOutlineItem(nil)
  3671. // mwcFlags.updatingOutlineSelection = 0;
  3672. // if ([self interactionMode] == SKPresentationMode && [[NSUserDefaults standardUserDefaults] boolForKey:SKAutoHidePresentationContentsKey])
  3673. // [self hideLeftSideWindow];
  3674. }
  3675. }
  3676. func outlineViewItemDidExpand(_ notification: Notification) {
  3677. if self.tocOutlineView.isEqual(to: notification.object) {
  3678. self.updateOutlineSelection()
  3679. }
  3680. }
  3681. func outlineViewItemDidCollapse(_ notification: Notification) {
  3682. if self.tocOutlineView.isEqual(to: notification.object) {
  3683. self.updateOutlineSelection()
  3684. }
  3685. }
  3686. /*
  3687. #pragma mark NSOutlineView datasource protocol
  3688. - (void)outlineView:(NSOutlineView *)ov setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item{
  3689. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3690. PDFAnnotation *note = item;
  3691. if ([note type]) {
  3692. if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  3693. if ([(object ?: @"") isEqualToString:([note string] ?: @"")] == NO)
  3694. [note setString:object];
  3695. } else if ([[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3696. if ([(object ?: @"") isEqualToString:([note userName] ?: @"")] == NO)
  3697. [note setUserName:object];
  3698. }
  3699. }
  3700. }
  3701. }
  3702. #pragma mark Drag
  3703. - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard{
  3704. if ([outlineView isEqual:leftSideController.tocOutlineView]) {
  3705. if (leftSideController.tocOutlineView.selectedRowIndexes.count > 1) {
  3706. return NO;
  3707. }
  3708. NSIndexSet *tIndex = [[[NSIndexSet alloc] initWithIndex:leftSideController.tocOutlineView.clickedRow] autorelease];
  3709. [leftSideController.tocOutlineView deselectRow:tIndex.firstIndex];
  3710. self.dragPDFOutline = items.firstObject;
  3711. NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
  3712. NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:set];
  3713. [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  3714. [pasteboard setData:zNSIndexSetData forType:kKMPDFViewOutlineDragDataType];
  3715. return YES;
  3716. }
  3717. return NO;
  3718. }
  3719. - (NSDragOperation)outlineView:(NSOutlineView *)ov validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)anIndex {
  3720. NSDragOperation dragOp = NSDragOperationNone;
  3721. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3722. NSPasteboard *pboard = [info draggingPasteboard];
  3723. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]] &&
  3724. anIndex == NSOutlineViewDropOnItemIndex && [(PDFAnnotation *)item type] != nil)
  3725. dragOp = NSDragOperationEvery;
  3726. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3727. if (anIndex == -1) {
  3728. dragOp = NSDragOperationNone;
  3729. } else {
  3730. dragOp = NSDragOperationMove;
  3731. }
  3732. }
  3733. return dragOp;
  3734. }
  3735. - (BOOL)outlineView:(NSOutlineView *)ov acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)anIndex {
  3736. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3737. NSPasteboard *pboard = [info draggingPasteboard];
  3738. if ([pboard canReadObjectForClasses:[NSArray arrayWithObject:[NSColor class]] options:[NSDictionary dictionary]]) {
  3739. BOOL isShift = ([NSEvent standardModifierFlags] & NSEventModifierFlagShift) != 0;
  3740. BOOL isAlt = ([NSEvent standardModifierFlags] & NSEventModifierFlagOption) != 0;
  3741. [item setColor:[NSColor colorFromPasteboard:pboard] alternate:isAlt updateDefaults:isShift];
  3742. return YES;
  3743. }
  3744. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3745. if (anIndex < 0) {
  3746. return NO;
  3747. }
  3748. PDFOutline *outline = item;
  3749. //root,drag item to root
  3750. if (!outline.parent) {
  3751. //fetch root
  3752. PDFOutline *root = self.dragPDFOutline;
  3753. while (root.parent) {
  3754. root = root.parent;
  3755. }
  3756. if ([self.dragPDFOutline.parent isEqual:root]) {
  3757. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3758. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3759. } else {
  3760. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:root];
  3761. }
  3762. } else {
  3763. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:root];
  3764. }
  3765. } else {
  3766. //在同一个层级内移动
  3767. if ([self.dragPDFOutline.parent isEqual:item]) {
  3768. if (self.dragPDFOutline.index) {
  3769. if (self.dragPDFOutline.index > (NSUInteger)anIndex) {
  3770. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3771. }else{
  3772. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex - 1 newParentOutline:outline];
  3773. }
  3774. } else {
  3775. return NO;
  3776. }
  3777. } else {
  3778. PDFOutline *tOutlline = outline;
  3779. BOOL isContains = NO;
  3780. while (tOutlline) {
  3781. if ([tOutlline isEqual:self.dragPDFOutline]) {
  3782. isContains = YES;
  3783. break;
  3784. }
  3785. tOutlline = tOutlline.parent;
  3786. }
  3787. if (!isContains) {
  3788. [self dragPDFOutline:self.dragPDFOutline toIndex:anIndex newParentOutline:outline];
  3789. }
  3790. }
  3791. }
  3792. return YES;
  3793. }
  3794. return NO;
  3795. }
  3796. #pragma mark NSOutlineView delegate protocol
  3797. - (NSCell *)outlineView:(NSOutlineView *)ov dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3798. if ([ov isEqual:rightSideController.noteOutlineView] && tableColumn == nil && [(PDFAnnotation *)item type] == nil) {
  3799. return [[ov tableColumnWithIdentifier:NOTE_COLUMNID] dataCellForRow:[ov rowForItem:item]];
  3800. }
  3801. return [tableColumn dataCellForRow:[ov rowForItem:item]];
  3802. }
  3803. - (void)outlineView:(NSOutlineView *)ov willDisplayOutlineCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item {
  3804. if ([ov isEqual:leftSideController.tocOutlineView] &&
  3805. [ov selectionHighlightStyle] == NSTableViewSelectionHighlightStyleRegular &&
  3806. [ov isRowSelected:[ov rowForItem:item]]) {
  3807. [cell setBackgroundStyle:NSBackgroundStyleLowered];
  3808. }
  3809. }
  3810. - (BOOL)outlineView:(NSOutlineView *)ov shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{
  3811. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3812. if (tableColumn == nil) {
  3813. if ([pdfView hideNotes] == NO && [[(SKNoteText *)item note] isNote]) {
  3814. PDFAnnotation *annotation = [(SKNoteText *)item note];
  3815. [pdfView scrollAnnotationToVisible:annotation];
  3816. [pdfView setActiveAnnotation:annotation];
  3817. [self showNote:annotation];
  3818. SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  3819. [[noteController window] makeFirstResponder:[noteController textView]];
  3820. [[noteController textView] selectAll:nil];
  3821. }
  3822. return NO;
  3823. } else if ([[tableColumn identifier] isEqualToString:NOTE_COLUMNID] || [[tableColumn identifier] isEqualToString:AUTHOR_COLUMNID]) {
  3824. return YES;
  3825. }
  3826. }
  3827. return NO;
  3828. }
  3829. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  3830. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3831. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  3832. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  3833. NSMutableArray *sortDescriptors = nil;
  3834. BOOL ascending = YES;
  3835. if ([oldTableColumn isEqual:newTableColumn]) {
  3836. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  3837. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  3838. ascending = [[sortDescriptors firstObject] ascending];
  3839. } else {
  3840. NSString *tcID = [newTableColumn identifier];
  3841. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  3842. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  3843. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  3844. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  3845. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  3846. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  3847. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  3848. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  3849. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3850. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  3851. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  3852. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  3853. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  3854. }
  3855. if (oldTableColumn)
  3856. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  3857. [ov setHighlightedTableColumn:newTableColumn];
  3858. }
  3859. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  3860. if (newTableColumn)
  3861. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  3862. inTableColumn:newTableColumn];
  3863. [ov reloadData];
  3864. }
  3865. }
  3866. - (NSString *)outlineView:(NSOutlineView *)ov toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tableColumn item:(id)item mouseLocation:(NSPoint)mouseLocation {
  3867. if ([ov isEqual:rightSideController.noteOutlineView] &&
  3868. (tableColumn == nil || [[tableColumn identifier] isEqualToString:NOTE_COLUMNID])) {
  3869. return [item string];
  3870. }
  3871. return @"";
  3872. }
  3873. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  3874. if (mwcFlags.autoResizeNoteRows &&
  3875. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  3876. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  3877. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  3878. [rowHeights removeAllFloats];
  3879. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  3880. }
  3881. }
  3882. - (void)updateSelectRowHeight{
  3883. CGFloat rowHeight = 0;
  3884. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:leftSideController.tocOutlineView.selectedRow];
  3885. if (!outline){
  3886. return;
  3887. }
  3888. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3889. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3890. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3891. [attributedString appendAttributedString:attr1];
  3892. NSInteger *row = [leftSideController.tocOutlineView selectedRow];
  3893. NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:row makeIfNecessary:YES];
  3894. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3895. // id cell = [tableColumn dataCell];
  3896. id cell = [tableColumn dataCellForRow:row];
  3897. [cell setObjectValue:attributedString];
  3898. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3899. NSInteger num = [self getNum:outline];
  3900. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3901. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3902. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3903. [rowHeights setFloat:rowHeight forKey:outline];
  3904. if (@available(macOS 10.13, *)) {
  3905. } else {
  3906. rowHeight = 40.0;
  3907. }
  3908. CGRect fram = viewS.frame;
  3909. viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3910. [leftSideController.tocOutlineView reloadData];
  3911. }
  3912. - (NSInteger)getNum:(PDFOutline *)ol{
  3913. NSInteger num = 0;
  3914. PDFOutline *outLine = [ol parent];
  3915. do {
  3916. outLine = [outLine parent];
  3917. if (outLine){
  3918. num ++;
  3919. }
  3920. } while (outLine);
  3921. return num;
  3922. }
  3923. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  3924. {
  3925. NSInteger rowCount = [outlineView numberOfRows];
  3926. for (NSInteger i = 0; i < rowCount; i++){
  3927. CGFloat rowHeight = 0;
  3928. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  3929. if (!outline){
  3930. continue;
  3931. }
  3932. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  3933. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  3934. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  3935. [attributedString appendAttributedString:attr1];
  3936. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  3937. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  3938. // id cell = [tableColumn dataCell];
  3939. id cell = [tableColumn dataCellForRow:i];
  3940. [cell setObjectValue:attributedString];
  3941. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  3942. NSInteger num = [self getNum:outline];
  3943. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  3944. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  3945. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  3946. [rowHeights setFloat:rowHeight forKey:outline];
  3947. if (@available(macOS 10.13, *)) {
  3948. } else {
  3949. rowHeight = 40.0;
  3950. }
  3951. // CGRect fram = viewS.frame;
  3952. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  3953. }
  3954. [leftSideController.tocOutlineView reloadData];
  3955. }
  3956. */
  3957. func noteItems(_ items: NSArray) -> NSArray {
  3958. var noteItems = NSMutableArray()
  3959. for item in items {
  3960. guard let anno = (item as? KMBOTAAnnotationItem)?.annotation else {
  3961. continue
  3962. }
  3963. if anno.type == nil {
  3964. // item = [(SKNoteText *)item note];
  3965. }
  3966. if noteItems.contains(anno) == false {
  3967. noteItems.add(anno)
  3968. }
  3969. }
  3970. return noteItems
  3971. }
  3972. /*
  3973. - (NSArray *)outlineView:(NSOutlineView *)ov typeSelectHelperSelectionStrings:(SKTypeSelectHelper *)typeSelectHelper {
  3974. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3975. NSInteger i, count = [rightSideController.noteOutlineView numberOfRows];
  3976. NSMutableArray *texts = [NSMutableArray arrayWithCapacity:count];
  3977. for (i = 0; i < count; i++) {
  3978. id item = [rightSideController.noteOutlineView itemAtRow:i];
  3979. NSString *string = [item string];
  3980. [texts addObject:string ?: @""];
  3981. }
  3982. return texts;
  3983. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3984. NSInteger i, count = [leftSideController.tocOutlineView numberOfRows];
  3985. NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
  3986. for (i = 0; i < count; i++)
  3987. [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  3988. return array;
  3989. }
  3990. return nil;
  3991. }
  3992. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper didFailToFindMatchForSearchString:(NSString *)searchString {
  3993. if ([ov isEqual:rightSideController.noteOutlineView]) {
  3994. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3995. } else if ([ov isEqual:leftSideController.tocOutlineView]) {
  3996. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"No match: \"%@\"", @"Status message"), searchString]];
  3997. }
  3998. }
  3999. - (void)outlineView:(NSOutlineView *)ov typeSelectHelper:(SKTypeSelectHelper *)typeSelectHelper updateSearchString:(NSString *)searchString {
  4000. if ([typeSelectHelper isEqual:[leftSideController.thumbnailTableView typeSelectHelper]] || [typeSelectHelper isEqual:[pdfView typeSelectHelper]]) {
  4001. if (searchString)
  4002. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Go to page: %@", @"Status message"), searchString]];
  4003. else
  4004. [self updateLeftStatus];
  4005. } else if ([typeSelectHelper isEqual:[rightSideController.noteOutlineView typeSelectHelper]]) {
  4006. if (searchString)
  4007. [statusBar setRightStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding note: \"%@\"", @"Status message"), searchString]];
  4008. else
  4009. [self updateRightStatus];
  4010. } else if ([typeSelectHelper isEqual:[leftSideController.tocOutlineView typeSelectHelper]]) {
  4011. if (searchString)
  4012. [statusBar setLeftStringValue:[NSString stringWithFormat:NSLocalizedString(@"Finding: \"%@\"", @"Status message"), searchString]];
  4013. else
  4014. [self updateLeftStatus];
  4015. }
  4016. }
  4017. */
  4018. }
  4019. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  4020. extension KMLeftSideViewController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  4021. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  4022. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4023. return self.listView.hideNotes == false && items.count > 0
  4024. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  4025. return items.count > 0
  4026. }
  4027. return false
  4028. }
  4029. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  4030. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4031. if (items.isEmpty) {
  4032. return
  4033. }
  4034. for item in self.noteItems(items as NSArray) {
  4035. guard let anno = item as? CPDFAnnotation else {
  4036. continue
  4037. }
  4038. self.listView.remove(anno)
  4039. }
  4040. self.listView.undoManager?.setActionName(KMLocalizedString("Remove Note", "Undo action name"))
  4041. self.reloadAnnotation()
  4042. self.annotationSort(sortArray: [])
  4043. self.noteOutlineView.reloadData()
  4044. } else if anOutlineView.isEqual(to: self.tocOutlineView) {
  4045. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  4046. }
  4047. }
  4048. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  4049. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4050. if (items.count == 1) {
  4051. // PDFAnnotation *annotation = [[self noteItems:items] lastObject];
  4052. // if ([annotation isKindOfClass:[PDFAnnotationStamp class]] ||
  4053. // [annotation isKindOfClass:[PDFAnnotationLink class]]) {
  4054. // return NO;
  4055. // }
  4056. }
  4057. return items.count > 0
  4058. }
  4059. return false
  4060. }
  4061. func outlineView(_ anOutlineView: NSOutlineView, copyItems items: [Any]) {
  4062. if anOutlineView.isEqual(to: self.noteOutlineView) && items.isEmpty == false {
  4063. let pboard = NSPasteboard.general
  4064. var copiedItems: [Any] = []
  4065. var attrString = NSMutableAttributedString()
  4066. var isAttributed = false
  4067. var item: AnyObject?
  4068. // for (item in [self noteItems:items]) {
  4069. // if ([item isMovable])
  4070. // [copiedItems addObject:item];
  4071. // }
  4072. // for (item in items) {
  4073. // if ([attrString length])
  4074. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:@"\n\n"];
  4075. // if ([(PDFAnnotation *)item type] == nil && [[(SKNoteText *)item note] isNote]) {
  4076. // [attrString appendAttributedString:[(SKNoteText *)item text]];
  4077. // isAttributed = YES;
  4078. // } else {
  4079. // [attrString replaceCharactersInRange:NSMakeRange([attrString length], 0) withString:[item string] ?: @""];
  4080. // }
  4081. // }
  4082. //
  4083. // [pboard clearContents];
  4084. // if (isAttributed)
  4085. // [pboard writeObjects:[NSArray arrayWithObjects:attrString, nil]];
  4086. // else
  4087. // [pboard writeObjects:[NSArray arrayWithObjects:[attrString string], nil]];
  4088. // if ([copiedItems count] > 0)
  4089. // [pboard writeObjects:copiedItems];
  4090. }
  4091. }
  4092. }
  4093. // MARK: - KMTocOutlineViewDelegate
  4094. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  4095. // func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  4096. // if ([ov isEqual:leftSideController.tocOutlineView]) {
  4097. // NSInteger numRows = [ov numberOfRows];
  4098. // NSUInteger firstPage = [[[ov itemAtRow:row] page] pageIndex];
  4099. // NSUInteger lastPage = row + 1 < numRows ? [[[ov itemAtRow:row + 1] page] pageIndex] : [[self pdfDocument] pageCount];
  4100. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  4101. // NSUInteger i, iMax = [lastViewedPages count];
  4102. // for (i = 0; i < iMax; i++) {
  4103. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  4104. // return i;
  4105. // }
  4106. // }
  4107. // return NSNotFound;
  4108. // }
  4109. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  4110. if anOutlineView.isEqual(to: self.tocOutlineView) {
  4111. if item == nil {
  4112. return true as AnyObject
  4113. }
  4114. if item is CPDFOutline {
  4115. return (item as! CPDFOutline).destination
  4116. }
  4117. }
  4118. return nil
  4119. }
  4120. }
  4121. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  4122. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  4123. if anOutlineView.isEqual(to: self.noteOutlineView) {
  4124. return true
  4125. }
  4126. return false
  4127. }
  4128. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  4129. // [rowHeights setFloat:newHeight forKey:item];
  4130. }
  4131. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  4132. // if (mwcFlags.autoResizeNoteRows &&
  4133. // [ov isEqual:rightSideController.noteOutlineView] &&
  4134. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  4135. // [rowHeights removeAllFloats];
  4136. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  4137. // }
  4138. }
  4139. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  4140. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  4141. // if (annotation) {
  4142. // [pdfView scrollAnnotationToVisible:annotation];
  4143. // [pdfView setActiveAnnotation:annotation];
  4144. // }
  4145. }
  4146. }
  4147. // MARK: - Menu Item Actions
  4148. extension KMLeftSideViewController {
  4149. @objc func cutPage(_ sender: AnyObject?) {
  4150. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4151. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4152. // return;
  4153. // }
  4154. self._tableView(self.thumbnailTableView, cutRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4155. }
  4156. @objc func copyPage(_ sender: AnyObject?) {
  4157. self.tableView(self.thumbnailTableView, copyRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4158. }
  4159. @objc func pastePage(_ sender: AnyObject?) {
  4160. self.tableView(self.thumbnailTableView, pasteFromPasteboard: nil)
  4161. }
  4162. @objc func deletePage(_ sender: AnyObject?) {
  4163. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4164. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4165. // return;
  4166. // }
  4167. self.tableView(self.thumbnailTableView, deleteRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4168. }
  4169. @objc func rotatePageMenuAction(_ sender: AnyObject?) {
  4170. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4171. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4172. // return;
  4173. // }
  4174. //
  4175. self.tableView(self.thumbnailTableView, rotateRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes as NSIndexSet)
  4176. }
  4177. @objc func quickInsert(_ sender: AnyObject?) {
  4178. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4179. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4180. // return;
  4181. // }
  4182. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4183. if idx == NSNotFound || idx >= self.listView.document.pageCount {
  4184. return
  4185. }
  4186. let result = self.listView.insertPage(KMNormalBlankSize, at: idx+1)
  4187. if result == false {
  4188. return
  4189. }
  4190. var selectedIndexSet = IndexSet()
  4191. selectedIndexSet.insert(idx+1)
  4192. self.insertPages(selectedIndexSet, pageAt: idx)
  4193. }
  4194. @objc func insert(_ sender: AnyObject?) {
  4195. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4196. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4197. // return;
  4198. // }
  4199. guard let document = self.listView.document else {
  4200. return
  4201. }
  4202. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4203. if idx == NSNotFound || idx >= document.pageCount {
  4204. return
  4205. }
  4206. if document.allowsCopying == false || document.allowsPrinting == false {
  4207. Task {
  4208. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4209. }
  4210. return
  4211. }
  4212. let insertVC = KMPDFEditInsertBlankPageWindow(document: document)
  4213. insertVC.insertLocation = 3
  4214. insertVC.currentPage = idx + 1
  4215. insertVC.callback = { [weak self] pdfDoc, _, pages, insertI in
  4216. if let _pages = pages {
  4217. // mm 单位的大小
  4218. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  4219. self?.km_endSheet()
  4220. return
  4221. }
  4222. var pageSize = _winC.pageSize
  4223. let direction = _winC.pageRotation == 0 ? 0 : 1
  4224. if (direction == 0) { // 纵向
  4225. if (pageSize.width > pageSize.height) { // 需要交换
  4226. let tmp = pageSize.width
  4227. pageSize.width = pageSize.height
  4228. pageSize.height = tmp
  4229. } else {
  4230. // no things.
  4231. }
  4232. } else { // 横向
  4233. if (pageSize.width > pageSize.height) {
  4234. // no things.
  4235. } else { // 需要交换
  4236. let tmp = pageSize.width
  4237. pageSize.width = pageSize.height
  4238. pageSize.height = tmp
  4239. }
  4240. }
  4241. /// 插入位置
  4242. let document = CPDFDocument()
  4243. document?.insertPage(pageSize, at: 0)
  4244. if let page: CPDFPage = (document?.page(at: 0)) {
  4245. self?.insertPage(page, pageAt: insertI)
  4246. }
  4247. }
  4248. self?.km_quick_endSheet()
  4249. }
  4250. self.km_beginSheet(windowC: insertVC)
  4251. }
  4252. @objc func insertPDF(_ sender: AnyObject?) {
  4253. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  4254. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4255. // return;
  4256. // }
  4257. guard let document = self.listView.document else {
  4258. return
  4259. }
  4260. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  4261. if idx == NSNotFound || idx >= document.pageCount {
  4262. return
  4263. }
  4264. if document.allowsCopying == false || document.allowsPrinting == false {
  4265. Task {
  4266. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  4267. }
  4268. return
  4269. }
  4270. let panel = NSOpenPanel()
  4271. panel.allowedFileTypes = ["pdf"]
  4272. panel.beginSheetModal(for: self.view.window!) { response in
  4273. if response == .cancel {
  4274. return
  4275. }
  4276. for fileURL in panel.urls {
  4277. let pdfDoc = CPDFDocument(url: fileURL)
  4278. if let data = pdfDoc?.isLocked, data {
  4279. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  4280. let com = PasswordWindowController(windowNibName: "PasswordWindowController")
  4281. com.fileURL = fileURL
  4282. self.km_beginSheet(windowC: com)
  4283. com.closeCallBack = { [unowned self] password in
  4284. self.km_quick_endSheet()
  4285. // }
  4286. if (password.isEmpty == false) {
  4287. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL, password: password)
  4288. insertVC.insertLocation = 3
  4289. insertVC.currentPage = idx + 1
  4290. self.km_beginSheet(windowC: insertVC)
  4291. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4292. var indexs = IndexSet()
  4293. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4294. self?.km_quick_endSheet()
  4295. return
  4296. }
  4297. let doc = _winC.insertDocument!
  4298. let fileAttribute = _winC.fileAttribute
  4299. var insertIndex = insertIdx
  4300. var insertPages: [CPDFPage] = []
  4301. for number in fileAttribute.fetchSelectPages() {
  4302. if let page = doc.page(at: UInt(number-1)) {
  4303. insertPages.append(page)
  4304. indexs.insert(insertIndex)
  4305. insertIndex += 1
  4306. }
  4307. }
  4308. for (i, page) in insertPages.enumerated() {
  4309. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4310. }
  4311. self?.insertPages(indexs, pageAt: insertIdx)
  4312. self?.km_quick_endSheet()
  4313. }
  4314. }
  4315. }
  4316. }
  4317. } else {
  4318. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL)
  4319. insertVC.insertLocation = 3
  4320. insertVC.currentPage = idx + 1
  4321. self.km_beginSheet(windowC: insertVC)
  4322. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  4323. var indexs = IndexSet()
  4324. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  4325. self?.km_quick_endSheet()
  4326. return
  4327. }
  4328. let doc = _winC.insertDocument!
  4329. let fileAttribute = _winC.fileAttribute
  4330. var insertIndex = insertIdx
  4331. var insertPages: [CPDFPage] = []
  4332. for number in fileAttribute.fetchSelectPages() {
  4333. if let page = doc.page(at: UInt(number-1)) {
  4334. insertPages.append(page)
  4335. indexs.insert(insertIndex)
  4336. insertIndex += 1
  4337. }
  4338. }
  4339. for (i, page) in insertPages.enumerated() {
  4340. self?.listView.document.insertPageObject(page, at: UInt(insertIdx + i))
  4341. }
  4342. self?.insertPages(indexs, pageAt: insertIdx)
  4343. self?.km_quick_endSheet()
  4344. }
  4345. }
  4346. }
  4347. }
  4348. }
  4349. @objc func extractPage(_ sender: AnyObject?) {
  4350. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4351. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4352. // return;
  4353. // }
  4354. self.tableView(self.thumbnailTableView, extractRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  4355. }
  4356. @objc func pageEdit(_ sender: AnyObject?) {
  4357. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .pageEdit, params: nil)
  4358. }
  4359. @objc func displayPageSize(_ sender: AnyObject?) {
  4360. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4361. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4362. // return;
  4363. // }
  4364. self.isDisplayPageSize = !self.isDisplayPageSize;
  4365. UserDefaults.standard.setValue(self.isDisplayPageSize, forKey: "kKMThumbnailDisplayPageSizeKey")
  4366. UserDefaults.standard.synchronize()
  4367. Task { @MainActor in
  4368. self.thumbnailTableView.reloadData()
  4369. }
  4370. }
  4371. @objc func sharePage(_ sender: AnyObject?) {
  4372. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  4373. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  4374. // return;
  4375. // }
  4376. guard let document = self.listView.document else {
  4377. return
  4378. }
  4379. var pages = NSMutableArray()
  4380. for idx in self.thumbnailTableView.selectedRowIndexes {
  4381. if (idx < document.pageCount) {
  4382. if let page = self.listView.document.page(at: UInt(idx)) {
  4383. pages.add(page)
  4384. }
  4385. }
  4386. }
  4387. let pdf = CPDFDocument()
  4388. for page in pages {
  4389. // PDFPage *copyPage = [[page copy] autorelease];
  4390. if let _page = page as? CPDFPage {
  4391. pdf?.insertPageObject(_page, at: pdf?.pageCount ?? 0)
  4392. }
  4393. }
  4394. // NSString * = nil;
  4395. var fileName = ""
  4396. // NSString * = [self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension];
  4397. var documentFileName = document.documentURL?.deletingPathExtension().lastPathComponent ?? ""
  4398. var tName = self.fileNameWithSelectedPages(self.thumbnailTableView.selectedRowIndexes)
  4399. if (tName.count > 50) {
  4400. tName = tName.substring(to: 50)
  4401. }
  4402. if (pages.count > 1) {
  4403. fileName = String(format: "%@ pages %@", documentFileName, tName)
  4404. } else {
  4405. fileName = String(format: "%@ page %@", documentFileName, tName)
  4406. }
  4407. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  4408. var cachesDir = paths.first ?? ""
  4409. cachesDir = "\(cachesDir)/\(fileName).pdf"
  4410. var array = NSMutableArray()
  4411. let url = URL(fileURLWithPath: cachesDir)
  4412. array.add(url)
  4413. let vc = KMProgressWindowController()
  4414. // // [NSApp beginSheet:[vc window]
  4415. // // modalForWindow:self.window
  4416. // // modalDelegate:nil
  4417. // // didEndSelector:nil
  4418. // // contextInfo:NULL];
  4419. self.view.window?.beginSheet(vc.window!, completionHandler: { [unowned self] returnCode in
  4420. NSApp.endSheet(self.view.window!, returnCode: returnCode.rawValue)
  4421. })
  4422. DispatchQueue.global().async {
  4423. let sucess = pdf?.write(toFile: cachesDir) ?? false
  4424. if (sucess) {
  4425. DispatchQueue.main.async {
  4426. // [[sender representedObject] performWithItems:array];
  4427. let represent : NSSharingService = (sender as! NSMenuItem).representedObject as! NSSharingService
  4428. represent.perform(withItems: [url])
  4429. NSApp.endSheet(vc.window!)
  4430. vc.close()
  4431. }
  4432. } else {
  4433. NSApp.endSheet(vc.window!)
  4434. vc.close()
  4435. }
  4436. }
  4437. // [vc release];
  4438. }
  4439. @objc func toggleCaseInsensitiveNoteSearch(_ sender: AnyObject?) {
  4440. KMPrint("KMLeftSideViewController-toggleCaseInsensitiveNoteSearch...")
  4441. }
  4442. @objc func searchNotes(_ sender: AnyObject?) {
  4443. self.noteSearchMode = false
  4444. if self.findState == .note {
  4445. if self.noteSearchField.isEqual(to: sender) {
  4446. self.noteSearchMode = true
  4447. }
  4448. self.updateNoteFilterPredicate()
  4449. } else {
  4450. self.updateSnapshotFilterPredicate()
  4451. }
  4452. let textfield = sender as? NSSearchField
  4453. if let data = textfield?.stringValue.isEmpty, data == false {
  4454. let findPboard = NSPasteboard(name: .find)
  4455. findPboard.clearContents()
  4456. // findPboard.writeObjects([textfield!.stringValue])
  4457. }
  4458. }
  4459. @objc func toggleSelectedSnapshots(_ sender: AnyObject?) {
  4460. let indexs = self.snapshotTableView.selectedRowIndexes
  4461. if indexs.isEmpty {
  4462. return
  4463. }
  4464. let model = self.snapshots[indexs.last!]
  4465. let windowC = model.windowC
  4466. if let data = windowC?.window?.isVisible, data {
  4467. windowC?.miniaturize()
  4468. } else {
  4469. windowC?.deminiaturize()
  4470. }
  4471. var rowIndexSet = IndexSet()
  4472. let row = self.snapshotTableView.selectedRow
  4473. if row >= 0 && row < self.snapshots.count {
  4474. rowIndexSet.insert(row)
  4475. }
  4476. var columnIndexSet = IndexSet()
  4477. columnIndexSet.insert(0)
  4478. self.snapshotTableView.reloadData(forRowIndexes: rowIndexSet, columnIndexes: columnIndexSet)
  4479. }
  4480. private func _tableView(_ tv: NSTableView, cutRowsWithIndexes rowIndexes: IndexSet) {
  4481. if tv.isEqual(to: self.thumbnailTableView) {
  4482. self._copysPages.removeAll()
  4483. for idx in rowIndexes {
  4484. if (idx != NSNotFound) {
  4485. if let page = self.listView.document.page(at: UInt(idx))?.copy() as? CPDFPage {
  4486. self._copysPages.append(page)
  4487. }
  4488. }
  4489. }
  4490. self.tableView(tv, deleteRowsWithIndexes: rowIndexes)
  4491. }
  4492. }
  4493. // MARK: - Snapshot
  4494. @objc func menuItemClick_ExportPNG(_ sender: AnyObject?) {
  4495. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4496. return
  4497. }
  4498. let image = snapshot.thumbnailWithSize(0)
  4499. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.pngData(), allowedTypes: ["png"]) { url in
  4500. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4501. }
  4502. }
  4503. @objc func menuItemClick_ExportJPG(_ sender: AnyObject?) {
  4504. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4505. return
  4506. }
  4507. let image = snapshot.thumbnailWithSize(0)
  4508. NSPanel.savePanel_data_success(self.view.window!, imageData: image?.jpgData(), allowedTypes: ["jpg"]) { url in
  4509. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4510. }
  4511. }
  4512. @objc func menuItemClick_ExportPDF(_ sender: AnyObject?) {
  4513. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4514. return
  4515. }
  4516. if let image = snapshot.thumbnailWithSize(0) {
  4517. let document = CPDFDocument()
  4518. _ = document?.km_insert(image: image, at: 0)
  4519. NSPanel.savePanel_pdf_success(self.view.window!, document: document) { url in
  4520. NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: "")
  4521. }
  4522. }
  4523. }
  4524. @objc func menuItemClick_Print(_ sender: AnyObject?) {
  4525. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4526. return
  4527. }
  4528. if let image = snapshot.thumbnailWithSize(0) {
  4529. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .print, params: image)
  4530. }
  4531. }
  4532. @objc func menuItemClick_SelectAll(_ sender: AnyObject?) {
  4533. let selected = self.snapshotListIsAllSelected()
  4534. for model in self.snapshots {
  4535. model.isSelected = !selected
  4536. }
  4537. Task { @MainActor in
  4538. self.snapshotTableView.reloadData()
  4539. }
  4540. }
  4541. @objc func deleteAllSnapshot(_ sender: AnyObject?) {
  4542. for model in self.snapshots {
  4543. model.windowC?.close()
  4544. }
  4545. }
  4546. @objc func hideSnapshot(_ sender: AnyObject?) {
  4547. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4548. return
  4549. }
  4550. if let data = snapshot.window?.isVisible, data {
  4551. snapshot.miniaturize()
  4552. }
  4553. }
  4554. @objc func showSnapshot(_ sender: AnyObject?) {
  4555. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4556. return
  4557. }
  4558. if let data = snapshot.window?.isVisible, data {
  4559. snapshot.window?.orderFront(nil)
  4560. } else {
  4561. snapshot.deminiaturize()
  4562. }
  4563. }
  4564. @objc func deleteSnapshot(_ sender: AnyObject?) {
  4565. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4566. return
  4567. }
  4568. snapshot.close()
  4569. }
  4570. @objc func menuItemClick_Copy(_ sender: AnyObject?) {
  4571. guard let snapshot = (sender as? NSMenuItem)?.representedObject as? KMSnapshotWindowController else {
  4572. return
  4573. }
  4574. let image = snapshot.thumbnailWithSize(0)
  4575. if let tiffData = image?.tiffRepresentation {
  4576. let pasteboardItem = NSPasteboardItem()
  4577. pasteboardItem.setData(tiffData, forType: .tiff)
  4578. let pboard = NSPasteboard.general
  4579. pboard.clearContents()
  4580. pboard.writeObjects([pasteboardItem])
  4581. }
  4582. }
  4583. func updateSnapshotFilterPredicate() {
  4584. let searchString = self.snapshotSearchField.stringValue
  4585. self.searchSnapshots.removeAll()
  4586. if self.findState == .snapshot && searchString.isEmpty == false {
  4587. self.searchSnapshots = self.snapshots.filter({ model in
  4588. let data = model.windowC?.string.contains(searchString) ?? false
  4589. return data
  4590. })
  4591. }
  4592. Task { @MainActor in
  4593. self.updataLeftSideSnapView()
  4594. self.snapshotTableView.reloadData()
  4595. }
  4596. }
  4597. func snapshotListIsAllSelected() -> Bool {
  4598. if self.snapshots.isEmpty {
  4599. return false
  4600. }
  4601. for model in self.snapshots {
  4602. if model.isSelected == false {
  4603. return false
  4604. }
  4605. }
  4606. return true
  4607. }
  4608. }
  4609. // MARK: - Undo & Redo
  4610. extension KMLeftSideViewController {
  4611. @objc dynamic func tableView(_ tv: NSTableView, rotateRowsWithIndexes rowIndexes: NSIndexSet) {
  4612. if tv.isEqual(to: self.thumbnailTableView) {
  4613. for idx in rowIndexes {
  4614. if (idx != NSNotFound) {
  4615. let page = self.listView.document.page(at: UInt(idx))
  4616. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).rotatePage(page, pageAt: idx)
  4617. page?.rightRotate()
  4618. self.listView.layoutDocumentView()
  4619. self.resetThumbnails()
  4620. // NSInteger pageIndex = MIN(idx, [[pdfView document] pageCount]-1);
  4621. // [pdfView goToPage:[[pdfView document] pageAtIndex:pageIndex]];
  4622. }
  4623. self.thumbnailTableView.selectRowIndexes(rowIndexes as IndexSet, byExtendingSelection: true)
  4624. }
  4625. }
  4626. }
  4627. @objc dynamic func rotatePage(_ page: CPDFPage?, pageAt index: Int) {
  4628. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, rotateRowsWithIndexes: NSIndexSet(index: index))
  4629. page?.leftRotate()
  4630. self.listView.layoutDocumentView()
  4631. self.resetThumbnails()
  4632. }
  4633. @objc dynamic func insertPage(_ page: CPDFPage, pageAt index: Int) {
  4634. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: index))
  4635. self.listView.document.insertPageObject(page, at: UInt(index))
  4636. self.listView.layoutDocumentView()
  4637. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4638. self.resetThumbnails()
  4639. let pageIndex = min(index, Int((self.listView.document?.pageCount ?? 0))-1)
  4640. self.listView.go(toPageIndex: pageIndex, animated: false)
  4641. }
  4642. @objc dynamic func insertPages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4643. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(selectedIndexSet, pageAt: index)
  4644. self.listView.layoutDocumentView()
  4645. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4646. self.resetThumbnails()
  4647. if let pageIndex = selectedIndexSet.first {
  4648. self.listView.go(toPageIndex: pageIndex, animated: false)
  4649. }
  4650. }
  4651. @objc dynamic func deletePages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  4652. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPages(selectedIndexSet, pageAt: index)
  4653. for idx in selectedIndexSet {
  4654. if idx < self.listView.document.pageCount {
  4655. self.listView.document.removePage(at: UInt(idx))
  4656. }
  4657. }
  4658. self.listView.layoutDocumentView()
  4659. // [pageLabels setArray:[[pdfView document] pageLabels]];
  4660. self.resetThumbnails()
  4661. let pageIndex = min(index, Int(self.listView.document.pageCount)-1)
  4662. self.listView.go(toPageIndex: pageIndex, animated: false)
  4663. }
  4664. }
  4665. // MARK: - Other
  4666. extension KMLeftSideViewController {
  4667. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  4668. let outlineItem = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow)
  4669. let outline = self.tocOutlineView
  4670. if let cnt = outline?.selectedRowIndexes.count, cnt == 1 {
  4671. if outlineItem is CPDFOutline {
  4672. let outline = (outlineItem as! CPDFOutline)
  4673. if let des = outline.destination {
  4674. self.listView.go(to: des)
  4675. } else if let action = outline.action {
  4676. self.listView.perform(action)
  4677. }
  4678. } else if outlineItem is CPDFBookmark {
  4679. let bookmark = outlineItem as! CPDFBookmark
  4680. self.listView.go(toPageIndex: bookmark.pageIndex, animated: true)
  4681. }
  4682. }
  4683. }
  4684. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  4685. KMPrint("KMLeftSideViewController-goToSelectedFindResults...")
  4686. }
  4687. func tableView(_ tv: NSTableView, extractRowsWithIndexes rowIndexes: IndexSet) {
  4688. if tv.isEqual(to: self.thumbnailTableView) {
  4689. guard let document = self.listView.document else {
  4690. return
  4691. }
  4692. var pages = NSMutableArray()
  4693. for idx in self.thumbnailTableView.selectedRowIndexes {
  4694. if (idx < document.pageCount) {
  4695. if let page = self.listView.document.page(at: UInt(idx)) {
  4696. pages.add(page)
  4697. }
  4698. }
  4699. }
  4700. let fileName = document.getFileNameAccordingSelctPages(pages as! [CPDFPage])
  4701. let saveAccessCtr = KMSavePanelAccessoryController()
  4702. let outputSavePanel = NSSavePanel()
  4703. outputSavePanel.allowedFileTypes = ["pdf"]
  4704. outputSavePanel.accessoryView = saveAccessCtr.view
  4705. outputSavePanel.nameFieldStringValue = fileName
  4706. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  4707. if (result == .OK) {
  4708. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  4709. let vc = KMProgressWindowController()
  4710. self.view.window?.beginSheet(vc.window!)
  4711. let saveFilePath = outputSavePanel.url?.path
  4712. DispatchQueue.global().async {
  4713. let pdf = CPDFDocument()
  4714. let success = pdf?.extractAsOneDocument(withPages: pages as! [CPDFPage], savePath: saveFilePath) ?? false
  4715. DispatchQueue.main.async {
  4716. if (success) {
  4717. if (saveAccessCtr.openAutomaticButton.state == .on) {
  4718. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  4719. }
  4720. } else {
  4721. KMTools.viewFile(at: saveFilePath!)
  4722. }
  4723. }
  4724. NSApp.endSheet(vc.window!)
  4725. vc.close()
  4726. }
  4727. }
  4728. }
  4729. }
  4730. }
  4731. }
  4732. }
  4733. func fileNameWithSelectedPages(_ itemIndexes: IndexSet) -> String {
  4734. var pagesName = ""
  4735. if (itemIndexes.count > 1) {
  4736. pagesName.append(" pages")
  4737. } else {
  4738. pagesName.append("page")
  4739. }
  4740. let docmentName = self.listView.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  4741. var fileName = ""
  4742. if (itemIndexes.count > 0) {
  4743. if (itemIndexes.count == 1) {
  4744. let idx = itemIndexes.first! + 1
  4745. let tFileName = String(format: "%@ %@", pagesName, "\(idx)")
  4746. return String(format: "%@%@", docmentName, tFileName)
  4747. }
  4748. var sortIndex = IndexSet()
  4749. for idx in itemIndexes {
  4750. let _idx = idx + 1
  4751. sortIndex.insert(_idx)
  4752. }
  4753. // NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
  4754. // NSArray *sortDesc = @[sort];
  4755. // NSArray *sortArray = [sortIndex sortedArrayUsingDescriptors:sortDesc];
  4756. let sortArray = sortIndex.sorted()
  4757. var a = 0
  4758. var b = 0
  4759. for num in sortArray {
  4760. // for (NSNumber *num in sortArray) {
  4761. if (fileName.isEmpty == false) {
  4762. if (num == b+1) {
  4763. b = num
  4764. if (num == sortArray.last) {
  4765. fileName = "\(fileName)\(a)-\(b)"
  4766. }
  4767. } else {
  4768. if (a == b) {
  4769. fileName = "\(fileName)\(a),"
  4770. } else {
  4771. fileName = "\(fileName)\(a)-\(b),"
  4772. }
  4773. b = num
  4774. a = b
  4775. if (num == sortArray.last) {
  4776. fileName = "\(fileName)\(a)"
  4777. }
  4778. }
  4779. } else {
  4780. fileName = ""
  4781. b = num
  4782. a = b
  4783. }
  4784. }
  4785. let tFileName = String(format: "%@ %@", pagesName,fileName)
  4786. return String(format: "%@%@", docmentName,tFileName)
  4787. }
  4788. return ""
  4789. }
  4790. func switchType(_ type: BotaType) {
  4791. if type == .Thumbnail {
  4792. self.leftView.segmentedControl.selectedSegment = 0
  4793. } else if type == .Outline {
  4794. self.leftView.segmentedControl.selectedSegment = 1
  4795. } else if type == .Annotation {
  4796. self.leftView.segmentedControl.selectedSegment = 2
  4797. } else if type == .snapshot {
  4798. self.leftView.segmentedControl.selectedSegment = 3
  4799. } else if type == .Search {
  4800. self.leftView.segmentedControl.selectedSegment = 4
  4801. }
  4802. }
  4803. var TINY_SIZE: Float {
  4804. get {
  4805. return 32.0
  4806. }
  4807. }
  4808. var SMALL_SIZE: Float {
  4809. get {
  4810. return 64.0
  4811. }
  4812. }
  4813. var LARGE_SIZE: Float {
  4814. get {
  4815. return 128.0
  4816. }
  4817. }
  4818. var HUGE_SIZE: Float {
  4819. get {
  4820. return 256.0
  4821. }
  4822. }
  4823. var FUDGE_SIZE: Float {
  4824. get {
  4825. return 0.1
  4826. }
  4827. }
  4828. func updateTableFont() {
  4829. let font = NSFont.systemFont(ofSize: KMPreference.shared.outlineFontSize.cgFloat)
  4830. self.tocOutlineView.font = font
  4831. self.noteOutlineView.font = font
  4832. self.findTableView.font = font
  4833. self.groupedFindTableView.font = font
  4834. }
  4835. }