KMMainViewController+Action.swift 296 KB

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