KMMainViewController+Action.swift 301 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121
  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. // KMProductCompareWC.shared.orientation = false
  1111. // KMProductCompareWC.shared.showWindow(nil)
  1112. // return
  1113. // }
  1114. if KMMemberInfo.shared.isMemberAllFunction == false {
  1115. KMMemberInfo.shared.advancedFunctionUsage()
  1116. return
  1117. }
  1118. }
  1119. var point = mouseRightMenuEvent?.locationInWindow
  1120. if (point == nil) {
  1121. point = NSZeroPoint
  1122. }
  1123. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  1124. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  1125. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  1126. var annotation: CPDFAnnotation?
  1127. if self.isReadMode {
  1128. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1129. self.listView.toolMode = .noteToolMode
  1130. }
  1131. switch sender.tag {
  1132. case 0:
  1133. self.listView.annotationType = CAnnotationType.ink
  1134. case 1:
  1135. // self.listView.annotationType = CAnnotationType.freeText
  1136. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1137. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1138. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1139. if ((annotation) != nil) {
  1140. self.listView.updateActiveAnnotations([annotation!])
  1141. self.listView.edit(annotation)
  1142. }
  1143. case 2:
  1144. // self.listView.annotationType = CAnnotationType.anchored
  1145. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1146. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1147. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1148. self.listView.edit(annotation)
  1149. case 3:
  1150. // self.listView.annotationType = CAnnotationType.square
  1151. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1152. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1153. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1154. case 4:
  1155. // self.listView.annotationType = CAnnotationType.circle
  1156. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1157. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1158. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1159. case 5:
  1160. // self.listView.annotationType = CAnnotationType.arrow
  1161. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1162. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1163. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1164. case 6:
  1165. // self.listView.annotationType = CAnnotationType.line
  1166. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1167. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1168. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1169. case 7:
  1170. self.listView.annotationType = CAnnotationType.link
  1171. self.openRightPane()
  1172. case 8:
  1173. self.listView.annotationType = CAnnotationType.stamp
  1174. self.openRightPane()
  1175. case 9:
  1176. self.listView.annotationType = CAnnotationType.signSignature
  1177. self.openRightPane()
  1178. default:
  1179. break
  1180. }
  1181. self.rightSideViewController.isHidden = true
  1182. self.rightSideViewController.subViewType = .AnnotationProperts
  1183. } else {
  1184. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1185. if(self.toolbarController.toolbarType == .None) {
  1186. self.toolbarController.toolbarType = .Annatiton
  1187. }
  1188. self.listView.toolMode = .noteToolMode
  1189. }
  1190. switch sender.tag {
  1191. case 0:
  1192. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  1193. self.model.rightMouseEventing = true
  1194. if(self.toolbarController.toolbarType == .None) {
  1195. self.toolbarController.toolbarType = .Annatiton
  1196. }
  1197. self.listView.toolMode = .noteToolMode
  1198. self.listView.annotationType = CAnnotationType.ink
  1199. case 1:
  1200. // self.listView.annotationType = CAnnotationType.freeText
  1201. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1202. if (pagePoint.x - defaultSize.width > 0){
  1203. pagePoint.x -= defaultSize.width;
  1204. }else{
  1205. pagePoint.x = 0;
  1206. }
  1207. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1208. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1209. // self.view.window?.makeFirstResponder()
  1210. if ((annotation) != nil) {
  1211. // self.listView.updateActiveAnnotations([annotation!])
  1212. self.listView.edit(annotation)
  1213. }
  1214. case 2:
  1215. // self.listView.annotationType = CAnnotationType.anchored
  1216. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1217. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1218. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1219. self.listView.edit(annotation)
  1220. case 3:
  1221. // self.listView.annotationType = CAnnotationType.square
  1222. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1223. if (pagePoint.x - defaultSize.width > 0){
  1224. pagePoint.x -= defaultSize.width;
  1225. }else{
  1226. pagePoint.x = 0;
  1227. }
  1228. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1229. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1230. case 4:
  1231. // self.listView.annotationType = CAnnotationType.circle
  1232. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1233. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1234. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1235. case 5:
  1236. // self.listView.annotationType = CAnnotationType.arrow
  1237. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1238. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1239. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1240. case 6:
  1241. // self.listView.annotationType = CAnnotationType.line
  1242. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1243. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1244. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1245. case 7:
  1246. self.listView.annotationType = CAnnotationType.link
  1247. self.openRightPane()
  1248. case 8:
  1249. self.listView.annotationType = CAnnotationType.stamp
  1250. self.openRightPane()
  1251. case 9:
  1252. self.listView.annotationType = CAnnotationType.signSignature
  1253. self.openRightPane()
  1254. case 10:
  1255. self.addImgAnnotationToView(center: pagePoint)
  1256. default:
  1257. break
  1258. }
  1259. self.rightSideViewController.isHidden = false
  1260. self.rightSideViewController.subViewType = .AnnotationProperts
  1261. if annotation != nil{
  1262. self.listView.activeAnnotations.removeAllObjects()
  1263. // self.listView.activeAnnotations.add(annotation as Any)
  1264. var newAnnonations : [CPDFAnnotation] = []
  1265. newAnnonations.append(annotation!)
  1266. self.listView.updateActiveAnnotations(newAnnonations)
  1267. // self.openRightPane()
  1268. }
  1269. // self.rightSideViewController.view.isHidden = false
  1270. }
  1271. // if (annotation != nil) {
  1272. // self.listView.updateIsRightActiveAnnotations([annotation!])
  1273. // }
  1274. }
  1275. }
  1276. func addImgAnnotationToView(center: NSPoint) {
  1277. let accessoryCtr = KMImageAccessoryController()
  1278. let openPanel = NSOpenPanel()
  1279. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1280. openPanel.allowsMultipleSelection = false
  1281. openPanel.accessoryView = accessoryCtr.view
  1282. openPanel.isAccessoryViewDisclosed = true
  1283. openPanel.beginSheetModal(for: self.view.window!) { result in
  1284. if result == .OK {
  1285. let fileURL = openPanel.urls.first
  1286. let filePath = fileURL!.path
  1287. if filePath.pathExtension == "pdf" {
  1288. let pdf = CPDFDocument(url: fileURL)
  1289. if pdf!.isEncrypted {
  1290. NSSound.beep()
  1291. return
  1292. }
  1293. }
  1294. let img = NSImage(contentsOfFile: filePath)
  1295. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1296. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  1297. }
  1298. }
  1299. }
  1300. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  1301. if self.listView?.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  1302. let index = self.listView.currentPageIndex
  1303. self.listView?.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  1304. self.listView?.setNeedsDisplayForVisiblePages()
  1305. } else {
  1306. self.listView?.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1307. self.listView?.setNeedsDisplayForVisiblePages()
  1308. }
  1309. self.setDocumentEditedState(window: self.view.window)
  1310. if self.isReadMode {
  1311. } else {
  1312. self.leftSideViewController.showBookmarkTab()
  1313. }
  1314. }
  1315. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1316. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1317. }
  1318. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1319. let rect = listView.currentSelectionRect()
  1320. let page = listView.currentPage()
  1321. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1322. copyPage.setBounds(rect, for: .cropBox)
  1323. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1324. // let pdfDocument : PDFDocument = PDFDocument()
  1325. // let newpage : PDFPage = PDFPage(image: image)!
  1326. // pdfDocument.insert(newpage, at: 0)
  1327. // 执行右键操作后,需要取消框选区域
  1328. if self.listView.toolMode == .selectToolMode {
  1329. objc_sync_enter(self)
  1330. self.listView.selectionRect = NSZeroRect
  1331. self.listView.selectionPageIndex = UInt(NSNotFound)
  1332. objc_sync_exit(self)
  1333. }
  1334. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1335. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1336. if (result == .cancel) {
  1337. return
  1338. }
  1339. // 解除权限
  1340. self?.model.isSaveKeyChain = false
  1341. self?.listView.document.unlock(withPassword: password)
  1342. // 隐藏提示
  1343. self?.hiddenSecureLimitTip()
  1344. // 去打印
  1345. KMPrintWindowController.printImage(image: image)
  1346. }
  1347. return
  1348. }
  1349. KMPrintWindowController.printImage(image: image)
  1350. }
  1351. // MARK: - Measure
  1352. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1353. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1354. return
  1355. }
  1356. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1357. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1358. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1359. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1360. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1361. areaMeasureInfoWindowController?.hideFloatingWindow()
  1362. }
  1363. self.listView.updateActiveAnnotations([anno])
  1364. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1365. self.listView.setNeedsDisplayForVisiblePages()
  1366. }
  1367. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  1368. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1369. return
  1370. }
  1371. self.listView.edit(anno)
  1372. }
  1373. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1374. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1375. return
  1376. }
  1377. self.listView.updateActiveAnnotations([anno])
  1378. self.listView.setNeedsDisplayForVisiblePages()
  1379. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  1380. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  1381. } else if let data = anno as? CPDFPolylineAnnotation {
  1382. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  1383. } else if let data = anno as? CPDFPolygonAnnotation {
  1384. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  1385. }
  1386. }
  1387. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1388. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1389. return
  1390. }
  1391. self.listView.remove(anno)
  1392. }
  1393. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  1394. guard let mInfo = measureInfo else {
  1395. return
  1396. }
  1397. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  1398. if hideInfoWindow {
  1399. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  1400. }
  1401. winC.delegate = self
  1402. winC.startModal("")
  1403. }
  1404. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  1405. guard let mInfo = measureInfo else {
  1406. return
  1407. }
  1408. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  1409. if hideInfoWindow {
  1410. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1411. }
  1412. winC.delegate = self
  1413. winC.startModal("")
  1414. }
  1415. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  1416. guard let mInfo = measureInfo else {
  1417. return
  1418. }
  1419. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  1420. if hideInfoWindow {
  1421. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  1422. }
  1423. winC.delegate = self
  1424. winC.startModal("")
  1425. }
  1426. func splitView(withTag tag: Int) {
  1427. if tag == 0 {
  1428. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1429. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1430. } else if tag == 1 {
  1431. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1432. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1433. } else if tag == 2 {
  1434. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1435. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1436. }
  1437. self.listView.needsDisplay = true
  1438. }
  1439. // MARK: - 幻灯片
  1440. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1441. let view: NSView = self.view.window!.firstResponder as! NSView
  1442. if view.isDescendant(of: pdfSplitView){
  1443. self.view.window?.makeFirstResponder(nil)
  1444. }
  1445. self.mainWindow = self.view.window
  1446. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1447. fullScreenWindow.interactionParent = self.view.window
  1448. self.mainWindow?.delegate = nil
  1449. fullScreenWindow.fadeInBlocking()
  1450. self.browserWindowController?.window = fullScreenWindow
  1451. fullScreenWindow.makeKey()
  1452. // NSApp.updatePresentationOptions(for: fullScreenWindow)
  1453. let sel = NSSelectorFromString("setAnimationBehavior:")
  1454. if self.mainWindow?.responds(to: sel) ?? false{
  1455. self.mainWindow?.animationBehavior = .none
  1456. }
  1457. self.mainWindow?.orderOut(nil)
  1458. if self.mainWindow?.responds(to: sel) ?? false{
  1459. self.mainWindow?.animationBehavior = .default
  1460. }
  1461. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1462. fullScreenWindow.orderFront(nil)
  1463. // NSApp.addWindowsItem(fullScreenWindow, title: windowTitleForDocumentDisplayName(self.document?.displayName) ?? "", filename: false)
  1464. }
  1465. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1466. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1467. return
  1468. }
  1469. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1470. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1471. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1472. fullScreenWindow.contentView?.addSubview(view)
  1473. self.listView.layoutDocumentView()
  1474. self.listView.requiresDisplay()
  1475. fullScreenWindow.makeFirstResponder(self.listView)
  1476. fullScreenWindow.recalculateKeyViewLoop()
  1477. fullScreenWindow.delegate = self.browserWindowController
  1478. // if (RUNNING_BEFORE(10_7))
  1479. // [fullScreenWindow display];
  1480. fullScreenWindow.display()
  1481. fadeWindow.fadeOut()
  1482. }
  1483. // MARK: Redact 【密文标记】
  1484. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1485. self.listView.remove(self.listView.activeAnnotation)
  1486. }
  1487. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1488. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1489. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1490. self.view.window?.beginSheet(windowController.window!)
  1491. self.currentWindowController = windowController
  1492. windowController.itemClick = { [weak self] index, value in
  1493. if (index == 1) { /// 取消
  1494. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1495. self?.currentWindowController = nil
  1496. return
  1497. }
  1498. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1499. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1500. annotaton.setBorderColor(windowController_redact.outsideColor)
  1501. annotaton.setInteriorColor(windowController_redact.fillColor)
  1502. if (windowController_redact.isOver) {
  1503. annotaton.setFontColor(windowController_redact.fontColor)
  1504. annotaton.setAlignment(windowController_redact.aligement)
  1505. annotaton.setFont(windowController_redact.font)
  1506. annotaton.setOverlayText(windowController_redact.overText)
  1507. }
  1508. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1509. self?.currentWindowController = nil
  1510. }
  1511. }
  1512. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1513. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1514. return
  1515. }
  1516. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1517. let model = CPDFAnnotationModel(annotationType: .redact)
  1518. model?.setColor(annotation.borderColor())
  1519. model?.setInteriorColor(annotation.interiorColor())
  1520. let overlayText: String = annotation.overlayText()
  1521. if (overlayText.isEmpty) {
  1522. model?.setIsOverlayText(false)
  1523. } else {
  1524. model?.setIsOverlayText(true)
  1525. model?.setOverlayText(overlayText)
  1526. model?.setFontColor(annotation.fontColor())
  1527. model?.setAlignment(annotation.alignment())
  1528. model?.setFontName(annotation.font().fontName)
  1529. model?.setFontSize(annotation.font().pointSize)
  1530. }
  1531. }
  1532. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1533. let anno = self.listView.activeAnnotation
  1534. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1535. return
  1536. }
  1537. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1538. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1539. self.currentWindowController = windowController
  1540. self.view.window?.beginSheet(windowController.window!)
  1541. windowController.itemClick = { [weak self] index, value in
  1542. if (index == 1) {
  1543. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1544. self!.currentWindowController = nil
  1545. return
  1546. }
  1547. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1548. let pageType = windowController_mutilPageFlag.pageType
  1549. let pageString = windowController_mutilPageFlag.pageString
  1550. if (pageType == 4) { /// 自定义页面
  1551. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1552. if (array.count == 0) {
  1553. let alert = NSAlert()
  1554. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1555. alert.runModal()
  1556. return
  1557. }
  1558. }
  1559. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1560. self!.currentWindowController = nil
  1561. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1562. if (indexs.count == 0) {
  1563. return
  1564. }
  1565. for i in indexs {
  1566. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1567. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1568. self?.listView.add(redactAnno, to: page)
  1569. }
  1570. }
  1571. }
  1572. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1573. self.exeRedactConfirm(.redactOne) {}
  1574. }
  1575. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1576. self.exeRedactConfirm(.eraserOne) {}
  1577. }
  1578. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1579. }
  1580. @objc func exportStampImage(sender:NSMenuItem) {
  1581. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1582. var image : NSImage = NSImage()
  1583. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1584. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1585. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1586. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1587. } else {
  1588. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1589. }
  1590. let data = image.tiffRepresentation
  1591. if sender.tag == 0 {
  1592. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1593. imageRep.size = image.size
  1594. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1595. let savePanel = NSSavePanel()
  1596. savePanel.allowedFileTypes = ["png"]
  1597. savePanel.beginSheetModal(for: self.view.window!) { response in
  1598. if (response != .OK) {
  1599. return
  1600. }
  1601. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1602. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1603. }
  1604. }
  1605. } else {
  1606. let pdfdocument = CPDFDocument()
  1607. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1608. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1609. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1610. let savePanel = NSSavePanel()
  1611. savePanel.allowedFileTypes = ["pdf"]
  1612. savePanel.beginSheetModal(for: self.view.window!) { response in
  1613. if (response != .OK) {
  1614. return
  1615. }
  1616. if pdfdocument!.write(to: savePanel.url!) {
  1617. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1618. }
  1619. }
  1620. }
  1621. }
  1622. }
  1623. }
  1624. @objc func exportCorpImage(sender:NSMenuItem) {
  1625. let rect = NSIntegralRect(listView.currentSelectionRect())
  1626. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1627. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1628. page.setBounds(rect, for: .cropBox)
  1629. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1630. let data = image.tiffRepresentation
  1631. guard let data = data else { return }
  1632. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1633. imageRep.size = rect.size
  1634. let savePanel = NSSavePanel()
  1635. switch sender.tag {
  1636. case 0:
  1637. savePanel.allowedFileTypes = ["png"]
  1638. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1639. savePanel.beginSheetModal(for: self.view.window!) { response in
  1640. if (response != .OK) {
  1641. return
  1642. }
  1643. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1644. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1645. }
  1646. }
  1647. case 1:
  1648. savePanel.allowedFileTypes = ["jpg"]
  1649. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1650. savePanel.beginSheetModal(for: self.view.window!) { response in
  1651. if (response != .OK) {
  1652. return
  1653. }
  1654. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1655. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1656. }
  1657. }
  1658. case 2:
  1659. savePanel.allowedFileTypes = ["pdf"]
  1660. let pdfdocument = CPDFDocument()
  1661. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1662. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1663. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1664. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1665. savePanel.beginSheetModal(for: self.view.window!) { response in
  1666. if (response != .OK) {
  1667. return
  1668. }
  1669. if pdfdocument!.write(to: savePanel.url!) {
  1670. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1671. }
  1672. }
  1673. }
  1674. default:
  1675. break
  1676. }
  1677. // 执行右键操作后,需要取消框选区域
  1678. if self.listView.toolMode == .selectToolMode {
  1679. objc_sync_enter(self)
  1680. self.listView.selectionRect = NSZeroRect
  1681. self.listView.selectionPageIndex = UInt(NSNotFound)
  1682. objc_sync_exit(self)
  1683. }
  1684. }
  1685. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1686. let rect = listView.currentSelectionRect()
  1687. let page = listView.currentPage()
  1688. if NSIsEmptyRect(rect) == false && page != nil {
  1689. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1690. var bounds = listView.bounds
  1691. var scale = 1.0
  1692. if isLegacy {
  1693. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1694. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1695. }
  1696. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1697. scale = NSHeight(bounds) / NSHeight(rect)
  1698. } else {
  1699. scale = NSWidth(bounds) / NSWidth(rect)
  1700. }
  1701. listView.setScaleFactor(scale, animated: false)
  1702. let scrollView = listView.scroll()
  1703. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1704. if ((scrollView?.hasVerticalScroller) != nil) {
  1705. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1706. }
  1707. if ((scrollView?.hasHorizontalScroller) != nil) {
  1708. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1709. }
  1710. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1711. scale = NSHeight(bounds) / NSHeight(rect)
  1712. } else {
  1713. scale = NSWidth(bounds) / NSWidth(rect)
  1714. }
  1715. listView.setScaleFactor(scale, animated: false)
  1716. }
  1717. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1718. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1719. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1720. };
  1721. }
  1722. // 执行右键操作后,需要取消框选区域
  1723. if self.listView.toolMode == .selectToolMode {
  1724. objc_sync_enter(self)
  1725. self.listView.selectionRect = NSZeroRect
  1726. self.listView.selectionPageIndex = UInt(NSNotFound)
  1727. objc_sync_exit(self)
  1728. }
  1729. }
  1730. private func cropPagesToRects(rects:NSPointerArray) {
  1731. }
  1732. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1733. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1734. switch sender.tag {
  1735. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1736. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1737. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1738. var red: CGFloat = 0.0
  1739. var green: CGFloat = 0.0
  1740. var blue: CGFloat = 0.0
  1741. var alpha: CGFloat = 0.0
  1742. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1743. if sender.tag == CAnnotationType.highlight.rawValue {
  1744. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1745. } else if sender.tag == CAnnotationType.underline.rawValue {
  1746. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1747. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1748. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1749. }
  1750. case CAnnotationType.ink.rawValue:
  1751. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1752. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1753. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1754. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1755. var red: CGFloat = 0.0
  1756. var green: CGFloat = 0.0
  1757. var blue: CGFloat = 0.0
  1758. var alpha: CGFloat = 0.0
  1759. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1760. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1761. case CAnnotationType.freeText.rawValue:
  1762. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1763. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1764. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1765. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1766. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1767. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1768. var red: CGFloat = 0.0
  1769. var green: CGFloat = 0.0
  1770. var blue: CGFloat = 0.0
  1771. var alpha: CGFloat = 0.0
  1772. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1773. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1774. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1775. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1776. UserDefaults.standard.synchronize()
  1777. }
  1778. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1779. if (alignment == .left || alignment == .center || alignment == .right) {
  1780. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1781. UserDefaults.standard.synchronize()
  1782. }
  1783. case CAnnotationType.anchored.rawValue:
  1784. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1785. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1786. var red: CGFloat = 0.0
  1787. var green: CGFloat = 0.0
  1788. var blue: CGFloat = 0.0
  1789. var alpha: CGFloat = 0.0
  1790. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1791. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1792. case CAnnotationType.square.rawValue:
  1793. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1794. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1795. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1796. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1797. var red: CGFloat = 0.0
  1798. var green: CGFloat = 0.0
  1799. var blue: CGFloat = 0.0
  1800. var alpha: CGFloat = 0.0
  1801. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1802. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1803. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1804. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1805. case CAnnotationType.circle.rawValue:
  1806. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1807. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1808. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1809. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1810. var red: CGFloat = 0.0
  1811. var green: CGFloat = 0.0
  1812. var blue: CGFloat = 0.0
  1813. var alpha: CGFloat = 0.0
  1814. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1815. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1816. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1817. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1818. default:
  1819. break
  1820. }
  1821. }
  1822. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1823. self.showOrHideNotes()
  1824. }
  1825. //MARK: - action
  1826. @objc func cropCurrentPage() {
  1827. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1828. var page: CPDFPage?
  1829. if let data = self.listView.currentSelectionPage() {
  1830. page = data
  1831. } else {
  1832. page = self.listView.currentPage()
  1833. }
  1834. if (NSIsEmptyRect(rect)) {
  1835. rect = KMCropTools.getPageForegroundBox(page!)
  1836. }
  1837. let index: UInt = (page?.pageIndex()) ?? 0
  1838. self._cropPage(at: index, in: rect)
  1839. // 执行右键操作后,需要取消框选区域
  1840. if self.listView.toolMode == .selectToolMode {
  1841. objc_sync_enter(self)
  1842. self.listView.selectionRect = NSZeroRect
  1843. self.listView.selectionPageIndex = UInt(NSNotFound)
  1844. objc_sync_exit(self)
  1845. }
  1846. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1847. }
  1848. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1849. let oldRect = self.listView?.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1850. let undoManager = self.listView.undoManager
  1851. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1852. let page = self.listView.document.page(at: index)
  1853. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1854. page?.setBounds(newRect, for: .cropBox)
  1855. /// 刷新预览视图
  1856. self.listView.layoutDocumentView()
  1857. self.listView.displayBox = .cropBox
  1858. }
  1859. func beginProgressSheet(with message: String, maxValue: UInt) {
  1860. let progress = SKProgressController()
  1861. // progress.window?.backgroundColor = NSColor.km_init(hex: "#ffffff")
  1862. progress.window?.contentView?.wantsLayer = true
  1863. // progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#ffffff").cgColor
  1864. // progress.progressField.textColor = NSColor.black
  1865. progress.message = NSLocalizedString("Converting...", comment: "")
  1866. self.progressC = progress
  1867. self.progressC?.message = message
  1868. if maxValue > 0 {
  1869. progressC?.indeterminate = false
  1870. progressC?.maxValue = Double(maxValue)
  1871. } else {
  1872. progressC?.indeterminate = true
  1873. }
  1874. self.view.km_beginSheet(windowC: progressC!)
  1875. }
  1876. // 白边距
  1877. @objc func smart_cropAllPage() {
  1878. var size = NSZeroSize
  1879. for i in 0 ..< self.listView.document.pageCount {
  1880. let page = self.listView.document.page(at: i)
  1881. let rect = KMCropTools.getPageForegroundBox(page!)
  1882. size.width = fmax(size.width, NSWidth(rect))
  1883. size.height = fmax(size.height, NSHeight(rect))
  1884. }
  1885. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1886. var rectArray: Array<NSRect> = []
  1887. for i in 0 ..< self.listView.document.pageCount {
  1888. progressC?.increment(by: Double(i))
  1889. progressC?.doubleValue = Double(i)
  1890. let page = self.listView.document.page(at: i)
  1891. var rect = KMCropTools.getPageForegroundBox(page!)
  1892. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1893. // if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1894. // rect.origin.x = rect.maxX-size.width
  1895. // }
  1896. // rect.origin.y = rect.maxY-size.height
  1897. // rect.size = size
  1898. // if (NSWidth(rect) > NSWidth(bounds)) {
  1899. // rect.size.width = NSWidth(bounds)
  1900. // }
  1901. // if (NSHeight(rect) > NSHeight(bounds)) {
  1902. // rect.size.height = NSHeight(bounds)
  1903. // }
  1904. //
  1905. // if (NSMinX(rect) < NSMinX(bounds)) {
  1906. // rect.origin.x = NSMinX(bounds)
  1907. // } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1908. // rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1909. // }
  1910. //
  1911. // if (NSMinY(rect) < NSMinY(bounds)) {
  1912. // rect.origin.y = NSMinY(bounds)
  1913. // } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1914. // rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1915. // }
  1916. rectArray.append(rect)
  1917. }
  1918. cropPages(to: rectArray)
  1919. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1920. }
  1921. // 自动
  1922. @objc func auto_cropAllPage() {
  1923. var size = NSZeroSize
  1924. for i in 0 ..< self.listView.document.pageCount {
  1925. let page = self.listView.document.page(at: i)
  1926. let rect = KMCropTools.getPageForegroundBox(page!)
  1927. size.width = fmax(size.width, NSWidth(rect))
  1928. size.height = fmax(size.height, NSHeight(rect))
  1929. }
  1930. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1931. var rectArray: Array<NSRect> = []
  1932. for i in 0 ..< self.listView.document.pageCount {
  1933. progressC?.increment(by: Double(i))
  1934. progressC?.doubleValue = Double(i)
  1935. let page = self.listView.document.page(at: i)
  1936. var rect = KMCropTools.getPageForegroundBox(page!)
  1937. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1938. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1939. rect.origin.x = rect.maxX-size.width
  1940. }
  1941. rect.origin.y = rect.maxY-size.height
  1942. rect.size = size
  1943. if (NSWidth(rect) > NSWidth(bounds)) {
  1944. rect.size.width = NSWidth(bounds)
  1945. }
  1946. if (NSHeight(rect) > NSHeight(bounds)) {
  1947. rect.size.height = NSHeight(bounds)
  1948. }
  1949. if (NSMinX(rect) < NSMinX(bounds)) {
  1950. rect.origin.x = NSMinX(bounds)
  1951. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1952. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1953. }
  1954. if (NSMinY(rect) < NSMinY(bounds)) {
  1955. rect.origin.y = NSMinY(bounds)
  1956. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1957. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1958. }
  1959. rectArray.append(rect)
  1960. }
  1961. cropPages(to: rectArray)
  1962. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1963. }
  1964. @objc func cropAllPage() {
  1965. var rect = [NSIntegralRect(self.listView?.currentSelectionRect() ?? .zero), .zero]
  1966. var rectArray: Array<NSRect> = []
  1967. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1968. if (emptySelection) {
  1969. guard let count = self.listView?.document?.pageCount, count > 0 else {
  1970. KMPrint("listView | document is nil.", beep: true)
  1971. return
  1972. }
  1973. rect[0] = .zero
  1974. rect[1] = .zero
  1975. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1976. if (count == 1) {
  1977. if let page = self.listView.document.page(at: 0) {
  1978. rect[0] = KMCropTools.getPageForegroundBox(page)
  1979. }
  1980. progressC?.increment(by: 1)
  1981. } else if (count < 19) {
  1982. for i in 0 ..< 19 {
  1983. if let page = self.listView.document.page(at: UInt(i)) {
  1984. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1985. progressC?.increment(by: Double(i))
  1986. }
  1987. }
  1988. } else {
  1989. let start = [1, (count - 5) / 2, count - 6]
  1990. var cnt = 0
  1991. for j in 0 ..< 3 {
  1992. for i in 0 ..< 6 {
  1993. let k = Int(start[j] + UInt(i))
  1994. if let page = self.listView.document.page(at: UInt(k)) {
  1995. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1996. cnt += 1
  1997. progressC?.increment(by: Double(cnt))
  1998. }
  1999. }
  2000. }
  2001. }
  2002. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  2003. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  2004. for j in 0 ..< 2 {
  2005. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  2006. }
  2007. rectArray.append(rect.first ?? .zero)
  2008. rectArray.append(rect.last ?? .zero)
  2009. } else {
  2010. rectArray.append(rect.first ?? .zero)
  2011. }
  2012. self.cropPages(to: rectArray)
  2013. // 执行右键操作后,需要取消框选区域
  2014. if self.listView.toolMode == .selectToolMode {
  2015. objc_sync_enter(self)
  2016. self.listView.selectionRect = NSZeroRect
  2017. self.listView.selectionPageIndex = UInt(NSNotFound)
  2018. objc_sync_exit(self)
  2019. }
  2020. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  2021. }
  2022. func cropPages(to rects: Array<NSRect>) {
  2023. let currentPage = self.listView.currentPage()
  2024. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  2025. var oldRectArray: Array<NSRect> = []
  2026. let rectCount = rects.count
  2027. for i in 0 ..< self.listView.document.pageCount {
  2028. let page = self.listView.document.page(at: i)
  2029. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  2030. let oldRect = page?.bounds(for: .cropBox)
  2031. oldRectArray.append(oldRect!)
  2032. page?.setBounds(rect, for: .cropBox)
  2033. }
  2034. let undoManager = self.listView.undoManager
  2035. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  2036. /// 刷新预览视图
  2037. self.listView.layoutDocumentView()
  2038. self.listView.displayBox = .cropBox
  2039. self.listView.go(to: currentPage)
  2040. self.listView.go(to: visibleRect, on: currentPage)
  2041. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2042. self.dismissProgressSheet()
  2043. }
  2044. }
  2045. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  2046. if (limit) {
  2047. let document = self.listView.document ?? CPDFDocument()
  2048. if document?.documentURL == nil {
  2049. return
  2050. }
  2051. var doucumentURL : URL = self.listView.document.documentURL
  2052. if doucumentURL.path.count > 0 {
  2053. let docDir = NSTemporaryDirectory()
  2054. let documentName : String = doucumentURL.path.lastPathComponent
  2055. let path = docDir.stringByAppendingPathComponent(documentName)
  2056. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2057. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2058. let writeSuccess = data != nil
  2059. if writeSuccess == false {
  2060. __NSBeep()
  2061. return;
  2062. }
  2063. doucumentURL = URL(fileURLWithPath: path)
  2064. }
  2065. let array = [doucumentURL]
  2066. let picker = NSSharingServicePicker.init(items: array)
  2067. if sender.shareButton.window != nil {
  2068. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2069. } else {
  2070. 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)
  2071. }
  2072. return
  2073. }
  2074. let document = self.listView.document ?? CPDFDocument()
  2075. if document?.documentURL == nil {
  2076. return
  2077. }
  2078. var doucumentURL : URL = self.listView.document.documentURL
  2079. if doucumentURL.path.count > 0 {
  2080. let docDir = NSTemporaryDirectory()
  2081. let documentName : String = doucumentURL.path.lastPathComponent
  2082. let path = docDir.stringByAppendingPathComponent(documentName)
  2083. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2084. if writeSuccess == false {
  2085. __NSBeep()
  2086. return;
  2087. }
  2088. doucumentURL = URL(fileURLWithPath: path)
  2089. }
  2090. let array = [doucumentURL]
  2091. let picker = NSSharingServicePicker.init(items: array)
  2092. if sender.shareButton.window != nil {
  2093. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2094. } else {
  2095. 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)
  2096. }
  2097. }
  2098. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  2099. if (limit) {
  2100. let document = self.listView.document ?? CPDFDocument()
  2101. var path: String?
  2102. if document?.documentURL != nil {
  2103. path = document?.documentURL.path ?? ""
  2104. }
  2105. if path?.count ?? 0 > 0 {
  2106. let docDir = NSTemporaryDirectory()
  2107. let documentName : String = path?.lastPathComponent ?? ""
  2108. path = docDir.stringByAppendingPathComponent(documentName)
  2109. }
  2110. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2111. var tfileName = path?.deletingPathExtension.lastPathComponent
  2112. let tStdFileSuffix = "_flatten"
  2113. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2114. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2115. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path ?? ""))
  2116. let success = data != nil
  2117. if success {
  2118. let url = URL(fileURLWithPath: path ?? "")
  2119. let picker = NSSharingServicePicker.init(items: [url])
  2120. if sender.shareButton.window != nil {
  2121. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2122. } else {
  2123. 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)
  2124. }
  2125. }
  2126. return
  2127. }
  2128. let document = self.listView.document ?? CPDFDocument()
  2129. var path: String?
  2130. if document?.documentURL != nil {
  2131. path = document?.documentURL.path ?? ""
  2132. }
  2133. if path?.count ?? 0 > 0 {
  2134. let docDir = NSTemporaryDirectory()
  2135. let documentName : String = path?.lastPathComponent ?? ""
  2136. path = docDir.stringByAppendingPathComponent(documentName)
  2137. }
  2138. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2139. var tfileName = path?.deletingPathExtension.lastPathComponent
  2140. let tStdFileSuffix = "_flatten"
  2141. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2142. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2143. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2144. if success {
  2145. let url = URL(fileURLWithPath: path ?? "")
  2146. let picker = NSSharingServicePicker.init(items: [url])
  2147. if sender.shareButton.window != nil {
  2148. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2149. } else {
  2150. 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)
  2151. }
  2152. }
  2153. }
  2154. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  2155. guard let pdfDoc = self.listView.document else {
  2156. NSSound.beep()
  2157. return
  2158. }
  2159. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2160. let alert = NSAlert()
  2161. alert.alertStyle = .critical
  2162. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2163. alert.runModal()
  2164. return
  2165. }
  2166. if (limit) {
  2167. let document = self.listView.document ?? CPDFDocument()
  2168. var path: String?
  2169. if document?.documentURL != nil {
  2170. path = document?.documentURL.path ?? ""
  2171. }
  2172. if path?.count ?? 0 > 0{
  2173. let docDir = NSTemporaryDirectory()
  2174. let documentName : String = path?.lastPathComponent ?? ""
  2175. path = docDir.stringByAppendingPathComponent(documentName)
  2176. }
  2177. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2178. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path ?? ""), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2179. var writeSuccess = data != nil
  2180. if writeSuccess == false {
  2181. __NSBeep()
  2182. return;
  2183. }
  2184. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2185. let cnt = newDocument?.pageCount ?? 0
  2186. for i in 0 ..< cnt {
  2187. let page = newDocument?.page(at: i)
  2188. var annotations : [CPDFAnnotation] = []
  2189. for annotation in page!.annotations {
  2190. annotations.append(annotation)
  2191. }
  2192. for annotation in annotations {
  2193. annotation.page.removeAnnotation(annotation)
  2194. }
  2195. }
  2196. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? "")) ?? false
  2197. if writeSuccess {
  2198. let url = URL(fileURLWithPath: path ?? "")
  2199. let picker = NSSharingServicePicker.init(items: [url])
  2200. if sender.shareButton.window != nil {
  2201. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2202. } else {
  2203. 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)
  2204. }
  2205. }
  2206. return
  2207. }
  2208. let document = self.listView.document ?? CPDFDocument()
  2209. var path: String?
  2210. if document?.documentURL != nil {
  2211. path = document?.documentURL.path ?? ""
  2212. }
  2213. if path?.count ?? 0 > 0 {
  2214. let docDir = NSTemporaryDirectory()
  2215. let documentName : String = path?.lastPathComponent ?? ""
  2216. path = docDir.stringByAppendingPathComponent(documentName)
  2217. }
  2218. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2219. if writeSuccess == false {
  2220. __NSBeep()
  2221. return;
  2222. }
  2223. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2224. let cnt = newDocument?.pageCount ?? 0
  2225. for i in 0 ..< cnt {
  2226. let page = newDocument!.page(at: i)
  2227. var annotations : [CPDFAnnotation] = []
  2228. for annotation in page!.annotations {
  2229. annotations.append(annotation)
  2230. }
  2231. for annotation in annotations {
  2232. annotation.page.removeAnnotation(annotation)
  2233. }
  2234. }
  2235. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2236. if writeSuccess ?? false {
  2237. let url = URL(fileURLWithPath: path ?? "")
  2238. let picker = NSSharingServicePicker.init(items: [url])
  2239. if sender.shareButton.window != nil {
  2240. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2241. } else {
  2242. 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)
  2243. }
  2244. }
  2245. }
  2246. // 开启/关闭左边栏
  2247. @objc func toggleLeftPane() -> Void {
  2248. // if lastLeftPanWidth >= functionWidth {
  2249. self.model.leftPanelOpen = true
  2250. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2251. // } else {
  2252. // leftPanelOpen = false
  2253. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2254. // }
  2255. }
  2256. // 开启左边栏
  2257. @objc func openLeftPane() -> Void {
  2258. self.model.leftPanelOpen = true
  2259. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2260. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  2261. }
  2262. // 关闭左边栏
  2263. @objc func closeLeftPane() -> Void {
  2264. self.model.leftPanelOpen = false
  2265. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  2266. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = false
  2267. }
  2268. // 开启/关闭右边栏
  2269. @objc func toggleRightPane() -> Void {
  2270. if self.model.lastRightPanWidth > 5 {
  2271. self.model.rightPanelIsOpen = false
  2272. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2273. } else {
  2274. self.model.rightPanelIsOpen = true
  2275. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2276. }
  2277. }
  2278. @objc func openRightPane() -> Void {
  2279. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2280. if self.model.rightPanelIsOpen {
  2281. return
  2282. }
  2283. self.model.rightPanelIsOpen = true
  2284. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  2285. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: self.model.defaultRightWidth)
  2286. }
  2287. }
  2288. @objc func closeRightPane() -> Void {
  2289. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2290. self.model.rightPanelIsOpen = false
  2291. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  2292. applyLeftSideWidth(self.model.lastLeftPanWidth, rightSideWidth: 0)
  2293. cancelMeasureType()
  2294. }
  2295. }
  2296. func rename(_ sender: NSNotification) -> Void {
  2297. if (self.view.window == nil || self.view.window!.isVisible == false) {
  2298. return
  2299. }
  2300. let tabController = sender.object as? CTTabController
  2301. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  2302. if let doc = self.myDocument, doc.isDocumentEdited {
  2303. Task {
  2304. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  2305. if resp != .alertFirstButtonReturn { // 取消
  2306. return
  2307. }
  2308. doc.updateChangeCount(.changeCleared)
  2309. // doc.save(nil)
  2310. self.document?.write(to: doc.fileURL)
  2311. Task { @MainActor in
  2312. self._renameForSavePanel(tabController)
  2313. }
  2314. }
  2315. return
  2316. }
  2317. self._renameForSavePanel(tabController)
  2318. }
  2319. }
  2320. func savePdfAlertView() {
  2321. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  2322. return
  2323. }
  2324. AutoSaveManager.manager.isSaveNoti = true
  2325. var num = 0
  2326. if self.listView.document != nil{
  2327. num = Int(self.listView.document.pageCount)
  2328. }
  2329. if Thread.current.isMainThread {
  2330. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2331. } else {
  2332. DispatchQueue.main.async {
  2333. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  2334. }
  2335. }
  2336. }
  2337. func savePdfFinishAlertView() {
  2338. if !AutoSaveManager.manager.isSaveNoti{
  2339. return
  2340. }
  2341. AutoSaveManager.manager.isSaveNoti = false
  2342. if Thread.current.isMainThread {
  2343. self.dismissProgressSheet()
  2344. } else {
  2345. DispatchQueue.main.async {
  2346. self.dismissProgressSheet()
  2347. }
  2348. }
  2349. }
  2350. private func _renameForSavePanel(_ tabC: CTTabController?) {
  2351. let outputSavePanel = NSSavePanel()
  2352. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2353. outputSavePanel.allowedFileTypes = ["pdf"]
  2354. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2355. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2356. let resp = outputSavePanel.runModal()
  2357. if resp == .OK {
  2358. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2359. let fileURL = pdfDocument?.documentURL
  2360. let fileManager = FileManager.default
  2361. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2362. var result = true
  2363. do {
  2364. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2365. } catch {
  2366. result = false
  2367. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2368. }
  2369. if (result) {
  2370. tabC?.title = outputSavePanel.url!.lastPathComponent
  2371. // self.myDocument?.fileURL = newFileURL
  2372. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2373. self.model.isSaveKeyChain = false
  2374. newPdfDocument.unlock(withPassword: self.document?.password)
  2375. if (newPdfDocument.pageCount > 0) {
  2376. self.setDocument = newPdfDocument
  2377. }
  2378. }
  2379. }
  2380. } else {
  2381. outputSavePanel.close()
  2382. }
  2383. }
  2384. func showInFinder(_ sender: Any) -> Void {
  2385. if sender is NSNotification {
  2386. let tabController = (sender as! NSNotification).object as? CTTabController
  2387. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2388. if tabController?.title == path {
  2389. if let file = self.myDocument?.fileURL {
  2390. if FileManager.default.fileExists(atPath: file.path) {
  2391. NSWorkspace.shared.activateFileViewerSelecting([file])
  2392. }
  2393. }
  2394. }
  2395. } else {
  2396. guard let url = self.myDocument?.fileURL else { return }
  2397. let file: URL = url
  2398. if FileManager.default.fileExists(atPath: file.path) {
  2399. NSWorkspace.shared.activateFileViewerSelecting([file])
  2400. }
  2401. }
  2402. }
  2403. func showOrHideNotes() {
  2404. self.listView.hideNotes = !self.listView.hideNotes
  2405. for note in self.listView.notes as? [CPDFAnnotation] ?? [] {
  2406. if note.isForm() {
  2407. note.setAnnotationShouldDisplay(true)
  2408. note.setHidden(false)
  2409. }
  2410. }
  2411. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  2412. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  2413. //BOTA 注释列表显示隐藏
  2414. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2415. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2416. self.leftSideViewController.note_reloadDataIfNeed()
  2417. }
  2418. func closeTab(_ sender: NSNotification) -> Void {
  2419. // let tabController = sender.object as? CTTabController
  2420. // let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  2421. // if tabController?.title == path {
  2422. // print("closeTab")
  2423. // self.leftSideViewController.clearAnnotationFilterData()
  2424. // self.leftSideViewController.clearNotification()
  2425. // }
  2426. }
  2427. @IBAction func toggleSplitPDF(_ sender: Any) {
  2428. if let menuItem = sender as? NSMenuItem {
  2429. splitView(withTag: menuItem.tag)
  2430. }
  2431. }
  2432. @IBAction func readMode(_ sender: Any) {
  2433. isReadMode = !isReadMode
  2434. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  2435. UserDefaults.standard.synchronize()
  2436. if isReadMode {
  2437. CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2438. } else {
  2439. CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2440. }
  2441. }
  2442. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2443. // NSDictionary *info = [notification userInfo];
  2444. // PDFPage *page = [info objectForKey:SKPDFPagePageKey];
  2445. // NSString *action = [info objectForKey:SKPDFPageActionKey];
  2446. // BOOL displayChanged = [action isEqualToString:SKPDFPageActionCrop] == NO || [pdfView displayBox] == kPDFDisplayBoxCropBox;
  2447. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2448. // if self.listView.displayBox == .cropBox {
  2449. // KMPrint("cropBox")
  2450. // } else if self.listView.displayBox == .artBox {
  2451. // KMPrint("artBox")
  2452. // } else if self.listView.displayBox == .trimBox {
  2453. // KMPrint("trimBox")
  2454. // } else if self.listView.displayBox == .bleedBox {
  2455. // KMPrint("bleedBox")
  2456. // } else if self.listView.displayBox == .mediaBox {
  2457. // KMPrint("mediaBox")
  2458. // } else {
  2459. // KMPrint("other \(self.listView.displayBox.rawValue)")
  2460. // }
  2461. if (displayChanged) {
  2462. self.listView.layoutDocumentView()
  2463. }
  2464. if (page != nil) {
  2465. let idx = page!.pageIndex()
  2466. if (displayChanged) {
  2467. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2468. }
  2469. } else {
  2470. if (displayChanged) {
  2471. self.leftSideViewController.allThumbnailsNeedUpdate()
  2472. }
  2473. }
  2474. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2475. // [secondaryPdfView requiresDisplay];
  2476. self.secondaryPdfView?.setNeedsDisplayForVisiblePages()
  2477. //
  2478. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2479. // [self updateRightStatus];
  2480. }
  2481. }
  2482. func changeLineAttribute(_ sender: Any?) {
  2483. var inspector = sender as? KMLineInspector
  2484. if inspector == nil {
  2485. inspector = KMLineInspector.shared
  2486. }
  2487. let action = inspector?.currentLineChangeAction ?? .no
  2488. for annotation in self.listView.activeAnnotations {
  2489. guard let anno = annotation as? CPDFAnnotation else {
  2490. continue
  2491. }
  2492. if anno.hasBorder() {
  2493. // if (mwcFlags.updatingLine == 0 && [annotation hasBorder]) {
  2494. // mwcFlags.updatingLine = 1;
  2495. switch (action) {
  2496. case .lineWidth:
  2497. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2498. break
  2499. case .style:
  2500. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2501. break
  2502. case .dashPattern:
  2503. anno.setDashPattern(inspector?.dashPattern ?? [])
  2504. break
  2505. case .startLineStyle:
  2506. if anno.isLine() {
  2507. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2508. }
  2509. break
  2510. case .endLineStyle:
  2511. if anno.isLine() {
  2512. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2513. }
  2514. break
  2515. case .no:
  2516. break
  2517. }
  2518. // mwcFlags.updatingLine = 0;
  2519. // in case one property changes another, e.g. when adding a dashPattern the borderStyle can change
  2520. }
  2521. }
  2522. // [self updateLineInspector];
  2523. }
  2524. // MARK: -
  2525. // MARK: 显示窗口
  2526. internal func showCompressWindow(url: URL? = nil) {
  2527. // if let wc = self.compressWIndowControllerNew, let _ = wc.window?.isSheet {
  2528. // KMPrint("压缩窗口已显示")
  2529. // return
  2530. // }
  2531. self.compressWIndowControllerNew = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2532. self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  2533. self.compressWIndowControllerNew?.password = self.listView?.document?.password ?? ""
  2534. // if let _url = url {
  2535. // windowController.oriDocumentUrl = self.listView.document.documentURL
  2536. // windowController.documentURL = _url
  2537. // } else {
  2538. self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  2539. // }
  2540. self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  2541. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2542. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2543. }
  2544. self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  2545. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2546. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2547. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2548. // batchWindowController.window?.makeKeyAndOrderFront("")
  2549. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2550. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2551. batchWindowController.window?.makeKeyAndOrderFront("")
  2552. }
  2553. self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2554. self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  2555. if (result) {
  2556. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2557. if (openDocument) {
  2558. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2559. } else {
  2560. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2561. }
  2562. } else {
  2563. let alert = NSAlert()
  2564. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2565. alert.runModal()
  2566. }
  2567. }
  2568. }
  2569. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2570. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2571. KMPrint("转档窗口已显示")
  2572. return
  2573. }
  2574. var convertT: KMConvertType = .Word
  2575. var windowController: KMConvertBaseWindowController?
  2576. if (type == .word) { /// Word
  2577. convertT = .Word
  2578. } else if (type == .excel) {
  2579. convertT = .Excel
  2580. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2581. if (type == .ppt) {
  2582. convertT = .PPT
  2583. } else if (type == .rtf) {
  2584. convertT = .RTF
  2585. } else if (type == .html) {
  2586. convertT = .HTML
  2587. } else if (type == .conversion_text) {
  2588. convertT = .Text
  2589. }
  2590. } else if (type == .csv) {
  2591. convertT = .CSV
  2592. } else if (type == .conversion_image) {
  2593. windowController = KMConvertImageWindowController()
  2594. convertT = .JPEG
  2595. } else if type == .json {
  2596. convertT = .Json
  2597. }
  2598. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  2599. var url: URL?
  2600. if (documentUrl != nil) {
  2601. url = documentUrl
  2602. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2603. } else {
  2604. url = self.listView.document.documentURL
  2605. }
  2606. self.showAllConvertWindow(convertT: convertT)
  2607. }
  2608. //MARK: 转档 -
  2609. func showAllConvertWindow(convertT: KMConvertType) {
  2610. self.ConvertTrackEvent(type: convertT)
  2611. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2612. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2613. var type: KMConvertWithPDFType = .WordAdvance
  2614. switch convertT {
  2615. case .Word:
  2616. break
  2617. case .Excel:
  2618. type = .Excel
  2619. case .PPT:
  2620. type = .PowerPoint
  2621. case .RTF:
  2622. type = .RTF
  2623. case .CSV:
  2624. type = .CSV
  2625. case .HTML:
  2626. type = .HTML
  2627. case .Text:
  2628. type = .Text
  2629. case .JPEG:
  2630. type = .JPEG
  2631. case .PNG:
  2632. type = .PNG
  2633. case .GIF:
  2634. type = .GIF
  2635. case .JPG:
  2636. type = .JPG
  2637. case .TIFF:
  2638. type = .TIFF
  2639. case .TGA:
  2640. type = .TGA
  2641. case .BMP:
  2642. type = .BMP
  2643. case .JP2:
  2644. type = .JPEG2000
  2645. case .AdvancedWord:
  2646. break
  2647. case .Json:
  2648. type = .Json
  2649. break
  2650. default:
  2651. break
  2652. }
  2653. // let document = self.document
  2654. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2655. var needShowHint = false
  2656. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2657. needShowHint = true
  2658. } else {
  2659. var needContinue = false
  2660. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2661. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2662. let ss = self.document?.documentURL.path
  2663. if arr.contains(ss!) {
  2664. needContinue = false
  2665. }else {
  2666. needContinue = true
  2667. }
  2668. }else {
  2669. needContinue = true
  2670. }
  2671. if needContinue {
  2672. let ss = self.document?.documentURL.path
  2673. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2674. file.password = document?.password ?? ""
  2675. KMBatchOperateManager.defaultManager.files?.append(file)
  2676. }
  2677. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2678. batchWindowController.switchToConvertType(convertType: type)
  2679. }
  2680. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2681. if needShowHint {
  2682. batchWindowController.showIsConvertingHint()
  2683. } else {
  2684. }
  2685. }
  2686. }
  2687. self.km_beginSheet(windowC: convertWC)
  2688. }
  2689. func ConvertTrackEvent(type: KMConvertType) {
  2690. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2691. switch type {
  2692. case .Word:
  2693. eventStr = "Btn_SubTbr_Converter_ToWord"
  2694. break
  2695. case .Excel:
  2696. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2697. case .PPT:
  2698. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2699. case .RTF:
  2700. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2701. case .CSV:
  2702. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2703. case .HTML:
  2704. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2705. case .Text:
  2706. eventStr = "Btn_SubTbr_Converter_ToText"
  2707. case .JPEG:
  2708. eventStr = "Btn_SubTbr_Converter_ToImage"
  2709. case .PNG:
  2710. eventStr = "Btn_SubTbr_Converter_ToImage"
  2711. case .GIF:
  2712. eventStr = "Btn_SubTbr_Converter_ToImage"
  2713. case .JPG:
  2714. eventStr = "Btn_SubTbr_Converter_ToImage"
  2715. case .TIFF:
  2716. eventStr = "Btn_SubTbr_Converter_ToImage"
  2717. case .TGA:
  2718. eventStr = "Btn_SubTbr_Converter_ToImage"
  2719. case .BMP:
  2720. eventStr = "Btn_SubTbr_Converter_ToImage"
  2721. case .JP2:
  2722. eventStr = "Btn_SubTbr_Converter_ToImage"
  2723. case .AdvancedWord:
  2724. eventStr = "Btn_SubTbr_Converter_ToWord"
  2725. break
  2726. default:
  2727. break
  2728. }
  2729. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2730. }
  2731. //MARK: 转档 - OCR
  2732. func showOCRWindow() {
  2733. // if !IAPProductsManager.default().isAvailableAllFunction(){
  2734. // KMProductCompareWC.shared.orientation = false
  2735. // let winC = KMProductCompareWC.shared
  2736. // let type = self.toolbarController.toolbarType ?? .None
  2737. // if type == .Conversion {
  2738. // winC.kEventName = "Reading_Convert_OCR_BuyNow"
  2739. // } else {
  2740. // winC.kEventName = "Reading_OCR_BuyNow"
  2741. // }
  2742. // winC.showWindow(nil)
  2743. // return
  2744. // }
  2745. if KMMemberInfo.shared.isMemberAllFunction == false {
  2746. let winC = KMProductCompareWC.shared
  2747. let type = self.toolbarController.toolbarType ?? .None
  2748. if type == .Conversion {
  2749. winC.kEventName = "Reading_Convert_OCR_BuyNow"
  2750. } else {
  2751. winC.kEventName = "Reading_OCR_BuyNow"
  2752. }
  2753. KMMemberInfo.shared.advancedFunctionUsage()
  2754. return
  2755. }
  2756. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  2757. com.currentIndexPage = self.listView.currentPageIndex
  2758. self.km_beginSheet(windowC: com)
  2759. }
  2760. //MARK: 导出图片
  2761. func extractImageAction(num: Int) {
  2762. // if !IAPProductsManager.default().isAvailableAllFunction(){
  2763. // KMProductCompareWC.shared.orientation = false
  2764. // let winC = KMProductCompareWC.shared
  2765. // winC.kEventName = "Reading_ExtractImage_BuyNow"
  2766. // winC.showWindow(nil)
  2767. // return
  2768. // }
  2769. if KMMemberInfo.shared.isMemberAllFunction == false {
  2770. let winC = KMProductCompareWC.shared
  2771. winC.kEventName = "Reading_ExtractImage_BuyNow"
  2772. KMMemberInfo.shared.advancedFunctionUsage()
  2773. return
  2774. }
  2775. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2776. let alert = NSAlert()
  2777. alert.alertStyle = .critical
  2778. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2779. alert.runModal()
  2780. return
  2781. }
  2782. let document = self.listView.document
  2783. var fileURL = document?.documentURL
  2784. if num == 1 {
  2785. let pageCount = document?.pageCount ?? 0
  2786. let indeSet = NSMutableIndexSet()
  2787. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2788. if indeSet.count == 0 {
  2789. return
  2790. }
  2791. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2792. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2793. let outputSavePanel = NSSavePanel()
  2794. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2795. outputSavePanel.allowsOtherFileTypes = true
  2796. outputSavePanel.isExtensionHidden = true
  2797. outputSavePanel.canCreateDirectories = true
  2798. outputSavePanel.nameFieldStringValue = tFileName
  2799. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2800. if result == NSApplication.ModalResponse.OK {
  2801. DispatchQueue.main.async {
  2802. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2803. let tDestFile = outputSavePanel.url!.path
  2804. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2805. let pdfconverter = PDFConvertObject()
  2806. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2807. self.dismissProgressSheet()
  2808. let fileManager = FileManager.default
  2809. if fileManager.fileExists(atPath: tDestFile) {
  2810. let workspace = NSWorkspace.shared
  2811. let url = URL(fileURLWithPath: tDestFile)
  2812. workspace.activateFileViewerSelecting([url])
  2813. }
  2814. }
  2815. }
  2816. })
  2817. return
  2818. }
  2819. if fileURL != nil {
  2820. self.myDocument?.save(nil)
  2821. } else {
  2822. let myDocument = self.myDocument
  2823. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2824. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2825. if writeSuccess {
  2826. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2827. fileURL = document?.documentURL
  2828. } else {
  2829. NSSound.beep()
  2830. return
  2831. }
  2832. }
  2833. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2834. extract?.docPath = fileURL?.path ?? ""
  2835. extract?.password = document?.password ?? ""
  2836. extract?.currentPage = self.listView.currentPageIndex
  2837. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2838. self.km_beginSheet(windowC: extract!)
  2839. extract?.selectCurrentPageBtn()
  2840. // self.showCreateStamp()
  2841. // self.showAddSignature()
  2842. }
  2843. //MARK: 创建文字图章示例实际上不会在这里使用
  2844. func showCreateStamp() {
  2845. let stampCreaterWindowController = KMStampCreaterWindowController()
  2846. stampCreaterWindowController.window?.backgroundColor = .clear
  2847. self.km_beginSheet(windowC: stampCreaterWindowController)
  2848. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2849. if result == 1 {
  2850. }
  2851. }
  2852. }
  2853. //MARK: 添加签名示例实际上不会在这里使用
  2854. func showAddSignature() {
  2855. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")
  2856. // signatureWindowController.window?.backgroundColor = .clear
  2857. // signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2858. //
  2859. // }
  2860. self.view.window?.beginSheet(signatureWindowController.window!, completionHandler: { returnCode in
  2861. })
  2862. }
  2863. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2864. // if progressController == nil {
  2865. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2866. // }
  2867. let progress = SKProgressController()
  2868. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2869. progress.window?.contentView?.wantsLayer = true
  2870. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2871. progress.progressField.textColor = NSColor.white
  2872. progress.message = NSLocalizedString("Converting...", comment: "")
  2873. progressC = progress
  2874. progressC?.message = message
  2875. if maxValue > 0 {
  2876. progressC?.indeterminate = false
  2877. progressC?.maxValue = Double(maxValue)
  2878. progressC?.progressBar.doubleValue = 0.3
  2879. } else {
  2880. progressC?.indeterminate = true
  2881. }
  2882. self.view.km_beginSheet(windowC: progressC!)
  2883. }
  2884. func dismissProgressSheet() {
  2885. progressC?.stopAnimation()
  2886. self.view.km_endSheet()
  2887. progressC = nil
  2888. }
  2889. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2890. let newArr = NSMutableArray()
  2891. for item in files {
  2892. newArr.add(item.filePath)
  2893. }
  2894. return newArr as! [String]
  2895. }
  2896. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2897. self.saveDocument()
  2898. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2899. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2900. if (result == .cancel) {
  2901. return
  2902. }
  2903. // 解除权限
  2904. self?.listView.document.unlock(withPassword: password)
  2905. // 隐藏提示
  2906. self?.hiddenSecureLimitTip()
  2907. // 去打印
  2908. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2909. }
  2910. return
  2911. }
  2912. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2913. }
  2914. // MARK: - 图片注释
  2915. @IBAction func imageAnnotation(_ sender: Any) {
  2916. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2917. changeAnnotationMode(sender)
  2918. // guard IAPProductsManager.default().isAvailableAllFunction() else {
  2919. // KMProductCompareWC.shared.orientation = false
  2920. // KMProductCompareWC.shared.showWindow(nil)
  2921. // return
  2922. // }
  2923. guard KMMemberInfo.shared.isMemberAllFunction else {
  2924. KMMemberInfo.shared.advancedFunctionUsage()
  2925. return
  2926. }
  2927. let accessoryCtr = KMImageAccessoryController()
  2928. let openPanel = NSOpenPanel()
  2929. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2930. openPanel.allowsMultipleSelection = false
  2931. openPanel.accessoryView = accessoryCtr.view
  2932. // if #available(macOS 10.11, *) {
  2933. openPanel.canSelectHiddenExtension = true
  2934. // }
  2935. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2936. if result == .OK {
  2937. guard let url = openPanel.url else {
  2938. return
  2939. }
  2940. let filePath = url.path
  2941. if filePath.pathExtension.lowercased() == "pdf" {
  2942. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2943. NSSound.beep()
  2944. return
  2945. }
  2946. }
  2947. guard let image = NSImage(contentsOfFile: url.path) else {
  2948. let alert = NSAlert()
  2949. alert.alertStyle = .critical
  2950. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2951. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2952. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2953. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2954. if response == .alertFirstButtonReturn {
  2955. // Handle cancel button clicked
  2956. }
  2957. }
  2958. return
  2959. }
  2960. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2961. if isDamageImage {
  2962. let alert = NSAlert()
  2963. alert.alertStyle = .critical
  2964. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2965. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2966. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2967. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2968. if response == .alertFirstButtonReturn {
  2969. // Handle cancel button clicked
  2970. }
  2971. }
  2972. return
  2973. }
  2974. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2975. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2976. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2977. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  2978. }
  2979. }
  2980. }
  2981. }
  2982. @IBAction func tableAnnotation(_ sender: Any) {
  2983. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2984. changeAnnotationMode(sender)
  2985. // guard IAPProductsManager.default().isAvailableAllFunction() else {
  2986. // KMProductCompareWC.shared.orientation = false
  2987. // let winC = KMProductCompareWC.shared
  2988. // winC.kEventName = "Reading_Table_BuyNow"
  2989. // winC.showWindow(nil)
  2990. // return
  2991. // }
  2992. guard KMMemberInfo.shared.isMemberAllFunction else {
  2993. let winC = KMProductCompareWC.shared
  2994. winC.kEventName = "Reading_Table_BuyNow"
  2995. KMMemberInfo.shared.advancedFunctionUsage()
  2996. return
  2997. }
  2998. listView.addAnnotationWithTable()
  2999. openRightPane()
  3000. }
  3001. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  3002. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  3003. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  3004. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  3005. }
  3006. if let data = image.tiffRepresentation,
  3007. let imageRep = NSBitmapImageRep(data: data) {
  3008. imageRep.size = image.size
  3009. var imageData: Data?
  3010. if path.lowercased() == "png" {
  3011. imageData = imageRep.representation(using: .png, properties: [:])
  3012. } else {
  3013. imageData = imageRep.representation(using: .jpeg, properties: [:])
  3014. }
  3015. if let imageData = imageData {
  3016. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  3017. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  3018. return true
  3019. } else {
  3020. return false
  3021. }
  3022. }
  3023. }
  3024. return false
  3025. }
  3026. func tagString() -> String {
  3027. let dateFormatter = DateFormatter()
  3028. dateFormatter.dateFormat = "yyMMddHHmmss"
  3029. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  3030. }
  3031. // MARK: - Split View
  3032. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  3033. }
  3034. @objc func removeSecondaryPdfContentView(_ sender: Notification?) {
  3035. if let _ = sender {
  3036. NotificationCenter.default.removeObserver(self, name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  3037. }
  3038. self.secondaryPdfContentView?.removeFromSuperview()
  3039. self.newPDFSplitView.adjustSubviews()
  3040. }
  3041. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  3042. if !isSinglePage && isHorizontal {
  3043. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  3044. }
  3045. if (!isSinglePage && !isHorizontal) {
  3046. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3047. }
  3048. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  3049. }
  3050. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  3051. if isSinglePage {
  3052. if self.newPDFSplitView.animating {
  3053. return
  3054. }
  3055. if self.secondaryPdfContentView?.window != nil {
  3056. self.lastSplitPDFHeight = self.lastSplitPDFHeightFloat(self.secondaryPdfContentView?.frame ?? .zero)
  3057. self.newPDFSplitView.setPosition(self.newPDFSplitView.maxPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: true)
  3058. if self.newPDFSplitView.animating {
  3059. NotificationCenter.default.addObserver(self, selector: #selector(removeSecondaryPdfContentView), name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  3060. } else {
  3061. self.removeSecondaryPdfContentView(nil)
  3062. }
  3063. }
  3064. self.view.window?.recalculateKeyViewLoop()
  3065. if self.interactionMode == .legacyFullScreen {
  3066. self.view.window?.makeFirstResponder(self.listView)
  3067. }
  3068. } else {
  3069. if self.newPDFSplitView.animating {
  3070. return
  3071. }
  3072. self.newPDFSplitView.dividerStyle = .paneSplitter
  3073. self.newPDFSplitView.isVertical = isHorizontal
  3074. if self.secondaryPdfView?.window == nil {
  3075. let frame = self.newPDFSplitView.bounds
  3076. if (self.lastSplitPDFHeight <= 0.0) {
  3077. var DEFAULT_SPLIT_PDF_FACTOR: Float = 0.3
  3078. self.lastSplitPDFHeight = floorf(DEFAULT_SPLIT_PDF_FACTOR * self.lastSplitPDFHeightFloat(frame))
  3079. }
  3080. var position = self.lastSplitPDFHeightFloat(frame)-self.lastSplitPDFHeight-Float(self.newPDFSplitView.dividerThickness)
  3081. var point: NSPoint = .zero
  3082. var page: CPDFPage?
  3083. self.newPDFSplitView.setPosition(position.cgFloat, ofDividerAt: 0, animate: true)
  3084. if (self.secondaryPdfContentView == nil) {
  3085. // secondaryPdfContentView = [[SKGradientView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 200.0, 20.0)];
  3086. self.secondaryPdfContentView = NSView(frame: NSMakeRect(0, 0, 200, 20))
  3087. self.secondaryPdfView = KMSecondaryPDFView(frame: self.secondaryPdfContentView?.bounds ?? .zero)
  3088. self.secondaryPdfView?.autoresizingMask = [.width, .height]
  3089. // self.secondaryPdfContentView?.isHidden = true
  3090. self.secondaryPdfContentView?.addSubview(self.secondaryPdfView!)
  3091. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3092. // self.newPDFSplitView.addArrangedSubview(self.secondaryPdfContentView!)
  3093. // // Because of a PDFView bug, display properties can not be changed before it is placed in a window
  3094. self.secondaryPdfView?.synchronizedPDFView = self.listView
  3095. self.secondaryPdfView?.backgroundColor = self.listView.backgroundColor
  3096. // [secondaryPdfView applyDefaultPageBackgroundColor];
  3097. self.secondaryPdfView?.displaysPageBreaks = false
  3098. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  3099. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  3100. self.secondaryPdfView?.setGreekingThreshold(KMPreference.shared.greekThreshold.cgFloat)
  3101. self.secondaryPdfView?.setSynchronizeZoom(true)
  3102. // // [secondaryPdfView setDocument:[pdfView document]];
  3103. point = NSMakePoint(NSMinX(frame), NSMaxY(frame) - position.cgFloat - self.newPDFSplitView.dividerThickness)
  3104. page = self.listView.page(for: point, nearest: true)
  3105. //
  3106. let controlView = self.secondaryPdfView?.controlView
  3107. var color = NSColor(calibratedWhite: 0.97, alpha: 1.0)
  3108. if KMAppearance.isDarkMode() {
  3109. color = KMAppearance.Layout.l0Color()
  3110. }
  3111. // [(SKGradientView *)secondaryPdfContentView setGradient:[[[NSGradient alloc] initWithStartingColor:color endingColor:color] autorelease]];
  3112. // [(SKGradientView *)secondaryPdfContentView setAlternateGradient:nil];
  3113. var pdfRect: NSRect = .zero
  3114. var controlRect: NSRect = .zero
  3115. NSDivideRect(self.secondaryPdfContentView?.bounds ?? .zero, &controlRect, &pdfRect, NSHeight(controlView?.frame ?? .zero), .minY)
  3116. controlRect.size.width = NSWidth(controlView?.frame ?? .zero)
  3117. controlView?.frame = controlRect
  3118. controlView?.autoresizingMask = [.maxXMargin, .maxYMargin, .width]
  3119. // [(SKGradientView *)secondaryPdfContentView setMinSize:controlRect.size];
  3120. self.secondaryPdfView?.frame = pdfRect
  3121. self.secondaryPdfContentView?.addSubview(controlView!)
  3122. self.openSecondaryPdfView = KMSecondaryViewController()
  3123. self.openSecondaryPdfView?.view.frame = self.secondaryPdfContentView?.frame ?? .zero
  3124. self.secondaryPdfContentView?.addSubview(self.openSecondaryPdfView!.view)
  3125. self.openSecondaryPdfView?.secondaryView.receivedFileUrlBlock = { [weak self] fileUrl in
  3126. if let docUrl = fileUrl {
  3127. _ = self?.displaySecondaryPDFView(withUrl: docUrl)
  3128. self?.openSecondaryPdfView?.view.removeFromSuperview()
  3129. self?.openSecondaryPdfView = nil
  3130. }
  3131. }
  3132. self.openSecondaryPdfView?.delegate = self
  3133. if (!isHorizontal) {
  3134. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3135. }
  3136. } else {
  3137. self.secondaryPdfContentView?.isHidden = true
  3138. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3139. }
  3140. // self.newPDFSplitView.setPosition(self.secondaryPdfContentView?.bounds.size.width ?? 120, ofDividerAt: 1, animate: true)
  3141. if (page != nil) {
  3142. self.secondaryPdfView?.go(toPageIndex: Int(page!.pageIndex()), animated: false)
  3143. // point = [secondaryPdfView convertPoint:[secondaryPdfView convertPoint:[pdfView convertPoint:point toPage:page] fromPage:page] toView:[secondaryPdfView documentView]];
  3144. let tmpP = self.listView.convert(point, to: page)
  3145. let conP = self.secondaryPdfView?.convert(tmpP, from: page) ?? .zero
  3146. point = self.secondaryPdfView?.convert(conP, to: self.secondaryPdfView?.documentView()) ?? .zero
  3147. if let docView = self.secondaryPdfView?.documentView(), docView.contentView.isFlipped == false {
  3148. point.y -= docView.isFlipped ? -NSHeight(docView.visibleRect) : NSHeight(docView.visibleRect)
  3149. }
  3150. self.secondaryPdfView?.documentView()?.scroll(point)
  3151. self.secondaryPdfView?.layoutDocumentView()
  3152. }
  3153. }
  3154. self.view.window?.recalculateKeyViewLoop()
  3155. if self.interactionMode == .legacyFullScreen {
  3156. self.view.window?.makeFirstResponder(self.listView)
  3157. }
  3158. if self.secondaryPdfView?.document == nil {
  3159. self.openSecondaryPdfView?.viewHighlyAdaptive()
  3160. }
  3161. }
  3162. }
  3163. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  3164. if (self.newPDFSplitView.isVertical) {
  3165. return Float(NSWidth(rect))
  3166. } else {
  3167. return Float(NSHeight(rect))
  3168. }
  3169. }
  3170. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  3171. let document = CPDFDocument.init(url: url)
  3172. if document != nil {
  3173. self.secondaryPdfView?.document = nil
  3174. self.secondaryPdfView?.document = document
  3175. self.rightSideViewController.annotationProperties.openPropertiesType = .pageDisplay
  3176. return true
  3177. } else {
  3178. return false
  3179. }
  3180. }
  3181. func updateNextAndPreViousButtonState() {
  3182. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3183. let view = item?.customizeView as? KMToolbarPreviousNextItemView
  3184. if let can = self.listView?.canGoToPreviousPage() {
  3185. view?.previousButton.isEnabled = can
  3186. } else {
  3187. view?.previousButton.isEnabled = false
  3188. }
  3189. if let can = self.listView?.canGoToNextPage() {
  3190. view?.nextButton.isEnabled = can
  3191. } else {
  3192. view?.nextButton.isEnabled = false
  3193. }
  3194. }
  3195. func updateBackAndForwardButtonState() {
  3196. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3197. if self.listView.km_canGoForward() {
  3198. toItem?.unEnabled = false
  3199. } else {
  3200. toItem?.unEnabled = true
  3201. }
  3202. }
  3203. }
  3204. // MARK: -
  3205. // MARK: - KMSecondaryViewControllerDelegate
  3206. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  3207. func receivedFileUrl(_ url: URL!) {
  3208. let state = self.displaySecondaryPDFView(withUrl: url)
  3209. if !state {
  3210. let alert = NSAlert()
  3211. alert.alertStyle = .critical
  3212. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3213. alert.runModal()
  3214. return
  3215. } else {
  3216. self.openSecondaryPdfView?.view.removeFromSuperview()
  3217. self.openSecondaryPdfView = nil
  3218. }
  3219. }
  3220. func controllerDidClose(_ controller: KMSecondaryViewController!) {
  3221. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  3222. }
  3223. }
  3224. // MARK: -
  3225. // MARK: - KMToolbarViewControllerDelegate
  3226. extension KMMainViewController : KMToolbarViewControllerDelegate {
  3227. func changeModelAction(mode: CToolMode) {
  3228. self.listView.toolMode = mode
  3229. if mode == .editPDFToolMode {
  3230. self.childToolbarController.updateType(newType: .editPDF)
  3231. }
  3232. }
  3233. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  3234. switch selectedTag {
  3235. case 2:
  3236. if self.listView.scaleFactor != 1.0 {
  3237. self.listView.scaleFactor = 1.0
  3238. self.listView.autoScales = false
  3239. }
  3240. break
  3241. case 1:
  3242. let pageHeight = self.listView.currentPage()!.size.height
  3243. let pdfviewHeight = self.listView.bounds.size.height
  3244. self.listView.scaleFactor = pdfviewHeight/pageHeight
  3245. self.listView.autoScales = false
  3246. break
  3247. case 0:
  3248. // self.listView.autoScales = !self.listView.autoScales
  3249. self.listView.autoScales = true
  3250. break
  3251. case 3:
  3252. self.listView.scaleFactor = 0.1
  3253. break
  3254. case 4:
  3255. self.listView.scaleFactor = 0.25
  3256. break
  3257. case 5:
  3258. self.listView.scaleFactor = 0.5
  3259. break
  3260. case 6:
  3261. self.listView.scaleFactor = 0.75
  3262. break
  3263. case 7:
  3264. self.listView.scaleFactor = 1.0
  3265. break
  3266. case 8:
  3267. self.listView.scaleFactor = 1.5
  3268. break
  3269. case 9:
  3270. self.listView.scaleFactor = 2.0
  3271. break
  3272. case 10:
  3273. self.listView.scaleFactor = 4.0
  3274. break
  3275. case 11:
  3276. self.listView.scaleFactor = 8.0
  3277. break
  3278. case 12:
  3279. self.listView.scaleFactor = 16.0
  3280. break
  3281. case 13:
  3282. self.listView.scaleFactor = 32.0
  3283. break
  3284. case 14:
  3285. self.listView.scaleFactor = 64.0
  3286. break
  3287. case 15:
  3288. self.listView.scaleFactor = 100.0
  3289. break
  3290. default:
  3291. break
  3292. }
  3293. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3294. if self.digitalSignController?.pdfView != nil {
  3295. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  3296. }
  3297. if self.redactController?.redactPdfView != nil {
  3298. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  3299. }
  3300. }
  3301. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  3302. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3303. if scale > 100 {
  3304. scale = 100
  3305. }
  3306. if (scale <= 0.101) {
  3307. self.listView.scaleFactor = self.listView.minScaleFactor()
  3308. } else {
  3309. self.listView.scaleFactor = scale
  3310. }
  3311. if self.digitalSignController?.pdfView != nil {
  3312. self.digitalSignController?.pdfView.scaleFactor = self.listView.scaleFactor
  3313. }
  3314. if self.redactController?.redactPdfView != nil {
  3315. self.redactController?.redactPdfView.scaleFactor = self.listView.scaleFactor
  3316. }
  3317. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3318. }
  3319. func changePDFViewZoomInAction() {
  3320. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3321. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3322. switch scale {
  3323. case 0...0.25:
  3324. scale += 0.25
  3325. case 0.25...3:
  3326. scale += 0.25
  3327. case 3.1...10:
  3328. scale += 0.4
  3329. case 10.1...100:
  3330. scale += 1
  3331. default:
  3332. scale += 1
  3333. }
  3334. self.listView.scaleFactor = scale
  3335. // nearbyint
  3336. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3337. // self.listView.zoomIn(nil)
  3338. if self.digitalSignController?.pdfView != nil {
  3339. self.digitalSignController?.pdfView.scaleFactor = scale
  3340. }
  3341. if self.redactController?.redactPdfView != nil {
  3342. self.redactController?.redactPdfView.scaleFactor = scale
  3343. }
  3344. }
  3345. func changePDFViewZoomOutAction() {
  3346. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3347. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3348. switch scale {
  3349. case 0...0.25:
  3350. scale = 0
  3351. case 0.25...3:
  3352. scale -= 0.25
  3353. case 3.1...10:
  3354. scale -= 0.4
  3355. case 10.1...100:
  3356. scale -= 1
  3357. default:
  3358. scale -= 1
  3359. }
  3360. self.listView.scaleFactor = scale
  3361. // nearbyint
  3362. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3363. // self.listView.zoomOut(nil)
  3364. if self.digitalSignController?.pdfView != nil {
  3365. self.digitalSignController?.pdfView.scaleFactor = scale
  3366. }
  3367. if self.redactController?.redactPdfView != nil {
  3368. self.redactController?.redactPdfView.scaleFactor = scale
  3369. }
  3370. self.savePageNumberIfNeed()
  3371. }
  3372. func changePDFViewGotoNextPageAction() {
  3373. self.listView.km_goBack(nil)
  3374. if (self.listView.canGoToNextPage()) {
  3375. self.listView.goToNextPage(nil)
  3376. }
  3377. self.updateNextAndPreViousButtonState()
  3378. }
  3379. func changePDFViewGoToPreviousPageAction() {
  3380. if (self.listView.canGoToPreviousPage()) {
  3381. self.listView.goToPreviousPage(nil)
  3382. }
  3383. self.updateNextAndPreViousButtonState()
  3384. }
  3385. func changePDFViewGotoBackAction() {
  3386. self.listView.km_goBack(nil)
  3387. self.updateBackAndForwardButtonState()
  3388. }
  3389. func changePDFViewGoToForwardAction() {
  3390. self.listView.km_goForward(nil)
  3391. self.updateBackAndForwardButtonState()
  3392. }
  3393. func aiTranslationPDFFileAction() {
  3394. #if VERSION_DMG
  3395. #else
  3396. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  3397. KMLoginWindowController.show(window: NSApp.mainWindow!)
  3398. return
  3399. }
  3400. #endif
  3401. self.trackEvent_aiTranslate()
  3402. self._aiTranslationPDFFileAction()
  3403. }
  3404. private func _aiTranslationPDFFileAction() {
  3405. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  3406. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  3407. let alert = NSAlert()
  3408. alert.alertStyle = .critical
  3409. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  3410. alert.runModal()
  3411. return
  3412. } else if isExceedsLimit {
  3413. let alert = NSAlert()
  3414. alert.alertStyle = .critical
  3415. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  3416. alert.runModal()
  3417. return
  3418. }
  3419. let alert = NSAlert()
  3420. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  3421. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  3422. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3423. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  3424. if (result == .alertFirstButtonReturn) {
  3425. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  3426. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  3427. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  3428. } else if result == .alertSecondButtonReturn {
  3429. return
  3430. }
  3431. }
  3432. }
  3433. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  3434. self.trackEvent_share()
  3435. }
  3436. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  3437. self.shareDocument(sender: viewController)
  3438. }
  3439. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3440. // if IAPProductsManager.default().isAvailableAllFunction() == false {
  3441. // KMProductCompareWC.shared.orientation = false
  3442. // let winC = KMProductCompareWC.shared
  3443. // winC.kEventName = "Reading_Flatten_BuyNow"
  3444. // winC.showWindow(nil)
  3445. // return
  3446. // }
  3447. if KMMemberInfo.shared.isMemberAllFunction == false {
  3448. let winC = KMProductCompareWC.shared
  3449. winC.kEventName = "Reading_Flatten_BuyNow"
  3450. KMMemberInfo.shared.advancedFunctionUsage()
  3451. return
  3452. }
  3453. self.shareFlatten(sender: viewController)
  3454. }
  3455. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  3456. self.shareOriginalPDF(sender: viewController)
  3457. }
  3458. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  3459. if(0 == selectedTag) {
  3460. // self.documentAIViewController?.enteredIncreaseAllPage()
  3461. // self.documentAIViewController?.updateToolState(false)
  3462. } else {
  3463. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  3464. // self.documentAIViewController?.recognitionPartModel(with: .english)
  3465. // self.documentAIViewController?.updateToolState(true)
  3466. }
  3467. // 0 : Scan 1:OCR Text
  3468. }
  3469. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  3470. if beforeType == .editPDF {
  3471. self.editPDFHanddler.enterEditPDF()
  3472. }
  3473. if(type != .Page) {
  3474. if (hasEnterPageEdit()) {
  3475. self.exitPageEdit()
  3476. }
  3477. }
  3478. if type != .redact {
  3479. if self.hasEnterRedact() {
  3480. self.exitRedact()
  3481. }
  3482. }
  3483. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3484. if self.hasShowDigitalSign() {
  3485. self.exitDigitalSign()
  3486. }
  3487. }
  3488. if item.itemIdentifier != KMDocumentViewDisplayToolbarItemIdentifier {
  3489. self.toolbarController.findItem(KMDocumentViewDisplayToolbarItemIdentifier)?.isSelected = false
  3490. }
  3491. if(type != .Form) {
  3492. self.removeFromAlertView()
  3493. }
  3494. if (type == .Page) {
  3495. if (hasEnterPageEdit()) {
  3496. self.exitPageEdit()
  3497. } else {
  3498. self.enterPageEdit(pages)
  3499. }
  3500. } else if type == .editPDF {
  3501. self.enterEditPDF()
  3502. } else if type == .Annatiton {
  3503. self.rightSideViewController.subViewType = .AnnotationProperts
  3504. } else if type == .redact {
  3505. if self.needSaveDocument() {
  3506. self.saveDocumentWithProgressAlert { [unowned self] params in
  3507. self.enterRedact()
  3508. }
  3509. return
  3510. }
  3511. let isEdited = self.listView.isEdited()
  3512. let isPDFTextImageEdited = self.model.isPDFTextImageEdited
  3513. if isEdited || isPDFTextImageEdited {
  3514. self.commitEditingIfNeed()
  3515. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  3516. self.enterRedact()
  3517. // }
  3518. } else {
  3519. self.enterRedact()
  3520. }
  3521. } else if type == .Tool {
  3522. if KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  3523. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  3524. } else if KMGuideInfoWindowController.availableShow(.measureGuide) {
  3525. self.loadOpenFileFunctionGuide(.measureGuide)
  3526. }
  3527. } else if type == . Conversion {
  3528. self.loadOpenFileFunctionGuide(.convertGuide)
  3529. }else if type == .Form {
  3530. self.showFormAlertView()
  3531. }else if type == .Select {
  3532. self.rightSideViewController.isHidden = true
  3533. self.closeRightPane()
  3534. }
  3535. }
  3536. func clickChildTool(type: KMToolbarType, index: Int) {
  3537. if (type == .secure) {
  3538. if (index == 1) {
  3539. self.trackEvent_setPassword()
  3540. } else if (index == 2) {
  3541. self.trackEvent_removePassword()
  3542. }
  3543. } else {
  3544. self.trackEvent(toolBarType: type)
  3545. }
  3546. Task { @MainActor in
  3547. if (type == .compress) { /// 压缩
  3548. if !self.documentAllowsEdit() {
  3549. return
  3550. }
  3551. if (self.needSaveDocument()) {
  3552. self.saveDocumentWithProgressAlert { [unowned self] params in
  3553. self.showCompressWindow()
  3554. }
  3555. return
  3556. }
  3557. self.showCompressWindow()
  3558. return
  3559. }
  3560. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  3561. if type == .conversion_imageToPDF {
  3562. Task {
  3563. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  3564. }
  3565. return
  3566. }
  3567. var identifier: String?
  3568. if (type == .word) { /// Word
  3569. identifier = KMToolbarConversionWordItemIdentifier
  3570. } else if (type == .excel) {
  3571. identifier = KMToolbarConversionExcelItemIdentifier
  3572. } else if (type == .ppt) {
  3573. identifier = KMToolbarConversionPPTItemIdentifier
  3574. } else if (type == .rtf) {
  3575. identifier = KMToolbarConversionRTFItemIdentifier
  3576. } else if (type == .html) {
  3577. identifier = KMToolbarConversionHTMLItemIdentifier
  3578. } else if (type == .conversion_text) {
  3579. identifier = KMToolbarConversionTextItemIdentifier
  3580. } else if (type == .csv) {
  3581. identifier = KMToolbarConversionCSVItemIdentifier
  3582. } else if (type == .conversion_image) {
  3583. identifier = KMToolbarConversionImageItemIdentifier
  3584. }
  3585. if (self.needSaveDocument()) {
  3586. self.saveDocumentWithProgressAlert { [unowned self] params in
  3587. self.showConvertWindow(type: type, identifier: identifier)
  3588. }
  3589. return
  3590. }
  3591. self.showConvertWindow(type: type, identifier: identifier)
  3592. return
  3593. }
  3594. if (type == .merge) { /// 合并
  3595. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  3596. if !self.documentAllowsEdit() {
  3597. return
  3598. }
  3599. if (self.needSaveDocument()) {
  3600. self.saveDocumentWithProgressAlert { [unowned self] params in
  3601. self.showMergeWindow(self.listView.document.password)
  3602. }
  3603. return
  3604. }
  3605. self.showMergeWindow(self.listView.document.password)
  3606. return
  3607. }
  3608. if (type == .bates || type == .headerAndFooter) {
  3609. // if !IAPProductsManager.default().isAvailableAllFunction(){
  3610. // KMProductCompareWC.shared.orientation = false
  3611. // let winC = KMProductCompareWC.shared
  3612. // if type == .headerAndFooter {
  3613. // if index == 1 {
  3614. // winC.kEventName = "Reading_AddHeaderFooter_BuyNow"
  3615. // } else if index == 2 {
  3616. // winC.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  3617. // }
  3618. // } else if type == .bates {
  3619. // if index == 1 {
  3620. // winC.kEventName = "Reading_AddBates_BuyNow"
  3621. // } else if index == 2 {
  3622. // winC.kEventName = "Reading_RemoveBates_BuyNow"
  3623. // }
  3624. // }
  3625. // winC.showWindow(nil)
  3626. // return
  3627. // }
  3628. if KMMemberInfo.shared.isMemberAllFunction == false {
  3629. let winC = KMProductCompareWC.shared
  3630. if type == .headerAndFooter {
  3631. if index == 1 {
  3632. winC.kEventName = "Reading_AddHeaderFooter_BuyNow"
  3633. } else if index == 2 {
  3634. winC.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  3635. }
  3636. } else if type == .bates {
  3637. if index == 1 {
  3638. winC.kEventName = "Reading_AddBates_BuyNow"
  3639. } else if index == 2 {
  3640. winC.kEventName = "Reading_RemoveBates_BuyNow"
  3641. }
  3642. }
  3643. KMMemberInfo.shared.advancedFunctionUsage()
  3644. return
  3645. }
  3646. if !self.documentAllowsEdit() {
  3647. return
  3648. }
  3649. if (index == 1) {
  3650. var windowController: KMBaseWindowController = KMBaseWindowController()
  3651. if (type == .bates) {
  3652. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3653. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3654. let fpath = self.document?.documentURL?.path ?? ""
  3655. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3656. }
  3657. windowController.isBates = true
  3658. } else if (type == .headerAndFooter) {
  3659. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3660. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3661. let fpath = self.document?.documentURL?.path ?? ""
  3662. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3663. }
  3664. } else if (type == .background) {
  3665. } else if (type == .watermark) {
  3666. // controller = KMWatermarkViewController()
  3667. }
  3668. windowController.pdfDocument = self.listView.document
  3669. windowController.cancelAction = { [unowned self] controller in
  3670. self.view.window?.endSheet((self.currentWindowController.window)!)
  3671. self.currentWindowController = nil
  3672. }
  3673. self.currentWindowController = windowController
  3674. await self.view.window?.beginSheet(windowController.window!)
  3675. return
  3676. }
  3677. if (index == 1) { /// 取消
  3678. self.toolbarController.exitWatermarkAdjective()
  3679. // self.rightSideViewController.view.isHidden = true
  3680. self.rightSideViewController.isHidden = true
  3681. self.rightSideViewController.subViewType = .None
  3682. self.closeRightPane()
  3683. return
  3684. } else if index == 3 {
  3685. let fpath = self.document?.documentURL?.path ?? ""
  3686. if type == .bates {
  3687. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  3688. } else {
  3689. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  3690. }
  3691. } else if index == 4 {
  3692. let fpath = self.document?.documentURL?.path ?? ""
  3693. if type == .bates {
  3694. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  3695. } else {
  3696. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  3697. }
  3698. } else if (index == 2) { //// 移除
  3699. if type == .headerAndFooter {
  3700. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3701. let savePanel = NSSavePanel()
  3702. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3703. savePanel.allowedFileTypes = ["pdf"]
  3704. savePanel.accessoryView = savePanelAccessoryViewController.view
  3705. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3706. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3707. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3708. if success == 1 && savePanel.url?.path == self.listView?.document?.documentURL.path {
  3709. self.setDocument = CPDFDocument(url: savePanel.url!)
  3710. return
  3711. }
  3712. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3713. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3714. }
  3715. } else {
  3716. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3717. }
  3718. }
  3719. }
  3720. }
  3721. } else if type == .bates {
  3722. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3723. let savePanel = NSSavePanel()
  3724. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3725. savePanel.allowedFileTypes = ["pdf"]
  3726. savePanel.accessoryView = savePanelAccessoryViewController.view
  3727. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3728. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3729. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3730. if success == 1 && savePanel.url?.path == self.listView?.document?.documentURL.path {
  3731. self.setDocument = CPDFDocument(url: savePanel.url!)
  3732. return
  3733. }
  3734. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3735. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3736. }
  3737. } else {
  3738. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3739. }
  3740. }
  3741. }
  3742. }
  3743. }
  3744. return
  3745. } else if (index == 2) { /// 应用
  3746. let model = self.rightSideViewController.model
  3747. if (type == .bates || type == .headerAndFooter) {
  3748. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3749. let alert = NSAlert()
  3750. alert.alertStyle = .critical
  3751. alert.messageText = "没有找到模型"
  3752. alert.runModal()
  3753. return
  3754. }
  3755. if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3756. let alert = NSAlert()
  3757. alert.alertStyle = .critical
  3758. alert.messageText = "没有找到内容"
  3759. alert.runModal()
  3760. return
  3761. }
  3762. }
  3763. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3764. result in
  3765. DispatchQueue.main.async {
  3766. self.listView.layoutDocumentView()
  3767. self.listView.setNeedsDisplayForVisiblePages()
  3768. }
  3769. if (result) {
  3770. let alert = NSAlert()
  3771. alert.alertStyle = .warning
  3772. alert.messageText = "成功"
  3773. alert.runModal()
  3774. } else {
  3775. let alert = NSAlert()
  3776. alert.alertStyle = .critical
  3777. alert.messageText = "失败"
  3778. alert.runModal()
  3779. }
  3780. }
  3781. return
  3782. } else if index == 5 {
  3783. self.rightSideViewController.isHidden = false
  3784. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3785. self.openRightPane()
  3786. }
  3787. } else if (type == .redact) { /// 标记密文
  3788. // if !IAPProductsManager.default().isAvailableAllFunction(){
  3789. // KMProductCompareWC.shared.orientation = false
  3790. // KMProductCompareWC.shared.showWindow(nil)
  3791. // return
  3792. // }
  3793. if KMMemberInfo.shared.isMemberAllFunction == false {
  3794. KMMemberInfo.shared.advancedFunctionUsage()
  3795. return
  3796. }
  3797. if (index == 1) { /// 取消
  3798. if (self.model.hasAddRedact) {
  3799. let alert = NSAlert()
  3800. 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: "")
  3801. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3802. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3803. let result = alert.runModal()
  3804. if (result == .alertFirstButtonReturn) {
  3805. self.listView.toolMode = .moveToolMode
  3806. self.toolbarController.exitRedact()
  3807. }
  3808. return
  3809. }
  3810. self.listView.toolMode = .moveToolMode
  3811. self.toolbarController.exitRedact()
  3812. return
  3813. }
  3814. if (index == 2) { /// 擦除
  3815. self.exeRedactConfirm(.eraserAll) {}
  3816. return
  3817. }
  3818. if (index == 3) { /// 应用
  3819. self.exeRedactConfirm(.redactAll) {}
  3820. return
  3821. }
  3822. if (index == 4) { /// 文本&图像
  3823. self.listView.toolMode = .redactToolMode
  3824. return
  3825. }
  3826. if (index == 5) { /// 页面
  3827. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3828. await self.view.window?.beginSheet(windowController.window!)
  3829. self.currentWindowController = windowController
  3830. windowController.itemClick = { [weak self] index, value in
  3831. if (index == 1) {
  3832. let topBarView = self?.toolbarController.fetchTopBarView()
  3833. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3834. return
  3835. }
  3836. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3837. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3838. self?.currentWindowController = nil
  3839. return
  3840. }
  3841. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3842. let pageType = windowController_pageRange.pageType
  3843. let pageString = windowController_pageRange.pageString
  3844. if (pageType == 5) { /// 自定义页面
  3845. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  3846. if (array.count == 0) {
  3847. let alert = NSAlert()
  3848. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3849. alert.runModal()
  3850. return
  3851. }
  3852. }
  3853. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3854. self!.currentWindowController = nil
  3855. var indexs: IndexSet = []
  3856. if (pageType == 1) { /// 当前页面
  3857. indexs.insert((self?.listView.currentPageIndex)!)
  3858. } else {
  3859. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  3860. }
  3861. if (indexs.count == 0) {
  3862. return
  3863. }
  3864. for i in indexs {
  3865. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3866. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3867. redactAnno.bounds = page.bounds
  3868. self?.listView.add(redactAnno, to: page)
  3869. }
  3870. }
  3871. return
  3872. }
  3873. } else if (type == .secure) { /// 安全
  3874. if (index == 1) { /// 设置密码
  3875. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3876. if !self.documentAllowsEdit() {
  3877. return
  3878. }
  3879. // KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3880. // if (result == .cancel) {
  3881. // return
  3882. // }
  3883. //
  3884. // self?.isSaveKeyChain = false
  3885. // self?.listView.document.unlock(withPassword: password)
  3886. // self?.hiddenSecureLimitTip()
  3887. //
  3888. // self?.showSecureWindow((self?.listView.document.documentURL)!)
  3889. // }
  3890. // return
  3891. }
  3892. self.showSecureWindow(self.listView.document.documentURL)
  3893. return
  3894. } else if index == 2 {
  3895. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3896. let alert = NSAlert()
  3897. alert.alertStyle = .warning
  3898. alert.messageText = NSLocalizedString("Warning", comment: "")
  3899. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3900. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3901. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3902. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3903. if returnCode == .alertSecondButtonReturn {
  3904. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3905. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3906. if success {
  3907. self.document?.unlock(withPassword: resultPassword)
  3908. self.clickChildTool(type: .secure, index: 2)
  3909. }
  3910. }
  3911. }
  3912. }
  3913. }
  3914. } else {
  3915. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3916. controller.pdfDocument = self.document
  3917. self.currentWindowController = controller
  3918. controller.batchAction = { [unowned self] controller, files in
  3919. self.view.window?.endSheet((self.currentWindowController.window)!)
  3920. self.currentWindowController = nil
  3921. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3922. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3923. if #available(macOS 10.13, *) {
  3924. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3925. } else {
  3926. baseWindowController.showWindow(nil)
  3927. }
  3928. let arr = NSMutableArray()
  3929. let file = KMBatchOperateFile(filePath: self.listView!.document!.documentURL!.path, type: .RemovePassword)
  3930. file.password = document?.password ?? ""
  3931. arr.add(file)
  3932. // baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .RemovePassword, files: arr as! [KMBatchOperateFile])
  3933. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  3934. }
  3935. controller.cancelAction = { [unowned self] controller in
  3936. self.view.window?.endSheet((self.currentWindowController.window)!)
  3937. self.currentWindowController = nil
  3938. }
  3939. controller.doneAction = { [unowned self] controller in
  3940. self.view.window?.endSheet((self.currentWindowController.window)!)
  3941. self.currentWindowController = nil
  3942. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  3943. if success {
  3944. // let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3945. let savePanel = NSSavePanel()
  3946. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3947. savePanel.allowedFileTypes = ["pdf"]
  3948. // savePanel.accessoryView = savePanelAccessoryViewController.view
  3949. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3950. guard result == .OK else { return }
  3951. /// 删除安全性设置
  3952. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3953. self.model.isSaveKeyChain = false
  3954. self.listView.document.unlock(withPassword: resultPassword)
  3955. }
  3956. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3957. guard let document = document else { return }
  3958. document.unlock(withPassword: resultPassword)
  3959. let success = document.writeDecrypt(to: savePanel.url)
  3960. if success {
  3961. self.hiddenSecureLimitTip()
  3962. let tip = KMRemovePasswordResultTipView()
  3963. tip.result = .success
  3964. tip.showInView(superView: (self.listView.superview)!)
  3965. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3966. } else {
  3967. self.hiddenSecureLimitTip()
  3968. let tip = KMRemovePasswordResultTipView()
  3969. tip.result = .failure
  3970. tip.showInView(superView: (self.listView.superview)!)
  3971. }
  3972. }
  3973. }
  3974. }
  3975. }
  3976. await NSWindow.currentWindow().beginSheet(controller.window!)
  3977. }
  3978. return
  3979. }
  3980. } else if type == .comparison {
  3981. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3982. // if !IAPProductsManager.default().isAvailableAllFunction(){
  3983. // KMProductCompareWC.shared.orientation = false
  3984. // let winC = KMProductCompareWC.shared
  3985. // winC.kEventName = "Reading_Compare_BuyNow"
  3986. // winC.showWindow(nil)
  3987. // return
  3988. // }
  3989. if KMMemberInfo.shared.isMemberAllFunction == false {
  3990. let winC = KMProductCompareWC.shared
  3991. winC.kEventName = "Reading_Compare_BuyNow"
  3992. KMMemberInfo.shared.advancedFunctionUsage()
  3993. return
  3994. }
  3995. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3996. self.currentWindowController = controller
  3997. controller.password = self.document?.password ?? ""
  3998. controller.filePath = (self.document?.documentURL.path)!
  3999. controller.cancelAction = { [unowned self] controller in
  4000. self.view.window?.endSheet((self.currentWindowController.window)!)
  4001. self.currentWindowController = nil
  4002. }
  4003. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  4004. self.view.window?.endSheet((self.currentWindowController.window)!)
  4005. self.currentWindowController = nil
  4006. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  4007. }
  4008. controller.coveringComplete = { [unowned self] controller, document in
  4009. self.view.window?.endSheet((self.currentWindowController.window)!)
  4010. self.currentWindowController = nil
  4011. self.openCoveringCompareVC(with: document)
  4012. }
  4013. if index == 1 {
  4014. controller.fileType = .content
  4015. } else {
  4016. controller.fileType = .coverting
  4017. }
  4018. await NSWindow.currentWindow().beginSheet(controller.window!)
  4019. } else if type == .watermark {
  4020. // if !IAPProductsManager.default().isAvailableAllFunction(){
  4021. // KMProductCompareWC.shared.orientation = false
  4022. // let winC = KMProductCompareWC.shared
  4023. // if index == 1 {
  4024. // winC.kEventName = "Reading_AddWatermark_BuyNow"
  4025. // } else if index == 2 {
  4026. // winC.kEventName = "Reading_RemoveWatermark_BuyNow"
  4027. // }
  4028. // winC.showWindow(nil)
  4029. // return
  4030. // }
  4031. if KMMemberInfo.shared.isMemberAllFunction == false {
  4032. let winC = KMProductCompareWC.shared
  4033. if index == 1 {
  4034. winC.kEventName = "Reading_AddWatermark_BuyNow"
  4035. } else if index == 2 {
  4036. winC.kEventName = "Reading_RemoveWatermark_BuyNow"
  4037. }
  4038. KMMemberInfo.shared.advancedFunctionUsage()
  4039. return
  4040. }
  4041. if !self.documentAllowsEdit() {
  4042. return
  4043. }
  4044. if index == 1 {
  4045. self.watermarkWindowController = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  4046. self.watermarkWindowController!.pdfDocument = self.document
  4047. self.watermarkWindowController!.cancelAction = { [unowned self] controller in
  4048. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  4049. self.km_endSheet()
  4050. }
  4051. self.watermarkWindowController!.operateCallBack = { [unowned self] controller, watermark, countType in
  4052. // self.view.window?.endSheet((self.watermarkWindowController!.window)!)
  4053. self.km_endSheet()
  4054. let fpath = self.document?.documentURL?.path ?? ""
  4055. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  4056. }
  4057. // NSWindow.currentWindow().beginSheet(controller.window!)
  4058. // NSWindow.currentWindow().beginSheet(self.watermarkWindowController!.window!, completionHandler: nil)
  4059. self.km_beginSheet(windowC: self.watermarkWindowController!)
  4060. } else if index == 2 {
  4061. let watermarks = self.listView.document.watermarks()
  4062. if (watermarks == nil || watermarks!.count <= 0) {
  4063. let alert = NSAlert()
  4064. alert.alertStyle = .warning
  4065. 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: "")
  4066. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  4067. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  4068. alert.runModal()
  4069. return
  4070. }
  4071. let alert = NSAlert()
  4072. alert.alertStyle = .warning
  4073. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  4074. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  4075. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  4076. let result = alert.runModal()
  4077. if (result != .alertFirstButtonReturn) {
  4078. return
  4079. }
  4080. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  4081. let savePanel = NSSavePanel()
  4082. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  4083. savePanel.allowedFileTypes = ["pdf"]
  4084. savePanel.accessoryView = savePanelAccessoryViewController.view
  4085. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  4086. guard result == .OK else { return }
  4087. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  4088. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  4089. result in
  4090. DispatchQueue.main.async {
  4091. self.listView.layoutDocumentView()
  4092. self.listView.setNeedsDisplayForVisiblePages()
  4093. }
  4094. if (result) {
  4095. let alert = NSAlert()
  4096. alert.alertStyle = .warning
  4097. alert.messageText = NSLocalizedString("Finish", comment: "")
  4098. alert.runModal()
  4099. if savePanel.url?.path == self.listView?.document?.documentURL.path {
  4100. self.setDocument = CPDFDocument(url: savePanel.url!)
  4101. return
  4102. }
  4103. let needOpen = savePanelAccessoryViewController.needOpen
  4104. if needOpen {
  4105. NSDocumentController.shared.km_safe_openDocument(withContentsOf: savePanel.url!, display: true) { document, hasOpen, err in }
  4106. } else {
  4107. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4108. }
  4109. } else {
  4110. let alert = NSAlert()
  4111. alert.alertStyle = .critical
  4112. alert.messageText = NSLocalizedString("Failed", comment: "")
  4113. alert.runModal()
  4114. }
  4115. }
  4116. }
  4117. } else if index == 3 {
  4118. let fpath = self.document?.documentURL?.path ?? ""
  4119. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  4120. } else if index == 4 {
  4121. let fpath = self.document?.documentURL?.path ?? ""
  4122. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  4123. } else if index == 5 {
  4124. self.rightSideViewController.isHidden = false
  4125. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  4126. self.openRightPane()
  4127. return
  4128. }
  4129. } else if type == .background {
  4130. // if !IAPProductsManager.default().isAvailableAllFunction(){
  4131. // KMProductCompareWC.shared.orientation = false
  4132. // let winC = KMProductCompareWC.shared
  4133. // if index == 1 {
  4134. // winC.kEventName = "Reading_AddBackground_BuyNow"
  4135. // } else if index == 2 {
  4136. // winC.kEventName = "Reading_RemoveBackground_BuyNow"
  4137. // }
  4138. // winC.showWindow(nil)
  4139. // return
  4140. // }
  4141. if KMMemberInfo.shared.isMemberAllFunction == false {
  4142. let winC = KMProductCompareWC.shared
  4143. if index == 1 {
  4144. winC.kEventName = "Reading_AddBackground_BuyNow"
  4145. } else if index == 2 {
  4146. winC.kEventName = "Reading_RemoveBackground_BuyNow"
  4147. }
  4148. KMMemberInfo.shared.advancedFunctionUsage()
  4149. return
  4150. }
  4151. if !self.documentAllowsEdit() {
  4152. return
  4153. }
  4154. if index == 1 {
  4155. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  4156. self.currentWindowController = controller
  4157. controller.pdfDocument = self.document
  4158. controller.cancelAction = { [unowned self] controller in
  4159. self.view.window?.endSheet((self.currentWindowController.window)!)
  4160. self.currentWindowController = nil
  4161. }
  4162. controller.operateCallBack = { [unowned self] controller, background, countType in
  4163. let fpath = self.document?.documentURL?.path ?? ""
  4164. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  4165. }
  4166. await NSWindow.currentWindow().beginSheet(controller.window!)
  4167. } else if index == 2 {
  4168. guard let document = self.document else { return }
  4169. if !document.allowsPrinting || !document.allowsCopying {
  4170. let alert = NSAlert()
  4171. alert.alertStyle = .critical
  4172. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4173. alert.runModal()
  4174. return
  4175. }
  4176. guard let documentURL = document.documentURL else { return }
  4177. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  4178. let savePanel = NSSavePanel()
  4179. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  4180. savePanel.allowedFileTypes = ["pdf"]
  4181. savePanel.accessoryView = savePanelAccessoryViewController.view
  4182. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  4183. guard result == .OK else { return }
  4184. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  4185. if success == 1 {
  4186. if savePanel.url?.path == self.listView?.document?.documentURL.path {
  4187. self.setDocument = CPDFDocument(url: savePanel.url!)
  4188. return
  4189. }
  4190. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  4191. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  4192. } else {
  4193. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  4194. }
  4195. }
  4196. })
  4197. }
  4198. } else if index == 3 {
  4199. let fpath = self.document?.documentURL?.path ?? ""
  4200. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  4201. } else if index == 4 {
  4202. let fpath = self.document?.documentURL?.path ?? ""
  4203. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  4204. } else if index == 5 {
  4205. self.rightSideViewController.isHidden = false
  4206. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  4207. self.openRightPane()
  4208. return
  4209. }
  4210. } else if type == .measure {
  4211. // if !IAPProductsManager.default().isAvailableAllFunction(){
  4212. // KMProductCompareWC.shared.orientation = false
  4213. // let winC = KMProductCompareWC.shared
  4214. // winC.kEventName = "Reading_Measure_BuyNow"
  4215. // winC.showWindow(nil)
  4216. // return
  4217. // }
  4218. if KMMemberInfo.shared.isMemberAllFunction == false {
  4219. let winC = KMProductCompareWC.shared
  4220. winC.kEventName = "Reading_Measure_BuyNow"
  4221. KMMemberInfo.shared.advancedFunctionUsage()
  4222. return
  4223. }
  4224. if !self.documentAllowsEdit() {
  4225. return
  4226. }
  4227. self.listView.toolMode = .measureToolMode
  4228. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  4229. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4230. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  4231. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4232. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  4233. areaMeasureInfoWindowController?.hideFloatingWindow()
  4234. }
  4235. if distanceMeasureInfoWindowController == nil {
  4236. let measureInfo = CPDFDistanceMeasureInfo()
  4237. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  4238. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  4239. distanceMeasureInfoWindowController?.delegate = self
  4240. }
  4241. if perimeterMeasureInfoWindowController == nil {
  4242. let measureInfo = CPDFPerimeterMeasureInfo()
  4243. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  4244. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  4245. perimeterMeasureInfoWindowController?.delegate = self
  4246. }
  4247. if areaMeasureInfoWindowController == nil {
  4248. let measureInfo = CPDFAreaMeasureInfo()
  4249. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  4250. areaMeasureInfoWindowController?.measureInfo = measureInfo
  4251. areaMeasureInfoWindowController?.delegate = self
  4252. }
  4253. if index == 1 {
  4254. self.listView.annotationType = .line
  4255. let winW: CGFloat = 300
  4256. let rightW: CGFloat = 270
  4257. var winFrame = self.view.window?.frame ?? .zero
  4258. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4259. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4260. distanceMeasureInfoWindowController?.showWindow(nil)
  4261. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4262. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4263. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4264. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4265. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4266. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4267. self.trackEvent(toolMode: .measureToolMode)
  4268. } else if index == 2 {
  4269. self.listView.annotationType = .polyLine
  4270. let winW: CGFloat = 300
  4271. let rightW: CGFloat = 270
  4272. var winFrame = self.view.window?.frame ?? .zero
  4273. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4274. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4275. perimeterMeasureInfoWindowController?.showWindow(nil)
  4276. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4277. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4278. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4279. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4280. self.trackEvent(toolMode: .measureToolMode)
  4281. } else if index == 3 {
  4282. self.listView.annotationType = .polyGon
  4283. let winW: CGFloat = 300
  4284. let rightW: CGFloat = 270
  4285. var winFrame = self.view.window?.frame ?? .zero
  4286. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4287. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4288. areaMeasureInfoWindowController?.showWindow(nil)
  4289. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4290. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4291. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4292. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4293. self.trackEvent(toolMode: .measureToolMode)
  4294. } else if index == 4 {
  4295. self.listView.annotationType = .square
  4296. let winW: CGFloat = 300
  4297. let rightW: CGFloat = 270
  4298. var winFrame = self.view.window?.frame ?? .zero
  4299. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  4300. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  4301. areaMeasureInfoWindowController?.showWindow(nil)
  4302. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4303. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4304. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = true
  4305. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  4306. self.trackEvent(toolMode: .measureToolMode)
  4307. } else {
  4308. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  4309. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4310. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  4311. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4312. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  4313. areaMeasureInfoWindowController?.hideFloatingWindow()
  4314. }
  4315. self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = false
  4316. }
  4317. self.rightSideViewController.reloadDataWithPDFView(pdfView: listView, isShow: true)
  4318. self.openRightPane()
  4319. }
  4320. }
  4321. }
  4322. // func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  4323. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4324. //// batchWindowController.window?.makeKeyAndOrderFront("")
  4325. //
  4326. // var array: [KMBatchOperateFile] = []
  4327. // for file in files ?? [] {
  4328. // let batchOperateFile = KMBatchOperateFile(filePath: file.filePath, type: type)
  4329. // array.append(batchOperateFile)
  4330. // }
  4331. // batchWindowController.switchToOperateType(type, files: array)
  4332. // batchWindowController.window?.makeKeyAndOrderFront("")
  4333. // }
  4334. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  4335. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4336. var array: [KMBatchOperateFile] = []
  4337. for fpath in filepaths ?? [] {
  4338. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  4339. array.append(batchOperateFile)
  4340. }
  4341. batchWindowController.switchToOperateType(type, files: array)
  4342. batchWindowController.window?.makeKeyAndOrderFront("")
  4343. }
  4344. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  4345. self.toolbarItemClickForExitMode(toolbarItem)
  4346. if let itemID = toolbarItem.itemIdentifier {
  4347. if isMainToolItem(itemID) {
  4348. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  4349. openNewWindowAlertWindow()
  4350. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  4351. self.changePDFViewGoToPreviousPageAction()
  4352. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4353. let isSelected = toolbarItem.isSelected
  4354. self.toolbarController.toolbarType = isSelected ? .None : .viewSetting
  4355. toolbarItem.isSelected = !isSelected
  4356. if toolbarItem.isSelected {
  4357. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  4358. self.rightSideViewController.isHidden = false
  4359. self.rightSideViewController.mainController = self
  4360. self.rightSideViewController.subViewType = .ViewSettings
  4361. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4362. self.openRightPane()
  4363. }else{
  4364. self.rightSideViewController.isHidden = true
  4365. self.rightSideViewController.subViewType = .AnnotationProperts
  4366. closeRightPane()
  4367. }
  4368. if toolbarItem.isSelected {
  4369. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  4370. }
  4371. let rightItem = self.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  4372. if isSelected {
  4373. rightItem?.isSelected = false
  4374. } else {
  4375. rightItem?.isSelected = true
  4376. }
  4377. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  4378. toolbarItem.isSelected = !toolbarItem.isSelected
  4379. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  4380. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4381. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  4382. self.rightSideViewController.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
  4383. }
  4384. toolbarItem.isSelected = !toolbarItem.isSelected
  4385. self.toggleRightPane()
  4386. if self.listView.toolMode == .editPDFToolMode {
  4387. self.editPDFHanddler.rightSideLastState = toolbarItem.isSelected ? .open : .close
  4388. }
  4389. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  4390. self.listView.toolMode = .redactToolMode
  4391. self.enterRedact()
  4392. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  4393. showOCRWindow()
  4394. } else if itemID == KMDocumentAIToolsToolbarItemIdentifier {
  4395. self.showAITypeChooseView(aiConfigType: .none)
  4396. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  4397. if self.canEnterDigitalSign() == false {
  4398. Task {
  4399. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4400. }
  4401. return
  4402. }
  4403. toolbarItem.isSelected = !toolbarItem.isSelected
  4404. self.toolbarController.lastItemBox = toolbarItem
  4405. if toolbarItem.isSelected {
  4406. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4407. }
  4408. self.enterDigitalSign()
  4409. } else if itemID == KMDocumentPrintToolbarItemIdentifier {
  4410. self.showPrintWindow()
  4411. } else if itemID == KMDocumentPresentationToolbarItemIdentifier {
  4412. self.enterPresentation()
  4413. } else if itemID == KMDocumentSignToolbarItemIdentifier {
  4414. let isSelected = toolbarItem.isSelected
  4415. self.toolbarController.toolbarType = isSelected ? .None : .sign
  4416. toolbarItem.isSelected = !isSelected
  4417. self.toolbarController.lastItemBox = toolbarItem
  4418. }
  4419. } else {
  4420. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  4421. toolbarItem.isSelected = false
  4422. let windowC = KMToolbarCustomWindowController()
  4423. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  4424. windowC.resetCallback = { [weak self] in
  4425. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4426. toolbar?.reloadData()
  4427. }
  4428. self.km_beginSheet(windowC: windowC) { [weak self] resp, obj in
  4429. if resp == .OK {
  4430. let toolbar = self?.toolbarController.childToolBarView?.toolbar
  4431. toolbar?.reloadData()
  4432. }
  4433. }
  4434. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  4435. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  4436. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  4437. self.trackEvent_print()
  4438. self.showPrintWindow()
  4439. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  4440. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  4441. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  4442. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  4443. windowC.callBack = { [weak self] string in
  4444. if (string.isEmpty == false) {
  4445. self?.listView.addTextField(subType: .profile, string: string)
  4446. }
  4447. self?.km_endSheet()
  4448. }
  4449. self.km_beginSheet(windowC: windowC)
  4450. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  4451. toolbarItem.isSelected = !toolbarItem.isSelected
  4452. rightSideViewController.mainController = self
  4453. self.rightSideViewController.isHidden = toolbarItem.isSelected ? false : true
  4454. self.rightSideViewController.subViewType = .ViewSettings
  4455. // self.toggleRightPane()
  4456. self.listView.annotationType = .unkown
  4457. if toolbarItem.isSelected {
  4458. self.rightSideViewController.isHidden = false
  4459. self.rightSideViewController.mainController = self
  4460. self.rightSideViewController.subViewType = .ViewSettings
  4461. self.toolbarController.findItem(KMToolbarViewSettingIdentifier)?.isSelected = true
  4462. self.openRightPane()
  4463. }else{
  4464. self.rightSideViewController.isHidden = true
  4465. self.rightSideViewController.subViewType = .AnnotationProperts
  4466. closeRightPane()
  4467. }
  4468. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  4469. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  4470. self.listView.takeSnapshot(nil)
  4471. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  4472. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  4473. self.listView.annotationType = .unkown
  4474. self.showTTSWindow()
  4475. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4476. self.showOCRWindow()
  4477. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  4478. toolbarItem.isSelected = false
  4479. self.imageAnnotation(toolbarItem)
  4480. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  4481. self.tableAnnotation(toolbarItem)
  4482. } else if toolbarItem.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { // 插入
  4483. self.leftSideViewController.insertPDF(nil)
  4484. } else if toolbarItem.itemIdentifier == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4485. let windowC = SplitWindowController(document: self.listView.document)
  4486. self.km_beginSheet(windowC: windowC)
  4487. } else if itemID == KMSignDigitalSignToolbarItemIdentifier {
  4488. if self.canEnterDigitalSign() == false {
  4489. Task {
  4490. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4491. }
  4492. return
  4493. }
  4494. toolbarItem.isSelected = !toolbarItem.isSelected
  4495. self.toolbarController.lastItemBox = toolbarItem
  4496. if toolbarItem.isSelected {
  4497. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4498. }
  4499. self.enterDigitalSign()
  4500. } else if itemID == KMToolbarMeasureItemIdentifier {
  4501. if toolbarItem.isSelected {
  4502. toolbarItem.isSelected = false
  4503. self.listView.toolMode = .textToolMode
  4504. self.listView.annotationType = .unkown
  4505. }
  4506. }
  4507. }
  4508. }
  4509. }
  4510. func openNewWindowAlertWindow() {
  4511. var needShowChooseWindow = false
  4512. //#if VERSION_FREE
  4513. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  4514. needShowChooseWindow = true
  4515. }
  4516. //#endif
  4517. if needShowChooseWindow {
  4518. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  4519. if preferenceNoteShow {
  4520. menuItemAction_newTagPageToNewWindow("")
  4521. } else {
  4522. if !KMDataManager.default.isTabbingWin{
  4523. KMDataManager.default.isTabbingWin = true
  4524. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  4525. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  4526. KMDataManager.default.isTabbingWin = false
  4527. if continueOrNot {
  4528. self?.reopenDocument(forPaths: [])
  4529. } else {
  4530. }
  4531. }
  4532. self.km_beginSheet(windowC: tabbingWin)
  4533. }
  4534. }
  4535. }else{
  4536. handleTabbingLogic()
  4537. }
  4538. }
  4539. func reopenDocument(forPaths paths: [String]) -> Void {
  4540. let browser = KMBrowser.init() as KMBrowser
  4541. browser.windowController = KMBrowserWindowController.init(browser: browser)
  4542. browser.addHomeTabContents()
  4543. browser.windowController.showWindow(self)
  4544. }
  4545. func handleTabbingLogic() {
  4546. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  4547. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  4548. }
  4549. func showTTSWindow() {
  4550. var lastPDFView: CPDFView?
  4551. let ttsView = KMTTSWindowController.share
  4552. if (ttsView.window?.isVisible ?? false) {
  4553. lastPDFView = ttsView.pdfView
  4554. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  4555. lastPDFView = nil
  4556. ttsView.window?.orderOut(nil)
  4557. } else {
  4558. ttsView.pdfView = self.listView
  4559. ttsView.showWindow(nil)
  4560. }
  4561. } else {
  4562. ttsView.pdfView = self.listView
  4563. ttsView.showWindow(nil)
  4564. }
  4565. // weak var blockSelf = self
  4566. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  4567. if isCloseWindow {
  4568. // for item in blockSelf?.toolbar.items ?? [] {
  4569. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  4570. // item.isSelected = false
  4571. // }
  4572. // }
  4573. }
  4574. }
  4575. if let currentSelection = self.listView.currentSelection {
  4576. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  4577. ttsView.startSpeakingPDFSelection(currentSelection)
  4578. }
  4579. }
  4580. if let lastPDFView = lastPDFView {
  4581. lastPDFView.setHighlightedSelections([])
  4582. ttsView.stopSpeaking()
  4583. }
  4584. }
  4585. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4586. self.toolbarItemClickForExitMode(toolbarItem)
  4587. let itemId = toolbarItem.itemIdentifier
  4588. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  4589. self.clickChildTool(type: .watermark, index: index)
  4590. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  4591. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  4592. self.clickChildTool(type: .background, index: index)
  4593. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  4594. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  4595. self.clickChildTool(type: .headerAndFooter, index: index)
  4596. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  4597. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  4598. self.clickChildTool(type: .bates, index: index)
  4599. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  4600. } else if (toolbarItem.itemIdentifier == KMToolbarMeasureItemIdentifier) {
  4601. self.clickChildTool(type: .measure, index: index)
  4602. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  4603. self.clickChildTool(type: .comparison, index: index)
  4604. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  4605. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  4606. convertToImg(index: index)
  4607. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  4608. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  4609. extractImageAction(num: index)
  4610. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  4611. self.createPdf(index: index)
  4612. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  4613. if index == 2 { // 裁剪当前页面
  4614. self.cropCurrentPage()
  4615. } else if index == 3 { // Auto Crop – Separate
  4616. self.smart_cropAllPage()
  4617. } else if index == 4 { // Auto Crop – Combined
  4618. self.auto_cropAllPage()
  4619. } else if index == 5 { // Select Area
  4620. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  4621. }
  4622. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  4623. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  4624. self.clickChildTool(type: .secure, index: index)
  4625. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  4626. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  4627. if index == 11 {
  4628. self.view.window?.makeFirstResponder(nil)
  4629. let winC = KMSearchReplaceWindowController(with: self.listView, type: .search)
  4630. self.currentWindowController = winC
  4631. winC.replaceCallback = { [weak self] in
  4632. let toolMode = self?.listView?.toolMode ?? .none
  4633. let isEditing = self?.listView?.isEditing() ?? false
  4634. if toolMode == .editPDFToolMode && isEditing {
  4635. } else { // 进入内容编辑模式
  4636. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4637. }
  4638. }
  4639. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4640. // - (winC.window?.frame.size.width ?? 0)
  4641. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4642. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 248 - 16
  4643. let winFramePoint = NSPoint(x: x, y: y)
  4644. winC.window?.setFrameOrigin(winFramePoint)
  4645. winC.startModal(nil)
  4646. } else if index == 12 {
  4647. // if IAPProductsManager.default().isAvailableAllFunction() == false {
  4648. // KMProductCompareWC.shared.orientation = false
  4649. // let winC = KMProductCompareWC.shared
  4650. // winC.kEventName = "Reading_ReplaceText_BuyNow"
  4651. // winC.showWindow(nil)
  4652. // return
  4653. // }
  4654. if KMMemberInfo.shared.isMemberAllFunction == false {
  4655. let winC = KMProductCompareWC.shared
  4656. winC.kEventName = "Reading_ReplaceText_BuyNow"
  4657. KMMemberInfo.shared.advancedFunctionUsage()
  4658. return
  4659. }
  4660. self.view.window?.makeFirstResponder(nil)
  4661. let toolMode = self.listView?.toolMode ?? .none
  4662. let isEditing = self.listView?.isEditing() ?? false
  4663. if toolMode == .editPDFToolMode && isEditing {
  4664. } else { // 进入内容编辑模式
  4665. self.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4666. }
  4667. self.trackEvent_replace()
  4668. let winC = KMSearchReplaceWindowController(with: self.listView, type: .replace)
  4669. self.currentWindowController = winC
  4670. winC.replaceCallback = { [weak self] in
  4671. let toolMode = self?.listView?.toolMode ?? .none
  4672. let isEditing = self?.listView?.isEditing() ?? false
  4673. if toolMode == .editPDFToolMode && isEditing {
  4674. } else { // 进入内容编辑模式
  4675. self?.toolbarController.clickItem(KMDocumentEditToolbarItemIdentifier)
  4676. }
  4677. }
  4678. let point = toolbarItem.convert(toolbarItem.frame.origin, to: nil)
  4679. // - (winC.window?.frame.size.width ?? 0)
  4680. let x = point.x + (toolbarItem.window?.frame.origin.x ?? 0) - 200
  4681. let y = point.y + (toolbarItem.window?.frame.origin.y ?? 0) - 388
  4682. let winFramePoint = NSPoint(x: x, y: y)
  4683. winC.window?.setFrameOrigin(winFramePoint)
  4684. winC.startModal(nil)
  4685. } else {
  4686. self.toolbarController.showFindBar()
  4687. }
  4688. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4689. toolbarItem.isSelected = !toolbarItem.isSelected
  4690. self.toggleRightPane()
  4691. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4692. self.toolbarController.toolbarType = .viewSetting
  4693. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4694. self.showOCRWindow()
  4695. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  4696. if index == 1 {
  4697. self.showAITypeChooseView(aiConfigType: .summarize)
  4698. } else if index == 2 {
  4699. self.showAITypeChooseView(aiConfigType: .reWriting)
  4700. } else if index == 3 {
  4701. self.showAITypeChooseView(aiConfigType: .proofreading)
  4702. } else if index == 4 {
  4703. self.showAITypeChooseView(aiConfigType: .translate)
  4704. }
  4705. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  4706. self.showOCRWindow()
  4707. } else if toolbarItem.itemIdentifier == KMDocumentEditToolbarItemIdentifier {
  4708. self.toolbarController.toolbarType = .editPDF
  4709. self.enterEditPDF()
  4710. } else if toolbarItem.itemIdentifier == KMDocumentFillSginToolbarItemIdentifier {
  4711. self.toolbarController.toolbarType = .FillSign
  4712. } else if toolbarItem.itemIdentifier == KMDocumentFormToolbarItemIdentifier {
  4713. self.toolbarController.toolbarType = .Form
  4714. } else if itemId == KMDocumentDigitalSignToolbarItemIdentifier {
  4715. if self.canEnterDigitalSign() == false {
  4716. Task {
  4717. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4718. }
  4719. return
  4720. }
  4721. toolbarItem.isSelected = !toolbarItem.isSelected
  4722. self.toolbarController.lastItemBox = toolbarItem
  4723. if toolbarItem.isSelected {
  4724. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4725. }
  4726. self.enterDigitalSign()
  4727. } else if itemId == KMSignDigitalSignToolbarItemIdentifier {
  4728. if self.canEnterDigitalSign() == false {
  4729. Task {
  4730. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  4731. }
  4732. return
  4733. }
  4734. toolbarItem.isSelected = !toolbarItem.isSelected
  4735. self.toolbarController.lastItemBox = toolbarItem
  4736. if toolbarItem.isSelected {
  4737. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4738. }
  4739. self.enterDigitalSign()
  4740. } else if itemId == KMDocumentAIToolsToolbarItemIdentifier {
  4741. self.showAITypeChooseView(aiConfigType: .none)
  4742. } else if itemId == KMToolbarToolCompressItemIdentifier {
  4743. self.clickChildTool(type: .compress, index: 0)
  4744. } else if itemId == KMToolbarPageEditSplitItemIdentifier { // 拆分
  4745. let windowC = SplitWindowController(document: self.listView.document)
  4746. self.km_beginSheet(windowC: windowC)
  4747. } else if itemId == KMToolbarToolMergeItemIdentifier {
  4748. self.clickChildTool(type: .merge, index: 0)
  4749. } else if itemId == KMToolbarPageEditInsetItemIdentifier {
  4750. self.leftSideViewController.insertPDF(nil)
  4751. } else if itemId == KMToolbarShowToolbarItemIdentifier {
  4752. self.showOrHideNotes()
  4753. } else if itemId == KMAnnotationTableToolbarItemIdentifier {
  4754. self.tableAnnotation(toolbarItem)
  4755. } else if itemId == KMToolbarConversionTextItemIdentifier {
  4756. self.clickChildTool(type: .conversion_text, index: 0)
  4757. } else if itemId == KMToolbarConversionHTMLItemIdentifier {
  4758. self.clickChildTool(type: .html, index: 0)
  4759. } else if itemId == KMToolbarConversionCSVItemIdentifier {
  4760. self.clickChildTool(type: .csv, index: 0)
  4761. } else if itemId == KMToolbarConversionRTFItemIdentifier {
  4762. self.clickChildTool(type: .rtf, index: 0)
  4763. } else if itemId == KMToolbarConversionPPTItemIdentifier {
  4764. self.clickChildTool(type: .ppt, index: 0)
  4765. } else if itemId == KMToolbarConversionExcelItemIdentifier {
  4766. self.clickChildTool(type: .excel, index: 0)
  4767. } else if itemId == KMToolbarConversionWordItemIdentifier {
  4768. self.clickChildTool(type: .word, index: 0)
  4769. } else if itemId == KMToolbarConversionOtherItemIdentifier {
  4770. if index == KMPDFConvertType.text.rawValue {
  4771. self.clickChildTool(type: .conversion_text, index: 0)
  4772. } else if index == KMPDFConvertType.rtf.rawValue {
  4773. self.clickChildTool(type: .rtf, index: 0)
  4774. } else if index == KMPDFConvertType.html.rawValue {
  4775. self.clickChildTool(type: .html, index: 0)
  4776. } else if index == KMPDFConvertType.csv.rawValue {
  4777. self.clickChildTool(type: .csv, index: 0)
  4778. } else if index == KMPDFConvertType.json.rawValue {
  4779. self.clickChildTool(type: .json, index: 0)
  4780. }
  4781. }
  4782. }
  4783. func convertToImg(index: Int) {
  4784. var convertT: KMConvertType = .JPEG
  4785. switch index {
  4786. case 7:
  4787. convertT = .JPEG
  4788. case 8:
  4789. convertT = .JPG
  4790. case 9:
  4791. convertT = .PNG
  4792. case 10:
  4793. convertT = .GIF
  4794. case 11:
  4795. convertT = .TIFF
  4796. case 12:
  4797. convertT = .TGA
  4798. case 13:
  4799. convertT = .BMP
  4800. default:
  4801. convertT = .JPEG
  4802. }
  4803. showAllConvertWindow(convertT: convertT)
  4804. }
  4805. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  4806. // if self.searchResults.count == 0 {
  4807. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4808. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4809. self.search(searchString: searchString, isCase: caseInsensitive, display: false)
  4810. // }
  4811. var row = max(searchIndex - 1, 0)
  4812. if forward {
  4813. row = searchIndex + 1
  4814. }
  4815. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4816. let model = self.searchResults[row]
  4817. if model.selection != nil {
  4818. self.listView.setHighlightedSelections([])
  4819. self.listView.go(to: model.selection, animated: true)
  4820. self.listView.setHighlightedSelection(model.selection, animated: true)
  4821. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4822. searchIndex = row
  4823. }
  4824. }
  4825. self.leftSideViewController.showSearchMode(searchString)
  4826. }
  4827. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAction searchString: String, forward: Bool) {
  4828. // if self.searchResults.count == 0 {
  4829. // let caseInsensitive = UserDefaults.standard.bool(forKey: "SKCaseInsensitiveFindKey")
  4830. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4831. self.search(searchString: searchString, isCase: !caseInsensitive, display: false)
  4832. // }
  4833. var row = max(searchIndex - 1, 0)
  4834. if forward {
  4835. row = searchIndex + 1
  4836. }
  4837. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4838. let model = self.searchResults[row]
  4839. if model.selection != nil {
  4840. self.listView.setHighlightedSelections([])
  4841. self.listView.go(to: model.selection, animated: true)
  4842. self.listView.setHighlightedSelection(model.selection, animated: true)
  4843. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4844. searchIndex = row
  4845. }
  4846. }
  4847. }
  4848. func toolbarViewController(_ viewController: KMToolbarViewController, findSearchAllAction searchString: String, forward: Bool) {
  4849. let caseInsensitive = UserDefaults.standard.bool(forKey: SKCaseInsensitiveSearchKey)
  4850. self.search(searchString: searchString, isCase: !caseInsensitive, display: false, needShowAll: true)
  4851. self.leftSideViewController.showSearchMode(searchString)
  4852. }
  4853. func toolbarViewController(_ viewController: KMToolbarViewController, viewItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4854. let itemId = toolbarItem.itemIdentifier
  4855. if itemId == KMDocumentFirstLastToolbarItemIdentifier {
  4856. if index == 1 {
  4857. if self.listView.canGoToFirstPage() {
  4858. self.listView.goToFirstPage(nil)
  4859. }
  4860. } else if index == 2 {
  4861. if self.listView.canGoToLastPage() {
  4862. self.listView.goToLastPage(nil)
  4863. }
  4864. }
  4865. } else if itemId == KMDocumentPageInputToolbarItemIdentifier {
  4866. var valid = false
  4867. if let number = Int(info as? String ?? "") {
  4868. let cnt = self.listView?.document?.pageCount ?? 0
  4869. if number > 0 && number <= cnt {
  4870. self.listView.go(toPageIndex: number-1, animated: false)
  4871. valid = true
  4872. }
  4873. }
  4874. if valid == false {
  4875. Task {@MainActor in
  4876. _ = await KMAlertTool.runModel(message: NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))
  4877. }
  4878. }
  4879. }
  4880. }
  4881. }
  4882. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  4883. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  4884. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4885. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  4886. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4887. distanceSettingWC.delegate = self
  4888. distanceSettingWC.startModal("")
  4889. }
  4890. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  4891. }
  4892. }
  4893. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  4894. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  4895. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  4896. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  4897. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  4898. distanceSettingWC.delegate = self
  4899. distanceSettingWC.startModal("")
  4900. }
  4901. }
  4902. // MARK: CAreaMeasureInfoWindowControllerDelegate
  4903. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  4904. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  4905. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  4906. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  4907. areaSettingWC.delegate = self
  4908. areaSettingWC.startModal("")
  4909. }
  4910. }
  4911. // MARK: CDistanceSettingWindowControllerDelegate
  4912. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  4913. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  4914. if distanceMeasureInfo != nil {
  4915. if self.listView.activeAnnotations.count > 0 {
  4916. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  4917. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  4918. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4919. }
  4920. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  4921. } else {
  4922. distanceMeasureInfo?.leadLength = 0
  4923. self.listView.distanceMeasureInfo = distanceMeasureInfo
  4924. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  4925. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4926. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  4927. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  4928. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  4929. }
  4930. if let data = self.listView?.activeAnnotation {
  4931. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4932. }
  4933. }
  4934. self.distanceMeasureInfoWindowController?.showWindow(self)
  4935. }
  4936. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  4937. if perimeterMeasureInfo != nil {
  4938. if self.listView.activeAnnotations.count > 0 {
  4939. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  4940. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  4941. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4942. }
  4943. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  4944. } else {
  4945. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  4946. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  4947. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  4948. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  4949. }
  4950. if let data = self.listView?.activeAnnotation {
  4951. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  4952. }
  4953. }
  4954. self.perimeterMeasureInfoWindowController?.showWindow(self)
  4955. }
  4956. }
  4957. // MARK: CAreaSettingWindowControllerDelegate
  4958. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  4959. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  4960. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  4961. if measureInfo != nil {
  4962. if self.listView.activeAnnotations.count > 0 {
  4963. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4964. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4965. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4966. }
  4967. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4968. } else {
  4969. self.listView.squareAreaMeasureInfo = measureInfo
  4970. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  4971. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4972. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4973. }
  4974. }
  4975. self.areaMeasureInfoWindowController?.showWindow(self)
  4976. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  4977. if measureInfo != nil {
  4978. if self.listView.activeAnnotations.count > 0 {
  4979. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4980. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4981. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4982. }
  4983. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  4984. } else {
  4985. self.listView.polygonAreaMeasureInfo = measureInfo
  4986. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  4987. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  4988. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  4989. }
  4990. }
  4991. self.areaMeasureInfoWindowController?.showWindow(self)
  4992. } else {
  4993. if measureInfo != nil {
  4994. if self.listView.activeAnnotations.count > 0 {
  4995. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  4996. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  4997. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  4998. }
  4999. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  5000. }
  5001. }
  5002. self.areaMeasureInfoWindowController?.showWindow(self)
  5003. }
  5004. if measureInfo != nil {
  5005. if let data = self.listView?.activeAnnotation {
  5006. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  5007. }
  5008. }
  5009. }
  5010. }
  5011. // MARK: -
  5012. // MARK: - Mouse
  5013. extension KMMainViewController {
  5014. override func mouseDown(with event: NSEvent) {
  5015. super.mouseDown(with: event)
  5016. // KMPrint("KMMainViewController mouseDown")
  5017. self.leftSideViewCancelSelect()
  5018. self.pageNumberDisplayView.isEdit = false
  5019. }
  5020. }
  5021. //MARK: LeftSideViewController
  5022. extension KMMainViewController {
  5023. func leftSideViewCancelSelect() {
  5024. // switch self.leftSideViewController.type.methodType {
  5025. // case .Thumbnail:
  5026. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  5027. // break
  5028. // case .Outline:
  5029. //// self.leftSideViewController.outlineViewController.cancelSelect()
  5030. // break
  5031. // case .BookMark:
  5032. //// self.leftSideViewController.bookViewController.cancelSelect()
  5033. // break
  5034. // case .Search:
  5035. //// self.leftSideViewController.searchViewController.cancelSelect()
  5036. // break
  5037. // case .Annotation:
  5038. //// self.leftSideViewController.annotationViewController.cancelSelect()
  5039. // break
  5040. // default:
  5041. if self.listView.isEditing() {
  5042. if self.listView.editingAreas() != nil &&
  5043. self.listView.editingAreas().count != 0 {
  5044. let areas = self.listView.editingAreas().first
  5045. if areas is CPDFEditTextArea {
  5046. self.listView.clearEditingSelectCharItem()
  5047. self.listView.updateEditing([])
  5048. KMPrint("取消选中")
  5049. }
  5050. }
  5051. }
  5052. // KMPrint("其他")
  5053. // }
  5054. }
  5055. }
  5056. extension KMMainViewController: KMReadModelViewDelegate {
  5057. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  5058. self.listView.goToFirstPage(nil)
  5059. }
  5060. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  5061. self.listView.goToPreviousPage(nil)
  5062. }
  5063. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  5064. self.listView.goToNextPage(nil)
  5065. }
  5066. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  5067. self.listView.goToLastPage(nil)
  5068. }
  5069. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  5070. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  5071. }
  5072. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  5073. var scale: Double = 1.0
  5074. switch type {
  5075. case .fitWidth:
  5076. self.listView.autoScales = !self.listView.autoScales
  5077. scale = self.listView.scaleFactor
  5078. break
  5079. case .actualSize:
  5080. if self.listView.scaleFactor != 1.0 {
  5081. self.listView.scaleFactor = 1.0
  5082. self.listView.autoScales = false
  5083. }
  5084. scale = self.listView.scaleFactor
  5085. break
  5086. case .autoSize:
  5087. self.listView.autoScales = true
  5088. self.listView.autoScales = false
  5089. scale = self.listView.scaleFactor
  5090. break
  5091. case ._10:
  5092. scale = 0.1
  5093. break
  5094. case ._25:
  5095. scale = 0.25
  5096. break
  5097. case ._50:
  5098. scale = 0.5
  5099. break
  5100. case ._100:
  5101. scale = 1.0
  5102. break
  5103. case ._150:
  5104. scale = 1.5
  5105. break
  5106. case ._200:
  5107. scale = 2.0
  5108. break
  5109. case ._400:
  5110. scale = 4.0
  5111. break
  5112. case ._800:
  5113. scale = 8.0
  5114. break
  5115. default:
  5116. break
  5117. }
  5118. self.listView.scaleFactor = scale
  5119. self.toolbarController.mainViewController?.childToolbarController.zoomTextField?.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  5120. }
  5121. func cancelReadModel(view: KMReadModelView, sender: Any) {
  5122. if self.isReadMode {
  5123. self.closeReadModel()
  5124. }
  5125. }
  5126. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  5127. // if self.readModelViewWidthConstraint.constant != width {
  5128. self.readModelViewWidthConstraint.constant = width
  5129. // }
  5130. }
  5131. // MARK: - KMPresentationTopViewController (幻灯片)
  5132. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5133. if self.canExitPresentation() == true {
  5134. let mainDocument = self.myDocument as? KMMainDocument
  5135. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  5136. browserWindowController?.exitFullscreen()
  5137. }
  5138. }
  5139. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5140. listView.presentationDrawView?.clear()
  5141. }
  5142. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  5143. let presentationDrawView = listView.presentationDrawView
  5144. if presentationDrawView?.canUndo() == true {
  5145. presentationDrawView?.undo()
  5146. }
  5147. }
  5148. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  5149. listView.isPresentationMode = isSeletion
  5150. if listView.isEnterPresentationDrawMode() == true {
  5151. listView.exitPresentationDrawMode()
  5152. }
  5153. }
  5154. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  5155. if color == nil{
  5156. listView.exitPresentationDrawMode()
  5157. } else {
  5158. if listView.isEnterPresentationDrawMode() == false {
  5159. listView.enterPresentationDrawMode()
  5160. }
  5161. listView.changePresentationDrawModelColor(color)
  5162. }
  5163. }
  5164. }
  5165. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  5166. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  5167. self.listView.go(toPageIndex: pageIndex, animated: true)
  5168. }
  5169. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  5170. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  5171. self.tipCurrentPageBoxWidthConstraint.constant = width
  5172. }
  5173. }
  5174. func commitEditingIfNeed() {
  5175. self.editPDFHanddler.commitEditing()
  5176. }
  5177. }
  5178. extension KMMainViewController: KMInteractionProviderProtocol {
  5179. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  5180. let view = self.listView
  5181. if(interactionMode == .presentation) {
  5182. if view?.presentationDrawView == nil {
  5183. view?.createPresentationDraw()
  5184. }
  5185. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  5186. presentationTopViewController?.pdfView = view
  5187. presentationTopViewController?.delegate = self
  5188. presentationTopViewController?.isSelectionPre = true
  5189. listView.isPresentationMode = true
  5190. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  5191. if((presentationTopViewController) != nil) {
  5192. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  5193. }
  5194. } else {
  5195. view?.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  5196. }
  5197. if let v = view {
  5198. fullScreenWindow.contentView?.addSubview(v)
  5199. if(interactionMode == .presentation) {
  5200. v.mas_makeConstraints { make in
  5201. make?.left.mas_equalTo()(0)
  5202. make?.right.mas_equalTo()(0)
  5203. make?.top.mas_equalTo()(presentationTopViewController!.view.frame.height)
  5204. make?.bottom.mas_equalTo()(0)
  5205. }
  5206. }
  5207. }
  5208. return view
  5209. }
  5210. }
  5211. // MARK: - Analytics (埋点)
  5212. extension KMMainViewController {
  5213. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  5214. if (type == .Annatiton) {
  5215. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  5216. } else if (type == .editPDF) {
  5217. } else if (type == .Page) {
  5218. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  5219. } else if (type == .Conversion) {
  5220. } else if (type == .Tool) {
  5221. }
  5222. }
  5223. func trackEvent_aiTranslate() -> Void {
  5224. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  5225. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5226. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5227. }
  5228. func trackEvent_print() -> Void {
  5229. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  5230. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5231. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5232. }
  5233. func trackEvent_share() -> Void {
  5234. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  5235. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5236. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5237. }
  5238. func trackEvent_upgrade() -> Void {
  5239. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  5240. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  5241. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  5242. }
  5243. func trackEvent(annotationType type: CAnnotationType) -> Void {
  5244. if (type == .highlight) {
  5245. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  5246. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  5247. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5248. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5249. } else if (type == .underline) {
  5250. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  5251. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  5252. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5253. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5254. } else if (type == .strikeOut) {
  5255. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  5256. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  5257. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5258. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5259. } else if (type == .ink) {
  5260. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  5261. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  5262. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5263. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5264. } else if (type == .freeText) {
  5265. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  5266. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  5267. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5268. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5269. } else if (type == .anchored) {
  5270. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  5271. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  5272. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5273. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5274. } else if (type == .square) {
  5275. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  5276. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  5277. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5278. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5279. } else if (type == .link) {
  5280. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  5281. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  5282. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5283. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5284. } else if (type == .stamp) {
  5285. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  5286. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  5287. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5288. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5289. } else if (type == .signSignature) {
  5290. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  5291. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  5292. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5293. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5294. } else if (type == .circle) {
  5295. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  5296. } else if (type == .arrow) {
  5297. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  5298. } else if (type == .line) {
  5299. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  5300. } else if (type == .addText) {
  5301. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  5302. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  5303. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5304. } else if (type == .addImage) {
  5305. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  5306. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  5307. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  5308. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5309. } else if (type == .textField) {
  5310. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  5311. } else if (type == .checkBox) {
  5312. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  5313. } else if (type == .radioButton) {
  5314. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  5315. } else if (type == .listMenu) {
  5316. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  5317. } else if (type == .comboBox) {
  5318. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  5319. } else if (type == .actionButton) {
  5320. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  5321. } else if (type == .actionButton) {
  5322. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  5323. } else if (type == .signature) {
  5324. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  5325. } else if (type == .squiggly) {
  5326. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  5327. } else if (type == .eraser) {
  5328. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  5329. }
  5330. }
  5331. func trackEvent(toolMode mode: CToolMode) -> Void {
  5332. if (mode == .selectToolMode) {
  5333. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  5334. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5335. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5336. } else if (mode == .moveToolMode) {
  5337. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  5338. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  5339. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5340. } else if mode == .measureToolMode {
  5341. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  5342. }
  5343. }
  5344. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  5345. if (type == .word) {
  5346. } else if (type == .excel) {
  5347. } else if (type == .ppt) {
  5348. } else if (type == .rtf) {
  5349. } else if (type == .csv) {
  5350. } else if (type == .html) {
  5351. } else if (type == .conversion_text) {
  5352. } else if (type == .conversion_image) {
  5353. } else if (type == .compress) {
  5354. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  5355. } else if (type == .merge) {
  5356. } else if (type == .secure) {
  5357. } else if (type == .crop) {
  5358. } else if type == .json {
  5359. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  5360. }
  5361. }
  5362. func trackEvent_setPassword() -> Void {
  5363. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  5364. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  5365. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5366. }
  5367. func trackEvent_removePassword() -> Void {
  5368. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  5369. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  5370. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  5371. }
  5372. func trackEvent_replace() -> Void {
  5373. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  5374. }
  5375. }
  5376. extension KMMainViewController {
  5377. //文件对比
  5378. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  5379. self.isCompareModel = true
  5380. let compareContentView = KMCompareContentView()
  5381. compareContentView.oldDocument = oldDocument
  5382. compareContentView.document = document
  5383. compareContentView.compareResults = results
  5384. compareContentView.saveHandle = { [unowned self] view in
  5385. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  5386. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  5387. self.currentWindowController = saveController
  5388. saveController.cancelHandle = { [unowned self] controller in
  5389. self.view.window!.endSheet(controller.window!)
  5390. self.currentWindowController = nil
  5391. }
  5392. saveController.saveHandle = { [unowned self] controller, saveType in
  5393. let folderPath = controller.fileSaveFolderPath
  5394. if folderPath != nil {
  5395. if !FileManager.default.fileExists(atPath: folderPath) {
  5396. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  5397. }
  5398. #if VERSION_DMG
  5399. #else
  5400. let url = URL(fileURLWithPath: folderPath)
  5401. let fileAccess = AppSandboxFileAccess()
  5402. fileAccess?.persistPermissionURL(url)
  5403. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  5404. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  5405. let urlString = url.path
  5406. let _url = URL(fileURLWithPath: urlString)
  5407. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  5408. }
  5409. #endif
  5410. var savePath: String
  5411. switch saveType {
  5412. case 0:
  5413. let filePath = oldDocument.documentURL.path
  5414. let fileName = filePath.deletingPathExtension.lastPathComponent
  5415. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5416. savePath = self.getValidFilePath(savePath)
  5417. oldDocument.write(to: URL(fileURLWithPath: savePath))
  5418. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5419. case 1:
  5420. let filePath = document.documentURL.path
  5421. let fileName = filePath.deletingPathExtension.lastPathComponent
  5422. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  5423. savePath = self.getValidFilePath(savePath)
  5424. document.write(to: URL(fileURLWithPath: savePath))
  5425. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5426. case 2:
  5427. let filePath = oldDocument.documentURL.path
  5428. let fileName = filePath.deletingPathExtension.lastPathComponent
  5429. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  5430. savePath = self.getValidFilePath(savePath)
  5431. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  5432. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  5433. default:
  5434. break
  5435. }
  5436. }
  5437. self.view.window!.endSheet(controller.window!)
  5438. self.currentWindowController = nil
  5439. }
  5440. NSWindow.currentWindow().beginSheet(saveController.window!)
  5441. }
  5442. }
  5443. compareContentView.closeHandle = { [unowned self] view in
  5444. // self.view.window!.endSheet(controller.window!)
  5445. self.isCompareModel = false
  5446. view.removeFromSuperview()
  5447. }
  5448. self.PDFContendView.addSubview(compareContentView)
  5449. compareContentView.frame = self.PDFContendView.bounds
  5450. compareContentView.autoresizingMask = [.width,.height]
  5451. }
  5452. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  5453. self.isCompareModel = true
  5454. let coveringView = KMCompareCoveringView()
  5455. coveringView.pdfDocument = pdfDocument
  5456. coveringView.closeHandle = { [unowned self] view in
  5457. self.isCompareModel = false
  5458. view.removeFromSuperview()
  5459. }
  5460. coveringView.saveHandle = { [unowned self] view in
  5461. let savePanel = NSSavePanel()
  5462. savePanel.nameFieldStringValue = "untitled"
  5463. savePanel.allowedFileTypes = ["pdf"]
  5464. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  5465. if result == .OK {
  5466. pdfDocument.write(to: savePanel.url!)
  5467. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  5468. }
  5469. }
  5470. }
  5471. self.PDFContendView.addSubview(coveringView)
  5472. coveringView.frame = self.PDFContendView.bounds
  5473. coveringView.autoresizingMask = [.width,.height]
  5474. }
  5475. func getValidFilePath(_ oldPath: String) -> String {
  5476. let fileManager = FileManager.default
  5477. do {
  5478. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  5479. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  5480. return oldPath
  5481. }
  5482. var i = 1
  5483. var newPath = oldPath
  5484. while fileManager.fileExists(atPath: newPath) {
  5485. if fileType == FileAttributeType.typeDirectory.rawValue {
  5486. newPath = oldPath + "(\(i))"
  5487. } else {
  5488. let fileExtension = (oldPath as NSString).pathExtension
  5489. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  5490. }
  5491. i += 1
  5492. }
  5493. return newPath
  5494. } catch {
  5495. print("Error getting file attributes: \(error)")
  5496. return oldPath
  5497. }
  5498. }
  5499. }
  5500. extension KMMainViewController {
  5501. func documentAllowsEdit() -> Bool {
  5502. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  5503. let alert = NSAlert()
  5504. alert.alertStyle = .critical
  5505. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  5506. alert.runModal()
  5507. return false
  5508. } else {
  5509. return true
  5510. }
  5511. }
  5512. }