KMMainViewController+Action.swift 298 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView?.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. // self.srHanddler.newSearch(keyword: searchString, isCase: isCase, isWholeWord: isWholeWord) { models in
  26. // KMPrint("")
  27. // }
  28. var opt = CPDFSearchOptions()
  29. if isCase == false {
  30. opt.insert(.caseSensitive)
  31. }
  32. if isWholeWord {
  33. opt.insert(.matchWholeWord)
  34. }
  35. let datas = self.srHanddler.pdfView?.document.findEditAllPageString(searchString, with: opt) ?? []
  36. if let sel = datas.first?.first {
  37. self.srHanddler.showSelection(sel)
  38. }
  39. self.searchResults.removeAll()
  40. var _selections: [CPDFSelection] = []
  41. for selections in datas {
  42. for selection in selections {
  43. let mode : KMSearchMode = KMSearchMode()
  44. mode.selection = selection
  45. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  46. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  47. self.searchResults.insert(mode, at: self.searchResults.count)
  48. _selections.append(selection)
  49. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  50. // self.listView.setHighlight(selection, forBorderColor: .yellow, fill: .red, animated: false)
  51. }
  52. // self.listView.setHighlightedSelections(selections )
  53. }
  54. if needShowAll {
  55. self.listView.setHighlightedSelections(_selections)
  56. }
  57. if _selections.isEmpty {
  58. self.listView.setHighlightedSelection(nil, animated: false)
  59. }
  60. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  61. self.leftSideViewController.searchResults = self.searchResults
  62. if display {
  63. if self.leftSideViewController.findPaneState == .singular {
  64. self.leftSideViewController.displayFindViewAnimating(true)
  65. } else {
  66. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  67. }
  68. }
  69. return
  70. }
  71. let document = self.listView.document
  72. if let data = document?.isFinding, data {
  73. document?.cancelFindString()
  74. }
  75. if searchString == "" {
  76. self.searchResults = []
  77. self.leftSideViewController.searchResults = self.searchResults
  78. self.listView.setHighlightedSelections([])
  79. self.listView.setHighlightedSelection(nil, animated: false)
  80. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  81. } else {
  82. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  83. var findArray : [[CPDFSelection]]
  84. if isCase {
  85. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  86. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  87. } else {
  88. findArray = self.listView.document.findString(searchString) ?? []
  89. }
  90. } else {
  91. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  92. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  93. } else {
  94. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  95. }
  96. }
  97. self.searchResults.removeAll()
  98. var _selections: [CPDFSelection] = []
  99. for selections in findArray {
  100. for selection in selections {
  101. let mode : KMSearchMode = KMSearchMode()
  102. mode.selection = selection
  103. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  104. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  105. self.searchResults.insert(mode, at: self.searchResults.count)
  106. _selections.append(selection)
  107. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  108. // self.listView.setHighlight(selection, forBorderColor: .yellow, fill: .red, animated: false)
  109. }
  110. // self.listView.setHighlightedSelections(selections )
  111. }
  112. if needShowAll {
  113. self.listView.setHighlightedSelections(_selections)
  114. }
  115. if _selections.isEmpty {
  116. self.listView.setHighlightedSelection(nil, animated: false)
  117. }
  118. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  119. self.leftSideViewController.searchResults = self.searchResults
  120. }
  121. if display {
  122. if self.leftSideViewController.findPaneState == .singular {
  123. self.leftSideViewController.displayFindViewAnimating(true)
  124. } else {
  125. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  126. }
  127. }
  128. }
  129. func removeSignatures(signatures:[CPDFSignature]) {
  130. for signature in signatures {
  131. self.listView.document.removeSignature(signature)
  132. }
  133. for i in 0..<self.listView.document.pageCount {
  134. let page : CPDFPage = self.listView.document.page(at: i)
  135. let annotations : [CPDFAnnotation] = page.annotations
  136. for j in 0..<annotations.count {
  137. let annotation = annotations[j]
  138. if annotation is CPDFSignatureWidgetAnnotation {
  139. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  140. }
  141. }
  142. }
  143. self.listView.setNeedsDisplayForVisiblePages()
  144. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  145. var mSignatures : [CPDFSignature] = []
  146. for sign in tSignatures {
  147. if sign.signers.count > 0 {
  148. mSignatures.append(sign)
  149. }
  150. }
  151. // self.leftSideViewController.signatureViewController.signatures = signatures
  152. // self.leftSideViewController.signatureViewController.reloadData()
  153. }
  154. //MARK: menu菜单
  155. func fontColorMenuItem()->NSMenuItem {
  156. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  157. return fontColorItem;
  158. }
  159. func fontSizeMenuItem()->NSMenuItem {
  160. let currentFontSize = self.listView.editingTextFontSize()
  161. let fontSizes = self.fontSizes()
  162. let submenu = NSMenu(title: "")
  163. for i in 0 ... fontSizes.count - 1 {
  164. let fontSize : String = fontSizes.object(at: i) as! String
  165. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  166. item.target = self
  167. item.tag = i
  168. submenu.addItem(item)
  169. if (Int(currentFontSize) == Int(fontSize)) {
  170. item.state = .on
  171. }
  172. }
  173. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  174. fontSizeItem.submenu = submenu
  175. return fontSizeItem;
  176. }
  177. func corpImageMenuItem()->NSMenuItem {
  178. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  179. return corpImageItem
  180. }
  181. func cancelCorpImageMenuItem()->NSMenuItem {
  182. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  183. return cancelCorpImageItem
  184. }
  185. func restoreCorpImageMenuItem()->NSMenuItem {
  186. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  187. return cancelCorpImageItem
  188. }
  189. func cutImageArea()->NSMenuItem {
  190. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  191. return deleteItem
  192. }
  193. func editAddBlanMenu(menu:NSMenu){
  194. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  195. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  196. }
  197. func addText() -> NSMenuItem {
  198. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  199. return addTextItem
  200. }
  201. func addImage() -> NSMenuItem {
  202. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  203. return addImageItem
  204. }
  205. func replaceImageArea()->NSMenuItem {
  206. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  207. return replaceItem
  208. }
  209. func exportImageArea()->NSMenuItem {
  210. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  211. let menu = NSMenu()
  212. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  213. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  214. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  215. exportItem.submenu = menu
  216. return exportItem
  217. }
  218. func exportImageStampItem()->NSMenuItem {
  219. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  220. let menu = NSMenu()
  221. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  222. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  223. exportItem.submenu = menu
  224. return exportItem
  225. }
  226. func exportMenu() -> NSMenu {
  227. let menu = NSMenu()
  228. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  229. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  230. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  231. return menu
  232. }
  233. func cropMenu() -> NSMenu {
  234. let menu = NSMenu()
  235. _ = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  236. _ = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  237. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  238. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(smartAutoCropAll), target: self, at: 2)
  239. return menu
  240. }
  241. func zoomSelectionMenuItem() -> NSMenuItem {
  242. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  243. return item
  244. }
  245. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  246. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  247. return item
  248. }
  249. func enterAnnotationStype() -> NSMenuItem {
  250. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  251. let stypeMenu = NSMenu()
  252. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  254. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  255. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  256. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  257. stypeMenu.addItem(NSMenuItem.separator())
  258. }
  259. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  260. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  261. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  262. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  263. stypeMenu.addItem(NSMenuItem.separator())
  264. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  265. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  266. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  267. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  268. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  269. if self.isReadMode {
  270. } else {
  271. stypeMenu.addItem(NSMenuItem.separator())
  272. // _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  273. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  274. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  275. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  276. }
  277. stypItem.submenu = stypeMenu
  278. if self.listView.annotationType == .ink {
  279. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  280. } else if self.listView.annotationType == .freeText {
  281. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  282. } else if self.listView.annotationType == .anchored {
  283. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  284. } else if self.listView.annotationType == .square {
  285. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  286. } else if self.listView.annotationType == .circle {
  287. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  288. } else if self.listView.annotationType == .arrow {
  289. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  290. } else if self.listView.annotationType == .line {
  291. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  292. } else if self.listView.annotationType == .link {
  293. stypeMenu.item(at: 7)?.state = .on
  294. } else if self.listView.annotationType == .stamp {
  295. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  296. } else if self.listView.annotationType == .signSignature {
  297. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  298. }
  299. return stypItem
  300. }
  301. func setAnnotationToolStype() -> NSMenuItem {
  302. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  303. let stypeMenu = NSMenu()
  304. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  305. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  306. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  307. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  308. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  309. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  310. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  311. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  312. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  313. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.squiggly.rawValue)
  314. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  315. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  316. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  317. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  318. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  319. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  320. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  321. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  322. stypItem.submenu = stypeMenu
  323. if self.toolbarController.toolbarType == .Annatiton {
  324. stypeMenu.item(at: 0)?.state = .on
  325. } else if self.toolbarController.toolbarType == .Move {
  326. stypeMenu.item(at: 1)?.state = .on
  327. } else if self.toolbarController.toolbarType == .Magnify {
  328. stypeMenu.item(at: 2)?.state = .on
  329. } else if self.toolbarController.toolbarType == .Select {
  330. stypeMenu.item(at: 3)?.state = .on
  331. } else if self.toolbarController.toolbarType == .SelectZoom {
  332. stypeMenu.item(at: 4)?.state = .on
  333. }
  334. return stypItem
  335. }
  336. func addReadModelStype() -> NSMenuItem {
  337. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  338. if self.isReadMode {
  339. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  340. }
  341. return stypItem
  342. }
  343. func addOutlineStype() -> NSMenuItem {
  344. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  345. return stypItem
  346. }
  347. func setTTSStype() -> NSMenuItem {
  348. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  349. return stypItem
  350. }
  351. func setShareStype() -> NSMenuItem {
  352. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  353. var string = ""
  354. if listView.activeAnnotation != nil {
  355. string = self.listView?.activeAnnotation?.contents ?? ""
  356. }
  357. if string.count < 1{
  358. string = self.listView?.currentSelection?.string() ?? ""
  359. }
  360. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  361. return stypItem
  362. }
  363. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  364. var number = 0
  365. var indexN = 0
  366. guard str.count > 0 else {return (0, 0)}
  367. for i in 0...str.count - 1 {
  368. let c: unichar = (str as NSString).character(at: i)
  369. if (c >= 0x4E00) {
  370. number += 2
  371. }else {
  372. number += 1
  373. }
  374. if number > 56{
  375. indexN = i
  376. number = 100
  377. break
  378. }
  379. }
  380. return (number, indexN)
  381. }
  382. func setLookUpStype() -> NSMenuItem {
  383. guard let str = listView?.currentSelection?.string() else {
  384. return NSMenuItem.separator()
  385. }//String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  386. let dic = numberOfChars(str)
  387. var newStr = str
  388. if dic.num == 100{
  389. newStr = str.prefix(dic.indexN) + "..."
  390. }
  391. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  392. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  393. return stypItem
  394. }
  395. func setSearchBaiduStype() -> NSMenuItem {
  396. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  397. return stypItem
  398. }
  399. func setCutStype() -> NSMenuItem {
  400. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  401. return stypItem
  402. }
  403. func setDeleteStype() -> NSMenuItem {
  404. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  405. return stypItem
  406. }
  407. func setColorsStype() -> NSMenuItem {
  408. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  409. return stypItem
  410. }
  411. func setLinesStype() -> NSMenuItem {
  412. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  413. return stypItem
  414. }
  415. func setEditNoteStype() -> NSMenuItem {
  416. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  417. return stypItem
  418. }
  419. func setRotateStype() -> NSMenuItem {
  420. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  421. let stypeMenu = NSMenu()
  422. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  423. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  424. stypItem.submenu = stypeMenu
  425. if self.toolbarController.toolbarType == .Annatiton {
  426. stypeMenu.item(at: 0)?.state = .on
  427. } else if self.toolbarController.toolbarType == .Move {
  428. stypeMenu.item(at: 1)?.state = .on
  429. }
  430. return stypItem
  431. }
  432. func setNextPageStype() -> NSMenuItem {
  433. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  434. stypItem.isEnabled = false
  435. if listView.canGoToNextPage() {
  436. stypItem.isEnabled = true
  437. }
  438. return stypItem
  439. }
  440. func setPreviousPageStype() -> NSMenuItem {
  441. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  442. stypItem.isEnabled = false
  443. if listView.canGoToPreviousPage() {
  444. stypItem.isEnabled = true
  445. }
  446. return stypItem
  447. }
  448. func setTranslateStype() -> NSMenuItem {
  449. let str = listView?.currentSelection?.string() ?? ""//String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  450. let dic = numberOfChars(str)
  451. var newStr = str
  452. if dic.num == 100{
  453. newStr = str.prefix(dic.indexN) + "..."
  454. }
  455. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  456. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  457. return stypItem
  458. }
  459. func setAutoScrollStype() -> NSMenuItem {
  460. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  461. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  462. return stypItem
  463. }
  464. func setSnapshotStype() -> NSMenuItem {
  465. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  466. let stypeMenu = NSMenu()
  467. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  468. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  469. stypItem.submenu = stypeMenu
  470. // if self.toolbarController.toolbarType == .Annatiton {
  471. // stypeMenu.item(at: 0)?.state = .on
  472. // } else if self.toolbarController.toolbarType == .Move {
  473. // stypeMenu.item(at: 1)?.state = .on
  474. // }
  475. return stypItem
  476. }
  477. func setServicesStype() -> NSMenuItem {
  478. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  479. let stypeMenu = NSMenu()
  480. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  481. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  482. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  483. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  484. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  485. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  486. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  487. stypItem.submenu = stypeMenu
  488. // if self.toolbarController.toolbarType == .Annatiton {
  489. // stypeMenu.item(at: 0)?.state = .on
  490. // } else if self.toolbarController.toolbarType == .Move {
  491. // stypeMenu.item(at: 1)?.state = .on
  492. // }
  493. return stypItem
  494. }
  495. func setCropStype() -> NSMenuItem {
  496. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  497. let stypeMenu = NSMenu()
  498. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  499. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  500. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  501. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  502. if NSIsEmptyRect(listView.selectionRect){
  503. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  504. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  505. }
  506. stypItem.submenu = stypeMenu
  507. // if self.toolbarController.toolbarType == .Annatiton {
  508. // stypeMenu.item(at: 0)?.state = .on
  509. // } else if self.toolbarController.toolbarType == .Move {
  510. // stypeMenu.item(at: 1)?.state = .on
  511. // } else if self.toolbarController.toolbarType == .Magnify {
  512. // stypeMenu.item(at: 2)?.state = .on
  513. // } else if self.toolbarController.toolbarType == .Select {
  514. // stypeMenu.item(at: 3)?.state = .on
  515. // } else if self.toolbarController.toolbarType == .SelectZoom {
  516. // stypeMenu.item(at: 4)?.state = .on
  517. // }
  518. return stypItem
  519. }
  520. func setAITranslateStype() -> NSMenuItem {
  521. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  522. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  523. return stypItem
  524. }
  525. func setAIProofreadStype() -> NSMenuItem {
  526. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  527. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  528. return stypItem
  529. }
  530. func setAIRewriteStype() -> NSMenuItem {
  531. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  532. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  533. return stypItem
  534. }
  535. func addHighlightLinksStype() -> NSMenuItem {
  536. let highlightLink = KMPreferenceManager.shared.highlightLinks
  537. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  538. if highlightLink {
  539. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  540. }
  541. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  542. return highlightLinksItem
  543. }
  544. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  545. if item == nil {
  546. return
  547. }
  548. let menu = NSMenu()
  549. item?.submenu = menu
  550. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  551. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  552. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  553. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  554. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  555. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  556. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  557. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  558. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  559. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  560. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  561. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  562. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  563. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  564. if listView.currentSelection.selectionType() != .image {
  565. menu.insertItem(height, at: menu.items.count)
  566. menu.insertItem(underline, at: menu.items.count)
  567. menu.insertItem(strickout, at: menu.items.count)
  568. menu.insertItem(wavyLine, at: menu.items.count)
  569. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  570. }
  571. if self.isReadMode {
  572. } else {
  573. if listView.currentSelection.selectionType() != .image &&
  574. listView.currentSelection.selectionType() != .text {
  575. menu.insertItem(text, at: menu.items.count)
  576. menu.insertItem(note, at: menu.items.count)
  577. }
  578. }
  579. if self.isReadMode {
  580. } else {
  581. if listView.currentSelection.selectionType() != .image {
  582. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  583. menu.insertItem(rectangle, at: menu.items.count)
  584. menu.insertItem(oval, at: menu.items.count)
  585. }
  586. }
  587. if self.isReadMode {
  588. } else {
  589. if listView.currentSelection.selectionType() != .image &&
  590. listView.currentSelection.selectionType() != .text {
  591. menu.insertItem(line, at: menu.items.count)
  592. }
  593. }
  594. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  595. if self.isReadMode {
  596. } else {
  597. menu.insertItem(link, at: menu.items.count)
  598. }
  599. if self.isReadMode {
  600. } else {
  601. if listView.currentSelection.selectionType() != .image {
  602. menu.insertItem(outline, at: menu.items.count)
  603. }
  604. }
  605. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  606. if self.isReadMode {
  607. } else {
  608. if (listView.currentSelection.selectionType() != .image) {
  609. menu.insertItem(aiTranslation, at: menu.items.count)
  610. }
  611. }
  612. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  613. }
  614. func addBookmarkMenu() -> NSMenuItem {
  615. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  616. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  617. return bookMarkItem
  618. } else {
  619. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  620. return bookMarkItem
  621. }
  622. }
  623. func findStringMenu() -> NSMenuItem {
  624. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  625. menuItem.keyEquivalent = "f"
  626. return menuItem
  627. }
  628. func printingMenu() -> NSMenuItem {
  629. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  630. return menuItem
  631. }
  632. func fontSizes()->NSArray {
  633. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  634. }
  635. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  636. if interactionMode == .presentation {
  637. listView.goToPreviousPage(nil)
  638. return true
  639. }
  640. return false
  641. }
  642. func canEnterFullscreen() -> Bool {
  643. if (mwcFlags.isSwitchingFullScreen != 0) {
  644. return false
  645. }
  646. if useNativeFullScreen() {
  647. return interactionMode == .normal || interactionMode == .presentation
  648. } else {
  649. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  650. }
  651. }
  652. override func canEnterPresentation() -> Bool {
  653. let can = super.canEnterPresentation()
  654. if can == false {
  655. return false
  656. }
  657. guard let doc = self.listView?.document, doc.isLocked == false else {
  658. return false
  659. }
  660. return can
  661. }
  662. func useNativeFullScreen() -> Bool {
  663. var isFull = false
  664. // NSWindow.instancesRespond(toSelector: #selector(toggleFullScreen:))
  665. let sel = NSSelectorFromString("toggleFullscreen:")
  666. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  667. isFull = true
  668. }
  669. return isFull
  670. }
  671. func enterPresentation() {
  672. self.view.window?.enterPresentation(provider: self)
  673. }
  674. func removeBlankingWindows() {
  675. // blankingWindows.makeObjectsPerform(#selector(fadeOut))
  676. // blankingWindows = nil
  677. }
  678. func hideLeftSideWindow() {
  679. // if leftSideViewController.view.window == leftSideWindow {
  680. // self.leftView.remove()
  681. // if leftSideWindow.firstResponder()?.isDescendant(of: leftSideController.view()) {
  682. // leftSideWindow.makeFirstResponder(nil)
  683. // }
  684. // leftSideController.view().setFrame(SKShrinkRect(NSInsetRect(leftSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  685. // leftSideContentView.addSubview(leftSideController.view())
  686. //
  687. // if self.interactionMode() == SKPresentationMode {
  688. // self.setLeftSidePaneState(mwcFlags.savedLeftSidePaneState)
  689. // }
  690. //
  691. // leftSideWindow = nil
  692. // }
  693. }
  694. func hideRightSideWindow() {
  695. // if rightSideController.view().window() == rightSideWindow {
  696. // rightSideWindow.remove()
  697. // if rightSideWindow.firstResponder()?.isDescendant(of: rightSideController.view()) {
  698. // rightSideWindow.makeFirstResponder(nil)
  699. // }
  700. // rightSideController.view().setFrame(SKShrinkRect(NSInsetRect(rightSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  701. // rightSideContentView.addSubview(rightSideController.view())
  702. //
  703. // rightSideWindow = nil
  704. // }
  705. }
  706. func forceSubwindowsOnTop(_ flag: Bool) {
  707. // let winC: NSWindowController = self.kmCurrentWindowC!
  708. // for wc in winC.document!.windowControllers {
  709. // let sel = NSSelectorFromString("setForceOnTop:")
  710. // if wc.responds(to: sel){
  711. // wc.
  712. // }
  713. // }
  714. }
  715. func enterPresentationMode() {
  716. let scrollView = listView.documentView().enclosingScrollView
  717. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  718. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  719. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  720. // Set up presentation mode
  721. // if RUNNING(version: 10_12) {
  722. // pdfView.setBackgroundColor(NSColor.black)
  723. // } else {
  724. listView.backgroundColor = NSColor.clear
  725. // }
  726. listView.setDisplay(.singlePage)
  727. listView.autoScales = true
  728. listView.displayBox = .cropBox
  729. listView.displaysPageBreaks = false
  730. scrollView?.autohidesScrollers = true
  731. scrollView?.hasHorizontalScroller = false
  732. scrollView?.hasVerticalScroller = false
  733. listView.setCurrentSelection(nil, animate: true)
  734. // if listView.hasReadingBar() {
  735. // listView.toggleReadingBar()
  736. // }
  737. // myDocument!.currentPage(presentationNotesDocument.pdfDocument().page(at: listView.currentPage().pageIndex()))
  738. // Prevent sleep
  739. // if activityAssertionID == kIOPMNullAssertionID && kIOReturnSuccess != IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Skim" as CFString, &activityAssertionID) {
  740. // activityAssertionID = kIOPMNullAssertionID
  741. // }
  742. }
  743. func exitFullscreenMode() {
  744. if self.interactionMode == .presentation {
  745. self.exitPresentationMode()
  746. }
  747. self.applyPDFSettings(self.savedNormalSetup)
  748. self.savedNormalSetup.removeAllObjects()
  749. self.listView.layoutDocumentView()
  750. self.listView.requiresDisplay()
  751. // if ([[[self pdfView] currentPage] isEqual:page] == NO)
  752. // [[self pdfView] goToPage:page];
  753. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  754. self.listView.backgroundColor = backgroundColor
  755. self.secondaryPdfView?.backgroundColor = backgroundColor
  756. }
  757. }
  758. func applyPDFSettings(_ setup: NSDictionary) {
  759. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  760. self.listView.autoScales = data.boolValue
  761. }
  762. if self.listView.autoScales == false {
  763. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  764. self.listView.scaleFactor = data.floatValue.cgFloat
  765. }
  766. }
  767. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  768. self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
  769. }
  770. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  771. self.listView.displaysAsBook = data.boolValue
  772. }
  773. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  774. self.listView.displaysPageBreaks = data.boolValue
  775. }
  776. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  777. // self.listView.displayBox = CPDFDisplayBox(rawValue: data.intValue) ?? .cropBox
  778. }
  779. self.listView.layoutDocumentView()
  780. // self.savePageNumberIfNeed()
  781. }
  782. func exitPresentationMode() {
  783. // if (activityAssertionID != kIOPMNullAssertionID && kIOReturnSuccess == IOPMAssertionRelease(activityAssertionID))
  784. // activityAssertionID = kIOPMNullAssertionID;
  785. //
  786. // NSScrollView *scrollView = [[pdfView documentView] enclosingScrollView];
  787. // [scrollView setHasHorizontalScroller:[[savedNormalSetup objectForKey:HASHORIZONTALSCROLLER_KEY] boolValue]];
  788. // [scrollView setHasVerticalScroller:[[savedNormalSetup objectForKey:HASVERTICALSCROLLER_KEY] boolValue]];
  789. // [scrollView setAutohidesScrollers:[[savedNormalSetup objectForKey:AUTOHIDESSCROLLERS_KEY] boolValue]];
  790. self.selectDisplay(display: KMPDFDisplayType(rawValue: KMPDFDisplayType.RawValue(self.listView.fetchDisplayViewMode().rawValue)) ?? .singlePage, viewSettingIsReload: false)
  791. // NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CPDFListViewDisplayModeChangeNotification"), object: nil)
  792. }
  793. func currentPDFSettings() -> NSDictionary {
  794. let setup = NSMutableDictionary()
  795. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  796. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  797. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  798. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  799. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  800. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
  801. return setup
  802. }
  803. //MARK: menuItem Action
  804. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  805. let color = listView.editingSelectionFontColor()
  806. let panel = NSColorPanel.shared
  807. panel.setTarget(self)
  808. panel.setAction(#selector(fontColorChangeAction))
  809. panel.orderFront(nil)
  810. panel.showsAlpha = false
  811. panel.color = color ?? NSColor.black
  812. }
  813. @objc func fontColorChangeAction(sender: NSColorPanel) {
  814. self.listView.setEditingSelectionFontColor(sender.color)
  815. }
  816. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  817. let fontSize = self.fontSizes().object(at: sender.tag)
  818. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  819. }
  820. @objc func addImageText(sender: NSMenuItem) {
  821. let event = NSApp.currentEvent
  822. let clickLocation = event?.locationInWindow
  823. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  824. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  825. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  826. point = point2
  827. if sender.tag == 0 {
  828. KMPrint("添加文字")
  829. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  830. if !isSelect {
  831. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  832. }
  833. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  834. } else if sender.tag == 1 {
  835. KMPrint("添加图片")
  836. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  837. if !isSelect {
  838. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  839. }
  840. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  841. } else if sender.tag == 2 {
  842. KMPrint("粘贴")
  843. }
  844. }
  845. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  846. if self.rightSideViewController.eidtPDFImageProperty != nil {
  847. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  848. } else {
  849. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  850. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  851. }
  852. }
  853. }
  854. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  855. if self.rightSideViewController.eidtPDFImageProperty != nil {
  856. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  857. } else {
  858. self.listView.exitCrop(with: self.listView.selectImageAreas)
  859. self.listView.cropAreas = nil
  860. self.listView.isEditImage = false
  861. }
  862. }
  863. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  864. if self.rightSideViewController.eidtPDFImageProperty != nil {
  865. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  866. } else {
  867. self.listView.resetCrop(with: self.listView.selectImageAreas)
  868. }
  869. }
  870. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  871. // if self.listView.selectImageAreas != nil {
  872. // self.listView.isEditImage = true
  873. // self.listView.enterCrop(with: self.listView.selectImageAreas)
  874. // self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  875. // }
  876. self.editPDFHanddler.cropAction()
  877. }
  878. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  879. if self.listView.selectImageAreas == nil {
  880. return
  881. }
  882. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  883. let panel = NSOpenPanel()
  884. panel.allowsMultipleSelection = false
  885. panel.allowedFileTypes = ["png","jpg"]
  886. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  887. if response == .OK {
  888. let openPath = panel.url?.path
  889. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  890. if s {
  891. }
  892. }
  893. }
  894. }
  895. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  896. if self.listView.selectImageAreas == nil {
  897. return
  898. }
  899. let panel = NSSavePanel()
  900. // panel.nameFieldStringValue = "[新文件].png"
  901. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  902. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  903. // button.state = .on
  904. // panel.accessoryView = button
  905. panel.isExtensionHidden = true
  906. let response = panel.runModal()
  907. if response == .OK {
  908. let url = panel.url
  909. if FileManager.default.fileExists(atPath: url!.path) {
  910. try?FileManager.default.removeItem(atPath: url!.path)
  911. }
  912. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  913. if result {
  914. NSWorkspace.shared.activateFileViewerSelecting([url!])
  915. // if button.state == .on { /// 开启文档
  916. // NSWorkspace.shared.openFile(url!.path)
  917. // } else {
  918. //
  919. // }
  920. }
  921. }
  922. }
  923. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  924. }
  925. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  926. }
  927. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  928. }
  929. @objc func OpenItemAction(sender: NSMenuItem) {
  930. }
  931. @objc func cropAllPageItem(sender: NSMenuItem) {
  932. self.cropAll(nil)
  933. }
  934. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  935. self.crop(nil)
  936. }
  937. @objc func autoCropAllItem(sender: NSMenuItem) {
  938. self.autoCropAll(nil)
  939. }
  940. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  941. self.smartAutoCropAll(nil)
  942. }
  943. @objc func customCropModel(sender: NSMenuItem) {
  944. let pdfDoc: CPDFDocument = self.listView.document
  945. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  946. let alert = NSAlert()
  947. alert.alertStyle = .critical
  948. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  949. alert.runModal()
  950. return
  951. }
  952. let window = NSWindow.currentWindow()
  953. let currentPage = pdfDoc.index(for: self.listView.currentPage())
  954. let cropVC = KMPDFCropWindowController(document: pdfDoc, pwd: "", currentPage: Int(currentPage), cropSize: NSMakeRect(100, 100, 50, 80), selectPageString: "\(currentPage)")
  955. window.km_beginSheet(windowC: cropVC)
  956. cropVC.cropWindowCloseBlock = { [weak self] doc in
  957. window.km_quick_endSheet()
  958. let isSuccessful = doc.write(to: self?.listView.document?.documentURL)
  959. if isSuccessful {
  960. if let documen = CPDFDocument(url: self?.document?.documentURL) {
  961. if documen.isLocked {
  962. documen.unlock(withPassword: pdfDoc.password)
  963. }
  964. self?.setDocument = documen
  965. }
  966. }
  967. }
  968. }
  969. @objc func rotateRightAction(sender: NSMenuItem) {
  970. }
  971. @objc func rotateLeftAction(sender: NSMenuItem) {
  972. }
  973. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  974. self.listView.toolMode = .noteToolMode
  975. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  976. var model : KMToolbarViewType = .None
  977. switch sender.tag {
  978. case 0:
  979. identifier = KMDocumentAnnotationToolbarItemIdentifier
  980. model = .Annatiton
  981. case 1:
  982. identifier = KMToolbarMoveToolModeItemIdentifier
  983. model = .Move
  984. case 2:
  985. identifier = KMToolbarMagnifyToolModeItemIdentifier
  986. model = .Magnify
  987. case 3:
  988. identifier = KMToolbarSelectToolModeItemIdentifier
  989. model = .Select
  990. case 4:
  991. identifier = KMToolbarZoomToSelectionItemIdentifier
  992. model = .SelectZoom
  993. default:
  994. break
  995. }
  996. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  997. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  998. }
  999. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  1000. var itemId: String?
  1001. if sender.tag == CAnnotationType.highlight.rawValue {
  1002. itemId = KMToolbarHighlightAnnotationItemIdentifier
  1003. } else if sender.tag == CAnnotationType.underline.rawValue {
  1004. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  1005. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1006. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  1007. } else if sender.tag == CAnnotationType.squiggly.rawValue {
  1008. itemId = KMToolbarSquigglyAnnotationItemIdentifier
  1009. } else if sender.tag == CAnnotationType.ink.rawValue {
  1010. itemId = KMToolbarInkAnnotationItemIdentifier
  1011. } else if sender.tag == CAnnotationType.freeText.rawValue {
  1012. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  1013. } else if sender.tag == CAnnotationType.anchored.rawValue {
  1014. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  1015. } else if sender.tag == CAnnotationType.square.rawValue {
  1016. itemId = KMToolbarSquareAnnotationItemIdentifier
  1017. } else if sender.tag == CAnnotationType.circle.rawValue {
  1018. itemId = KMToolbarCircleAnnotationItemIdentifier
  1019. } else if sender.tag == CAnnotationType.arrow.rawValue {
  1020. itemId = KMToolbarArrowAnnotationItemIdentifier
  1021. } else if sender.tag == CAnnotationType.line.rawValue {
  1022. itemId = KMToolbarLineAnnotationItemIdentifier
  1023. } else if sender.tag == CAnnotationType.link.rawValue {
  1024. itemId = KMToolbarLinkAnnotationItemIdentifier
  1025. }
  1026. if let data = itemId {
  1027. self.toolbarController.clickItem(data)
  1028. }
  1029. }
  1030. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  1031. var annotationType : CAnnotationType = .unkown
  1032. switch sender.tag {
  1033. case 0:
  1034. annotationType = .highlight
  1035. case 1:
  1036. annotationType = .underline
  1037. case 2:
  1038. if sender.title == NSLocalizedString("Squiggly", comment: "") {
  1039. annotationType = .squiggly
  1040. } else {
  1041. annotationType = .strikeOut
  1042. }
  1043. case 3:
  1044. annotationType = .freeText
  1045. case 4:
  1046. annotationType = .anchored
  1047. case 5:
  1048. annotationType = .square
  1049. case 6:
  1050. annotationType = .circle
  1051. case 7:
  1052. annotationType = .line
  1053. case 8:
  1054. annotationType = .link
  1055. case 9:
  1056. // var newOutline : CPDFOutline = CPDFOutline()
  1057. // newOutline.label = "11111111"
  1058. // let des = self.listView.currentDestination
  1059. // if "\(des?.point.x ?? 0)" != "nan" {
  1060. // newOutline.destination = self.listView.currentDestination
  1061. // } else {
  1062. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  1063. // newOutline.destination = destination
  1064. // }
  1065. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  1066. // let parent = current.parent ?? CPDFOutline()
  1067. // let index = current.index + 1
  1068. // parent.insertChild(newOutline, at: index)
  1069. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  1070. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  1071. }
  1072. // self.leftSideViewController.outlineViewController.addItemAction()
  1073. return
  1074. case 10:
  1075. annotationType = .unkown
  1076. default:
  1077. break
  1078. }
  1079. if (annotationType != .link) {
  1080. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  1081. self.listView.currentSelection = nil;
  1082. return
  1083. }
  1084. // link
  1085. let selection = self.listView.currentSelection
  1086. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  1087. DispatchQueue.main.async {
  1088. Task { @MainActor in
  1089. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  1090. self.listView.currentSelection = nil;
  1091. if (annotation != nil) {
  1092. self.listView.updateActiveAnnotations([annotation!])
  1093. }
  1094. }
  1095. }
  1096. }
  1097. @objc func aiTranslationAction(sender: NSMenuItem) {
  1098. let content = self.listView.currentSelection.string() ?? ""
  1099. let origin = self.listView.currentSelection.bounds.origin
  1100. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  1101. self.aiTranslationWindow?.content = content
  1102. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  1103. self.aiTranslationWindow!.window?.center()
  1104. }
  1105. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  1106. Task { @MainActor in
  1107. let idx = sender.tag
  1108. if idx == 10 {
  1109. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1110. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1111. return
  1112. }
  1113. }
  1114. var point = mouseRightMenuEvent?.locationInWindow
  1115. if (point == nil) {
  1116. point = NSZeroPoint
  1117. }
  1118. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  1119. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  1120. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  1121. var annotation: CPDFAnnotation?
  1122. if self.isReadMode {
  1123. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1124. self.listView.toolMode = .noteToolMode
  1125. }
  1126. switch sender.tag {
  1127. case 0:
  1128. self.listView.annotationType = CAnnotationType.ink
  1129. case 1:
  1130. // self.listView.annotationType = CAnnotationType.freeText
  1131. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1132. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1133. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1134. if ((annotation) != nil) {
  1135. self.listView.updateActiveAnnotations([annotation!])
  1136. self.listView.edit(annotation)
  1137. }
  1138. case 2:
  1139. // self.listView.annotationType = CAnnotationType.anchored
  1140. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1141. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1142. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1143. self.listView.edit(annotation)
  1144. case 3:
  1145. // self.listView.annotationType = CAnnotationType.square
  1146. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1147. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1148. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1149. case 4:
  1150. // self.listView.annotationType = CAnnotationType.circle
  1151. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1152. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1153. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1154. case 5:
  1155. // self.listView.annotationType = CAnnotationType.arrow
  1156. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1157. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1158. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1159. case 6:
  1160. // self.listView.annotationType = CAnnotationType.line
  1161. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1162. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1163. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1164. case 7:
  1165. self.listView.annotationType = CAnnotationType.link
  1166. self.openRightPane()
  1167. case 8:
  1168. self.listView.annotationType = CAnnotationType.stamp
  1169. self.openRightPane()
  1170. case 9:
  1171. self.listView.annotationType = CAnnotationType.signSignature
  1172. self.openRightPane()
  1173. default:
  1174. break
  1175. }
  1176. self.rightSideViewController.isHidden = true
  1177. self.rightSideViewController.subViewType = .AnnotationProperts
  1178. } else {
  1179. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1180. if(self.toolbarController.toolbarType == .None) {
  1181. self.toolbarController.toolbarType = .Annatiton
  1182. }
  1183. self.listView.toolMode = .noteToolMode
  1184. }
  1185. switch sender.tag {
  1186. case 0:
  1187. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  1188. self.model.rightMouseEventing = true
  1189. if(self.toolbarController.toolbarType == .None) {
  1190. self.toolbarController.toolbarType = .Annatiton
  1191. }
  1192. self.listView.toolMode = .noteToolMode
  1193. self.listView.annotationType = CAnnotationType.ink
  1194. case 1:
  1195. // self.listView.annotationType = CAnnotationType.freeText
  1196. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1197. if (pagePoint.x - defaultSize.width > 0){
  1198. pagePoint.x -= defaultSize.width;
  1199. }else{
  1200. pagePoint.x = 0;
  1201. }
  1202. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1203. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1204. // self.view.window?.makeFirstResponder()
  1205. if ((annotation) != nil) {
  1206. // self.listView.updateActiveAnnotations([annotation!])
  1207. self.listView.edit(annotation)
  1208. }
  1209. case 2:
  1210. // self.listView.annotationType = CAnnotationType.anchored
  1211. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1212. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1213. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1214. self.listView.edit(annotation)
  1215. case 3:
  1216. // self.listView.annotationType = CAnnotationType.square
  1217. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1218. if (pagePoint.x - defaultSize.width > 0){
  1219. pagePoint.x -= defaultSize.width;
  1220. }else{
  1221. pagePoint.x = 0;
  1222. }
  1223. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1224. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1225. case 4:
  1226. // self.listView.annotationType = CAnnotationType.circle
  1227. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1228. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1229. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1230. case 5:
  1231. // self.listView.annotationType = CAnnotationType.arrow
  1232. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1233. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1234. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1235. case 6:
  1236. // self.listView.annotationType = CAnnotationType.line
  1237. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1238. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1239. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1240. case 7:
  1241. self.listView.annotationType = CAnnotationType.link
  1242. self.openRightPane()
  1243. case 8:
  1244. self.listView.annotationType = CAnnotationType.stamp
  1245. self.openRightPane()
  1246. case 9:
  1247. self.listView.annotationType = CAnnotationType.signSignature
  1248. self.openRightPane()
  1249. case 10:
  1250. self.addImgAnnotationToView(center: pagePoint)
  1251. default:
  1252. break
  1253. }
  1254. self.rightSideViewController.isHidden = false
  1255. self.rightSideViewController.subViewType = .AnnotationProperts
  1256. if annotation != nil{
  1257. self.listView.activeAnnotations.removeAllObjects()
  1258. // self.listView.activeAnnotations.add(annotation as Any)
  1259. var newAnnonations : [CPDFAnnotation] = []
  1260. newAnnonations.append(annotation!)
  1261. self.listView.updateActiveAnnotations(newAnnonations)
  1262. // self.openRightPane()
  1263. }
  1264. // self.rightSideViewController.view.isHidden = false
  1265. }
  1266. // if (annotation != nil) {
  1267. // self.listView.updateIsRightActiveAnnotations([annotation!])
  1268. // }
  1269. }
  1270. }
  1271. func addImgAnnotationToView(center: NSPoint) {
  1272. let accessoryCtr = KMImageAccessoryController()
  1273. let openPanel = NSOpenPanel()
  1274. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1275. openPanel.allowsMultipleSelection = false
  1276. openPanel.accessoryView = accessoryCtr.view
  1277. openPanel.isAccessoryViewDisclosed = true
  1278. openPanel.beginSheetModal(for: self.view.window!) { result in
  1279. if result == .OK {
  1280. let fileURL = openPanel.urls.first
  1281. let filePath = fileURL!.path
  1282. if filePath.pathExtension == "pdf" {
  1283. let pdf = CPDFDocument(url: fileURL)
  1284. if pdf!.isEncrypted {
  1285. NSSound.beep()
  1286. return
  1287. }
  1288. }
  1289. let img = NSImage(contentsOfFile: filePath)
  1290. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1291. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  1292. }
  1293. }
  1294. }
  1295. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  1296. if self.listView?.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  1297. let index = self.listView.currentPageIndex
  1298. self.listView?.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  1299. self.listView?.setNeedsDisplayForVisiblePages()
  1300. } else {
  1301. self.listView?.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1302. self.listView?.setNeedsDisplayForVisiblePages()
  1303. }
  1304. self.setDocumentEditedState(window: self.view.window)
  1305. if self.isReadMode {
  1306. } else {
  1307. self.leftSideViewController.showBookmarkTab()
  1308. }
  1309. }
  1310. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1311. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1312. }
  1313. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1314. let rect = listView.currentSelectionRect()
  1315. let page = listView.currentPage()
  1316. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1317. copyPage.setBounds(rect, for: .cropBox)
  1318. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1319. // let pdfDocument : PDFDocument = PDFDocument()
  1320. // let newpage : PDFPage = PDFPage(image: image)!
  1321. // pdfDocument.insert(newpage, at: 0)
  1322. // 执行右键操作后,需要取消框选区域
  1323. if self.listView.toolMode == .selectToolMode {
  1324. objc_sync_enter(self)
  1325. self.listView.selectionRect = NSZeroRect
  1326. self.listView.selectionPageIndex = UInt(NSNotFound)
  1327. objc_sync_exit(self)
  1328. }
  1329. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1330. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1331. if (result == .cancel) {
  1332. return
  1333. }
  1334. // 解除权限
  1335. self?.model.isSaveKeyChain = false
  1336. self?.listView.document.unlock(withPassword: password)
  1337. // 隐藏提示
  1338. self?.hiddenSecureLimitTip()
  1339. // 去打印
  1340. KMPrintWindowController.printImage(image: image)
  1341. }
  1342. return
  1343. }
  1344. KMPrintWindowController.printImage(image: image)
  1345. }
  1346. // MARK: - Measure
  1347. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1348. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1349. return
  1350. }
  1351. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1352. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1353. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1354. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1355. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1356. areaMeasureInfoWindowController?.hideFloatingWindow()
  1357. }
  1358. self.listView.updateActiveAnnotations([anno])
  1359. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1360. self.listView.setNeedsDisplayForVisiblePages()
  1361. }
  1362. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  1363. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1364. return
  1365. }
  1366. self.listView.edit(anno)
  1367. }
  1368. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1369. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1370. return
  1371. }
  1372. self.listView.updateActiveAnnotations([anno])
  1373. self.listView.setNeedsDisplayForVisiblePages()
  1374. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  1375. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  1376. } else if let data = anno as? CPDFPolylineAnnotation {
  1377. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  1378. } else if let data = anno as? CPDFPolygonAnnotation {
  1379. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  1380. }
  1381. }
  1382. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1383. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1384. return
  1385. }
  1386. self.listView.remove(anno)
  1387. }
  1388. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  1389. guard let mInfo = measureInfo else {
  1390. return
  1391. }
  1392. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  1393. if hideInfoWindow {
  1394. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  1395. }
  1396. winC.delegate = self
  1397. winC.startModal("")
  1398. }
  1399. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  1400. guard let mInfo = measureInfo else {
  1401. return
  1402. }
  1403. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  1404. if hideInfoWindow {
  1405. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1406. }
  1407. winC.delegate = self
  1408. winC.startModal("")
  1409. }
  1410. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  1411. guard let mInfo = measureInfo else {
  1412. return
  1413. }
  1414. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  1415. if hideInfoWindow {
  1416. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  1417. }
  1418. winC.delegate = self
  1419. winC.startModal("")
  1420. }
  1421. func splitView(withTag tag: Int) {
  1422. if tag == 0 {
  1423. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1424. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1425. } else if tag == 1 {
  1426. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1427. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1428. } else if tag == 2 {
  1429. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1430. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1431. }
  1432. self.listView.needsDisplay = true
  1433. }
  1434. // MARK: - 幻灯片
  1435. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1436. let view: NSView = self.view.window!.firstResponder as! NSView
  1437. if view.isDescendant(of: pdfSplitView){
  1438. self.view.window?.makeFirstResponder(nil)
  1439. }
  1440. self.mainWindow = self.view.window
  1441. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1442. fullScreenWindow.interactionParent = self.view.window
  1443. self.mainWindow?.delegate = nil
  1444. fullScreenWindow.fadeInBlocking()
  1445. self.browserWindowController?.window = fullScreenWindow
  1446. fullScreenWindow.makeKey()
  1447. // NSApp.updatePresentationOptions(for: fullScreenWindow)
  1448. let sel = NSSelectorFromString("setAnimationBehavior:")
  1449. if self.mainWindow?.responds(to: sel) ?? false{
  1450. self.mainWindow?.animationBehavior = .none
  1451. }
  1452. self.mainWindow?.orderOut(nil)
  1453. if self.mainWindow?.responds(to: sel) ?? false{
  1454. self.mainWindow?.animationBehavior = .default
  1455. }
  1456. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1457. fullScreenWindow.orderFront(nil)
  1458. // NSApp.addWindowsItem(fullScreenWindow, title: windowTitleForDocumentDisplayName(self.document?.displayName) ?? "", filename: false)
  1459. }
  1460. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1461. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1462. return
  1463. }
  1464. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1465. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1466. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1467. fullScreenWindow.contentView?.addSubview(view)
  1468. self.listView.layoutDocumentView()
  1469. self.listView.requiresDisplay()
  1470. fullScreenWindow.makeFirstResponder(self.listView)
  1471. fullScreenWindow.recalculateKeyViewLoop()
  1472. fullScreenWindow.delegate = self.browserWindowController
  1473. // if (RUNNING_BEFORE(10_7))
  1474. // [fullScreenWindow display];
  1475. fullScreenWindow.display()
  1476. fadeWindow.fadeOut()
  1477. }
  1478. // MARK: Redact 【密文标记】
  1479. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1480. self.listView.remove(self.listView.activeAnnotation)
  1481. }
  1482. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1483. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1484. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1485. self.view.window?.beginSheet(windowController.window!)
  1486. self.currentWindowController = windowController
  1487. windowController.itemClick = { [weak self] index, value in
  1488. if (index == 1) { /// 取消
  1489. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1490. self?.currentWindowController = nil
  1491. return
  1492. }
  1493. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1494. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1495. annotaton.setBorderColor(windowController_redact.outsideColor)
  1496. annotaton.setInteriorColor(windowController_redact.fillColor)
  1497. if (windowController_redact.isOver) {
  1498. annotaton.setFontColor(windowController_redact.fontColor)
  1499. annotaton.setAlignment(windowController_redact.aligement)
  1500. annotaton.setFont(windowController_redact.font)
  1501. annotaton.setOverlayText(windowController_redact.overText)
  1502. }
  1503. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1504. self?.currentWindowController = nil
  1505. }
  1506. }
  1507. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1508. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1509. return
  1510. }
  1511. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1512. let model = CPDFAnnotationModel(annotationType: .redact)
  1513. model?.setColor(annotation.borderColor())
  1514. model?.setInteriorColor(annotation.interiorColor())
  1515. let overlayText: String = annotation.overlayText()
  1516. if (overlayText.isEmpty) {
  1517. model?.setIsOverlayText(false)
  1518. } else {
  1519. model?.setIsOverlayText(true)
  1520. model?.setOverlayText(overlayText)
  1521. model?.setFontColor(annotation.fontColor())
  1522. model?.setAlignment(annotation.alignment())
  1523. model?.setFontName(annotation.font().fontName)
  1524. model?.setFontSize(annotation.font().pointSize)
  1525. }
  1526. }
  1527. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1528. let anno = self.listView.activeAnnotation
  1529. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1530. return
  1531. }
  1532. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1533. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1534. self.currentWindowController = windowController
  1535. self.view.window?.beginSheet(windowController.window!)
  1536. windowController.itemClick = { [weak self] index, value in
  1537. if (index == 1) {
  1538. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1539. self!.currentWindowController = nil
  1540. return
  1541. }
  1542. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1543. let pageType = windowController_mutilPageFlag.pageType
  1544. let pageString = windowController_mutilPageFlag.pageString
  1545. if (pageType == 4) { /// 自定义页面
  1546. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1547. if (array.count == 0) {
  1548. let alert = NSAlert()
  1549. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1550. alert.runModal()
  1551. return
  1552. }
  1553. }
  1554. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1555. self!.currentWindowController = nil
  1556. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1557. if (indexs.count == 0) {
  1558. return
  1559. }
  1560. for i in indexs {
  1561. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1562. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1563. self?.listView.add(redactAnno, to: page)
  1564. }
  1565. }
  1566. }
  1567. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1568. self.exeRedactConfirm(.redactOne) {}
  1569. }
  1570. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1571. self.exeRedactConfirm(.eraserOne) {}
  1572. }
  1573. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1574. }
  1575. @objc func exportStampImage(sender:NSMenuItem) {
  1576. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1577. var image : NSImage = NSImage()
  1578. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1579. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1580. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1581. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1582. } else {
  1583. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1584. }
  1585. let data = image.tiffRepresentation
  1586. if sender.tag == 0 {
  1587. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1588. imageRep.size = image.size
  1589. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1590. let savePanel = NSSavePanel()
  1591. savePanel.allowedFileTypes = ["png"]
  1592. savePanel.beginSheetModal(for: self.view.window!) { response in
  1593. if (response != .OK) {
  1594. return
  1595. }
  1596. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1597. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1598. }
  1599. }
  1600. } else {
  1601. let pdfdocument = CPDFDocument()
  1602. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1603. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1604. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1605. let savePanel = NSSavePanel()
  1606. savePanel.allowedFileTypes = ["pdf"]
  1607. savePanel.beginSheetModal(for: self.view.window!) { response in
  1608. if (response != .OK) {
  1609. return
  1610. }
  1611. if pdfdocument!.write(to: savePanel.url!) {
  1612. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1613. }
  1614. }
  1615. }
  1616. }
  1617. }
  1618. }
  1619. @objc func exportCorpImage(sender:NSMenuItem) {
  1620. let rect = NSIntegralRect(listView.currentSelectionRect())
  1621. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1622. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1623. page.setBounds(rect, for: .cropBox)
  1624. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1625. let data = image.tiffRepresentation
  1626. guard let data = data else { return }
  1627. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1628. imageRep.size = rect.size
  1629. let savePanel = NSSavePanel()
  1630. switch sender.tag {
  1631. case 0:
  1632. savePanel.allowedFileTypes = ["png"]
  1633. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1634. savePanel.beginSheetModal(for: self.view.window!) { response in
  1635. if (response != .OK) {
  1636. return
  1637. }
  1638. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1639. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1640. }
  1641. }
  1642. case 1:
  1643. savePanel.allowedFileTypes = ["jpg"]
  1644. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1645. savePanel.beginSheetModal(for: self.view.window!) { response in
  1646. if (response != .OK) {
  1647. return
  1648. }
  1649. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1650. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1651. }
  1652. }
  1653. case 2:
  1654. savePanel.allowedFileTypes = ["pdf"]
  1655. let pdfdocument = CPDFDocument()
  1656. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1657. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1658. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1659. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1660. savePanel.beginSheetModal(for: self.view.window!) { response in
  1661. if (response != .OK) {
  1662. return
  1663. }
  1664. if pdfdocument!.write(to: savePanel.url!) {
  1665. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1666. }
  1667. }
  1668. }
  1669. default:
  1670. break
  1671. }
  1672. // 执行右键操作后,需要取消框选区域
  1673. if self.listView.toolMode == .selectToolMode {
  1674. objc_sync_enter(self)
  1675. self.listView.selectionRect = NSZeroRect
  1676. self.listView.selectionPageIndex = UInt(NSNotFound)
  1677. objc_sync_exit(self)
  1678. }
  1679. }
  1680. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1681. let rect = listView.currentSelectionRect()
  1682. let page = listView.currentPage()
  1683. if NSIsEmptyRect(rect) == false && page != nil {
  1684. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1685. var bounds = listView.bounds
  1686. var scale = 1.0
  1687. if isLegacy {
  1688. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1689. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1690. }
  1691. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1692. scale = NSHeight(bounds) / NSHeight(rect)
  1693. } else {
  1694. scale = NSWidth(bounds) / NSWidth(rect)
  1695. }
  1696. listView.setScaleFactor(scale, animated: false)
  1697. let scrollView = listView.scroll()
  1698. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1699. if ((scrollView?.hasVerticalScroller) != nil) {
  1700. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1701. }
  1702. if ((scrollView?.hasHorizontalScroller) != nil) {
  1703. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1704. }
  1705. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1706. scale = NSHeight(bounds) / NSHeight(rect)
  1707. } else {
  1708. scale = NSWidth(bounds) / NSWidth(rect)
  1709. }
  1710. listView.setScaleFactor(scale, animated: false)
  1711. }
  1712. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1713. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1714. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1715. };
  1716. }
  1717. // 执行右键操作后,需要取消框选区域
  1718. if self.listView.toolMode == .selectToolMode {
  1719. objc_sync_enter(self)
  1720. self.listView.selectionRect = NSZeroRect
  1721. self.listView.selectionPageIndex = UInt(NSNotFound)
  1722. objc_sync_exit(self)
  1723. }
  1724. }
  1725. private func cropPagesToRects(rects:NSPointerArray) {
  1726. }
  1727. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1728. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1729. switch sender.tag {
  1730. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1731. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1732. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1733. var red: CGFloat = 0.0
  1734. var green: CGFloat = 0.0
  1735. var blue: CGFloat = 0.0
  1736. var alpha: CGFloat = 0.0
  1737. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1738. if sender.tag == CAnnotationType.highlight.rawValue {
  1739. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1740. } else if sender.tag == CAnnotationType.underline.rawValue {
  1741. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1742. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1743. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1744. }
  1745. case CAnnotationType.ink.rawValue:
  1746. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1747. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1748. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1749. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1750. var red: CGFloat = 0.0
  1751. var green: CGFloat = 0.0
  1752. var blue: CGFloat = 0.0
  1753. var alpha: CGFloat = 0.0
  1754. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1755. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1756. case CAnnotationType.freeText.rawValue:
  1757. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1758. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1759. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1760. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1761. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1762. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1763. var red: CGFloat = 0.0
  1764. var green: CGFloat = 0.0
  1765. var blue: CGFloat = 0.0
  1766. var alpha: CGFloat = 0.0
  1767. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1768. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1769. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1770. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1771. UserDefaults.standard.synchronize()
  1772. }
  1773. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1774. if (alignment == .left || alignment == .center || alignment == .right) {
  1775. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1776. UserDefaults.standard.synchronize()
  1777. }
  1778. case CAnnotationType.anchored.rawValue:
  1779. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1780. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1781. var red: CGFloat = 0.0
  1782. var green: CGFloat = 0.0
  1783. var blue: CGFloat = 0.0
  1784. var alpha: CGFloat = 0.0
  1785. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1786. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1787. case CAnnotationType.square.rawValue:
  1788. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1789. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1790. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1791. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1792. var red: CGFloat = 0.0
  1793. var green: CGFloat = 0.0
  1794. var blue: CGFloat = 0.0
  1795. var alpha: CGFloat = 0.0
  1796. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1797. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1798. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1799. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1800. case CAnnotationType.circle.rawValue:
  1801. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1802. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1803. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1804. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1805. var red: CGFloat = 0.0
  1806. var green: CGFloat = 0.0
  1807. var blue: CGFloat = 0.0
  1808. var alpha: CGFloat = 0.0
  1809. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1810. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1811. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1812. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1813. default:
  1814. break
  1815. }
  1816. }
  1817. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1818. self.showOrHideNotes()
  1819. }
  1820. //MARK: - action
  1821. @objc func cropCurrentPage() {
  1822. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1823. var page: CPDFPage?
  1824. if let data = self.listView.currentSelectionPage() {
  1825. page = data
  1826. } else {
  1827. page = self.listView.currentPage()
  1828. }
  1829. if (NSIsEmptyRect(rect)) {
  1830. rect = KMCropTools.getPageForegroundBox(page!)
  1831. }
  1832. let index: UInt = (page?.pageIndex()) ?? 0
  1833. self._cropPage(at: index, in: rect)
  1834. // 执行右键操作后,需要取消框选区域
  1835. if self.listView.toolMode == .selectToolMode {
  1836. objc_sync_enter(self)
  1837. self.listView.selectionRect = NSZeroRect
  1838. self.listView.selectionPageIndex = UInt(NSNotFound)
  1839. objc_sync_exit(self)
  1840. }
  1841. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1842. }
  1843. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1844. let oldRect = self.listView?.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1845. let undoManager = self.listView.undoManager
  1846. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1847. let page = self.listView.document.page(at: index)
  1848. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1849. page?.setBounds(newRect, for: .cropBox)
  1850. /// 刷新预览视图
  1851. self.listView.layoutDocumentView()
  1852. self.listView.displayBox = .cropBox
  1853. }
  1854. func beginProgressSheet(with message: String, maxValue: UInt) {
  1855. let progress = SKProgressController()
  1856. // progress.window?.backgroundColor = NSColor.km_init(hex: "#ffffff")
  1857. progress.window?.contentView?.wantsLayer = true
  1858. // progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#ffffff").cgColor
  1859. // progress.progressField.textColor = NSColor.black
  1860. progress.message = NSLocalizedString("Converting...", comment: "")
  1861. self.progressC = progress
  1862. self.progressC?.message = message
  1863. if maxValue > 0 {
  1864. progressC?.indeterminate = false
  1865. progressC?.maxValue = Double(maxValue)
  1866. } else {
  1867. progressC?.indeterminate = true
  1868. }
  1869. self.view.km_beginSheet(windowC: progressC!)
  1870. }
  1871. // 白边距
  1872. @objc func smart_cropAllPage() {
  1873. var size = NSZeroSize
  1874. for i in 0 ..< self.listView.document.pageCount {
  1875. let page = self.listView.document.page(at: i)
  1876. let rect = KMCropTools.getPageForegroundBox(page!)
  1877. size.width = fmax(size.width, NSWidth(rect))
  1878. size.height = fmax(size.height, NSHeight(rect))
  1879. }
  1880. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1881. var rectArray: Array<NSRect> = []
  1882. for i in 0 ..< self.listView.document.pageCount {
  1883. progressC?.increment(by: Double(i))
  1884. progressC?.doubleValue = Double(i)
  1885. let page = self.listView.document.page(at: i)
  1886. var rect = KMCropTools.getPageForegroundBox(page!)
  1887. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1888. // if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1889. // rect.origin.x = rect.maxX-size.width
  1890. // }
  1891. // rect.origin.y = rect.maxY-size.height
  1892. // rect.size = size
  1893. // if (NSWidth(rect) > NSWidth(bounds)) {
  1894. // rect.size.width = NSWidth(bounds)
  1895. // }
  1896. // if (NSHeight(rect) > NSHeight(bounds)) {
  1897. // rect.size.height = NSHeight(bounds)
  1898. // }
  1899. //
  1900. // if (NSMinX(rect) < NSMinX(bounds)) {
  1901. // rect.origin.x = NSMinX(bounds)
  1902. // } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1903. // rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1904. // }
  1905. //
  1906. // if (NSMinY(rect) < NSMinY(bounds)) {
  1907. // rect.origin.y = NSMinY(bounds)
  1908. // } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1909. // rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1910. // }
  1911. rectArray.append(rect)
  1912. }
  1913. cropPages(to: rectArray)
  1914. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1915. }
  1916. // 自动
  1917. @objc func auto_cropAllPage() {
  1918. var size = NSZeroSize
  1919. for i in 0 ..< self.listView.document.pageCount {
  1920. let page = self.listView.document.page(at: i)
  1921. let rect = KMCropTools.getPageForegroundBox(page!)
  1922. size.width = fmax(size.width, NSWidth(rect))
  1923. size.height = fmax(size.height, NSHeight(rect))
  1924. }
  1925. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1926. var rectArray: Array<NSRect> = []
  1927. for i in 0 ..< self.listView.document.pageCount {
  1928. progressC?.increment(by: Double(i))
  1929. progressC?.doubleValue = Double(i)
  1930. let page = self.listView.document.page(at: i)
  1931. var rect = KMCropTools.getPageForegroundBox(page!)
  1932. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1933. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1934. rect.origin.x = rect.maxX-size.width
  1935. }
  1936. rect.origin.y = rect.maxY-size.height
  1937. rect.size = size
  1938. if (NSWidth(rect) > NSWidth(bounds)) {
  1939. rect.size.width = NSWidth(bounds)
  1940. }
  1941. if (NSHeight(rect) > NSHeight(bounds)) {
  1942. rect.size.height = NSHeight(bounds)
  1943. }
  1944. if (NSMinX(rect) < NSMinX(bounds)) {
  1945. rect.origin.x = NSMinX(bounds)
  1946. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1947. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1948. }
  1949. if (NSMinY(rect) < NSMinY(bounds)) {
  1950. rect.origin.y = NSMinY(bounds)
  1951. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1952. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1953. }
  1954. rectArray.append(rect)
  1955. }
  1956. cropPages(to: rectArray)
  1957. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1958. }
  1959. @objc func cropAllPage() {
  1960. var rect = [NSIntegralRect(self.listView?.currentSelectionRect() ?? .zero), .zero]
  1961. var rectArray: Array<NSRect> = []
  1962. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1963. if (emptySelection) {
  1964. guard let count = self.listView?.document?.pageCount, count > 0 else {
  1965. KMPrint("listView | document is nil.", beep: true)
  1966. return
  1967. }
  1968. rect[0] = .zero
  1969. rect[1] = .zero
  1970. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1971. if (count == 1) {
  1972. if let page = self.listView.document.page(at: 0) {
  1973. rect[0] = KMCropTools.getPageForegroundBox(page)
  1974. }
  1975. progressC?.increment(by: 1)
  1976. } else if (count < 19) {
  1977. for i in 0 ..< 19 {
  1978. if let page = self.listView.document.page(at: UInt(i)) {
  1979. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1980. progressC?.increment(by: Double(i))
  1981. }
  1982. }
  1983. } else {
  1984. let start = [1, (count - 5) / 2, count - 6]
  1985. var cnt = 0
  1986. for j in 0 ..< 3 {
  1987. for i in 0 ..< 6 {
  1988. let k = Int(start[j] + UInt(i))
  1989. if let page = self.listView.document.page(at: UInt(k)) {
  1990. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1991. cnt += 1
  1992. progressC?.increment(by: Double(cnt))
  1993. }
  1994. }
  1995. }
  1996. }
  1997. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1998. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1999. for j in 0 ..< 2 {
  2000. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  2001. }
  2002. rectArray.append(rect.first ?? .zero)
  2003. rectArray.append(rect.last ?? .zero)
  2004. } else {
  2005. rectArray.append(rect.first ?? .zero)
  2006. }
  2007. self.cropPages(to: rectArray)
  2008. // 执行右键操作后,需要取消框选区域
  2009. if self.listView.toolMode == .selectToolMode {
  2010. objc_sync_enter(self)
  2011. self.listView.selectionRect = NSZeroRect
  2012. self.listView.selectionPageIndex = UInt(NSNotFound)
  2013. objc_sync_exit(self)
  2014. }
  2015. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  2016. }
  2017. func cropPages(to rects: Array<NSRect>) {
  2018. let currentPage = self.listView.currentPage()
  2019. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  2020. var oldRectArray: Array<NSRect> = []
  2021. let rectCount = rects.count
  2022. for i in 0 ..< self.listView.document.pageCount {
  2023. let page = self.listView.document.page(at: i)
  2024. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  2025. let oldRect = page?.bounds(for: .cropBox)
  2026. oldRectArray.append(oldRect!)
  2027. page?.setBounds(rect, for: .cropBox)
  2028. }
  2029. let undoManager = self.listView.undoManager
  2030. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  2031. /// 刷新预览视图
  2032. self.listView.layoutDocumentView()
  2033. self.listView.displayBox = .cropBox
  2034. self.listView.go(to: currentPage)
  2035. self.listView.go(to: visibleRect, on: currentPage)
  2036. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2037. self.dismissProgressSheet()
  2038. }
  2039. }
  2040. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  2041. if (limit) {
  2042. let document = self.listView.document ?? CPDFDocument()
  2043. if document?.documentURL == nil {
  2044. return
  2045. }
  2046. var doucumentURL : URL = self.listView.document.documentURL
  2047. if doucumentURL.path.count > 0 {
  2048. let docDir = NSTemporaryDirectory()
  2049. let documentName : String = doucumentURL.path.lastPathComponent
  2050. let path = docDir.stringByAppendingPathComponent(documentName)
  2051. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2052. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2053. let writeSuccess = data != nil
  2054. if writeSuccess == false {
  2055. __NSBeep()
  2056. return;
  2057. }
  2058. doucumentURL = URL(fileURLWithPath: path)
  2059. }
  2060. let array = [doucumentURL]
  2061. let picker = NSSharingServicePicker.init(items: array)
  2062. if sender.shareButton.window != nil {
  2063. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2064. } else {
  2065. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2066. }
  2067. return
  2068. }
  2069. let document = self.listView.document ?? CPDFDocument()
  2070. if document?.documentURL == nil {
  2071. return
  2072. }
  2073. var doucumentURL : URL = self.listView.document.documentURL
  2074. if doucumentURL.path.count > 0 {
  2075. let docDir = NSTemporaryDirectory()
  2076. let documentName : String = doucumentURL.path.lastPathComponent
  2077. let path = docDir.stringByAppendingPathComponent(documentName)
  2078. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2079. if writeSuccess == false {
  2080. __NSBeep()
  2081. return;
  2082. }
  2083. doucumentURL = URL(fileURLWithPath: path)
  2084. }
  2085. let array = [doucumentURL]
  2086. let picker = NSSharingServicePicker.init(items: array)
  2087. if sender.shareButton.window != nil {
  2088. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2089. } else {
  2090. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2091. }
  2092. }
  2093. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  2094. if (limit) {
  2095. let document = self.listView.document ?? CPDFDocument()
  2096. var path: String?
  2097. if document?.documentURL != nil {
  2098. path = document?.documentURL.path ?? ""
  2099. }
  2100. if path?.count ?? 0 > 0 {
  2101. let docDir = NSTemporaryDirectory()
  2102. let documentName : String = path?.lastPathComponent ?? ""
  2103. path = docDir.stringByAppendingPathComponent(documentName)
  2104. }
  2105. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2106. var tfileName = path?.deletingPathExtension.lastPathComponent
  2107. let tStdFileSuffix = "_flatten"
  2108. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2109. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2110. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  2111. let success = data != nil
  2112. if success {
  2113. let url = URL(fileURLWithPath: path ?? "")
  2114. let picker = NSSharingServicePicker.init(items: [url])
  2115. if sender.shareButton.window != nil {
  2116. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2117. } else {
  2118. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2119. }
  2120. }
  2121. return
  2122. }
  2123. let document = self.listView.document ?? CPDFDocument()
  2124. var path: String?
  2125. if document?.documentURL != nil {
  2126. path = document?.documentURL.path ?? ""
  2127. }
  2128. if path?.count ?? 0 > 0 {
  2129. let docDir = NSTemporaryDirectory()
  2130. let documentName : String = path?.lastPathComponent ?? ""
  2131. path = docDir.stringByAppendingPathComponent(documentName)
  2132. }
  2133. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2134. var tfileName = path?.deletingPathExtension.lastPathComponent
  2135. let tStdFileSuffix = "_flatten"
  2136. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2137. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2138. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2139. if success {
  2140. let url = URL(fileURLWithPath: path ?? "")
  2141. let picker = NSSharingServicePicker.init(items: [url])
  2142. if sender.shareButton.window != nil {
  2143. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2144. } else {
  2145. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2146. }
  2147. }
  2148. }
  2149. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  2150. guard let pdfDoc = self.listView.document else {
  2151. NSSound.beep()
  2152. return
  2153. }
  2154. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2155. let alert = NSAlert()
  2156. alert.alertStyle = .critical
  2157. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2158. alert.runModal()
  2159. return
  2160. }
  2161. if (limit) {
  2162. let document = self.listView.document ?? CPDFDocument()
  2163. var path: String?
  2164. if document?.documentURL != nil {
  2165. path = document?.documentURL.path ?? ""
  2166. }
  2167. if path?.count ?? 0 > 0{
  2168. let docDir = NSTemporaryDirectory()
  2169. let documentName : String = path?.lastPathComponent ?? ""
  2170. path = docDir.stringByAppendingPathComponent(documentName)
  2171. }
  2172. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2173. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2174. var writeSuccess = data != nil
  2175. if writeSuccess == false {
  2176. __NSBeep()
  2177. return;
  2178. }
  2179. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2180. let cnt = newDocument?.pageCount ?? 0
  2181. for i in 0 ..< cnt {
  2182. let page = newDocument?.page(at: i)
  2183. var annotations : [CPDFAnnotation] = []
  2184. for annotation in page!.annotations {
  2185. annotations.append(annotation)
  2186. }
  2187. for annotation in annotations {
  2188. annotation.page.removeAnnotation(annotation)
  2189. }
  2190. }
  2191. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  2192. if writeSuccess {
  2193. let url = URL(fileURLWithPath: path ?? "")
  2194. let picker = NSSharingServicePicker.init(items: [url])
  2195. if sender.shareButton.window != nil {
  2196. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2197. } else {
  2198. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2199. }
  2200. }
  2201. return
  2202. }
  2203. let document = self.listView.document ?? CPDFDocument()
  2204. var path: String?
  2205. if document?.documentURL != nil {
  2206. path = document?.documentURL.path ?? ""
  2207. }
  2208. if path?.count ?? 0 > 0 {
  2209. let docDir = NSTemporaryDirectory()
  2210. let documentName : String = path?.lastPathComponent ?? ""
  2211. path = docDir.stringByAppendingPathComponent(documentName)
  2212. }
  2213. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2214. if writeSuccess == false {
  2215. __NSBeep()
  2216. return;
  2217. }
  2218. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2219. let cnt = newDocument?.pageCount ?? 0
  2220. for i in 0 ..< cnt {
  2221. let page = newDocument!.page(at: i)
  2222. var annotations : [CPDFAnnotation] = []
  2223. for annotation in page!.annotations {
  2224. annotations.append(annotation)
  2225. }
  2226. for annotation in annotations {
  2227. annotation.page.removeAnnotation(annotation)
  2228. }
  2229. }
  2230. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2231. if writeSuccess ?? false {
  2232. let url = URL(fileURLWithPath: path ?? "")
  2233. let picker = NSSharingServicePicker.init(items: [url])
  2234. if sender.shareButton.window != nil {
  2235. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2236. } else {
  2237. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  2238. }
  2239. }
  2240. }
  2241. // 开启/关闭左边栏
  2242. @objc func toggleLeftPane() -> Void {
  2243. // if lastLeftPanWidth >= functionWidth {
  2244. self.model.leftPanelOpen = true
  2245. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2246. // } else {
  2247. // leftPanelOpen = false
  2248. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2249. // }
  2250. }
  2251. // 开启左边栏
  2252. @objc func openLeftPane() -> Void {
  2253. self.model.leftPanelOpen = true
  2254. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2255. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  2256. }
  2257. // 关闭左边栏
  2258. @objc func closeLeftPane() -> Void {
  2259. self.model.leftPanelOpen = false
  2260. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2261. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = false
  2262. }
  2263. // 开启/关闭右边栏
  2264. @objc func toggleRightPane() -> Void {
  2265. if self.model.lastRightPanWidth > 5 {
  2266. self.model.rightPanelIsOpen = false
  2267. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2268. } else {
  2269. self.model.rightPanelIsOpen = true
  2270. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2271. }
  2272. }
  2273. @objc func openRightPane() -> Void {
  2274. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2275. if self.model.rightPanelIsOpen {
  2276. return
  2277. }
  2278. self.model.rightPanelIsOpen = true
  2279. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  2280. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2281. }
  2282. }
  2283. @objc func closeRightPane() -> Void {
  2284. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2285. self.model.rightPanelIsOpen = false
  2286. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  2287. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2288. cancelMeasureType()
  2289. }
  2290. }
  2291. func rename(_ sender: NSNotification) -> Void {
  2292. if (self.view.window == nil || self.view.window!.isVisible == false) {
  2293. return
  2294. }
  2295. let tabController = sender.object as? CTTabController
  2296. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  2297. if let doc = self.myDocument, doc.isDocumentEdited {
  2298. Task {
  2299. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  2300. if resp != .alertFirstButtonReturn { // 取消
  2301. return
  2302. }
  2303. doc.updateChangeCount(.changeCleared)
  2304. // doc.save(nil)
  2305. self.document?.write(to: doc.fileURL)
  2306. Task { @MainActor in
  2307. self._renameForSavePanel(tabController)
  2308. }
  2309. }
  2310. return
  2311. }
  2312. self._renameForSavePanel(tabController)
  2313. }
  2314. }
  2315. func savePdfAlertView() {
  2316. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  2317. return
  2318. }
  2319. AutoSaveManager.manager.isSaveNoti = true
  2320. var num = 0
  2321. if self.listView.document != nil{
  2322. num = Int(self.listView.document.pageCount)
  2323. }
  2324. if Thread.current.isMainThread {
  2325. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2326. } else {
  2327. DispatchQueue.main.async {
  2328. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2329. }
  2330. }
  2331. }
  2332. func savePdfFinishAlertView() {
  2333. if !AutoSaveManager.manager.isSaveNoti{
  2334. return
  2335. }
  2336. AutoSaveManager.manager.isSaveNoti = false
  2337. if Thread.current.isMainThread {
  2338. self.dismissProgressSheet()
  2339. } else {
  2340. DispatchQueue.main.async {
  2341. self.dismissProgressSheet()
  2342. }
  2343. }
  2344. }
  2345. private func _renameForSavePanel(_ tabC: CTTabController?) {
  2346. let outputSavePanel = NSSavePanel()
  2347. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2348. outputSavePanel.allowedFileTypes = ["pdf"]
  2349. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2350. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2351. let resp = outputSavePanel.runModal()
  2352. if resp == .OK {
  2353. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2354. let fileURL = pdfDocument?.documentURL
  2355. let fileManager = FileManager.default
  2356. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2357. var result = true
  2358. do {
  2359. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2360. } catch {
  2361. result = false
  2362. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2363. }
  2364. if (result) {
  2365. tabC?.title = outputSavePanel.url!.lastPathComponent
  2366. // self.myDocument?.fileURL = newFileURL
  2367. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2368. self.model.isSaveKeyChain = false
  2369. newPdfDocument.unlock(withPassword: self.document?.password)
  2370. if (newPdfDocument.pageCount > 0) {
  2371. self.setDocument = newPdfDocument
  2372. }
  2373. }
  2374. }
  2375. } else {
  2376. outputSavePanel.close()
  2377. }
  2378. }
  2379. func showInFinder(_ sender: Any) -> Void {
  2380. if sender is NSNotification {
  2381. let tabController = (sender as! NSNotification).object as? CTTabController
  2382. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2383. if tabController?.title == path {
  2384. if let file = self.myDocument?.fileURL {
  2385. if FileManager.default.fileExists(atPath: file.path) {
  2386. NSWorkspace.shared.activateFileViewerSelecting([file])
  2387. }
  2388. }
  2389. }
  2390. } else {
  2391. guard let url = self.myDocument?.fileURL else { return }
  2392. let file: URL = url
  2393. if FileManager.default.fileExists(atPath: file.path) {
  2394. NSWorkspace.shared.activateFileViewerSelecting([file])
  2395. }
  2396. }
  2397. }
  2398. func showOrHideNotes() {
  2399. self.listView.hideNotes = !self.listView.hideNotes
  2400. for note in self.listView.notes as? [CPDFAnnotation] ?? [] {
  2401. if note.isForm() {
  2402. note.setAnnotationShouldDisplay(true)
  2403. note.setHidden(false)
  2404. }
  2405. }
  2406. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2407. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  2408. //BOTA 注释列表显示隐藏
  2409. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2410. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2411. self.leftSideViewController.note_reloadDataIfNeed()
  2412. }
  2413. func closeTab(_ sender: NSNotification) -> Void {
  2414. // let tabController = sender.object as? CTTabController
  2415. // let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2416. // if tabController?.title == path {
  2417. // print("closeTab")
  2418. // self.leftSideViewController.clearAnnotationFilterData()
  2419. // self.leftSideViewController.clearNotification()
  2420. // }
  2421. }
  2422. @IBAction func toggleSplitPDF(_ sender: Any) {
  2423. if let menuItem = sender as? NSMenuItem {
  2424. splitView(withTag: menuItem.tag)
  2425. }
  2426. }
  2427. @IBAction func readMode(_ sender: Any) {
  2428. isReadMode = !isReadMode
  2429. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  2430. UserDefaults.standard.synchronize()
  2431. if isReadMode {
  2432. CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2433. } else {
  2434. CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2435. }
  2436. }
  2437. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2438. // NSDictionary *info = [notification userInfo];
  2439. // PDFPage *page = [info objectForKey:SKPDFPagePageKey];
  2440. // NSString *action = [info objectForKey:SKPDFPageActionKey];
  2441. // BOOL displayChanged = [action isEqualToString:SKPDFPageActionCrop] == NO || [pdfView displayBox] == kPDFDisplayBoxCropBox;
  2442. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2443. // if self.listView.displayBox == .cropBox {
  2444. // KMPrint("cropBox")
  2445. // } else if self.listView.displayBox == .artBox {
  2446. // KMPrint("artBox")
  2447. // } else if self.listView.displayBox == .trimBox {
  2448. // KMPrint("trimBox")
  2449. // } else if self.listView.displayBox == .bleedBox {
  2450. // KMPrint("bleedBox")
  2451. // } else if self.listView.displayBox == .mediaBox {
  2452. // KMPrint("mediaBox")
  2453. // } else {
  2454. // KMPrint("other \(self.listView.displayBox.rawValue)")
  2455. // }
  2456. if (displayChanged) {
  2457. self.listView.layoutDocumentView()
  2458. }
  2459. if (page != nil) {
  2460. let idx = page!.pageIndex()
  2461. if (displayChanged) {
  2462. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2463. }
  2464. } else {
  2465. if (displayChanged) {
  2466. self.leftSideViewController.allThumbnailsNeedUpdate()
  2467. }
  2468. }
  2469. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2470. // [secondaryPdfView requiresDisplay];
  2471. self.secondaryPdfView?.setNeedsDisplayForVisiblePages()
  2472. //
  2473. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2474. // [self updateRightStatus];
  2475. }
  2476. }
  2477. func changeLineAttribute(_ sender: Any?) {
  2478. var inspector = sender as? KMLineInspector
  2479. if inspector == nil {
  2480. inspector = KMLineInspector.shared
  2481. }
  2482. let action = inspector?.currentLineChangeAction ?? .no
  2483. for annotation in self.listView.activeAnnotations {
  2484. guard let anno = annotation as? CPDFAnnotation else {
  2485. continue
  2486. }
  2487. if anno.hasBorder() {
  2488. // if (mwcFlags.updatingLine == 0 && [annotation hasBorder]) {
  2489. // mwcFlags.updatingLine = 1;
  2490. switch (action) {
  2491. case .lineWidth:
  2492. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2493. break
  2494. case .style:
  2495. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2496. break
  2497. case .dashPattern:
  2498. anno.setDashPattern(inspector?.dashPattern ?? [])
  2499. break
  2500. case .startLineStyle:
  2501. if anno.isLine() {
  2502. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2503. }
  2504. break
  2505. case .endLineStyle:
  2506. if anno.isLine() {
  2507. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2508. }
  2509. break
  2510. case .no:
  2511. break
  2512. }
  2513. // mwcFlags.updatingLine = 0;
  2514. // in case one property changes another, e.g. when adding a dashPattern the borderStyle can change
  2515. }
  2516. }
  2517. // [self updateLineInspector];
  2518. }
  2519. // MARK: -
  2520. // MARK: 显示窗口
  2521. internal func showCompressWindow(url: URL? = nil) {
  2522. // if let wc = self.compressWIndowControllerNew, let _ = wc.window?.isSheet {
  2523. // KMPrint("压缩窗口已显示")
  2524. // return
  2525. // }
  2526. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2527. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  2528. self.compressWIndowControllerNew?.password = self.listView?.document?.password ?? ""
  2529. // if let _url = url {
  2530. // windowController.oriDocumentUrl = self.listView.document.documentURL
  2531. // windowController.documentURL = _url
  2532. // } else {
  2533. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  2534. // }
  2535. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  2536. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2537. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2538. }
  2539. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  2540. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2541. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2542. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2543. // batchWindowController.window?.makeKeyAndOrderFront("")
  2544. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2545. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2546. batchWindowController.window?.makeKeyAndOrderFront("")
  2547. }
  2548. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2549. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2550. if (result) {
  2551. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2552. if (openDocument) {
  2553. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2554. } else {
  2555. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2556. }
  2557. } else {
  2558. let alert = NSAlert()
  2559. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2560. alert.runModal()
  2561. }
  2562. }
  2563. }
  2564. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2565. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2566. KMPrint("转档窗口已显示")
  2567. return
  2568. }
  2569. var convertT: KMConvertType = .Word
  2570. var windowController: KMConvertBaseWindowController?
  2571. if (type == .word) { /// Word
  2572. convertT = .Word
  2573. } else if (type == .excel) {
  2574. convertT = .Excel
  2575. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2576. if (type == .ppt) {
  2577. convertT = .PPT
  2578. } else if (type == .rtf) {
  2579. convertT = .RTF
  2580. } else if (type == .html) {
  2581. convertT = .HTML
  2582. } else if (type == .conversion_text) {
  2583. convertT = .Text
  2584. }
  2585. } else if (type == .csv) {
  2586. convertT = .CSV
  2587. } else if (type == .conversion_image) {
  2588. windowController = KMConvertImageWindowController()
  2589. convertT = .JPEG
  2590. } else if type == .json {
  2591. convertT = .Json
  2592. }
  2593. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  2594. var url: URL?
  2595. if (documentUrl != nil) {
  2596. url = documentUrl
  2597. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2598. } else {
  2599. url = self.listView.document.documentURL
  2600. }
  2601. self.showAllConvertWindow(convertT: convertT)
  2602. }
  2603. //MARK: 转档 -
  2604. func showAllConvertWindow(convertT: KMConvertType) {
  2605. if AccountManager.manager.isLogin == false {
  2606. let winC = AccountCenterWindowController()
  2607. self.km_beginSheet(windowC: winC)
  2608. return
  2609. }
  2610. AccountTools.canUseAdvance_success { result in
  2611. if result {
  2612. self.ome_showAllConvertWindow(convertT: convertT)
  2613. }
  2614. }
  2615. }
  2616. func ome_showAllConvertWindow(convertT: KMConvertType) {
  2617. self.ConvertTrackEvent(type: convertT)
  2618. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2619. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2620. var type: KMConvertWithPDFType = .WordAdvance
  2621. switch convertT {
  2622. case .Word:
  2623. break
  2624. case .Excel:
  2625. type = .Excel
  2626. case .PPT:
  2627. type = .PowerPoint
  2628. case .RTF:
  2629. type = .RTF
  2630. case .CSV:
  2631. type = .CSV
  2632. case .HTML:
  2633. type = .HTML
  2634. case .Text:
  2635. type = .Text
  2636. case .JPEG:
  2637. type = .JPEG
  2638. case .PNG:
  2639. type = .PNG
  2640. case .GIF:
  2641. type = .GIF
  2642. case .JPG:
  2643. type = .JPG
  2644. case .TIFF:
  2645. type = .TIFF
  2646. case .TGA:
  2647. type = .TGA
  2648. case .BMP:
  2649. type = .BMP
  2650. case .JP2:
  2651. type = .JPEG2000
  2652. case .AdvancedWord:
  2653. break
  2654. case .Json:
  2655. type = .Json
  2656. break
  2657. default:
  2658. break
  2659. }
  2660. // let document = self.document
  2661. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2662. var needShowHint = false
  2663. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2664. needShowHint = true
  2665. } else {
  2666. var needContinue = false
  2667. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2668. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2669. let ss = self.document?.documentURL.path
  2670. if arr.contains(ss!) {
  2671. needContinue = false
  2672. }else {
  2673. needContinue = true
  2674. }
  2675. }else {
  2676. needContinue = true
  2677. }
  2678. if needContinue {
  2679. let ss = self.document?.documentURL.path
  2680. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2681. file.password = document?.password ?? ""
  2682. KMBatchOperateManager.defaultManager.files?.append(file)
  2683. }
  2684. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2685. batchWindowController.switchToConvertType(convertType: type)
  2686. }
  2687. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2688. if needShowHint {
  2689. batchWindowController.showIsConvertingHint()
  2690. } else {
  2691. }
  2692. }
  2693. }
  2694. self.km_beginSheet(windowC: convertWC)
  2695. }
  2696. func ConvertTrackEvent(type: KMConvertType) {
  2697. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2698. switch type {
  2699. case .Word:
  2700. eventStr = "Btn_SubTbr_Converter_ToWord"
  2701. break
  2702. case .Excel:
  2703. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2704. case .PPT:
  2705. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2706. case .RTF:
  2707. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2708. case .CSV:
  2709. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2710. case .HTML:
  2711. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2712. case .Text:
  2713. eventStr = "Btn_SubTbr_Converter_ToText"
  2714. case .JPEG:
  2715. eventStr = "Btn_SubTbr_Converter_ToImage"
  2716. case .PNG:
  2717. eventStr = "Btn_SubTbr_Converter_ToImage"
  2718. case .GIF:
  2719. eventStr = "Btn_SubTbr_Converter_ToImage"
  2720. case .JPG:
  2721. eventStr = "Btn_SubTbr_Converter_ToImage"
  2722. case .TIFF:
  2723. eventStr = "Btn_SubTbr_Converter_ToImage"
  2724. case .TGA:
  2725. eventStr = "Btn_SubTbr_Converter_ToImage"
  2726. case .BMP:
  2727. eventStr = "Btn_SubTbr_Converter_ToImage"
  2728. case .JP2:
  2729. eventStr = "Btn_SubTbr_Converter_ToImage"
  2730. case .AdvancedWord:
  2731. eventStr = "Btn_SubTbr_Converter_ToWord"
  2732. break
  2733. default:
  2734. break
  2735. }
  2736. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2737. }
  2738. //MARK: 转档 - OCR
  2739. func showOCRWindow() {
  2740. if !IAPProductsManager.default().isAvailableAllFunction(){
  2741. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2742. let type = self.toolbarController.toolbarType ?? .None
  2743. if type == .Conversion {
  2744. winC?.kEventName = "Reading_Convert_OCR_BuyNow"
  2745. } else {
  2746. winC?.kEventName = "Reading_OCR_BuyNow"
  2747. }
  2748. winC?.showWindow(nil)
  2749. return
  2750. }
  2751. AccountTools.canUseAdvance_success { can in
  2752. if can {
  2753. self.oem_showOCRWindow()
  2754. }
  2755. }
  2756. }
  2757. func oem_showOCRWindow() {
  2758. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  2759. com.currentIndexPage = self.listView.currentPageIndex
  2760. self.km_beginSheet(windowC: com)
  2761. }
  2762. //MARK: 导出图片
  2763. func extractImageAction(num: Int) {
  2764. if !IAPProductsManager.default().isAvailableAllFunction(){
  2765. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2766. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  2767. winC?.showWindow(nil)
  2768. return
  2769. }
  2770. AccountTools.canUseAdvance_success { can in
  2771. if can {
  2772. self.oem_extractImageAction(num: num)
  2773. }
  2774. }
  2775. }
  2776. func oem_extractImageAction(num: Int) {
  2777. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2778. let alert = NSAlert()
  2779. alert.alertStyle = .critical
  2780. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2781. alert.runModal()
  2782. return
  2783. }
  2784. // if sender is KMToolbarItem {
  2785. // (sender as! KMToolbarItem).isSelected = false
  2786. // }
  2787. let document = self.listView.document
  2788. var fileURL = document?.documentURL
  2789. if num == 1 {
  2790. let pageCount = document?.pageCount ?? 0
  2791. let indeSet = NSMutableIndexSet()
  2792. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2793. if indeSet.count == 0 {
  2794. return
  2795. }
  2796. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2797. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2798. let outputSavePanel = NSSavePanel()
  2799. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2800. outputSavePanel.allowsOtherFileTypes = true
  2801. outputSavePanel.isExtensionHidden = true
  2802. outputSavePanel.canCreateDirectories = true
  2803. outputSavePanel.nameFieldStringValue = tFileName
  2804. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2805. if result == NSApplication.ModalResponse.OK {
  2806. DispatchQueue.main.async {
  2807. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2808. let tDestFile = outputSavePanel.url!.path
  2809. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2810. let pdfconverter = PDFConvertObject()
  2811. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2812. self.dismissProgressSheet()
  2813. let fileManager = FileManager.default
  2814. if fileManager.fileExists(atPath: tDestFile) {
  2815. let workspace = NSWorkspace.shared
  2816. let url = URL(fileURLWithPath: tDestFile)
  2817. workspace.activateFileViewerSelecting([url])
  2818. }
  2819. }
  2820. }
  2821. })
  2822. return
  2823. }
  2824. if fileURL != nil {
  2825. self.myDocument?.save(nil)
  2826. } else {
  2827. let myDocument = self.myDocument
  2828. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2829. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2830. if writeSuccess {
  2831. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2832. fileURL = document?.documentURL
  2833. } else {
  2834. NSSound.beep()
  2835. return
  2836. }
  2837. }
  2838. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2839. extract?.docPath = fileURL?.path ?? ""
  2840. extract?.password = document?.password ?? ""
  2841. extract?.currentPage = self.listView.currentPageIndex
  2842. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2843. self.km_beginSheet(windowC: extract!)
  2844. extract?.selectCurrentPageBtn()
  2845. // self.showCreateStamp()
  2846. // self.showAddSignature()
  2847. }
  2848. //MARK: 创建文字图章示例实际上不会在这里使用
  2849. func showCreateStamp() {
  2850. let stampCreaterWindowController = KMStampCreaterWindowController()
  2851. stampCreaterWindowController.window?.backgroundColor = .clear
  2852. self.km_beginSheet(windowC: stampCreaterWindowController)
  2853. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2854. if result == 1 {
  2855. }
  2856. }
  2857. }
  2858. //MARK: 添加签名示例实际上不会在这里使用
  2859. func showAddSignature() {
  2860. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2861. // signatureWindowController.window?.backgroundColor = .clear
  2862. // signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2863. //
  2864. // }
  2865. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2866. })
  2867. }
  2868. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2869. // if progressController == nil {
  2870. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2871. // }
  2872. let progress = SKProgressController()
  2873. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2874. progress.window?.contentView?.wantsLayer = true
  2875. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2876. progress.progressField.textColor = NSColor.white
  2877. progress.message = NSLocalizedString("Converting...", comment: "")
  2878. progressC = progress
  2879. progressC?.message = message
  2880. if maxValue > 0 {
  2881. progressC?.indeterminate = false
  2882. progressC?.maxValue = Double(maxValue)
  2883. progressC?.progressBar.doubleValue = 0.3
  2884. } else {
  2885. progressC?.indeterminate = true
  2886. }
  2887. self.view.km_beginSheet(windowC: progressC!)
  2888. }
  2889. func dismissProgressSheet() {
  2890. progressC?.stopAnimation()
  2891. self.view.km_endSheet()
  2892. progressC = nil
  2893. }
  2894. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2895. let newArr = NSMutableArray()
  2896. for item in files {
  2897. newArr.add(item.filePath)
  2898. }
  2899. return newArr as! [String]
  2900. }
  2901. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2902. self.saveDocument()
  2903. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2904. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2905. if (result == .cancel) {
  2906. return
  2907. }
  2908. // 解除权限
  2909. self?.listView.document.unlock(withPassword: password)
  2910. // 隐藏提示
  2911. self?.hiddenSecureLimitTip()
  2912. // 去打印
  2913. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2914. }
  2915. return
  2916. }
  2917. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2918. }
  2919. // MARK: - 图片注释
  2920. @IBAction func imageAnnotation(_ sender: Any) {
  2921. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2922. changeAnnotationMode(sender)
  2923. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2924. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2925. return
  2926. }
  2927. AccountTools.canUseAdvance_success { can in
  2928. if can {
  2929. self.oem_imageAnnotation(sender)
  2930. }
  2931. }
  2932. }
  2933. func oem_imageAnnotation(_ sender: Any) {
  2934. let accessoryCtr = KMImageAccessoryController()
  2935. let openPanel = NSOpenPanel()
  2936. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2937. openPanel.allowsMultipleSelection = false
  2938. openPanel.accessoryView = accessoryCtr.view
  2939. // if #available(macOS 10.11, *) {
  2940. openPanel.canSelectHiddenExtension = true
  2941. // }
  2942. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2943. if result == .OK {
  2944. guard let url = openPanel.url else {
  2945. return
  2946. }
  2947. let filePath = url.path
  2948. if filePath.pathExtension.lowercased() == "pdf" {
  2949. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2950. NSSound.beep()
  2951. return
  2952. }
  2953. }
  2954. guard let image = NSImage(contentsOfFile: url.path) else {
  2955. let alert = NSAlert()
  2956. alert.alertStyle = .critical
  2957. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2958. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2959. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2960. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2961. if response == .alertFirstButtonReturn {
  2962. // Handle cancel button clicked
  2963. }
  2964. }
  2965. return
  2966. }
  2967. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2968. if isDamageImage {
  2969. let alert = NSAlert()
  2970. alert.alertStyle = .critical
  2971. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2972. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDFull doesn’t recognize.", comment: "")
  2973. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2974. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2975. if response == .alertFirstButtonReturn {
  2976. // Handle cancel button clicked
  2977. }
  2978. }
  2979. return
  2980. }
  2981. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2982. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2983. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2984. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  2985. }
  2986. }
  2987. }
  2988. }
  2989. @IBAction func tableAnnotation(_ sender: Any) {
  2990. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2991. changeAnnotationMode(sender)
  2992. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2993. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2994. winC?.kEventName = "Reading_Table_BuyNow"
  2995. winC?.showWindow(nil)
  2996. return
  2997. }
  2998. AccountTools.canUseAdvance_success { can in
  2999. if can {
  3000. self.oem_tableAnnotation(sender)
  3001. }
  3002. }
  3003. }
  3004. func oem_tableAnnotation(_ sender: Any) {
  3005. listView.addAnnotationWithTable()
  3006. openRightPane()
  3007. }
  3008. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  3009. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  3010. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  3011. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  3012. }
  3013. if let data = image.tiffRepresentation,
  3014. let imageRep = NSBitmapImageRep(data: data) {
  3015. imageRep.size = image.size
  3016. var imageData: Data?
  3017. if path.lowercased() == "png" {
  3018. imageData = imageRep.representation(using: .png, properties: [:])
  3019. } else {
  3020. imageData = imageRep.representation(using: .jpeg, properties: [:])
  3021. }
  3022. if let imageData = imageData {
  3023. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  3024. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  3025. return true
  3026. } else {
  3027. return false
  3028. }
  3029. }
  3030. }
  3031. return false
  3032. }
  3033. func tagString() -> String {
  3034. let dateFormatter = DateFormatter()
  3035. dateFormatter.dateFormat = "yyMMddHHmmss"
  3036. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  3037. }
  3038. // MARK: - Split View
  3039. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  3040. }
  3041. @objc func removeSecondaryPdfContentView(_ sender: Notification?) {
  3042. if let _ = sender {
  3043. NotificationCenter.default.removeObserver(self, name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  3044. }
  3045. self.secondaryPdfContentView?.removeFromSuperview()
  3046. self.newPDFSplitView.adjustSubviews()
  3047. }
  3048. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  3049. if !isSinglePage && isHorizontal {
  3050. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  3051. }
  3052. if (!isSinglePage && !isHorizontal) {
  3053. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3054. }
  3055. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  3056. }
  3057. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  3058. if isSinglePage {
  3059. if self.newPDFSplitView.animating {
  3060. return
  3061. }
  3062. if self.secondaryPdfContentView?.window != nil {
  3063. self.lastSplitPDFHeight = self.lastSplitPDFHeightFloat(self.secondaryPdfContentView?.frame ?? .zero)
  3064. self.newPDFSplitView.setPosition(self.newPDFSplitView.maxPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: true)
  3065. if self.newPDFSplitView.animating {
  3066. NotificationCenter.default.addObserver(self, selector: #selector(removeSecondaryPdfContentView), name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  3067. } else {
  3068. self.removeSecondaryPdfContentView(nil)
  3069. }
  3070. }
  3071. self.view.window?.recalculateKeyViewLoop()
  3072. if self.interactionMode == .legacyFullScreen {
  3073. self.view.window?.makeFirstResponder(self.listView)
  3074. }
  3075. } else {
  3076. if self.newPDFSplitView.animating {
  3077. return
  3078. }
  3079. self.newPDFSplitView.dividerStyle = .paneSplitter
  3080. self.newPDFSplitView.isVertical = isHorizontal
  3081. if self.secondaryPdfView?.window == nil {
  3082. let frame = self.newPDFSplitView.bounds
  3083. if (self.lastSplitPDFHeight <= 0.0) {
  3084. var DEFAULT_SPLIT_PDF_FACTOR: Float = 0.3
  3085. self.lastSplitPDFHeight = floorf(DEFAULT_SPLIT_PDF_FACTOR * self.lastSplitPDFHeightFloat(frame))
  3086. }
  3087. var position = self.lastSplitPDFHeightFloat(frame)-self.lastSplitPDFHeight-Float(self.newPDFSplitView.dividerThickness)
  3088. var point: NSPoint = .zero
  3089. var page: CPDFPage?
  3090. self.newPDFSplitView.setPosition(position.cgFloat, ofDividerAt: 0, animate: true)
  3091. if (self.secondaryPdfContentView == nil) {
  3092. // secondaryPdfContentView = [[SKGradientView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 200.0, 20.0)];
  3093. self.secondaryPdfContentView = NSView(frame: NSMakeRect(0, 0, 200, 20))
  3094. self.secondaryPdfView = KMSecondaryPDFView(frame: self.secondaryPdfContentView?.bounds ?? .zero)
  3095. self.secondaryPdfView?.autoresizingMask = [.width, .height]
  3096. // self.secondaryPdfContentView?.isHidden = true
  3097. self.secondaryPdfContentView?.addSubview(self.secondaryPdfView!)
  3098. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3099. // self.newPDFSplitView.addArrangedSubview(self.secondaryPdfContentView!)
  3100. // // Because of a PDFView bug, display properties can not be changed before it is placed in a window
  3101. self.secondaryPdfView?.synchronizedPDFView = self.listView
  3102. self.secondaryPdfView?.backgroundColor = self.listView.backgroundColor
  3103. // [secondaryPdfView applyDefaultPageBackgroundColor];
  3104. self.secondaryPdfView?.displaysPageBreaks = false
  3105. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  3106. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  3107. self.secondaryPdfView?.setGreekingThreshold(KMPreference.shared.greekThreshold.cgFloat)
  3108. self.secondaryPdfView?.setSynchronizeZoom(true)
  3109. // // [secondaryPdfView setDocument:[pdfView document]];
  3110. point = NSMakePoint(NSMinX(frame), NSMaxY(frame) - position.cgFloat - self.newPDFSplitView.dividerThickness)
  3111. page = self.listView.page(for: point, nearest: true)
  3112. //
  3113. let controlView = self.secondaryPdfView?.controlView
  3114. var color = NSColor(calibratedWhite: 0.97, alpha: 1.0)
  3115. if KMAppearance.isDarkMode() {
  3116. color = KMAppearance.Layout.l0Color()
  3117. }
  3118. // [(SKGradientView *)secondaryPdfContentView setGradient:[[[NSGradient alloc] initWithStartingColor:color endingColor:color] autorelease]];
  3119. // [(SKGradientView *)secondaryPdfContentView setAlternateGradient:nil];
  3120. var pdfRect: NSRect = .zero
  3121. var controlRect: NSRect = .zero
  3122. NSDivideRect(self.secondaryPdfContentView?.bounds ?? .zero, &controlRect, &pdfRect, NSHeight(controlView?.frame ?? .zero), .minY)
  3123. controlRect.size.width = NSWidth(controlView?.frame ?? .zero)
  3124. controlView?.frame = controlRect
  3125. controlView?.autoresizingMask = [.maxXMargin, .maxYMargin, .width]
  3126. // [(SKGradientView *)secondaryPdfContentView setMinSize:controlRect.size];
  3127. self.secondaryPdfView?.frame = pdfRect
  3128. self.secondaryPdfContentView?.addSubview(controlView!)
  3129. self.openSecondaryPdfView = KMSecondaryViewController()
  3130. self.openSecondaryPdfView?.view.frame = self.secondaryPdfContentView?.frame ?? .zero
  3131. self.secondaryPdfContentView?.addSubview(self.openSecondaryPdfView!.view)
  3132. self.openSecondaryPdfView?.secondaryView.receivedFileUrlBlock = { [weak self] fileUrl in
  3133. if let docUrl = fileUrl {
  3134. _ = self?.displaySecondaryPDFView(withUrl: docUrl)
  3135. self?.openSecondaryPdfView?.view.removeFromSuperview()
  3136. self?.openSecondaryPdfView = nil
  3137. }
  3138. }
  3139. self.openSecondaryPdfView?.delegate = self
  3140. if (!isHorizontal) {
  3141. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3142. }
  3143. } else {
  3144. self.secondaryPdfContentView?.isHidden = true
  3145. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3146. }
  3147. // self.newPDFSplitView.setPosition(self.secondaryPdfContentView?.bounds.size.width ?? 120, ofDividerAt: 1, animate: true)
  3148. if (page != nil) {
  3149. self.secondaryPdfView?.go(toPageIndex: Int(page!.pageIndex()), animated: false)
  3150. // point = [secondaryPdfView convertPoint:[secondaryPdfView convertPoint:[pdfView convertPoint:point toPage:page] fromPage:page] toView:[secondaryPdfView documentView]];
  3151. let tmpP = self.listView.convert(point, to: page)
  3152. let conP = self.secondaryPdfView?.convert(tmpP, from: page) ?? .zero
  3153. point = self.secondaryPdfView?.convert(conP, to: self.secondaryPdfView?.documentView()) ?? .zero
  3154. if let docView = self.secondaryPdfView?.documentView(), docView.contentView.isFlipped == false {
  3155. point.y -= docView.isFlipped ? -NSHeight(docView.visibleRect) : NSHeight(docView.visibleRect)
  3156. }
  3157. self.secondaryPdfView?.documentView()?.scroll(point)
  3158. self.secondaryPdfView?.layoutDocumentView()
  3159. }
  3160. }
  3161. self.view.window?.recalculateKeyViewLoop()
  3162. if self.interactionMode == .legacyFullScreen {
  3163. self.view.window?.makeFirstResponder(self.listView)
  3164. }
  3165. if self.secondaryPdfView?.document == nil {
  3166. self.openSecondaryPdfView?.viewHighlyAdaptive()
  3167. }
  3168. }
  3169. }
  3170. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  3171. if (self.newPDFSplitView.isVertical) {
  3172. return Float(NSWidth(rect))
  3173. } else {
  3174. return Float(NSHeight(rect))
  3175. }
  3176. }
  3177. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  3178. let document = CPDFDocument.init(url: url)
  3179. if document != nil {
  3180. self.secondaryPdfView?.document = nil
  3181. self.secondaryPdfView?.document = document
  3182. self.rightSideViewController.annotationProperties.openPropertiesType = .pageDisplay
  3183. return true
  3184. } else {
  3185. return false
  3186. }
  3187. }
  3188. func updateNextAndPreViousButtonState() {
  3189. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3190. let view = item?.customizeView as? KMToolbarPreviousNextItemView
  3191. if let can = self.listView?.canGoToPreviousPage() {
  3192. view?.previousButton.isEnabled = can
  3193. } else {
  3194. view?.previousButton.isEnabled = false
  3195. }
  3196. if let can = self.listView?.canGoToNextPage() {
  3197. view?.nextButton.isEnabled = can
  3198. } else {
  3199. view?.nextButton.isEnabled = false
  3200. }
  3201. }
  3202. func updateBackAndForwardButtonState() {
  3203. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3204. if self.listView.km_canGoForward() {
  3205. toItem?.unEnabled = false
  3206. } else {
  3207. toItem?.unEnabled = true
  3208. }
  3209. }
  3210. }
  3211. // MARK: -
  3212. // MARK: - KMSecondaryViewControllerDelegate
  3213. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  3214. func receivedFileUrl(_ url: URL!) {
  3215. let state = self.displaySecondaryPDFView(withUrl: url)
  3216. if !state {
  3217. let alert = NSAlert()
  3218. alert.alertStyle = .critical
  3219. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3220. alert.runModal()
  3221. return
  3222. } else {
  3223. self.openSecondaryPdfView?.view.removeFromSuperview()
  3224. self.openSecondaryPdfView = nil
  3225. }
  3226. }
  3227. func controllerDidClose(_ controller: KMSecondaryViewController!) {
  3228. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  3229. }
  3230. }
  3231. // MARK: -
  3232. // MARK: - KMToolbarViewControllerDelegate
  3233. extension KMMainViewController : KMToolbarViewControllerDelegate {
  3234. func changeModelAction(mode: CToolMode) {
  3235. self.listView.toolMode = mode
  3236. if mode == .editPDFToolMode {
  3237. self.childToolbarController.updateType(newType: .editPDF)
  3238. }
  3239. }
  3240. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  3241. switch selectedTag {
  3242. case 2:
  3243. if self.listView.scaleFactor != 1.0 {
  3244. self.listView.scaleFactor = 1.0
  3245. self.listView.autoScales = false
  3246. }
  3247. break
  3248. case 1:
  3249. let pageHeight = self.listView.currentPage()!.size.height
  3250. let pdfviewHeight = self.listView.bounds.size.height
  3251. self.listView.scaleFactor = pdfviewHeight/pageHeight
  3252. self.listView.autoScales = false
  3253. break
  3254. case 0:
  3255. // self.listView.autoScales = !self.listView.autoScales
  3256. self.listView.autoScales = true
  3257. break
  3258. case 3:
  3259. self.listView.scaleFactor = 0.1
  3260. break
  3261. case 4:
  3262. self.listView.scaleFactor = 0.25
  3263. break
  3264. case 5:
  3265. self.listView.scaleFactor = 0.5
  3266. break
  3267. case 6:
  3268. self.listView.scaleFactor = 0.75
  3269. break
  3270. case 7:
  3271. self.listView.scaleFactor = 1.0
  3272. break
  3273. case 8:
  3274. self.listView.scaleFactor = 1.5
  3275. break
  3276. case 9:
  3277. self.listView.scaleFactor = 2.0
  3278. break
  3279. case 10:
  3280. self.listView.scaleFactor = 4.0
  3281. break
  3282. case 11:
  3283. self.listView.scaleFactor = 8.0
  3284. break
  3285. case 12:
  3286. self.listView.scaleFactor = 16.0
  3287. break
  3288. case 13:
  3289. self.listView.scaleFactor = 32.0
  3290. break
  3291. case 14:
  3292. self.listView.scaleFactor = 64.0
  3293. break
  3294. case 15:
  3295. self.listView.scaleFactor = 100.0
  3296. break
  3297. default:
  3298. break
  3299. }
  3300. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3301. if self.digitalSignController?.pdfView != nil {
  3302. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  3303. }
  3304. if self.redactController?.redactPdfView != nil {
  3305. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  3306. }
  3307. }
  3308. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  3309. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3310. if scale > 100 {
  3311. scale = 100
  3312. }
  3313. if (scale <= 0.101) {
  3314. self.listView.scaleFactor = self.listView.minScaleFactor()
  3315. } else {
  3316. self.listView.scaleFactor = scale
  3317. }
  3318. if self.digitalSignController?.pdfView != nil {
  3319. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  3320. }
  3321. if self.redactController?.redactPdfView != nil {
  3322. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  3323. }
  3324. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3325. }
  3326. func changePDFViewZoomInAction() {
  3327. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3328. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3329. switch scale {
  3330. case 0...0.25:
  3331. scale += 0.25
  3332. case 0.25...3:
  3333. scale += 0.25
  3334. case 3.1...10:
  3335. scale += 0.4
  3336. case 10.1...100:
  3337. scale += 1
  3338. default:
  3339. scale += 1
  3340. }
  3341. self.listView.scaleFactor = scale
  3342. // nearbyint
  3343. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3344. // self.listView.zoomIn(nil)
  3345. if self.digitalSignController?.pdfView != nil {
  3346. self.digitalSignController?.pdfView.scaleFactor = scale
  3347. }
  3348. if self.redactController?.redactPdfView != nil {
  3349. self.redactController?.redactPdfView.scaleFactor = scale
  3350. }
  3351. }
  3352. func changePDFViewZoomOutAction() {
  3353. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3354. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3355. switch scale {
  3356. case 0...0.25:
  3357. scale = 0
  3358. case 0.25...3:
  3359. scale -= 0.25
  3360. case 3.1...10:
  3361. scale -= 0.4
  3362. case 10.1...100:
  3363. scale -= 1
  3364. default:
  3365. scale -= 1
  3366. }
  3367. self.listView.scaleFactor = scale
  3368. // nearbyint
  3369. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3370. // self.listView.zoomOut(nil)
  3371. if self.digitalSignController?.pdfView != nil {
  3372. self.digitalSignController?.pdfView.scaleFactor = scale
  3373. }
  3374. if self.redactController?.redactPdfView != nil {
  3375. self.redactController?.redactPdfView.scaleFactor = scale
  3376. }
  3377. self.savePageNumberIfNeed()
  3378. }
  3379. func changePDFViewGotoNextPageAction() {
  3380. self.listView.km_goBack(nil)
  3381. if (self.listView.canGoToNextPage()) {
  3382. self.listView.goToNextPage(nil)
  3383. }
  3384. self.updateNextAndPreViousButtonState()
  3385. }
  3386. func changePDFViewGoToPreviousPageAction() {
  3387. if (self.listView.canGoToPreviousPage()) {
  3388. self.listView.goToPreviousPage(nil)
  3389. }
  3390. self.updateNextAndPreViousButtonState()
  3391. }
  3392. func changePDFViewGotoBackAction() {
  3393. self.listView.km_goBack(nil)
  3394. self.updateBackAndForwardButtonState()
  3395. }
  3396. func changePDFViewGoToForwardAction() {
  3397. self.listView.km_goForward(nil)
  3398. self.updateBackAndForwardButtonState()
  3399. }
  3400. func aiTranslationPDFFileAction() {
  3401. #if VERSION_DMG
  3402. #else
  3403. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  3404. KMLoginWindowController.show(window: NSApp.mainWindow!)
  3405. return
  3406. }
  3407. #endif
  3408. self.trackEvent_aiTranslate()
  3409. self._aiTranslationPDFFileAction()
  3410. }
  3411. private func _aiTranslationPDFFileAction() {
  3412. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  3413. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  3414. let alert = NSAlert()
  3415. alert.alertStyle = .critical
  3416. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  3417. alert.runModal()
  3418. return
  3419. } else if isExceedsLimit {
  3420. let alert = NSAlert()
  3421. alert.alertStyle = .critical
  3422. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  3423. alert.runModal()
  3424. return
  3425. }
  3426. let alert = NSAlert()
  3427. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  3428. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  3429. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3430. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  3431. if (result == .alertFirstButtonReturn) {
  3432. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  3433. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  3434. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  3435. } else if result == .alertSecondButtonReturn {
  3436. return
  3437. }
  3438. }
  3439. }
  3440. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  3441. self.trackEvent_share()
  3442. }
  3443. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  3444. self.shareDocument(sender: viewController)
  3445. }
  3446. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3447. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3448. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3449. winC?.kEventName = "Reading_Flatten_BuyNow"
  3450. winC?.showWindow(nil)
  3451. return
  3452. }
  3453. AccountTools.canUseAdvance_success { can in
  3454. if can {
  3455. self.oem_toolbarViewController(viewController, shareFlatten: item)
  3456. }
  3457. }
  3458. }
  3459. func oem_toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3460. self.shareFlatten(sender: viewController)
  3461. }
  3462. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  3463. self.shareOriginalPDF(sender: viewController)
  3464. }
  3465. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  3466. if(0 == selectedTag) {
  3467. // self.documentAIViewController?.enteredIncreaseAllPage()
  3468. // self.documentAIViewController?.updateToolState(false)
  3469. } else {
  3470. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  3471. // self.documentAIViewController?.recognitionPartModel(with: .english)
  3472. // self.documentAIViewController?.updateToolState(true)
  3473. }
  3474. // 0 : Scan 1:OCR Text
  3475. }
  3476. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  3477. if beforeType == .editPDF {
  3478. self.enterEditPDF()
  3479. }
  3480. if(type != .Page) {
  3481. if (hasEnterPageEdit()) {
  3482. self.exitPageEdit()
  3483. }
  3484. }
  3485. if type != .redact {
  3486. if self.hasEnterRedact() {
  3487. self.exitRedact()
  3488. }
  3489. }
  3490. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3491. if self.hasShowDigitalSign() {
  3492. self.exitDigitalSign()
  3493. }
  3494. }
  3495. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  3496. self.toolbarController.findItem(KMDocumentViewDisplayToolbarItemIdentifier)?.isSelected = false
  3497. }
  3498. if(type != .Form) {
  3499. self.removeFromAlertView()
  3500. }
  3501. if (type == .Page) {
  3502. if (hasEnterPageEdit()) {
  3503. self.exitPageEdit()
  3504. } else {
  3505. self.enterPageEdit(pages)
  3506. }
  3507. } else if type == .editPDF {
  3508. self.enterEditPDF()
  3509. } else if type == .Annatiton {
  3510. self.rightSideViewController.subViewType = .AnnotationProperts
  3511. } else if type == .redact {
  3512. if self.needSaveDocument() {
  3513. self.saveDocumentWithProgressAlert { [unowned self] params in
  3514. self.enterRedact()
  3515. }
  3516. return
  3517. }
  3518. let isEdited = self.listView.isEdited()
  3519. let isPDFTextImageEdited = self.model.isPDFTextImageEdited
  3520. if isEdited || isPDFTextImageEdited {
  3521. self.commitEditingIfNeed()
  3522. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  3523. self.enterRedact()
  3524. // }
  3525. } else {
  3526. self.enterRedact()
  3527. }
  3528. } else if type == .Tool {
  3529. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  3530. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  3531. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  3532. self.loadOpenFileFunctionGuide(.measureGuide)
  3533. }
  3534. } else if type == . Conversion {
  3535. self.loadOpenFileFunctionGuide(.convertGuide)
  3536. }else if type == .Form {
  3537. self.showFormAlertView()
  3538. }else if type == .Select {
  3539. self.rightSideViewController.isHidden = true
  3540. self.closeRightPane()
  3541. }
  3542. }
  3543. func clickChildTool(type: KMToolbarType, index: Int) {
  3544. if (type == .secure) {
  3545. if (index == 1) {
  3546. self.trackEvent_setPassword()
  3547. } else if (index == 2) {
  3548. self.trackEvent_removePassword()
  3549. }
  3550. } else {
  3551. self.trackEvent(toolBarType: type)
  3552. }
  3553. Task { @MainActor in
  3554. if (type == .compress) { /// 压缩
  3555. if !self.documentAllowsEdit() {
  3556. return
  3557. }
  3558. if (self.needSaveDocument()) {
  3559. self.saveDocumentWithProgressAlert { [unowned self] params in
  3560. self.showCompressWindow()
  3561. }
  3562. return
  3563. }
  3564. self.showCompressWindow()
  3565. return
  3566. }
  3567. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  3568. if type == .conversion_imageToPDF {
  3569. Task {
  3570. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  3571. }
  3572. return
  3573. }
  3574. var identifier: String?
  3575. if (type == .word) { /// Word
  3576. identifier = KMToolbarConversionWordItemIdentifier
  3577. } else if (type == .excel) {
  3578. identifier = KMToolbarConversionExcelItemIdentifier
  3579. } else if (type == .ppt) {
  3580. identifier = KMToolbarConversionPPTItemIdentifier
  3581. } else if (type == .rtf) {
  3582. identifier = KMToolbarConversionRTFItemIdentifier
  3583. } else if (type == .html) {
  3584. identifier = KMToolbarConversionHTMLItemIdentifier
  3585. } else if (type == .conversion_text) {
  3586. identifier = KMToolbarConversionTextItemIdentifier
  3587. } else if (type == .csv) {
  3588. identifier = KMToolbarConversionCSVItemIdentifier
  3589. } else if (type == .conversion_image) {
  3590. identifier = KMToolbarConversionImageItemIdentifier
  3591. }
  3592. if (self.needSaveDocument()) {
  3593. self.saveDocumentWithProgressAlert { [unowned self] params in
  3594. self.showConvertWindow(type: type, identifier: identifier)
  3595. }
  3596. return
  3597. }
  3598. self.showConvertWindow(type: type, identifier: identifier)
  3599. return
  3600. }
  3601. if (type == .merge) { /// 合并
  3602. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  3603. if !self.documentAllowsEdit() {
  3604. return
  3605. }
  3606. if (self.needSaveDocument()) {
  3607. self.saveDocumentWithProgressAlert { [unowned self] params in
  3608. self.showMergeWindow(self.listView.document.password)
  3609. }
  3610. return
  3611. }
  3612. self.showMergeWindow(self.listView.document.password)
  3613. return
  3614. }
  3615. if (type == .bates || type == .headerAndFooter) {
  3616. if !IAPProductsManager.default().isAvailableAllFunction(){
  3617. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3618. if type == .headerAndFooter {
  3619. if index == 1 {
  3620. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  3621. } else if index == 2 {
  3622. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  3623. }
  3624. } else if type == .bates {
  3625. if index == 1 {
  3626. winC?.kEventName = "Reading_AddBates_BuyNow"
  3627. } else if index == 2 {
  3628. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  3629. }
  3630. }
  3631. winC?.showWindow(nil)
  3632. return
  3633. }
  3634. if !self.documentAllowsEdit() {
  3635. return
  3636. }
  3637. if (index == 1) {
  3638. var windowController: KMBaseWindowController = KMBaseWindowController()
  3639. if (type == .bates) {
  3640. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3641. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3642. let fpath = self.document?.documentURL?.path ?? ""
  3643. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3644. }
  3645. windowController.isBates = true
  3646. } else if (type == .headerAndFooter) {
  3647. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3648. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3649. let fpath = self.document?.documentURL?.path ?? ""
  3650. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3651. }
  3652. } else if (type == .background) {
  3653. } else if (type == .watermark) {
  3654. // controller = KMWatermarkViewController()
  3655. }
  3656. windowController.pdfDocument = self.listView.document
  3657. windowController.cancelAction = { [unowned self] controller in
  3658. self.view.window?.endSheet((self.currentWindowController.window)!)
  3659. self.currentWindowController = nil
  3660. }
  3661. self.currentWindowController = windowController
  3662. await self.view.window?.beginSheet(windowController.window!)
  3663. return
  3664. }
  3665. if (index == 1) { /// 取消
  3666. self.toolbarController.exitWatermarkAdjective()
  3667. // self.rightSideViewController.view.isHidden = true
  3668. self.rightSideViewController.isHidden = true
  3669. self.rightSideViewController.subViewType = .None
  3670. self.closeRightPane()
  3671. return
  3672. } else if index == 3 {
  3673. let fpath = self.document?.documentURL?.path ?? ""
  3674. if type == .bates {
  3675. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3676. } else {
  3677. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3678. }
  3679. } else if index == 4 {
  3680. let fpath = self.document?.documentURL?.path ?? ""
  3681. if type == .bates {
  3682. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  3683. } else {
  3684. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  3685. }
  3686. } else if (index == 2) { //// 移除
  3687. if type == .headerAndFooter {
  3688. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3689. let savePanel = NSSavePanel()
  3690. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3691. savePanel.allowedFileTypes = ["pdf"]
  3692. savePanel.accessoryView = savePanelAccessoryViewController.view
  3693. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3694. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3695. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3696. if success == 1 && savePanel.url?.path == self.listView?.document?.documentURL.path {
  3697. self.setDocument = CPDFDocument(url: savePanel.url!)
  3698. return
  3699. }
  3700. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3701. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3702. }
  3703. } else {
  3704. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3705. }
  3706. }
  3707. }
  3708. }
  3709. } else if type == .bates {
  3710. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3711. let savePanel = NSSavePanel()
  3712. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3713. savePanel.allowedFileTypes = ["pdf"]
  3714. savePanel.accessoryView = savePanelAccessoryViewController.view
  3715. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3716. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3717. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3718. if success == 1 && savePanel.url?.path == self.listView?.document?.documentURL.path {
  3719. self.setDocument = CPDFDocument(url: savePanel.url!)
  3720. return
  3721. }
  3722. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3723. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3724. }
  3725. } else {
  3726. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3727. }
  3728. }
  3729. }
  3730. }
  3731. }
  3732. return
  3733. } else if (index == 2) { /// 应用
  3734. let model = self.rightSideViewController.model
  3735. if (type == .bates || type == .headerAndFooter) {
  3736. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3737. let alert = NSAlert()
  3738. alert.alertStyle = .critical
  3739. alert.messageText = "没有找到模型"
  3740. alert.runModal()
  3741. return
  3742. }
  3743. if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3744. let alert = NSAlert()
  3745. alert.alertStyle = .critical
  3746. alert.messageText = "没有找到内容"
  3747. alert.runModal()
  3748. return
  3749. }
  3750. }
  3751. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3752. result in
  3753. DispatchQueue.main.async {
  3754. self.listView.layoutDocumentView()
  3755. self.listView.setNeedsDisplayForVisiblePages()
  3756. }
  3757. if (result) {
  3758. let alert = NSAlert()
  3759. alert.alertStyle = .warning
  3760. alert.messageText = "成功"
  3761. alert.runModal()
  3762. } else {
  3763. let alert = NSAlert()
  3764. alert.alertStyle = .critical
  3765. alert.messageText = "失败"
  3766. alert.runModal()
  3767. }
  3768. }
  3769. return
  3770. } else if index == 5 {
  3771. self.rightSideViewController.isHidden = false
  3772. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3773. self.openRightPane()
  3774. }
  3775. } else if (type == .redact) { /// 标记密文
  3776. if !IAPProductsManager.default().isAvailableAllFunction(){
  3777. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3778. return
  3779. }
  3780. if (index == 1) { /// 取消
  3781. if (self.model.hasAddRedact) {
  3782. let alert = NSAlert()
  3783. alert.messageText = NSLocalizedString("You can save a document with unapplied cipher text and edit it again. If you do not save, all changes will be lost.", comment: "")
  3784. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3785. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3786. let result = alert.runModal()
  3787. if (result == .alertFirstButtonReturn) {
  3788. self.listView.toolMode = .moveToolMode
  3789. self.toolbarController.exitRedact()
  3790. }
  3791. return
  3792. }
  3793. self.listView.toolMode = .moveToolMode
  3794. self.toolbarController.exitRedact()
  3795. return
  3796. }
  3797. if (index == 2) { /// 擦除
  3798. self.exeRedactConfirm(.eraserAll) {}
  3799. return
  3800. }
  3801. if (index == 3) { /// 应用
  3802. self.exeRedactConfirm(.redactAll) {}
  3803. return
  3804. }
  3805. if (index == 4) { /// 文本&图像
  3806. self.listView.toolMode = .redactToolMode
  3807. return
  3808. }
  3809. if (index == 5) { /// 页面
  3810. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3811. await self.view.window?.beginSheet(windowController.window!)
  3812. self.currentWindowController = windowController
  3813. windowController.itemClick = { [weak self] index, value in
  3814. if (index == 1) {
  3815. let topBarView = self?.toolbarController.fetchTopBarView()
  3816. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3817. return
  3818. }
  3819. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3820. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3821. self?.currentWindowController = nil
  3822. return
  3823. }
  3824. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3825. let pageType = windowController_pageRange.pageType
  3826. let pageString = windowController_pageRange.pageString
  3827. if (pageType == 5) { /// 自定义页面
  3828. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  3829. if (array.count == 0) {
  3830. let alert = NSAlert()
  3831. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3832. alert.runModal()
  3833. return
  3834. }
  3835. }
  3836. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3837. self!.currentWindowController = nil
  3838. var indexs: IndexSet = []
  3839. if (pageType == 1) { /// 当前页面
  3840. indexs.insert((self?.listView.currentPageIndex)!)
  3841. } else {
  3842. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  3843. }
  3844. if (indexs.count == 0) {
  3845. return
  3846. }
  3847. for i in indexs {
  3848. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3849. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3850. redactAnno.bounds = page.bounds
  3851. self?.listView.add(redactAnno, to: page)
  3852. }
  3853. }
  3854. return
  3855. }
  3856. } else if (type == .secure) { /// 安全
  3857. if (index == 1) { /// 设置密码
  3858. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3859. if !self.documentAllowsEdit() {
  3860. return
  3861. }
  3862. // KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3863. // if (result == .cancel) {
  3864. // return
  3865. // }
  3866. //
  3867. // self?.isSaveKeyChain = false
  3868. // self?.listView.document.unlock(withPassword: password)
  3869. // self?.hiddenSecureLimitTip()
  3870. //
  3871. // self?.showSecureWindow((self?.listView.document.documentURL)!)
  3872. // }
  3873. // return
  3874. }
  3875. self.showSecureWindow(self.listView.document.documentURL)
  3876. return
  3877. } else if index == 2 {
  3878. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3879. let alert = NSAlert()
  3880. alert.alertStyle = .warning
  3881. alert.messageText = NSLocalizedString("Warning", comment: "")
  3882. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3883. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3884. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3885. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3886. if returnCode == .alertSecondButtonReturn {
  3887. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3888. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3889. if success {
  3890. self.document?.unlock(withPassword: resultPassword)
  3891. self.clickChildTool(type: .secure, index: 2)
  3892. }
  3893. }
  3894. }
  3895. }
  3896. }
  3897. } else {
  3898. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3899. controller.pdfDocument = self.document
  3900. self.currentWindowController = controller
  3901. controller.batchAction = { [unowned self] controller, files in
  3902. self.view.window?.endSheet((self.currentWindowController.window)!)
  3903. self.currentWindowController = nil
  3904. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3905. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3906. if #available(macOS 10.13, *) {
  3907. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3908. } else {
  3909. baseWindowController.showWindow(nil)
  3910. }
  3911. let arr = NSMutableArray()
  3912. let file = KMBatchOperateFile(filePath: self.listView!.document!.documentURL!.path, type: .RemovePassword)
  3913. file.password = document?.password ?? ""
  3914. arr.add(file)
  3915. // baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .RemovePassword, files: arr as! [KMBatchOperateFile])
  3916. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3917. }
  3918. controller.cancelAction = { [unowned self] controller in
  3919. self.view.window?.endSheet((self.currentWindowController.window)!)
  3920. self.currentWindowController = nil
  3921. }
  3922. controller.doneAction = { [unowned self] controller in
  3923. self.view.window?.endSheet((self.currentWindowController.window)!)
  3924. self.currentWindowController = nil
  3925. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3926. if success {
  3927. // let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3928. let savePanel = NSSavePanel()
  3929. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3930. savePanel.allowedFileTypes = ["pdf"]
  3931. // savePanel.accessoryView = savePanelAccessoryViewController.view
  3932. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3933. guard result == .OK else { return }
  3934. /// 删除安全性设置
  3935. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3936. self.model.isSaveKeyChain = false
  3937. self.listView.document.unlock(withPassword: resultPassword)
  3938. }
  3939. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3940. guard let document = document else { return }
  3941. document.unlock(withPassword: resultPassword)
  3942. let success = document.writeDecrypt(to: savePanel.url)
  3943. if success {
  3944. self.hiddenSecureLimitTip()
  3945. let tip = KMRemovePasswordResultTipView()
  3946. tip.result = .success
  3947. tip.showInView(superView: (self.listView.superview)!)
  3948. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3949. } else {
  3950. self.hiddenSecureLimitTip()
  3951. let tip = KMRemovePasswordResultTipView()
  3952. tip.result = .failure
  3953. tip.showInView(superView: (self.listView.superview)!)
  3954. }
  3955. }
  3956. }
  3957. }
  3958. }
  3959. await NSWindow.currentWindow().beginSheet(controller.window!)
  3960. }
  3961. return
  3962. }
  3963. } else if type == .comparison {
  3964. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3965. if !IAPProductsManager.default().isAvailableAllFunction(){
  3966. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3967. winC?.kEventName = "Reading_Compare_BuyNow"
  3968. winC?.showWindow(nil)
  3969. return
  3970. }
  3971. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3972. self.currentWindowController = controller
  3973. controller.password = self.document?.password ?? ""
  3974. controller.filePath = (self.document?.documentURL.path)!
  3975. controller.cancelAction = { [unowned self] controller in
  3976. self.view.window?.endSheet((self.currentWindowController.window)!)
  3977. self.currentWindowController = nil
  3978. }
  3979. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3980. self.view.window?.endSheet((self.currentWindowController.window)!)
  3981. self.currentWindowController = nil
  3982. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3983. }
  3984. controller.coveringComplete = { [unowned self] controller, document in
  3985. self.view.window?.endSheet((self.currentWindowController.window)!)
  3986. self.currentWindowController = nil
  3987. self.openCoveringCompareVC(with: document)
  3988. }
  3989. if index == 1 {
  3990. controller.fileType = .content
  3991. } else {
  3992. controller.fileType = .coverting
  3993. }
  3994. await NSWindow.currentWindow().beginSheet(controller.window!)
  3995. } else if type == .watermark {
  3996. if !IAPProductsManager.default().isAvailableAllFunction(){
  3997. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3998. if index == 1 {
  3999. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  4000. } else if index == 2 {
  4001. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  4002. }
  4003. winC?.showWindow(nil)
  4004. return
  4005. }
  4006. if !self.documentAllowsEdit() {
  4007. return
  4008. }
  4009. if index == 1 {
  4010. self.watermarkWindowController = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  4011. self.watermarkWindowController!.pdfDocument = self.document
  4012. self.watermarkWindowController!.cancelAction = { [unowned self] controller in
  4013. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  4014. self.km_endSheet()
  4015. }
  4016. self.watermarkWindowController!.operateCallBack = { [unowned self] controller, watermark, countType in
  4017. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  4018. self.km_endSheet()
  4019. let fpath = self.document?.documentURL?.path ?? ""
  4020. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  4021. }
  4022. // NSWindow.currentWindow().beginSheet(controller.window!)
  4023. // NSWindow.currentWindow().beginSheet(self.watermarkWindowController!.window!, completionHandler: nil)
  4024. self.km_beginSheet(windowC: self.watermarkWindowController!)
  4025. } else if index == 2 {
  4026. let watermarks = self.listView.document.watermarks()
  4027. if (watermarks == nil || watermarks!.count <= 0) {
  4028. let alert = NSAlert()
  4029. alert.alertStyle = .warning
  4030. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  4031. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  4032. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  4033. alert.runModal()
  4034. return
  4035. }
  4036. let alert = NSAlert()
  4037. alert.alertStyle = .warning
  4038. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  4039. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  4040. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  4041. let result = alert.runModal()
  4042. if (result != .alertFirstButtonReturn) {
  4043. return
  4044. }
  4045. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  4046. let savePanel = NSSavePanel()
  4047. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  4048. savePanel.allowedFileTypes = ["pdf"]
  4049. savePanel.accessoryView = savePanelAccessoryViewController.view
  4050. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  4051. guard result == .OK else { return }
  4052. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  4053. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  4054. result in
  4055. DispatchQueue.main.async {
  4056. self.listView.layoutDocumentView()
  4057. self.listView.setNeedsDisplayForVisiblePages()
  4058. }
  4059. if (result) {
  4060. let alert = NSAlert()
  4061. alert.alertStyle = .warning
  4062. alert.messageText = NSLocalizedString("Finish", comment: "")
  4063. alert.runModal()
  4064. if savePanel.url?.path == self.listView?.document?.documentURL.path {
  4065. self.setDocument = CPDFDocument(url: savePanel.url!)
  4066. return
  4067. }
  4068. let needOpen = savePanelAccessoryViewController.needOpen
  4069. if needOpen {
  4070. NSDocumentController.shared.km_safe_openDocument(withContentsOf: savePanel.url!, display: true) { document, hasOpen, err in }
  4071. } else {
  4072. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4073. }
  4074. } else {
  4075. let alert = NSAlert()
  4076. alert.alertStyle = .critical
  4077. alert.messageText = NSLocalizedString("Failed", comment: "")
  4078. alert.runModal()
  4079. }
  4080. }
  4081. }
  4082. } else if index == 3 {
  4083. let fpath = self.document?.documentURL?.path ?? ""
  4084. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  4085. } else if index == 4 {
  4086. let fpath = self.document?.documentURL?.path ?? ""
  4087. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  4088. } else if index == 5 {
  4089. self.rightSideViewController.isHidden = false
  4090. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  4091. self.openRightPane()
  4092. return
  4093. }
  4094. } else if type == .background {
  4095. if !IAPProductsManager.default().isAvailableAllFunction(){
  4096. let winC = KMPurchaseCompareWindowController.sharedInstance()
  4097. if index == 1 {
  4098. winC?.kEventName = "Reading_AddBackground_BuyNow"
  4099. } else if index == 2 {
  4100. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  4101. }
  4102. winC?.showWindow(nil)
  4103. return
  4104. }
  4105. if !self.documentAllowsEdit() {
  4106. return
  4107. }
  4108. if index == 1 {
  4109. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  4110. self.currentWindowController = controller
  4111. controller.pdfDocument = self.document
  4112. controller.cancelAction = { [unowned self] controller in
  4113. self.view.window?.endSheet((self.currentWindowController.window)!)
  4114. self.currentWindowController = nil
  4115. }
  4116. controller.operateCallBack = { [unowned self] controller, background, countType in
  4117. let fpath = self.document?.documentURL?.path ?? ""
  4118. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  4119. }
  4120. await NSWindow.currentWindow().beginSheet(controller.window!)
  4121. } else if index == 2 {
  4122. guard let document = self.document else { return }
  4123. if !document.allowsPrinting || !document.allowsCopying {
  4124. let alert = NSAlert()
  4125. alert.alertStyle = .critical
  4126. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4127. alert.runModal()
  4128. return
  4129. }
  4130. guard let documentURL = document.documentURL else { return }
  4131. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  4132. let savePanel = NSSavePanel()
  4133. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  4134. savePanel.allowedFileTypes = ["pdf"]
  4135. savePanel.accessoryView = savePanelAccessoryViewController.view
  4136. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  4137. guard result == .OK else { return }
  4138. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  4139. if success == 1 {
  4140. if savePanel.url?.path == self.listView?.document?.documentURL.path {
  4141. self.setDocument = CPDFDocument(url: savePanel.url!)
  4142. return
  4143. }
  4144. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  4145. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  4146. } else {
  4147. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  4148. }
  4149. }
  4150. })
  4151. }
  4152. } else if index == 3 {
  4153. let fpath = self.document?.documentURL?.path ?? ""
  4154. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  4155. } else if index == 4 {
  4156. let fpath = self.document?.documentURL?.path ?? ""
  4157. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  4158. } else if index == 5 {
  4159. self.rightSideViewController.isHidden = false
  4160. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  4161. self.openRightPane()
  4162. return
  4163. }
  4164. } else if type == .measure {
  4165. if !IAPProductsManager.default().isAvailableAllFunction(){
  4166. let winC = KMPurchaseCompareWindowController.sharedInstance()
  4167. winC?.kEventName = "Reading_Measure_BuyNow"
  4168. winC?.showWindow(nil)
  4169. return
  4170. }
  4171. if !self.documentAllowsEdit() {
  4172. return
  4173. }
  4174. self.listView.toolMode = .measureToolMode
  4175. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  4176. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4177. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  4178. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4179. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  4180. areaMeasureInfoWindowController?.hideFloatingWindow()
  4181. }
  4182. if distanceMeasureInfoWindowController == nil {
  4183. let measureInfo = CPDFDistanceMeasureInfo()
  4184. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  4185. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  4186. distanceMeasureInfoWindowController?.delegate = self
  4187. }
  4188. if perimeterMeasureInfoWindowController == nil {
  4189. let measureInfo = CPDFPerimeterMeasureInfo()
  4190. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  4191. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  4192. perimeterMeasureInfoWindowController?.delegate = self
  4193. }
  4194. if areaMeasureInfoWindowController == nil {
  4195. let measureInfo = CPDFAreaMeasureInfo()
  4196. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  4197. areaMeasureInfoWindowController?.measureInfo = measureInfo
  4198. areaMeasureInfoWindowController?.delegate = self
  4199. }
  4200. if index == 1 {
  4201. self.listView.annotationType = .line
  4202. let winW: CGFloat = 300
  4203. let rightW: CGFloat = 270
  4204. var winFrame = self.view.window?.frame ?? .zero
  4205. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4206. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4207. distanceMeasureInfoWindowController?.showWindow(nil)
  4208. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4209. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4210. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4211. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4212. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4213. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4214. self.trackEvent(toolMode: .measureToolMode)
  4215. } else if index == 2 {
  4216. self.listView.annotationType = .polyLine
  4217. let winW: CGFloat = 300
  4218. let rightW: CGFloat = 270
  4219. var winFrame = self.view.window?.frame ?? .zero
  4220. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4221. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4222. perimeterMeasureInfoWindowController?.showWindow(nil)
  4223. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4224. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4225. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4226. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4227. self.trackEvent(toolMode: .measureToolMode)
  4228. } else if index == 3 {
  4229. self.listView.annotationType = .polyGon
  4230. let winW: CGFloat = 300
  4231. let rightW: CGFloat = 270
  4232. var winFrame = self.view.window?.frame ?? .zero
  4233. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4234. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4235. areaMeasureInfoWindowController?.showWindow(nil)
  4236. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4237. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4238. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4239. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4240. self.trackEvent(toolMode: .measureToolMode)
  4241. } else if index == 4 {
  4242. self.listView.annotationType = .square
  4243. let winW: CGFloat = 300
  4244. let rightW: CGFloat = 270
  4245. var winFrame = self.view.window?.frame ?? .zero
  4246. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4247. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4248. areaMeasureInfoWindowController?.showWindow(nil)
  4249. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4250. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4251. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4252. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4253. self.trackEvent(toolMode: .measureToolMode)
  4254. } else {
  4255. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  4256. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4257. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  4258. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4259. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  4260. areaMeasureInfoWindowController?.hideFloatingWindow()
  4261. }
  4262. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = false
  4263. }
  4264. self.rightSideViewController.reloadDataWithPDFView(pdfView: listView, isShow: true)
  4265. self.openRightPane()
  4266. }
  4267. }
  4268. }
  4269. // func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  4270. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4271. //// batchWindowController.window?.makeKeyAndOrderFront("")
  4272. //
  4273. // var array: [KMBatchOperateFile] = []
  4274. // for file in files ?? [] {
  4275. // let batchOperateFile = KMBatchOperateFile(filePath: file.filePath, type: type)
  4276. // array.append(batchOperateFile)
  4277. // }
  4278. // batchWindowController.switchToOperateType(type, files: array)
  4279. // batchWindowController.window?.makeKeyAndOrderFront("")
  4280. // }
  4281. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  4282. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4283. var array: [KMBatchOperateFile] = []
  4284. for fpath in filepaths ?? [] {
  4285. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  4286. array.append(batchOperateFile)
  4287. }
  4288. batchWindowController.switchToOperateType(type, files: array)
  4289. batchWindowController.window?.makeKeyAndOrderFront("")
  4290. }
  4291. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  4292. self.toolbarItemClickForExitMode(toolbarItem)
  4293. if let itemID = toolbarItem.itemIdentifier {
  4294. if isMainToolItem(itemID) {
  4295. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  4296. openNewWindowAlertWindow()
  4297. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  4298. self.changePDFViewGoToPreviousPageAction()
  4299. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4300. let isSelected = toolbarItem.isSelected
  4301. self.toolbarController.toolbarType = isSelected ? .None : .viewSetting
  4302. toolbarItem.isSelected = !isSelected
  4303. if toolbarItem.isSelected {
  4304. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  4305. self.rightSideViewController.isHidden = false
  4306. self.rightSideViewController.mainController = self
  4307. self.rightSideViewController.subViewType = .ViewSettings
  4308. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4309. self.openRightPane()
  4310. }else{
  4311. self.rightSideViewController.isHidden = true
  4312. self.rightSideViewController.subViewType = .AnnotationProperts
  4313. closeRightPane()
  4314. }
  4315. if toolbarItem.isSelected {
  4316. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  4317. }
  4318. let rightItem = self.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  4319. if isSelected {
  4320. rightItem?.isSelected = false
  4321. } else {
  4322. rightItem?.isSelected = true
  4323. }
  4324. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  4325. toolbarItem.isSelected = !toolbarItem.isSelected
  4326. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  4327. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4328. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  4329. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  4330. }
  4331. toolbarItem.isSelected = !toolbarItem.isSelected
  4332. self.toggleRightPane()
  4333. if self.listView.toolMode == .editPDFToolMode {
  4334. self.editPDFHanddler.rightSideLastState = toolbarItem.isSelected ? .open : .close
  4335. }
  4336. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  4337. self.listView.toolMode = .redactToolMode
  4338. self.enterRedact()
  4339. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  4340. showOCRWindow()
  4341. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  4342. self.showAITypeChooseView(aiConfigType: .none)
  4343. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  4344. if self.canEnterDigitalSign() == false {
  4345. Task {
  4346. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4347. }
  4348. return
  4349. }
  4350. toolbarItem.isSelected = !toolbarItem.isSelected
  4351. self.toolbarController.lastItemBox = toolbarItem
  4352. if toolbarItem.isSelected {
  4353. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4354. }
  4355. self.enterDigitalSign()
  4356. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  4357. self.showPrintWindow()
  4358. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  4359. self.enterPresentation()
  4360. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  4361. let isSelected = toolbarItem.isSelected
  4362. self.toolbarController.toolbarType = isSelected ? .None : .sign
  4363. toolbarItem.isSelected = !isSelected
  4364. self.toolbarController.lastItemBox = toolbarItem
  4365. }
  4366. } else {
  4367. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  4368. toolbarItem.isSelected = false
  4369. let windowC = KMToolbarCustomWindowController()
  4370. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  4371. windowC.resetCallback = { [weak self] in
  4372. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4373. toolbar?.reloadData()
  4374. }
  4375. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  4376. if resp == .OK {
  4377. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4378. toolbar?.reloadData()
  4379. }
  4380. }
  4381. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  4382. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  4383. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  4384. self.trackEvent_print()
  4385. self.showPrintWindow()
  4386. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  4387. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  4388. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  4389. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  4390. windowC.callBack = { [weak self] string in
  4391. if (string.isEmpty == false) {
  4392. self?.listView.addTextField(subType: .profile, string: string)
  4393. }
  4394. self?.km_endSheet()
  4395. }
  4396. self.km_beginSheet(windowC: windowC)
  4397. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  4398. toolbarItem.isSelected = !toolbarItem.isSelected
  4399. rightSideViewController.mainController = self
  4400. self.rightSideViewController.isHidden = toolbarItem.isSelected ? false : true
  4401. self.rightSideViewController.subViewType = .ViewSettings
  4402. // self.toggleRightPane()
  4403. self.listView.annotationType = .unkown
  4404. if toolbarItem.isSelected {
  4405. self.rightSideViewController.isHidden = false
  4406. self.rightSideViewController.mainController = self
  4407. self.rightSideViewController.subViewType = .ViewSettings
  4408. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4409. self.openRightPane()
  4410. }else{
  4411. self.rightSideViewController.isHidden = true
  4412. self.rightSideViewController.subViewType = .AnnotationProperts
  4413. closeRightPane()
  4414. }
  4415. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  4416. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  4417. self.listView.takeSnapshot(nil)
  4418. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  4419. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  4420. self.listView.annotationType = .unkown
  4421. self.showTTSWindow()
  4422. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4423. self.showOCRWindow()
  4424. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  4425. toolbarItem.isSelected = false
  4426. self.imageAnnotation(toolbarItem)
  4427. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  4428. self.tableAnnotation(toolbarItem)
  4429. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  4430. self.leftSideViewController.insertPDF(nil)
  4431. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4432. let windowC = SplitWindowController(document: self.listView.document)
  4433. self.km_beginSheet(windowC: windowC)
  4434. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  4435. if self.canEnterDigitalSign() == false {
  4436. Task {
  4437. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4438. }
  4439. return
  4440. }
  4441. toolbarItem.isSelected = !toolbarItem.isSelected
  4442. self.toolbarController.lastItemBox = toolbarItem
  4443. if toolbarItem.isSelected {
  4444. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4445. }
  4446. self.enterDigitalSign()
  4447. } else if itemID == KMToolbarMeasureItemIdentifier {
  4448. if toolbarItem.isSelected {
  4449. toolbarItem.isSelected = false
  4450. self.listView.toolMode = .textToolMode
  4451. self.listView.annotationType = .unkown
  4452. }
  4453. }
  4454. }
  4455. }
  4456. }
  4457. func openNewWindowAlertWindow() {
  4458. var needShowChooseWindow = false
  4459. //#if VERSION_FREE
  4460. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  4461. needShowChooseWindow = true
  4462. }
  4463. //#endif
  4464. if needShowChooseWindow {
  4465. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  4466. if preferenceNoteShow {
  4467. menuItemAction_newTagPageToNewWindow("")
  4468. } else {
  4469. if !KMDataManager.default.isTabbingWin{
  4470. KMDataManager.default.isTabbingWin = true
  4471. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  4472. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  4473. KMDataManager.default.isTabbingWin = false
  4474. if continueOrNot {
  4475. self?.reopenDocument(forPaths: [])
  4476. } else {
  4477. }
  4478. }
  4479. self.km_beginSheet(windowC: tabbingWin)
  4480. }
  4481. }
  4482. }else{
  4483. handleTabbingLogic()
  4484. }
  4485. }
  4486. func reopenDocument(forPaths paths: [String]) -> Void {
  4487. let browser = KMBrowser.init() as KMBrowser
  4488. browser.windowController = KMBrowserWindowController.init(browser: browser)
  4489. browser.addHomeTabContents()
  4490. browser.windowController.showWindow(self)
  4491. }
  4492. func handleTabbingLogic() {
  4493. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  4494. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  4495. }
  4496. func showTTSWindow() {
  4497. var lastPDFView: CPDFView?
  4498. let ttsView = KMTTSWindowController.share
  4499. if (ttsView.window?.isVisible ?? false) {
  4500. lastPDFView = ttsView.pdfView
  4501. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  4502. lastPDFView = nil
  4503. ttsView.window?.orderOut(nil)
  4504. } else {
  4505. ttsView.pdfView = self.listView
  4506. ttsView.showWindow(nil)
  4507. }
  4508. } else {
  4509. ttsView.pdfView = self.listView
  4510. ttsView.showWindow(nil)
  4511. }
  4512. // weak var blockSelf = self
  4513. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  4514. if isCloseWindow {
  4515. // for item in blockSelf?.toolbar.items ?? [] {
  4516. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  4517. // item.isSelected = false
  4518. // }
  4519. // }
  4520. }
  4521. }
  4522. if let currentSelection = self.listView.currentSelection {
  4523. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  4524. ttsView.startSpeakingPDFSelection(currentSelection)
  4525. }
  4526. }
  4527. if let lastPDFView = lastPDFView {
  4528. lastPDFView.setHighlightedSelections([])
  4529. ttsView.stopSpeaking()
  4530. }
  4531. }
  4532. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4533. self.toolbarItemClickForExitMode(toolbarItem)
  4534. let itemId = toolbarItem.itemIdentifier
  4535. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  4536. self.clickChildTool(type: .watermark, index: index)
  4537. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  4538. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  4539. self.clickChildTool(type: .background, index: index)
  4540. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  4541. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  4542. self.clickChildTool(type: .headerAndFooter, index: index)
  4543. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  4544. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  4545. self.clickChildTool(type: .bates, index: index)
  4546. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  4547. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  4548. self.clickChildTool(type: .measure, index: index)
  4549. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  4550. self.clickChildTool(type: .comparison, index: index)
  4551. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  4552. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  4553. convertToImg(index: index)
  4554. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  4555. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  4556. extractImageAction(num: index)
  4557. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  4558. self.createPdf(index: index)
  4559. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  4560. if index == 2 { // 裁剪当前页面
  4561. self.cropCurrentPage()
  4562. } else if index == 3 { // Auto Crop – Separate
  4563. self.smart_cropAllPage()
  4564. } else if index == 4 { // Auto Crop – Combined
  4565. self.auto_cropAllPage()
  4566. } else if index == 5 { // Select Area
  4567. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  4568. }
  4569. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  4570. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  4571. self.clickChildTool(type: .secure, index: index)
  4572. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  4573. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  4574. if index == 11 {
  4575. self.view.window?.makeFirstResponder(nil)
  4576. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  4577. self.currentWindowController = winC
  4578. winC.replaceCallback = { [weak self] in
  4579. let toolMode = self?.listView?.toolMode ?? .none
  4580. let isEditing = self?.listView?.isEditing() ?? false
  4581. if toolMode == .editPDFToolMode && isEditing {
  4582. } else { // 进入内容编辑模式
  4583. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4584. }
  4585. }
  4586. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4587. // - (winC.window?.frame.size.width ?? 0)
  4588. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4589. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  4590. let winFramePoint = NSPoint(x: x, y: y)
  4591. winC.window?.setFrameOrigin(winFramePoint)
  4592. winC.startModal(nil)
  4593. } else if index == 12 {
  4594. if IAPProductsManager.default().isAvailableAllFunction() == false {
  4595. let winC = KMPurchaseCompareWindowController.sharedInstance()
  4596. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  4597. winC?.showWindow(nil)
  4598. return
  4599. }
  4600. self.view.window?.makeFirstResponder(nil)
  4601. let toolMode = self.listView?.toolMode ?? .none
  4602. let isEditing = self.listView?.isEditing() ?? false
  4603. if toolMode == .editPDFToolMode && isEditing {
  4604. } else { // 进入内容编辑模式
  4605. self.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4606. }
  4607. self.trackEvent_replace()
  4608. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  4609. self.currentWindowController = winC
  4610. winC.replaceCallback = { [weak self] in
  4611. let toolMode = self?.listView?.toolMode ?? .none
  4612. let isEditing = self?.listView?.isEditing() ?? false
  4613. if toolMode == .editPDFToolMode && isEditing {
  4614. } else { // 进入内容编辑模式
  4615. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4616. }
  4617. }
  4618. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4619. // - (winC.window?.frame.size.width ?? 0)
  4620. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4621. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  4622. let winFramePoint = NSPoint(x: x, y: y)
  4623. winC.window?.setFrameOrigin(winFramePoint)
  4624. winC.startModal(nil)
  4625. } else {
  4626. self.toolbarController.showFindBar()
  4627. }
  4628. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4629. toolbarItem.isSelected = !toolbarItem.isSelected
  4630. self.toggleRightPane()
  4631. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4632. self.toolbarController.toolbarType = .viewSetting
  4633. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4634. self.showOCRWindow()
  4635. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  4636. if index == 1 {
  4637. self.showAITypeChooseView(aiConfigType: .summarize)
  4638. } else if index == 2 {
  4639. self.showAITypeChooseView(aiConfigType: .reWriting)
  4640. } else if index == 3 {
  4641. self.showAITypeChooseView(aiConfigType: .proofreading)
  4642. } else if index == 4 {
  4643. self.showAITypeChooseView(aiConfigType: .translate)
  4644. }
  4645. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  4646. self.showOCRWindow()
  4647. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  4648. self.toolbarController.toolbarType = .editPDF
  4649. self.enterEditPDF()
  4650. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  4651. self.toolbarController.toolbarType = .FillSign
  4652. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  4653. self.toolbarController.toolbarType = .Form
  4654. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  4655. if self.canEnterDigitalSign() == false {
  4656. Task {
  4657. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4658. }
  4659. return
  4660. }
  4661. toolbarItem.isSelected = !toolbarItem.isSelected
  4662. self.toolbarController.lastItemBox = toolbarItem
  4663. if toolbarItem.isSelected {
  4664. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4665. }
  4666. self.enterDigitalSign()
  4667. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  4668. if self.canEnterDigitalSign() == false {
  4669. Task {
  4670. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4671. }
  4672. return
  4673. }
  4674. toolbarItem.isSelected = !toolbarItem.isSelected
  4675. self.toolbarController.lastItemBox = toolbarItem
  4676. if toolbarItem.isSelected {
  4677. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4678. }
  4679. self.enterDigitalSign()
  4680. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  4681. self.showAITypeChooseView(aiConfigType: .none)
  4682. } else if itemId == KMToolbarToolCompressItemIdentifier {
  4683. self.clickChildTool(type: .compress, index: 0)
  4684. } else if itemId == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4685. let windowC = SplitWindowController(document: self.listView.document)
  4686. self.km_beginSheet(windowC: windowC)
  4687. } else if itemId == KMToolbarToolMergeItemIdentifier {
  4688. self.clickChildTool(type: .merge, index: 0)
  4689. } else if itemId == KMToolbarPageEditInsetItemIdentifier {
  4690. self.leftSideViewController.insertPDF(nil)
  4691. } else if itemId == KMToolbarShowToolbarItemIdentifier {
  4692. self.showOrHideNotes()
  4693. } else if itemId == KMAnnotationTableToolbarItemIdentifier {
  4694. self.tableAnnotation(toolbarItem)
  4695. } else if itemId == KMToolbarConversionTextItemIdentifier {
  4696. self.clickChildTool(type: .conversion_text, index: 0)
  4697. } else if itemId == KMToolbarConversionHTMLItemIdentifier {
  4698. self.clickChildTool(type: .html, index: 0)
  4699. } else if itemId == KMToolbarConversionCSVItemIdentifier {
  4700. self.clickChildTool(type: .csv, index: 0)
  4701. } else if itemId == KMToolbarConversionRTFItemIdentifier {
  4702. self.clickChildTool(type: .rtf, index: 0)
  4703. } else if itemId == KMToolbarConversionPPTItemIdentifier {
  4704. self.clickChildTool(type: .ppt, index: 0)
  4705. } else if itemId == KMToolbarConversionExcelItemIdentifier {
  4706. self.clickChildTool(type: .excel, index: 0)
  4707. } else if itemId == KMToolbarConversionWordItemIdentifier {
  4708. self.clickChildTool(type: .word, index: 0)
  4709. } else if itemId == KMToolbarConversionOtherItemIdentifier {
  4710. if index == KMPDFConvertType.text.rawValue {
  4711. self.clickChildTool(type: .conversion_text, index: 0)
  4712. } else if index == KMPDFConvertType.rtf.rawValue {
  4713. self.clickChildTool(type: .rtf, index: 0)
  4714. } else if index == KMPDFConvertType.html.rawValue {
  4715. self.clickChildTool(type: .html, index: 0)
  4716. } else if index == KMPDFConvertType.csv.rawValue {
  4717. self.clickChildTool(type: .csv, index: 0)
  4718. } else if index == KMPDFConvertType.json.rawValue {
  4719. self.clickChildTool(type: .json, index: 0)
  4720. }
  4721. }
  4722. }
  4723. func convertToImg(index: Int) {
  4724. var convertT: KMConvertType = .JPEG
  4725. switch index {
  4726. case 7:
  4727. convertT = .JPEG
  4728. case 8:
  4729. convertT = .JPG
  4730. case 9:
  4731. convertT = .PNG
  4732. case 10:
  4733. convertT = .GIF
  4734. case 11:
  4735. convertT = .TIFF
  4736. case 12:
  4737. convertT = .TGA
  4738. case 13:
  4739. convertT = .BMP
  4740. default:
  4741. convertT = .JPEG
  4742. }
  4743. showAllConvertWindow(convertT: convertT)
  4744. }
  4745. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  4746. // if self.searchResults.count == 0 {
  4747. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4748. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4749. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  4750. // }
  4751. var row = max(searchIndex - 1, 0)
  4752. if forward {
  4753. row = searchIndex + 1
  4754. }
  4755. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4756. let model = self.searchResults[row]
  4757. if model.selection != nil {
  4758. self.listView.setHighlightedSelections([])
  4759. self.listView.go(to: model.selection, animated: true)
  4760. self.listView.setHighlightedSelection(model.selection, animated: true)
  4761. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4762. searchIndex = row
  4763. }
  4764. }
  4765. self.leftSideViewController.showSearchMode(searchString)
  4766. }
  4767. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  4768. // if self.searchResults.count == 0 {
  4769. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4770. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4771. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  4772. // }
  4773. var row = max(searchIndex - 1, 0)
  4774. if forward {
  4775. row = searchIndex + 1
  4776. }
  4777. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4778. let model = self.searchResults[row]
  4779. if model.selection != nil {
  4780. self.listView.setHighlightedSelections([])
  4781. self.listView.go(to: model.selection, animated: true)
  4782. self.listView.setHighlightedSelection(model.selection, animated: true)
  4783. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4784. searchIndex = row
  4785. }
  4786. }
  4787. }
  4788. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  4789. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4790. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  4791. self.leftSideViewController.showSearchMode(searchString)
  4792. }
  4793. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4794. let itemId = toolbarItem.itemIdentifier
  4795. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  4796. if index == 1 {
  4797. if self.listView.canGoToFirstPage() {
  4798. self.listView.goToFirstPage(nil)
  4799. }
  4800. } else if index == 2 {
  4801. if self.listView.canGoToLastPage() {
  4802. self.listView.goToLastPage(nil)
  4803. }
  4804. }
  4805. } else if itemId == KMDocumentPageInputToolbarItemIdentifier {
  4806. var valid = false
  4807. if let number = Int(info as? String ?? "") {
  4808. let cnt = self.listView?.document?.pageCount ?? 0
  4809. if number > 0 && number <= cnt {
  4810. self.listView.go(toPageIndex: number-1, animated: false)
  4811. valid = true
  4812. }
  4813. }
  4814. if valid == false {
  4815. Task {@MainActor in
  4816. _ = await KMAlertTool.runModel(message: NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))
  4817. }
  4818. }
  4819. }
  4820. }
  4821. }
  4822. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  4823. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  4824. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4825. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  4826. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4827. distanceSettingWC.delegate = self
  4828. distanceSettingWC.startModal("")
  4829. }
  4830. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4831. }
  4832. }
  4833. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  4834. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  4835. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  4836. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  4837. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4838. distanceSettingWC.delegate = self
  4839. distanceSettingWC.startModal("")
  4840. }
  4841. }
  4842. // MARK: CAreaMeasureInfoWindowControllerDelegate
  4843. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  4844. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  4845. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  4846. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  4847. areaSettingWC.delegate = self
  4848. areaSettingWC.startModal("")
  4849. }
  4850. }
  4851. // MARK: CDistanceSettingWindowControllerDelegate
  4852. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  4853. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  4854. if distanceMeasureInfo != nil {
  4855. if self.listView.activeAnnotations.count > 0 {
  4856. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  4857. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  4858. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4859. }
  4860. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  4861. } else {
  4862. distanceMeasureInfo?.leadLength = 0
  4863. self.listView.distanceMeasureInfo = distanceMeasureInfo
  4864. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  4865. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4866. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4867. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4868. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4869. }
  4870. if let data = self.listView?.activeAnnotation {
  4871. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4872. }
  4873. }
  4874. self.distanceMeasureInfoWindowController?.showWindow(self)
  4875. }
  4876. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  4877. if perimeterMeasureInfo != nil {
  4878. if self.listView.activeAnnotations.count > 0 {
  4879. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  4880. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  4881. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4882. }
  4883. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  4884. } else {
  4885. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  4886. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  4887. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4888. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4889. }
  4890. if let data = self.listView?.activeAnnotation {
  4891. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4892. }
  4893. }
  4894. self.perimeterMeasureInfoWindowController?.showWindow(self)
  4895. }
  4896. }
  4897. // MARK: CAreaSettingWindowControllerDelegate
  4898. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  4899. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  4900. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  4901. if measureInfo != nil {
  4902. if self.listView.activeAnnotations.count > 0 {
  4903. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4904. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4905. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4906. }
  4907. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4908. } else {
  4909. self.listView.squareAreaMeasureInfo = measureInfo
  4910. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  4911. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4912. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4913. }
  4914. }
  4915. self.areaMeasureInfoWindowController?.showWindow(self)
  4916. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  4917. if measureInfo != nil {
  4918. if self.listView.activeAnnotations.count > 0 {
  4919. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4920. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4921. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4922. }
  4923. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4924. } else {
  4925. self.listView.polygonAreaMeasureInfo = measureInfo
  4926. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  4927. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4928. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4929. }
  4930. }
  4931. self.areaMeasureInfoWindowController?.showWindow(self)
  4932. } else {
  4933. if measureInfo != nil {
  4934. if self.listView.activeAnnotations.count > 0 {
  4935. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4936. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4937. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4938. }
  4939. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4940. }
  4941. }
  4942. self.areaMeasureInfoWindowController?.showWindow(self)
  4943. }
  4944. if measureInfo != nil {
  4945. if let data = self.listView?.activeAnnotation {
  4946. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4947. }
  4948. }
  4949. }
  4950. }
  4951. // MARK: -
  4952. // MARK: - Mouse
  4953. extension KMMainViewController {
  4954. override func mouseDown(with event: NSEvent) {
  4955. super.mouseDown(with: event)
  4956. // KMPrint("KMMainViewController mouseDown")
  4957. self.leftSideViewCancelSelect()
  4958. self.pageNumberDisplayView.isEdit = false
  4959. }
  4960. }
  4961. //MARK: LeftSideViewController
  4962. extension KMMainViewController {
  4963. func leftSideViewCancelSelect() {
  4964. // switch self.leftSideViewController.type.methodType {
  4965. // case .Thumbnail:
  4966. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  4967. // break
  4968. // case .Outline:
  4969. //// self.leftSideViewController.outlineViewController.cancelSelect()
  4970. // break
  4971. // case .BookMark:
  4972. //// self.leftSideViewController.bookViewController.cancelSelect()
  4973. // break
  4974. // case .Search:
  4975. //// self.leftSideViewController.searchViewController.cancelSelect()
  4976. // break
  4977. // case .Annotation:
  4978. //// self.leftSideViewController.annotationViewController.cancelSelect()
  4979. // break
  4980. // default:
  4981. if self.listView.isEditing() {
  4982. if self.listView.editingAreas() != nil &&
  4983. self.listView.editingAreas().count != 0 {
  4984. let areas = self.listView.editingAreas().first
  4985. if areas is CPDFEditTextArea {
  4986. self.listView.clearEditingSelectCharItem()
  4987. self.listView.updateEditing([])
  4988. KMPrint("取消选中")
  4989. }
  4990. }
  4991. }
  4992. // KMPrint("其他")
  4993. // }
  4994. }
  4995. }
  4996. extension KMMainViewController: KMReadModelViewDelegate {
  4997. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4998. self.listView.goToFirstPage(nil)
  4999. }
  5000. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  5001. self.listView.goToPreviousPage(nil)
  5002. }
  5003. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  5004. self.listView.goToNextPage(nil)
  5005. }
  5006. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  5007. self.listView.goToLastPage(nil)
  5008. }
  5009. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  5010. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  5011. }
  5012. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  5013. var scale: Double = 1.0
  5014. switch type {
  5015. case .fitWidth:
  5016. self.listView.autoScales = !self.listView.autoScales
  5017. scale = self.listView.scaleFactor
  5018. break
  5019. case .actualSize:
  5020. if self.listView.scaleFactor != 1.0 {
  5021. self.listView.scaleFactor = 1.0
  5022. self.listView.autoScales = false
  5023. }
  5024. scale = self.listView.scaleFactor
  5025. break
  5026. case .autoSize:
  5027. self.listView.autoScales = true
  5028. self.listView.autoScales = false
  5029. scale = self.listView.scaleFactor
  5030. break
  5031. case ._10:
  5032. scale = 0.1
  5033. break
  5034. case ._25:
  5035. scale = 0.25
  5036. break
  5037. case ._50:
  5038. scale = 0.5
  5039. break
  5040. case ._100:
  5041. scale = 1.0
  5042. break
  5043. case ._150:
  5044. scale = 1.5
  5045. break
  5046. case ._200:
  5047. scale = 2.0
  5048. break
  5049. case ._400:
  5050. scale = 4.0
  5051. break
  5052. case ._800:
  5053. scale = 8.0
  5054. break
  5055. default:
  5056. break
  5057. }
  5058. self.listView.scaleFactor = scale
  5059. self.toolbarController.mainViewController?.childToolbarController.zoomTextField?.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  5060. }
  5061. func cancelReadModel(view: KMReadModelView, sender: Any) {
  5062. if self.isReadMode {
  5063. self.closeReadModel()
  5064. }
  5065. }
  5066. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  5067. // if self.readModelViewWidthConstraint.constant != width {
  5068. self.readModelViewWidthConstraint.constant = width
  5069. // }
  5070. }
  5071. // MARK: - KMPresentationTopViewController (幻灯片)
  5072. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5073. if self.canExitPresentation() == true {
  5074. let mainDocument = self.myDocument as? KMMainDocument
  5075. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  5076. browserWindowController?.exitFullscreen()
  5077. }
  5078. }
  5079. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5080. listView.presentationDrawView?.clear()
  5081. }
  5082. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5083. let presentationDrawView = listView.presentationDrawView
  5084. if presentationDrawView?.canUndo() == true {
  5085. presentationDrawView?.undo()
  5086. }
  5087. }
  5088. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  5089. listView.isPresentationMode = isSeletion
  5090. if listView.isEnterPresentationDrawMode() == true {
  5091. listView.exitPresentationDrawMode()
  5092. }
  5093. }
  5094. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  5095. if color == nil{
  5096. listView.exitPresentationDrawMode()
  5097. } else {
  5098. if listView.isEnterPresentationDrawMode() == false {
  5099. listView.enterPresentationDrawMode()
  5100. }
  5101. listView.changePresentationDrawModelColor(color)
  5102. }
  5103. }
  5104. }
  5105. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  5106. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  5107. self.listView.go(toPageIndex: pageIndex, animated: true)
  5108. }
  5109. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  5110. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  5111. self.tipCurrentPageBoxWidthConstraint.constant = width
  5112. }
  5113. }
  5114. func commitEditingIfNeed() {
  5115. self.editPDFHanddler.commitEditing()
  5116. }
  5117. }
  5118. extension KMMainViewController: KMInteractionProviderProtocol {
  5119. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  5120. let view = self.listView
  5121. if(interactionMode == .presentation) {
  5122. if view?.presentationDrawView == nil {
  5123. view?.createPresentationDraw()
  5124. }
  5125. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  5126. presentationTopViewController?.pdfView = view
  5127. presentationTopViewController?.delegate = self
  5128. presentationTopViewController?.isSelectionPre = true
  5129. listView.isPresentationMode = true
  5130. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  5131. if((presentationTopViewController) != nil) {
  5132. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  5133. }
  5134. } else {
  5135. view?.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  5136. }
  5137. if let v = view {
  5138. fullScreenWindow.contentView?.addSubview(v)
  5139. if(interactionMode == .presentation) {
  5140. v.mas_makeConstraints { make in
  5141. make?.left.mas_equalTo()(0)
  5142. make?.right.mas_equalTo()(0)
  5143. make?.top.mas_equalTo()(presentationTopViewController!.view.frame.height)
  5144. make?.bottom.mas_equalTo()(0)
  5145. }
  5146. }
  5147. }
  5148. return view
  5149. }
  5150. }
  5151. // MARK: - Analytics (埋点)
  5152. extension KMMainViewController {
  5153. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  5154. if (type == .Annatiton) {
  5155. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  5156. } else if (type == .editPDF) {
  5157. } else if (type == .Page) {
  5158. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  5159. } else if (type == .Conversion) {
  5160. } else if (type == .Tool) {
  5161. }
  5162. }
  5163. func trackEvent_aiTranslate() -> Void {
  5164. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  5165. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5166. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5167. }
  5168. func trackEvent_print() -> Void {
  5169. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  5170. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5171. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5172. }
  5173. func trackEvent_share() -> Void {
  5174. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  5175. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5176. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5177. }
  5178. func trackEvent_upgrade() -> Void {
  5179. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  5180. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5181. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5182. }
  5183. func trackEvent(annotationType type: CAnnotationType) -> Void {
  5184. if (type == .highlight) {
  5185. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  5186. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  5187. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5188. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5189. } else if (type == .underline) {
  5190. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  5191. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  5192. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5193. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5194. } else if (type == .strikeOut) {
  5195. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  5196. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  5197. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5198. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5199. } else if (type == .ink) {
  5200. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  5201. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  5202. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5203. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5204. } else if (type == .freeText) {
  5205. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  5206. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  5207. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5208. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5209. } else if (type == .anchored) {
  5210. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  5211. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  5212. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5213. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5214. } else if (type == .square) {
  5215. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  5216. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  5217. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5218. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5219. } else if (type == .link) {
  5220. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  5221. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  5222. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5223. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5224. } else if (type == .stamp) {
  5225. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  5226. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  5227. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5228. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5229. } else if (type == .signSignature) {
  5230. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  5231. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  5232. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5233. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5234. } else if (type == .circle) {
  5235. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  5236. } else if (type == .arrow) {
  5237. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  5238. } else if (type == .line) {
  5239. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  5240. } else if (type == .addText) {
  5241. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  5242. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  5243. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5244. } else if (type == .addImage) {
  5245. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  5246. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  5247. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  5248. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5249. } else if (type == .textField) {
  5250. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  5251. } else if (type == .checkBox) {
  5252. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  5253. } else if (type == .radioButton) {
  5254. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  5255. } else if (type == .listMenu) {
  5256. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  5257. } else if (type == .comboBox) {
  5258. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  5259. } else if (type == .actionButton) {
  5260. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  5261. } else if (type == .actionButton) {
  5262. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  5263. } else if (type == .signature) {
  5264. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  5265. } else if (type == .squiggly) {
  5266. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  5267. } else if (type == .eraser) {
  5268. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  5269. }
  5270. }
  5271. func trackEvent(toolMode mode: CToolMode) -> Void {
  5272. if (mode == .selectToolMode) {
  5273. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  5274. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5275. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5276. } else if (mode == .moveToolMode) {
  5277. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  5278. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5279. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5280. } else if mode == .measureToolMode {
  5281. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  5282. }
  5283. }
  5284. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  5285. if (type == .word) {
  5286. } else if (type == .excel) {
  5287. } else if (type == .ppt) {
  5288. } else if (type == .rtf) {
  5289. } else if (type == .csv) {
  5290. } else if (type == .html) {
  5291. } else if (type == .conversion_text) {
  5292. } else if (type == .conversion_image) {
  5293. } else if (type == .compress) {
  5294. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  5295. } else if (type == .merge) {
  5296. } else if (type == .secure) {
  5297. } else if (type == .crop) {
  5298. } else if type == .json {
  5299. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  5300. }
  5301. }
  5302. func trackEvent_setPassword() -> Void {
  5303. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  5304. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  5305. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5306. }
  5307. func trackEvent_removePassword() -> Void {
  5308. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  5309. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  5310. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5311. }
  5312. func trackEvent_replace() -> Void {
  5313. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  5314. }
  5315. }
  5316. extension KMMainViewController {
  5317. //文件对比
  5318. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  5319. self.isCompareModel = true
  5320. let compareContentView = KMCompareContentView()
  5321. compareContentView.oldDocument = oldDocument
  5322. compareContentView.document = document
  5323. compareContentView.compareResults = results
  5324. compareContentView.saveHandle = { [unowned self] view in
  5325. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  5326. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  5327. self.currentWindowController = saveController
  5328. saveController.cancelHandle = { [unowned self] controller in
  5329. self.view.window!.endSheet(controller.window!)
  5330. self.currentWindowController = nil
  5331. }
  5332. saveController.saveHandle = { [unowned self] controller, saveType in
  5333. let folderPath = controller.fileSaveFolderPath
  5334. if folderPath != nil {
  5335. if !FileManager.default.fileExists(atPath: folderPath) {
  5336. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  5337. }
  5338. #if VERSION_DMG
  5339. #else
  5340. let url = URL(fileURLWithPath: folderPath)
  5341. let fileAccess = AppSandboxFileAccess()
  5342. fileAccess?.persistPermissionURL(url)
  5343. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  5344. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  5345. let urlString = url.path
  5346. let _url = URL(fileURLWithPath: urlString)
  5347. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  5348. }
  5349. #endif
  5350. var savePath: String
  5351. switch saveType {
  5352. case 0:
  5353. let filePath = oldDocument.documentURL.path
  5354. let fileName = filePath.deletingPathExtension.lastPathComponent
  5355. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5356. savePath = self.getValidFilePath(savePath)
  5357. oldDocument.write(to: URL(fileURLWithPath: savePath))
  5358. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5359. case 1:
  5360. let filePath = document.documentURL.path
  5361. let fileName = filePath.deletingPathExtension.lastPathComponent
  5362. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5363. savePath = self.getValidFilePath(savePath)
  5364. document.write(to: URL(fileURLWithPath: savePath))
  5365. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5366. case 2:
  5367. let filePath = oldDocument.documentURL.path
  5368. let fileName = filePath.deletingPathExtension.lastPathComponent
  5369. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  5370. savePath = self.getValidFilePath(savePath)
  5371. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  5372. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5373. default:
  5374. break
  5375. }
  5376. }
  5377. self.view.window!.endSheet(controller.window!)
  5378. self.currentWindowController = nil
  5379. }
  5380. NSWindow.currentWindow().beginSheet(saveController.window!)
  5381. }
  5382. }
  5383. compareContentView.closeHandle = { [unowned self] view in
  5384. // self.view.window!.endSheet(controller.window!)
  5385. self.isCompareModel = false
  5386. view.removeFromSuperview()
  5387. }
  5388. self.PDFContendView.addSubview(compareContentView)
  5389. compareContentView.frame = self.PDFContendView.bounds
  5390. compareContentView.autoresizingMask = [.width,.height]
  5391. }
  5392. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  5393. self.isCompareModel = true
  5394. let coveringView = KMCompareCoveringView()
  5395. coveringView.pdfDocument = pdfDocument
  5396. coveringView.closeHandle = { [unowned self] view in
  5397. self.isCompareModel = false
  5398. view.removeFromSuperview()
  5399. }
  5400. coveringView.saveHandle = { [unowned self] view in
  5401. let savePanel = NSSavePanel()
  5402. savePanel.nameFieldStringValue = "untitled"
  5403. savePanel.allowedFileTypes = ["pdf"]
  5404. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  5405. if result == .OK {
  5406. pdfDocument.write(to: savePanel.url!)
  5407. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  5408. }
  5409. }
  5410. }
  5411. self.PDFContendView.addSubview(coveringView)
  5412. coveringView.frame = self.PDFContendView.bounds
  5413. coveringView.autoresizingMask = [.width,.height]
  5414. }
  5415. func getValidFilePath(_ oldPath: String) -> String {
  5416. let fileManager = FileManager.default
  5417. do {
  5418. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  5419. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  5420. return oldPath
  5421. }
  5422. var i = 1
  5423. var newPath = oldPath
  5424. while fileManager.fileExists(atPath: newPath) {
  5425. if fileType == FileAttributeType.typeDirectory.rawValue {
  5426. newPath = oldPath + "(\(i))"
  5427. } else {
  5428. let fileExtension = (oldPath as NSString).pathExtension
  5429. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  5430. }
  5431. i += 1
  5432. }
  5433. return newPath
  5434. } catch {
  5435. print("Error getting file attributes: \(error)")
  5436. return oldPath
  5437. }
  5438. }
  5439. }
  5440. extension KMMainViewController {
  5441. func documentAllowsEdit() -> Bool {
  5442. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  5443. let alert = NSAlert()
  5444. alert.alertStyle = .critical
  5445. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  5446. alert.runModal()
  5447. return false
  5448. } else {
  5449. return true
  5450. }
  5451. }
  5452. }