KMMainViewController+Action.swift 295 KB

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