KMLeftSideViewController.swift 240 KB

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