KMLeftSideViewController.swift 253 KB

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