KMLeftSideViewController.swift 254 KB

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