KMMainViewController.swift 423 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. let MIN_SIDE_PANE_WIDTH: NSNumber = 264 // 最小值
  10. let CPDFViewIsReadModeKey = "kKMPDFViewIsReadMode"
  11. let CPDFViewLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  12. let CPDFViewIsEditFromDisplay = "CPDFViewIsEditFromDisplay" //记录进入水印,背景,页眉页脚,贝茨码等功能前,是否有展开DisplayView
  13. struct KMNMWCFlags {
  14. var settingUpWindow: Bool = true
  15. }
  16. @objcMembers class KMMainViewController: KMNBaseViewController, NSTextFieldDelegate {
  17. @IBOutlet var contendBox: NSBox!
  18. @IBOutlet var toolbarBox: NSBox! //工具栏Box
  19. @IBOutlet var bottomContendBox: NSBox! //
  20. @IBOutlet var sidebarBox: NSBox! //左侧边栏Box
  21. @IBOutlet var infoContendSplitView: NSSplitView!
  22. @IBOutlet var infoSplitLeftView: NSView!
  23. @IBOutlet var infoSplitRightView: NSView!
  24. @IBOutlet var infoSplitCenterView: NSView!
  25. @IBOutlet var infoSplitCenterSubView: NSBox!
  26. @IBOutlet var pdfSplitView: NSSplitView!
  27. @IBOutlet var pdfSplitTopView: NSView!
  28. @IBOutlet var pdfSplitBottomView: NSView!
  29. @IBOutlet var toolbarBoxHeightConst: NSLayoutConstraint!
  30. @IBOutlet var infoSplitViewLeftConst: NSLayoutConstraint!
  31. @IBOutlet var infoSplitViewRightConst: NSLayoutConstraint!
  32. @IBOutlet var infoSplitViewTopConst: NSLayoutConstraint!
  33. var viewManager: KMPDFViewManager = KMPDFViewManager.init()
  34. var toolbarManager: KMPDFToolbarManager = KMPDFToolbarManager.init()
  35. var listView: CPDFListView = CPDFListView.init()
  36. var document: CPDFDocument?
  37. var myDocument: NSDocument?
  38. var isFirstOpen: Bool = true
  39. var insertDocuments: Set<CPDFDocument> = [] //插入新文档时,SDK会出现崩溃,临时记录
  40. //工具栏
  41. private var pdfToolbarController: KMPDFToolbarController?
  42. //BOTA SideBar
  43. private var sideBarController: KMPDFSideBarController?
  44. //页面编辑
  45. private var pageEditViewController: KMNPageEditViewController?
  46. //DisplaySetting
  47. private var displaySettingController: KMNDisplayViewController?
  48. //SPlitPDF分屏视图
  49. private var splitPDFController: KMSplitPDFViewController?
  50. private var pageNumberToolbar: KMPageNumberPromptView?
  51. //PPT操作界面
  52. var presentationTopViewController: KMPresentationTopViewController?
  53. //Edit
  54. var editToolbarView: KMEditToolbarView?
  55. //水印
  56. var watermarkViewController: KMWatermarkController?
  57. //背景
  58. var backgroundViewController: KMBackgroundController?
  59. //Header&Footer
  60. var headerFooterViewController: KMHeaderFooterController?
  61. //Bates
  62. var batesViewController: KMBatesController?
  63. //Crop
  64. var cropController: KMCropController?
  65. //左边
  66. var botaViewController: KMNLeftSideViewController?
  67. //右边
  68. var rightSideController: KMRightSideController?
  69. let alertTipViewController: KMNAlertTipViewController = KMNAlertTipViewController(nibName: "KMNAlertTipViewController", bundle: nil)
  70. //合并
  71. var mergeWindowController: KMMergeWindowController?
  72. //春季活动
  73. var recommondPopWindowVC: KMRecommondPopWindow?
  74. //数字签名状态
  75. var signaturestateVC: CDSignatureCertificateStateViewController = CDSignatureCertificateStateViewController.init()
  76. //PDFView右键菜单
  77. private var groupListMenuGroup: ComponentGroup? = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  78. var textFieldSheet: KMTextFieldSheetController = KMTextFieldSheetController.init(windowNibName: "KMTextFieldSheetController")
  79. @IBOutlet weak var leftView: NSView!
  80. var model = KMMainModel()
  81. //Search
  82. var searchIndex: Int = 0
  83. //对比
  84. var isCompareModel: Bool = false
  85. //密码弹窗
  86. var passwordWindow: KMPasswordInputWindow?
  87. var securityWindowController: KMSecurityWindowController?
  88. //压缩
  89. var compressWindowController: KMCompressWindowController?
  90. //引导
  91. var guideInfoWindowController: KMGuideInfoWindowController?
  92. //测量
  93. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  94. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  95. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  96. //打印
  97. var bookletWindowController: KMPDFBookletWindowController?
  98. var multiplePrintWindowController: KMPDFMultiplePrintWindowController?
  99. var posterPrintWindowController: KMPDFPosterPrintWindowController?
  100. var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  101. var componentMessageView: ComponentMessage = ComponentMessage()
  102. var blockSaveWindow = AutoSavePopController()
  103. private var isShowQuickBar: Bool = false
  104. private var _needSave = false
  105. var needSave: Bool {
  106. set {
  107. _needSave = newValue
  108. if (_needSave == false) {
  109. self.clearIsPDFDocumentEdited()
  110. }
  111. }
  112. get {
  113. return _needSave
  114. }
  115. }
  116. var isPDFDocumentEdited: Bool {
  117. get {
  118. return self.model.isPDFDocumentEdited
  119. }
  120. }
  121. var newMwcFlags = KMNMWCFlags(settingUpWindow: true)
  122. var searchResults: [KMSearchMode] = []
  123. var mwcFlags: MwcFlags = MwcFlags()
  124. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  125. var currentWindowController: NSWindowController!
  126. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  127. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  128. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  129. var extract: KMExtractImageWindowController?
  130. var pageNumber: UInt?
  131. var autoSaveTimer: Timer?
  132. private var _documentFirstLoad: Bool = true
  133. var eventMonitor: Any?
  134. var keyEventMonitor: Any?
  135. var mouseRightMenuEvent: NSEvent?
  136. lazy private var homeVC: KMNHomeViewController? = {
  137. let vc = KMNHomeViewController()
  138. return vc
  139. }()
  140. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  141. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  142. get {
  143. return self._secureOptions
  144. }
  145. }
  146. var documentAttribute: [CPDFDocumentAttribute : Any]?
  147. fileprivate var _removeSecureFlag = false
  148. var removeSecureFlag: Bool {
  149. get {
  150. return self._removeSecureFlag
  151. }
  152. }
  153. fileprivate var _saveWatermarkFlag = false
  154. var saveWatermarkFlag: Bool {
  155. get {
  156. return self._saveWatermarkFlag
  157. }
  158. }
  159. private var mainWindow_: NSWindow?
  160. var mainWindow: NSWindow? {
  161. get {
  162. return self.mainWindow_
  163. }
  164. set {
  165. self.mainWindow_ = newValue
  166. }
  167. }
  168. var setDocument: CPDFDocument? {
  169. get {
  170. return document
  171. }
  172. set {
  173. if document != newValue {
  174. document = newValue
  175. }
  176. listView.document = document
  177. botaViewController?.changeDocument(document: document)
  178. }
  179. }
  180. var setPageNumber: UInt {
  181. get {
  182. return pageNumber!
  183. }
  184. set {
  185. let pageCount = listView.document?.pageCount ?? 0
  186. var value = newValue
  187. if value > pageCount {
  188. value = pageCount
  189. }
  190. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  191. listView.go(to: listView.document?.page(at: value-1))
  192. }
  193. if pageNumber != value {
  194. pageNumber = value
  195. }
  196. }
  197. }
  198. //MARK: - func
  199. deinit {
  200. NotificationCenter.default.removeObserver(self)
  201. self.listView.delegate = nil
  202. self.listView.document?.delegate = nil
  203. self.removeEventMonitor()
  204. }
  205. override func viewDidLoad() {
  206. super.viewDidLoad()
  207. // Do view setup here.
  208. setupData()
  209. setupUI()
  210. }
  211. override func viewDidAppear() {
  212. super.viewDidAppear()
  213. reloadPopUIWindow()
  214. addEventMonitor()
  215. addKeyEventMonitor()
  216. }
  217. override func viewDidDisappear() {
  218. super.viewDidDisappear()
  219. toggleClosePopUIWindow()
  220. }
  221. override func initContentView() {
  222. super.initContentView()
  223. }
  224. override func updateUIThemeColor() {
  225. super.updateUIThemeColor()
  226. }
  227. override func updateUILanguage() {
  228. super.updateUILanguage()
  229. }
  230. //MARK: - private
  231. func setupUI() {
  232. initPDFView()
  233. initToolbar()
  234. initSideBar()
  235. setUpSplitView()
  236. addNotificationCenter()
  237. }
  238. func setupData() {
  239. toolbarManager.pdfViewManager = viewManager
  240. if (UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) != nil) {
  241. UserDefaults.standard.set(MIN_SIDE_PANE_WIDTH, forKey: CPDFViewLeftSidePaneWidthKey)
  242. UserDefaults.standard.synchronize()
  243. }
  244. newMwcFlags.settingUpWindow = true
  245. Task {
  246. self.addAutoSaveEvent()
  247. }
  248. updateUndoRedoState()
  249. }
  250. @objc func editFontColorItemPanelAction(_ sender: Any) {
  251. if let color = (sender as? NSColorPanel)?.color {
  252. listView.changeEditingTextarea_Color(color: color)
  253. }
  254. }
  255. //MARK: - document load成功
  256. private func documentLoadComplete() {
  257. initLeftSideController()
  258. activityLoadMethod()
  259. let readModel = UserDefaults.standard.bool(forKey: CPDFViewIsReadModeKey)
  260. if readModel == true {
  261. self.openPDFReadMode()
  262. }
  263. reloadDigitalSigns()
  264. alertTipViewController.showInView(listView: listView, subView: infoSplitCenterView)
  265. alertTipViewController.formFieldHighlightCallback = { [weak self] in
  266. let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  267. CPDFAnnotation.updateHighlightFormFiled(self?.listView, highlightFormFiled: !value)
  268. self?.toolbarManager.refreshDefaultConfigItem()
  269. }
  270. alertTipViewController.enterPasswordCallback = { [weak self] in
  271. self?.removeOwnerPassword()
  272. }
  273. alertTipViewController.digitalDetailsCallback = { [weak self] in
  274. }
  275. alertTipViewController.redactApplyCallback = { [weak self] in
  276. self?.redactApplyAction()
  277. }
  278. alertTipViewController.heightCallback = { [weak self] height in
  279. self?.infoSplitViewTopConst.constant = height
  280. }
  281. newMwcFlags.settingUpWindow = false
  282. loadUserDefaultsData()
  283. NotificationCenter.default.addObserver(self,
  284. selector: #selector(redoChangeNotification(_:)),
  285. name: NSNotification.Name.NSUndoManagerDidUndoChange,
  286. object: listView.undoManager)
  287. NotificationCenter.default.addObserver(self,
  288. selector: #selector(redoChangeNotification(_:)),
  289. name: NSNotification.Name.NSUndoManagerDidRedoChange,
  290. object: listView.undoManager)
  291. NotificationCenter.default.addObserver(self,
  292. selector: #selector(redoChangeNotification(_:)),
  293. name: NSNotification.Name.NSUndoManagerWillCloseUndoGroup,
  294. object: listView.undoManager)
  295. }
  296. private func reloadDigitalSigns() {
  297. let signatures = listView.document.signatures()
  298. for i in 0 ..< (signatures?.count ?? 0) {
  299. let signature:CPDFSignature = signatures?[i] ?? CPDFSignature()
  300. if signature.signers.count > 0 {
  301. signature.verifySignature(with: listView.document)//耗时,注意
  302. }
  303. }
  304. listView.signatures = signatures
  305. }
  306. //MARK: - 活动加载相关
  307. private func activityLoadMethod() {
  308. }
  309. private func addNotificationCenter() {
  310. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  311. NotificationCenter.default.addObserver(self, selector: #selector(signatureStateChangeNoti), name: NSNotification.Name(rawValue: "CSignatureTrustCerDidChangeNotification"), object: nil)
  312. NotificationCenter.default.addObserver(self, selector: #selector(pdfViewScrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: nil)
  313. NotificationCenter.default.addObserver(self, selector: #selector(pageCountChangedNotification), name: NSNotification.Name.CPDFDocumentPageCountChanged, object: listView.document)
  314. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  315. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  316. NotificationCenter.default.addObserver(self, selector: #selector(pdfViewHighlightFormFiledUpdateNoti), name: kPDFViewHighlightFormFiledUpdateNotiName, object: nil)
  317. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  318. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  319. }
  320. internal func removeNotifications() {
  321. NotificationCenter.default.removeObserver(self)
  322. }
  323. //MARK: - 初始化默认PDF数据
  324. private func loadUserDefaultsData() {
  325. applyLeftSideWidth(0, rightSideWidth: 0) //初始打开左边栏
  326. //初始化侧边栏打开内容
  327. if SettingsManager.sharedInstance.leftPanelType == .defaultOpen {
  328. if SettingsManager.sharedInstance.defaultOpen == .thumbnail {
  329. viewManager.pdfSideBarType = .thumbnail
  330. } else if SettingsManager.sharedInstance.defaultOpen == .outline {
  331. viewManager.pdfSideBarType = .outline
  332. } else if SettingsManager.sharedInstance.defaultOpen == .bookmark {
  333. viewManager.pdfSideBarType = .bookmark
  334. } else if SettingsManager.sharedInstance.defaultOpen == .annotation {
  335. viewManager.pdfSideBarType = .annotation
  336. }
  337. } else if SettingsManager.sharedInstance.leftPanelType == .sameAsLastOpen {
  338. if let value = UserDefaults.standard.value(forKey: "KMPDFSidebarTypeKey"), let data = value as? Int {
  339. let pdfSideBarType: KMPDFSidebarType = KMPDFSidebarType(rawValue: data) ?? .none
  340. viewManager.pdfSideBarType = pdfSideBarType
  341. }
  342. } else if SettingsManager.sharedInstance.leftPanelType == .hideLeftSide {
  343. viewManager.pdfSideBarType = .none
  344. } else if SettingsManager.sharedInstance.leftPanelType == .prioritizeOutline {
  345. if let rootOutline = self.listView.document.outlineRoot(), rootOutline.numberOfChildren > 0 {
  346. viewManager.pdfSideBarType = .outline
  347. }
  348. }
  349. if viewManager.pdfSideBarType == .none {
  350. toggleCloseLeftSide()
  351. } else {
  352. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  353. self.toggleCloseLeftSide()
  354. self.toggleOpenLeftSide(pdfSideBarType: self.viewManager.pdfSideBarType)
  355. }
  356. }
  357. //Layout & Zoom
  358. let layoutType = SettingsManager.sharedInstance.layoutType
  359. if layoutType == .singlePage {
  360. self.updatePDFViewDisplayMode(viewMode: .singlePage)
  361. } else if layoutType == .singlePageContinue {
  362. self.updatePDFViewDisplayMode(viewMode: .singlePageContinuous)
  363. } else if layoutType == .twoPage {
  364. self.updatePDFViewDisplayMode(viewMode: .twoUp)
  365. } else if layoutType == .twoPageContinue {
  366. self.updatePDFViewDisplayMode(viewMode: .twoUpContinuous)
  367. } else if layoutType == .bookMode {
  368. self.updatePDFViewDisplayMode(isbookMode: true, direction: .horizontal)
  369. } else if layoutType == .bookModeContinue {
  370. self.updatePDFViewDisplayMode(isbookMode: true, direction: .vertical)
  371. }
  372. if self.listView.document != nil {
  373. if let pageIndex = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path) {
  374. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  375. self.listView.go(toPageIndex: pageIndex, animated: false)
  376. self.listView.setNeedsDisplayForVisiblePages()
  377. }
  378. }
  379. if let scale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path) {
  380. self.listView.scaleFactor = CGFloat(scale)
  381. } else {
  382. let zoomType = SettingsManager.sharedInstance.zoomType
  383. self.refreshPDFViewZoomInfo(zoomType)
  384. }
  385. }
  386. }
  387. func refreshPDFViewZoomInfo(_ zoomType: zoomInfoType) {
  388. if zoomType == .adaptationWidth {
  389. listView.autoScales = true
  390. } else if zoomType == .adapPage {
  391. let pageHeight = listView.currentPage().size.height
  392. let pdfviewHeight = listView.bounds.size.height
  393. listView.scaleFactor = pdfviewHeight/pageHeight
  394. listView.autoScales = false
  395. } else if zoomType == .actualSize {
  396. if listView.scaleFactor != 1.0 {
  397. listView.scaleFactor = 1.0
  398. listView.autoScales = false
  399. }
  400. } else if zoomType == .percent_10 {
  401. listView.scaleFactor = 0.1
  402. } else if zoomType == .percent_25 {
  403. listView.scaleFactor = 0.25
  404. } else if zoomType == .percent_50 {
  405. listView.scaleFactor = 0.5
  406. } else if zoomType == .percent_75 {
  407. listView.scaleFactor = 0.75
  408. } else if zoomType == .percent_100 {
  409. listView.scaleFactor = 1.0
  410. } else if zoomType == .percent_150 {
  411. listView.scaleFactor = 1.5
  412. } else if zoomType == .percent_200 {
  413. listView.scaleFactor = 2.0
  414. } else if zoomType == .percent_400 {
  415. listView.scaleFactor = 4.0
  416. } else if zoomType == .percent_800 {
  417. listView.scaleFactor = 8.0
  418. }
  419. }
  420. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  421. infoContendSplitView.setPosition(infoContendSplitView.maxPossiblePositionOfDivider(at: 1) - infoContendSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  422. infoContendSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  423. }
  424. //MARK: - PDFView
  425. func initPDFView() {
  426. listView.autoresizingMask = [.width, .height]
  427. listView.autoScales = true
  428. listView.delegate = self
  429. listView.pdfListViewDelegate = self
  430. listView.document = self.document
  431. listView.pageBreakMargins = NSEdgeInsetsMake(10, 0, 10, 10)
  432. listView.hideNotes = false
  433. if let _ = UserDefaults.standard.value(forKey: "kPDFViewShowFormFieldNameKey") {
  434. listView.showFormFieldName = UserDefaults.getDefaultBoolValue(forKey: "kPDFViewShowFormFieldNameKey")
  435. } else {
  436. listView.showFormFieldName = true
  437. }
  438. reloadPDFSplitInfo()
  439. }
  440. func updatePDFViewAnnotationMode() {
  441. let toolbarMode = viewManager.toolMode
  442. let subToolMode = viewManager.subToolMode
  443. listView.isHidden = false
  444. if toolbarMode == .None {
  445. listView.toolMode = .CTextToolMode
  446. listView.annotationType = .unkown
  447. } else if toolbarMode == .Markup {
  448. if subToolMode == .None {
  449. listView.toolMode = .CTextToolMode
  450. } else {
  451. listView.toolMode = .CNoteToolMode
  452. }
  453. //MARK: -Markup
  454. if subToolMode == .None {
  455. listView.annotationType = .unkown
  456. } else if subToolMode == .Highlight {
  457. listView.annotationType = .highlight
  458. } else if subToolMode == .Underline {
  459. listView.annotationType = .underline
  460. } else if subToolMode == .Waveline {
  461. listView.annotationType = .squiggly
  462. } else if subToolMode == .Strikethrough {
  463. listView.annotationType = .strikeOut
  464. } else if subToolMode == .Text {
  465. listView.annotationType = .freeText
  466. } else if subToolMode == .Note {
  467. listView.annotationType = .anchored
  468. } else if subToolMode == .Pen {
  469. listView.annotationType = .ink
  470. } else if subToolMode == .Eraser {
  471. listView.annotationType = .eraser
  472. } else if subToolMode == .Rectangle {
  473. listView.annotationType = .square
  474. } else if subToolMode == .Circle {
  475. listView.annotationType = .circle
  476. } else if subToolMode == .Arrow {
  477. listView.annotationType = .arrow
  478. } else if subToolMode == .Line {
  479. listView.annotationType = .line
  480. } else if subToolMode == .Measure {
  481. listView.annotationType = CPDFMeasureDefaultInfo.default_measureType()
  482. refreshMeasureInfo()
  483. } else if subToolMode == .Stamp {
  484. listView.annotationType = .stamp
  485. } else if subToolMode == .Sign {
  486. listView.annotationType = .signSignature
  487. }
  488. } else if toolbarMode == .Edit {
  489. //MARK: -编辑
  490. if subToolMode == .None {
  491. if KMMemberInfo.shared.isLogin == true {
  492. if listView.toolMode != .CEditPDFToolMode {
  493. listView.toolMode = .CEditPDFToolMode
  494. listView.configPDFEditingInfo()
  495. }
  496. let editingPDFLoadType: CEditingLoadType = listView.editingPDFLoadType()
  497. listView.setShouAddEdit([])
  498. listView.change([.text, .image])
  499. }
  500. } else if subToolMode == .Edit_text {
  501. if listView.toolMode != .CEditPDFToolMode {
  502. listView.toolMode = .CEditPDFToolMode
  503. listView.configPDFEditingInfo()
  504. }
  505. listView.setShouAddEdit([.text])
  506. listView.change(.text)
  507. } else if subToolMode == .Edit_Image {
  508. if listView.toolMode != .CEditPDFToolMode {
  509. listView.toolMode = .CEditPDFToolMode
  510. listView.configPDFEditingInfo()
  511. }
  512. listView.setShouAddEdit([.image])
  513. listView.change(.image)
  514. } else if subToolMode == .Edit_Link {
  515. listView.toolMode = .CEditLinkToolMode
  516. listView.annotationType = .link
  517. } else if subToolMode == .Edit_Crop {
  518. listView.isHidden = true
  519. listView.toolMode = .CCropToolMode
  520. }
  521. if viewManager.editType == .watermark ||
  522. viewManager.editType == .background ||
  523. viewManager.editType == .header_Footer ||
  524. viewManager.editType == .bates {
  525. listView.isHidden = true
  526. listView.toolMode = .CTextToolMode
  527. }
  528. if subToolMode != .Edit_Crop {
  529. removeCropController()
  530. }
  531. self.showOCREditAlert()
  532. } else if toolbarMode == .Form {
  533. //MARK: -Form表单
  534. listView.toolMode = .CFormToolMode
  535. if subToolMode == .None {
  536. listView.annotationType = .unkown
  537. } else if subToolMode == .Form_text {
  538. listView.annotationType = .textField
  539. } else if subToolMode == .Form_checkbox {
  540. listView.annotationType = .checkBox
  541. } else if subToolMode == .Form_radio {
  542. listView.annotationType = .radioButton
  543. } else if subToolMode == .Form_list {
  544. listView.annotationType = .listMenu
  545. } else if subToolMode == .Form_dropdown {
  546. listView.annotationType = .comboBox
  547. } else if subToolMode == .Form_OK {
  548. listView.annotationType = .actionButton
  549. } else if subToolMode == .Form_digitalSign {
  550. listView.annotationType = .signature
  551. }
  552. } else if toolbarMode == .Fill {
  553. //MARK: -填充
  554. if subToolMode == .None {
  555. listView.toolMode = .CTextToolMode
  556. } else {
  557. listView.toolMode = .CNoteToolMode
  558. }
  559. if subToolMode == .None {
  560. } else if subToolMode == .Fill_tick {
  561. listView.annotationType = .signTure
  562. } else if subToolMode == .fill_fork {
  563. listView.annotationType = .signFalse
  564. } else if subToolMode == .fill_rectangle {
  565. listView.annotationType = .signCircle
  566. } else if subToolMode == .fill_line {
  567. listView.annotationType = .signLine
  568. } else if subToolMode == .fill_dot {
  569. listView.annotationType = .signDot
  570. } else if subToolMode == .fill_date {
  571. listView.annotationType = .signDate
  572. } else if subToolMode == .fill_sign {
  573. listView.annotationType = .signSignature
  574. }
  575. } else if toolbarMode == .Convert {
  576. //MARK: -转档
  577. listView.toolMode = .CTextToolMode
  578. } else if toolbarMode == .Protect {
  579. //MARK: -Protect
  580. listView.toolMode = .CTextToolMode
  581. if subToolMode == .Redact {
  582. //密文
  583. listView.annotationType = .redact
  584. listView.toolMode = .CRedactToolMode
  585. } else if subToolMode == .Digital_Sign {
  586. //数字签名
  587. listView.annotationType = .digitalSign
  588. listView.toolMode = .CDigitalSignToolMode
  589. self.enterDigitalSignature()
  590. }
  591. } else if toolbarMode == .Tools {
  592. listView.toolMode = .CTextToolMode
  593. }
  594. if (toolbarMode != .Edit) {
  595. self.closeOCREditAlert()
  596. }
  597. }
  598. func showOrHideNotes() {
  599. self.listView.hideNotes = !self.listView.hideNotes
  600. let items = [toolbarManager.highlightProperty, toolbarManager.UnderlineProperty,
  601. toolbarManager.wavelineProperty, toolbarManager.strikethroughProperty,
  602. toolbarManager.textProperty, toolbarManager.noteProperty,
  603. toolbarManager.penProperty, toolbarManager.eraserProperty,
  604. toolbarManager.rectangleProperty, toolbarManager.circleProperty,
  605. toolbarManager.arrowProperty, toolbarManager.lineProperty,
  606. toolbarManager.measureProperty, toolbarManager.stampProperty,
  607. toolbarManager.signProperty]
  608. for item in items {
  609. item.isDisabled = listView.hideNotes
  610. }
  611. pdfToolbarController?.resetSecondToolbar(forceRefresh: true)
  612. }
  613. //MARK: - SplitView
  614. func setUpSplitView() {
  615. infoContendSplitView.wantsLayer = true
  616. infoContendSplitView.layer?.backgroundColor = NSColor.clear.cgColor
  617. infoContendSplitView.delegate = self
  618. infoContendSplitView.layer?.masksToBounds = true
  619. }
  620. func setupSplitPDFController() {
  621. if splitPDFController == nil {
  622. splitPDFController = KMSplitPDFViewController.init()
  623. }
  624. splitPDFController?.view.frame = pdfSplitBottomView.bounds
  625. splitPDFController?.view.autoresizingMask = [.height, .width]
  626. splitPDFController?.viewManager = self.viewManager
  627. splitPDFController?.delegate = self
  628. splitPDFController?.pdfView?.pdfListViewDelegate = self
  629. splitPDFController?.reloadData()
  630. pdfSplitBottomView.addSubview(splitPDFController!.view)
  631. }
  632. //MARK: - 工具栏
  633. func initToolbar() {
  634. toolbarBox.borderWidth = 0
  635. if pdfToolbarController == nil {
  636. pdfToolbarController = KMPDFToolbarController.init()
  637. }
  638. pdfToolbarController?.view.frame = toolbarBox.bounds
  639. pdfToolbarController?.view.autoresizingMask = [.width, .height]
  640. pdfToolbarController?.delegate = self
  641. toolbarBox.contentView = pdfToolbarController?.view
  642. pdfToolbarController?.viewManager = viewManager
  643. pdfToolbarController?.toolbarManager = toolbarManager
  644. pdfToolbarController?.pdfView = listView
  645. pdfToolbarController?.setUpData()
  646. refreshToolbarViewHeightInfo()
  647. if listView.showFormFieldName {
  648. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  649. } else {
  650. toolbarManager.form_ShowName_Property.righticon = nil
  651. }
  652. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  653. self.pdfToolbarController?.clickWithIdentify(KMPDFToolbar_Markup_Identifier)
  654. }
  655. }
  656. func refreshToolbarViewHeightInfo() {
  657. let _viewManager = viewManager
  658. if viewManager.isPageEditMode {
  659. toolbarBoxHeightConst.constant = 80
  660. } else if viewManager.editType == .watermark ||
  661. viewManager.editType == .background ||
  662. viewManager.editType == .header_Footer ||
  663. viewManager.editType == .bates {
  664. toolbarBoxHeightConst.constant = 40
  665. } else if _viewManager.toolMode == .Markup ||
  666. _viewManager.toolMode == .Edit ||
  667. _viewManager.toolMode == .Form ||
  668. _viewManager.toolMode == .Fill ||
  669. _viewManager.toolMode == .Convert ||
  670. _viewManager.toolMode == .Protect ||
  671. _viewManager.toolMode == .Tools {
  672. toolbarBoxHeightConst.constant = 80
  673. if _viewManager.subToolMode == .Redact {
  674. toolbarBoxHeightConst.constant = 40
  675. }
  676. } else {
  677. toolbarBoxHeightConst.constant = 40
  678. }
  679. }
  680. func toolbarViewModeChanged() {
  681. updatePDFViewAnnotationMode()
  682. refreshToolbarRightViewInfo()
  683. if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
  684. removeCropController()
  685. }
  686. if viewManager.toolMode != .Markup && viewManager.subToolMode != .Measure {
  687. self.hideMeasureFloatingWindows()
  688. }
  689. }
  690. func updatePDFViewToolsType(_ viewToolsType: KMPDFViewToolsType) {
  691. viewManager.viewToolsType = viewToolsType
  692. pdfToolbarController?.reloadToolsView()
  693. if let toolbarVC = pdfToolbarController {
  694. kmPDFToolbarControllerDidViewToolsChanged(toolbarVC)
  695. }
  696. }
  697. //MARK: - 右边属性栏
  698. func refreshToolbarRightViewInfo() {
  699. //统一刷新viewManager.showRightSide, 由这个参数控制右边属性边框的展开与隐藏
  700. if viewManager.showRightSide == true {
  701. toolbarManager.rightViewProperty.state = .pressed
  702. toggleOpenRightSide()
  703. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  704. } else {
  705. toggleCloseRightSide()
  706. }
  707. if viewManager.showRightSide == true {
  708. toolbarManager.rightViewProperty.state = .pressed
  709. } else {
  710. toolbarManager.rightViewProperty.state = .normal
  711. }
  712. pdfToolbarController?.reloadRightToolsView()
  713. }
  714. //MARK: - 侧边工具栏
  715. func initSideBar() {
  716. sidebarBox.borderWidth = 0
  717. if sideBarController == nil {
  718. sideBarController = KMPDFSideBarController.init()
  719. }
  720. sideBarController?.view.frame = sidebarBox.bounds
  721. sideBarController?.view.autoresizingMask = [.width, .height]
  722. sidebarBox.contentView = sideBarController?.view
  723. sideBarController?.pdfView = listView
  724. sideBarController?.delegate = self
  725. sideBarController?.pdfViewManager = viewManager
  726. sideBarController?.reloadData()
  727. }
  728. func reloadSideBar() {
  729. sideBarController?.reloadData()
  730. if viewManager.editType == .none {
  731. sideBarController?.searchItem.isHidden = false
  732. sideBarController?.thumbnailItem.isHidden = false
  733. sideBarController?.outlineItem.isHidden = false
  734. sideBarController?.bookmarkItem.isHidden = false
  735. sideBarController?.annotationItem.isHidden = false
  736. sideBarController?.aiToolItem.isHidden = false
  737. } else {
  738. sideBarController?.searchItem.isHidden = true
  739. sideBarController?.thumbnailItem.isHidden = true
  740. sideBarController?.outlineItem.isHidden = true
  741. sideBarController?.bookmarkItem.isHidden = true
  742. sideBarController?.annotationItem.isHidden = true
  743. sideBarController?.aiToolItem.isHidden = true
  744. }
  745. }
  746. //MARK: - 左边侧边栏
  747. func initLeftSideController() {
  748. Task { @MainActor in
  749. if self.botaViewController == nil {
  750. self.botaViewController = KMNLeftSideViewController(self.listView.document,currentUndoManager: self.listView.undoManager)
  751. }
  752. self.botaViewController?.leftSideViewDelegate = self
  753. self.botaViewController?.view.frame = self.infoSplitLeftView.bounds
  754. self.botaViewController?.view.autoresizingMask = [.width, .height]
  755. if self.botaViewController != nil {
  756. self.infoSplitLeftView?.addSubview(self.botaViewController!.view)
  757. }
  758. }
  759. }
  760. private func leftSidePaneIsOpen() -> Bool {
  761. return !infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) //第一次点击时存在问题,待解决
  762. }
  763. func toggleOpenLeftSide(pdfSideBarType: KMPDFSidebarType) {
  764. if pdfSideBarType == .search {
  765. viewManager.pdfSideBarType = .search
  766. botaViewController?.searchViewC.handdler.pdfView = listView
  767. botaViewController?.leftsideType = .search
  768. } else if pdfSideBarType == .thumbnail {
  769. botaViewController?.leftsideType = pdfSideBarType
  770. botaViewController?.currentPageDidChangedAction(listView: listView)
  771. } else if pdfSideBarType == .outline {
  772. botaViewController?.outlineViewC.handdler.pdfView = listView
  773. botaViewController?.leftsideType = pdfSideBarType
  774. } else if pdfSideBarType == .bookmark {
  775. botaViewController?.bookmarkViewC.handdler.pdfView = listView
  776. botaViewController?.leftsideType = pdfSideBarType
  777. } else if pdfSideBarType == .annotation {
  778. botaViewController?.annoController.listView = listView
  779. botaViewController?.leftsideType = .annotation
  780. } else if pdfSideBarType == .aiTools {
  781. botaViewController?.leftsideType = .aiTools
  782. }
  783. if(leftSidePaneIsOpen() == false && pdfSideBarType != .none) {
  784. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) as? NSNumber ?? MIN_SIDE_PANE_WIDTH
  785. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0) //暂时无法记录上一次打开的宽度
  786. }
  787. }
  788. func toggleCloseLeftSide() {
  789. if(leftSidePaneIsOpen() == true) {
  790. infoContendSplitView.setPosition(0, ofDividerAt: 0)
  791. }
  792. }
  793. //MARK: - 右侧属性栏
  794. func initRightSideController() {
  795. if rightSideController == nil {
  796. rightSideController = KMRightSideController.init()
  797. rightSideController?.delegate = self
  798. }
  799. rightSideController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, 680)
  800. rightSideController?.view.autoresizingMask = [.height, .maxXMargin]
  801. }
  802. func removeRightSideController() {
  803. rightSideController?.view.removeFromSuperview()
  804. rightSideController = nil
  805. }
  806. @objc func toggleOpenRightSide() -> Void {
  807. if rightSideController != nil {
  808. return
  809. }
  810. initRightSideController()
  811. rightSideController?.view.frame = infoSplitRightView.bounds
  812. rightSideController?.view.autoresizingMask = [.width, .height]
  813. infoSplitRightView.addSubview(rightSideController!.view)
  814. infoContendSplitView.setPosition(CGRectGetWidth(view.frame)-MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 1)
  815. rightSideController?.viewManager = self.viewManager
  816. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  817. }
  818. @objc func toggleCloseRightSide() -> Void {
  819. removeRightSideController()
  820. infoContendSplitView.setPosition(CGRectGetWidth(view.frame), ofDividerAt: 1)
  821. viewManager.showRightSide = false
  822. pdfToolbarController?.reloadRightToolsView()
  823. }
  824. func refreshRightSide() -> Void {
  825. if let rightVC = rightSideController, let _ = rightSideController?.view.superview {
  826. rightVC.reloadDataWithPDFView(pdfView: listView)
  827. }
  828. }
  829. //MARK: - PDFDisplayView
  830. func updatePDFDisplaySettingView() {
  831. if viewManager.showDisplayView {
  832. infoSplitViewLeftConst.constant = 0
  833. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0)
  834. } else {
  835. if viewManager.isPDFReadMode == false {
  836. infoSplitViewLeftConst.constant = 44
  837. if viewManager.pdfSideBarType == .none {
  838. toggleCloseLeftSide()
  839. } else {
  840. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  841. }
  842. } else {
  843. toggleCloseLeftSide()
  844. }
  845. }
  846. if viewManager.showDisplayView {
  847. if displaySettingController == nil {
  848. displaySettingController = KMNDisplayViewController.init()
  849. }
  850. displaySettingController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, CGRectGetHeight(bottomContendBox.frame))
  851. displaySettingController?.view.autoresizingMask = [.height, .width]
  852. infoSplitLeftView.addSubview(displaySettingController!.view)
  853. displaySettingController?.pdfView = self.listView
  854. displaySettingController?.viewManager = self.viewManager
  855. displaySettingController?.delegate = self
  856. displaySettingController?.reloadData()
  857. } else {
  858. displaySettingController?.view.removeFromSuperview()
  859. displaySettingController = nil
  860. }
  861. }
  862. //MARK: - 页面编辑
  863. func enterPageEditMode() {
  864. if(pageEditViewController == nil) {
  865. pageEditViewController = KMNPageEditViewController(self.document)
  866. pageEditViewController?.thumbnailBaseViewDelegate = self
  867. }
  868. pageEditViewController?.view.frame = bottomContendBox.bounds
  869. pageEditViewController?.restSelectCount()
  870. pageEditViewController?.view.autoresizingMask = [.width,.height]
  871. pageEditViewController?.currentUndoManager = listView.undoManager
  872. pageEditViewController?.reloadDatas()
  873. pageEditViewController?.selectionIndexPaths = [IndexPath(item: listView.currentPageIndex, section: 0)]
  874. bottomContendBox.addSubview(pageEditViewController!.view)
  875. toolbarManager.page_pageInfo_Property.text = String(listView.currentPageIndex + 1)
  876. pdfToolbarController?.refreshSecondToolbarItemsState()
  877. listView.isHidden = true
  878. listView.updateActiveAnnotations([])
  879. listView.updateEditing([])
  880. }
  881. func exitPageEditMode() {
  882. if pageEditViewController != nil {
  883. pageEditViewController?.view.removeFromSuperview()
  884. }
  885. listView.isHidden = false
  886. if listView.document?.isModified() == true {
  887. listView.layoutDocumentView()
  888. botaViewController?.reloadData()
  889. }
  890. botaViewController?.currentPageDidChangedAction(listView: listView)
  891. }
  892. //MARK: - 阅读模式
  893. func openPDFReadMode() {
  894. if viewManager.showDisplayView {
  895. UserDefaults.setDefaultBoolValue(true, toKey: "ShowDisplayViewWhenExitPDFReadMode")
  896. viewManager.showDisplayView = false
  897. pdfToolbarController?.reloadLeftIconView()
  898. updatePDFDisplaySettingView()
  899. }
  900. UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsReadModeKey)
  901. if infoSplitViewLeftConst.constant != 0 {
  902. infoSplitViewLeftConst.constant = 0
  903. updatePDFDisplaySettingView()
  904. }
  905. if viewManager.pdfSideBarType != .none {
  906. UserDefaults.setDefaultIntValue(viewManager.pdfSideBarType.rawValue, toKey: "viewManagerPdfSideBarTypeRawValue")
  907. viewManager.pdfSideBarType = .none
  908. }
  909. if listView.toolMode != .CNoteToolMode {
  910. listView.toolMode = .CNoteToolMode
  911. viewManager.viewToolsType = .Select
  912. pdfToolbarController?.reloadToolsView()
  913. }
  914. toolbarBoxHeightConst.constant = 0
  915. view.window?.makeFirstResponder(listView)
  916. self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode On"))
  917. self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
  918. CGRectGetHeight(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
  919. self.componentMessageView.properties.propertyInfo.viewWidth,
  920. self.componentMessageView.properties.propertyInfo.viewHeight)
  921. self.componentMessageView.reloadData()
  922. self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
  923. setUpPDFPageNumberToolbar()
  924. if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
  925. removeCropController()
  926. }
  927. }
  928. func exitPDFReadMode() {
  929. viewManager.isPDFReadMode = false
  930. if UserDefaults.getDefaultBoolValue(forKey: "ShowDisplayViewWhenExitPDFReadMode") == true {
  931. if viewManager.showDisplayView == false {
  932. viewManager.showDisplayView = true
  933. pdfToolbarController?.reloadLeftIconView()
  934. }
  935. UserDefaults.setDefaultBoolValue(false, toKey: "ShowDisplayViewWhenExitPDFReadMode")
  936. }
  937. UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsReadModeKey)
  938. if let index = UserDefaults.getDefaultIntValue(forKey: "viewManagerPdfSideBarTypeRawValue") {
  939. let type = KMPDFSidebarType(rawValue: index) ?? .none
  940. viewManager.pdfSideBarType = type
  941. UserDefaults.standard.removeObject(forKey: "viewManagerPdfSideBarTypeRawValue")
  942. UserDefaults.standard.synchronize()
  943. }
  944. updatePDFDisplaySettingView()
  945. refreshToolbarViewHeightInfo()
  946. reloadPDFPageNumberToolbar()
  947. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  948. self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode Off"))
  949. self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.infoSplitCenterView.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
  950. CGRectGetHeight(self.infoSplitCenterView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
  951. self.componentMessageView.properties.propertyInfo.viewWidth,
  952. self.componentMessageView.properties.propertyInfo.viewHeight)
  953. self.componentMessageView.reloadData()
  954. self.componentMessageView.showSelf(inView: self.infoSplitCenterView, autoHideSeconde: 2)
  955. }
  956. }
  957. //MARK: - PPT
  958. func togglePresentation(_ sender: Any?) {
  959. if KMMemberInfo.shared.isLogin == false {
  960. KMLoginWindowsController.shared.showWindow(nil)
  961. return
  962. }
  963. if self.canExitPresentation() {
  964. exitFullScreen()
  965. } else if self.canEnterPresentation() {
  966. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  967. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  968. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  969. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  970. view.window?.enterPresentation(provider: self)
  971. if listView.toolMode != .CNoteToolMode {
  972. listView.toolMode = .CNoteToolMode
  973. viewManager.viewToolsType = .Select
  974. pdfToolbarController?.reloadToolsView()
  975. }
  976. }
  977. }
  978. func enterPresentationMode() {
  979. let scrollView = listView.documentView().enclosingScrollView
  980. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  981. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  982. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  983. listView.backgroundColor = NSColor.clear
  984. listView.setDisplay(.singlePage)
  985. listView.autoScales = true
  986. listView.displayBox = .cropBox
  987. listView.displaysPageBreaks = false
  988. scrollView?.autohidesScrollers = true
  989. scrollView?.hasHorizontalScroller = false
  990. scrollView?.hasVerticalScroller = false
  991. listView.setCurrentSelection(nil, animate: true)
  992. }
  993. func exitPresentationMode() {
  994. NotificationCenter.default.removeObserver(self, name: NSWindow.willEnterInteractionModeNotification, object: nil)
  995. NotificationCenter.default.removeObserver(self, name: NSWindow.didEnterInteractionModeNotification, object: nil)
  996. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  997. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  998. }
  999. func exitFullScreen() {
  1000. if self.canExitPresentation() == true {
  1001. let mainDocument = self.myDocument as? KMMainDocument
  1002. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  1003. browserWindowController?.exitFullscreen()
  1004. }
  1005. }
  1006. func exitFullscreenMode() {
  1007. if self.interactionMode == .presentation {
  1008. self.exitPresentationMode()
  1009. }
  1010. self.applyPDFSettings(self.savedNormalSetup)
  1011. self.savedNormalSetup.removeAllObjects()
  1012. listView.layoutDocumentView()
  1013. listView.requiresDisplay()
  1014. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  1015. listView.backgroundColor = backgroundColor
  1016. }
  1017. reloadPDFSplitInfo()
  1018. }
  1019. func applyPDFSettings(_ setup: NSDictionary) {
  1020. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  1021. self.listView.autoScales = data.boolValue
  1022. }
  1023. if self.listView.autoScales == false {
  1024. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  1025. self.listView.scaleFactor = data.floatValue.cgFloat
  1026. }
  1027. }
  1028. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  1029. self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
  1030. }
  1031. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  1032. self.listView.displaysAsBook = data.boolValue
  1033. }
  1034. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  1035. self.listView.displaysPageBreaks = data.boolValue
  1036. }
  1037. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  1038. }
  1039. self.listView.layoutDocumentView()
  1040. }
  1041. func currentPDFSettings() -> NSDictionary {
  1042. let setup = NSMutableDictionary()
  1043. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  1044. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  1045. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  1046. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  1047. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  1048. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
  1049. return setup
  1050. }
  1051. func canEnterFullscreen() -> Bool {
  1052. if (mwcFlags.isSwitchingFullScreen != 0) {
  1053. return false
  1054. }
  1055. if useNativeFullScreen() {
  1056. return interactionMode == .normal || interactionMode == .presentation
  1057. } else {
  1058. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  1059. }
  1060. }
  1061. override func canEnterPresentation() -> Bool {
  1062. let can = super.canEnterPresentation()
  1063. if can == false {
  1064. return false
  1065. }
  1066. guard let doc = self.listView.document, doc.isLocked == false else {
  1067. return false
  1068. }
  1069. return can
  1070. }
  1071. func fadeOutFullScreenWindow() {
  1072. guard let fullScreenWindow = self.view.window as? KMFullScreenWindow else {
  1073. NSSound.beep()
  1074. return
  1075. }
  1076. let mainWindow = fullScreenWindow.interactionParent
  1077. let collectionBehavior = mainWindow?.collectionBehavior
  1078. mainWindow?.alphaValue = 0
  1079. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  1080. mainWindow?.animationBehavior = .none
  1081. }
  1082. // trick to make sure the main window shows up in the same space as the fullscreen window
  1083. fullScreenWindow.addChildWindow(mainWindow!, ordered: .below)
  1084. fullScreenWindow.removeChildWindow(mainWindow!)
  1085. fullScreenWindow.level = .popUpMenu
  1086. // these can change due to the child window trick
  1087. mainWindow?.level = .normal
  1088. mainWindow?.alphaValue = 1.0
  1089. mainWindow?.collectionBehavior = collectionBehavior!
  1090. mainWindow?.display()
  1091. mainWindow?.makeFirstResponder(self.listView)
  1092. mainWindow?.recalculateKeyViewLoop()
  1093. // mainWindow?.delegate = self
  1094. mainWindow?.makeKey()
  1095. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  1096. mainWindow?.animationBehavior = .default
  1097. }
  1098. NSApp.removeWindowsItem(fullScreenWindow)
  1099. fullScreenWindow.fadeOut()
  1100. }
  1101. //MARK: - PDF分屏视图
  1102. func reloadPDFSplitInfo() {
  1103. if listView.viewSplitMode == .disable {
  1104. pdfSplitView.isHidden = true
  1105. listView.frame = infoSplitCenterSubView.bounds
  1106. infoSplitCenterSubView.addSubview(listView)
  1107. if splitPDFController != nil {
  1108. splitPDFController = nil
  1109. }
  1110. } else {
  1111. pdfSplitView.isHidden = false
  1112. listView.frame = pdfSplitTopView.bounds
  1113. pdfSplitTopView.addSubview(listView)
  1114. setUpPDFPageNumberToolbar()
  1115. setupSplitPDFController()
  1116. if listView.viewSplitMode == .horizontal {
  1117. pdfSplitView.isVertical = false
  1118. } else if listView.viewSplitMode == .vertical {
  1119. pdfSplitView.isVertical = true
  1120. }
  1121. }
  1122. reloadPDFPageNumberToolbar()
  1123. }
  1124. func setUpPDFPageNumberToolbar() {
  1125. if pageNumberToolbar != nil {
  1126. pageNumberToolbar?.removeFromSuperview()
  1127. pageNumberToolbar = nil
  1128. }
  1129. if pageNumberToolbar == nil {
  1130. pageNumberToolbar = KMPageNumberPromptView.init()
  1131. }
  1132. if viewManager.isPDFReadMode {
  1133. pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-366/2, 20, 366, 40)
  1134. pageNumberToolbar?.hideBackForwordButton(false)
  1135. } else {
  1136. pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-288/2, 20, 288, 40)
  1137. pageNumberToolbar?.hideBackForwordButton(true)
  1138. }
  1139. pageNumberToolbar?.autoresizingMask = [.minXMargin, .maxXMargin, .maxYMargin]
  1140. pageNumberToolbar?.pdfView = self.listView
  1141. pageNumberToolbar?.reloadData()
  1142. pageNumberToolbar?.isHidden = true
  1143. listView.addSubview(pageNumberToolbar!)
  1144. reloadPDFPageNumberToolbar()
  1145. }
  1146. func reloadPDFPageNumberToolbar() {
  1147. if viewManager.isPDFReadMode == true ||
  1148. (viewManager.splitShowBottomBar && listView.viewSplitMode != .disable) {
  1149. pageNumberToolbar?.isHidden = false
  1150. pageNumberToolbar?.reloadData()
  1151. } else {
  1152. pageNumberToolbar?.isHidden = true
  1153. }
  1154. }
  1155. //MARK: - Edit模式
  1156. func showEditToolbarView() {
  1157. if editToolbarView == nil {
  1158. editToolbarView = KMEditToolbarView()
  1159. }
  1160. editToolbarView?.frame = toolbarBox.bounds
  1161. editToolbarView?.delegate = self
  1162. editToolbarView?.autoresizingMask = [.width, .height]
  1163. toolbarBox.contentView = editToolbarView
  1164. reloadSideBar()
  1165. }
  1166. func exitEditToolbarView() {
  1167. viewManager.editType = .none
  1168. viewManager.subToolMode = .None
  1169. editToolbarView?.removeFromSuperview()
  1170. editToolbarView = nil
  1171. watermarkViewController?.view.removeFromSuperview()
  1172. watermarkViewController = nil
  1173. backgroundViewController?.view.removeFromSuperview()
  1174. backgroundViewController = nil
  1175. headerFooterViewController?.view.removeFromSuperview()
  1176. headerFooterViewController = nil
  1177. batesViewController?.view.removeFromSuperview()
  1178. batesViewController = nil
  1179. refreshToolbarViewHeightInfo()
  1180. toolbarBox.contentView = pdfToolbarController?.view
  1181. if UserDefaults.getDefaultBoolValue(forKey: CPDFViewIsEditFromDisplay) == true {
  1182. toolbarManager.viewProperty.state = .pressed
  1183. viewManager.showDisplayView = true
  1184. updatePDFDisplaySettingView()
  1185. }
  1186. updatePDFViewAnnotationMode()
  1187. reloadSideBar()
  1188. KMWatermarkManager.defaultManager.defaultWatermarkData = KMWatermarkModel.defaultWDData()
  1189. }
  1190. func updateEditModeDocumentWhenPageChanged() {
  1191. if viewManager.editType == .watermark {
  1192. updateWatermarkDocument()
  1193. } else if viewManager.editType == .background {
  1194. updateBackgroundDocument()
  1195. } else if viewManager.editType == .header_Footer {
  1196. updateHeaderFooterDocument()
  1197. } else if viewManager.editType == .bates {
  1198. updateBatesDocument()
  1199. } else if viewManager.subToolMode == .Edit_Crop {
  1200. updateCropDocument()
  1201. }
  1202. }
  1203. func menuItemAction_FontPanel() {
  1204. NSFontManager.shared.target = self
  1205. NSFontManager.shared.action = #selector(changeFont(_:))
  1206. NSFontManager.shared.orderFrontFontPanel(nil)
  1207. }
  1208. func menuItemAction_FontAction(_ index: Int) {
  1209. if index == 0 {
  1210. self.listView.setEditingTextarea_Bold()
  1211. } else if index == 1 {
  1212. self.listView.setEditingTextarea_Italic()
  1213. } else if index == 2 {
  1214. self.listView.zoomInEditTextFontSize()
  1215. } else if index == 3 {
  1216. self.listView.zoomOutEditTextFontSize()
  1217. } else if index == 4 {
  1218. let colorPanel = NSColorPanel.shared
  1219. colorPanel.setTarget(self)
  1220. colorPanel.showsAlpha = false
  1221. colorPanel.setAction(#selector(self.menuItemAction_FontColor(_:)))
  1222. colorPanel.orderFront(nil)
  1223. }
  1224. }
  1225. func menuItemAction_FontAlign(_ index: Int) {
  1226. var align: NSTextAlignment = .left
  1227. if index == 0 {
  1228. align = .left
  1229. } else if index == 1 {
  1230. align = .center
  1231. } else if index == 2 {
  1232. align = .right
  1233. }
  1234. if(listView.isEditing() == true) {
  1235. self.listView.setEditingTextarea_Alignment(align: align)
  1236. } else {
  1237. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  1238. if listView.isEdit(withCurrentFreeText: freeTextAnnotation) == true {
  1239. listView.commitEditAnnotationFreeText(freeTextAnnotation)
  1240. }
  1241. freeTextAnnotation.alignment = align
  1242. listView.setNeedsDisplay(freeTextAnnotation)
  1243. }
  1244. }
  1245. }
  1246. func menuItemAction_CustomFont(_ index: Int) {
  1247. if index == 0 {
  1248. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h1)
  1249. self.updateEditPDFTextFontModel(model)
  1250. } else if index == 1 {
  1251. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h2)
  1252. self.updateEditPDFTextFontModel(model)
  1253. } else if index == 2 {
  1254. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h3)
  1255. self.updateEditPDFTextFontModel(model)
  1256. } else if index == 3 {
  1257. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b1)
  1258. self.updateEditPDFTextFontModel(model)
  1259. } else if index == 4 {
  1260. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b2)
  1261. self.updateEditPDFTextFontModel(model)
  1262. } else if index == 5 {
  1263. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b3)
  1264. self.updateEditPDFTextFontModel(model)
  1265. }
  1266. }
  1267. @objc func menuItemAction_FontColor(_ sender: Any) {
  1268. if let color = (sender as? NSColorPanel)?.color {
  1269. listView.changeEditingTextarea_Color(color: color)
  1270. }
  1271. }
  1272. @objc func changeFont(_ sender: NSFontManager) {
  1273. let newFont = sender.convert(NSFont.systemFont(ofSize: 14))
  1274. let value = CPDFFont(familyName: newFont.fontName, fontStyle: newFont.style ?? "Regular")
  1275. listView.setEditingTextarea_font(font: value)
  1276. listView.setEditingTextarea_FontSize(size: newFont.pointSize)
  1277. rightSideController?.reloadData()
  1278. }
  1279. //MARK: - 数字签名
  1280. func writeSignatureToWidget(_ widget: CPDFSignatureWidgetAnnotation, _ path: String, _ password: String, _ config: CPDFSignatureConfig, _ isLock: Bool) ->() {
  1281. let fileName = listView.document.documentURL?.lastPathComponent
  1282. let fileNameWithoutExtension = URL(fileURLWithPath: fileName!).deletingPathExtension().lastPathComponent
  1283. let outputSavePanel = NSSavePanel()
  1284. outputSavePanel.directoryURL = listView.document.documentURL.deletingLastPathComponent()
  1285. outputSavePanel.title = KMLocalizedString("", comment: "Save as PDF")
  1286. outputSavePanel.allowedFileTypes = ["pdf"]
  1287. outputSavePanel.nameFieldStringValue = fileNameWithoutExtension + "_" + KMLocalizedString("Signed", comment: "")
  1288. let result = outputSavePanel.runModal()
  1289. if result == .OK {
  1290. let contentArr = NSMutableArray()
  1291. var locationStr = ""
  1292. var reasonStr = KMLocalizedString("none", comment: "")
  1293. for item in config.contents {
  1294. if item.key == KMLocalizedString("Reason", comment: "") {
  1295. if item.value == KMLocalizedString("<your signing reason here>", comment: "") {
  1296. item.value = " " + KMLocalizedString("none", comment: "")
  1297. }
  1298. reasonStr = item.value
  1299. } else if item.key == KMLocalizedString("Location", comment: "") {
  1300. if item.value == KMLocalizedString("<your signing location here>", comment: "") {
  1301. item.value = " "
  1302. }
  1303. locationStr = item.value
  1304. }
  1305. contentArr.add(item)
  1306. }
  1307. config.contents = contentArr as? [CPDFSignatureConfigItem]
  1308. widget.setFieldName(widget.getValidName(inPage: widget.page))
  1309. widget.signAppearanceConfig(config)
  1310. let success = listView.document.writeSignature(to: outputSavePanel.url, withWidget: widget, pkcs12Cert: path, password: password, location: locationStr, reason: reasonStr, permissions: .forbidChange)
  1311. widget.removeSignature()
  1312. if success {
  1313. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1314. NSDocumentController.shared.openDocument(withContentsOf: outputSavePanel.url!, display: true) { document, documentWasAlreadyOpen, error in
  1315. if error != nil {
  1316. NSApp.presentError(error!)
  1317. return
  1318. }
  1319. }
  1320. }
  1321. } else {
  1322. let alert = NSAlert.init()
  1323. alert.messageText = KMLocalizedString("Save failed!", comment: "")
  1324. alert.addButton(withTitle: KMLocalizedString("OK", comment: ""))
  1325. alert.runModal()
  1326. }
  1327. widget.page.removeAnnotation(widget)
  1328. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1329. } else {
  1330. widget.page.removeAnnotation(widget)
  1331. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1332. }
  1333. }
  1334. func popUpSignatureWidgetState(_ signature: CPDFSignature, _ pdfListView: CPDFListView) ->(){
  1335. signaturestateVC.signature = signature
  1336. signaturestateVC.pdfListView = pdfListView
  1337. signaturestateVC.actionBlock = { [weak self, weak signaturestateVC] stateVCSelf, actionType in
  1338. guard let weakSelf = self, let stateVC = signaturestateVC else { return }
  1339. if actionType == .cancel {
  1340. stateVC.dismiss(stateVCSelf)
  1341. } else if actionType == .confirm {
  1342. if let signer = signature.signers.first, let data = signer.certificates {
  1343. let signatureDetail = DSignatureDetailsViewController.init()
  1344. signatureDetail.certificates = data
  1345. signatureDetail.signature = signature
  1346. signatureDetail.pdfListView = pdfListView
  1347. stateVCSelf.presentAsSheet(signatureDetail)
  1348. } else {
  1349. NSSound.beep()
  1350. }
  1351. }
  1352. }
  1353. self.presentAsSheet(signaturestateVC)
  1354. signaturestateVC.reloadData()
  1355. }
  1356. func enterDigitalSignature() {
  1357. if UserDefaults.standard.object(forKey: "kDigitalSignature") != nil {
  1358. return
  1359. }
  1360. let alert = NSAlert()
  1361. alert.alertStyle = .informational
  1362. alert.messageText = KMLocalizedString("Using your mouse, click and drag to draw the area where you would like the signature to appear. Once you finish dragging out the desired area, you will be taken to the next step of the signing process. ")
  1363. alert.addButton(withTitle: KMLocalizedString("OK"))
  1364. alert.showsSuppressionButton = true
  1365. let response = alert.runModal()
  1366. if response.rawValue == 1000 {
  1367. if alert.suppressionButton?.state == .on {
  1368. UserDefaults.standard.set("YES", forKey: "kDigitalSignature")
  1369. UserDefaults.standard.synchronize()
  1370. }
  1371. }
  1372. }
  1373. // MARK: - 显示合并窗口
  1374. public func showMergeWindow(url: URL? = nil) {
  1375. DispatchQueue.main.async {
  1376. // var documentURL = url
  1377. //
  1378. // let filePath = documentURL?.path ?? ""
  1379. // if !FileManager.default.fileExists(atPath: filePath) {
  1380. // let alert = NSAlert.init()
  1381. // alert.alertStyle = .critical
  1382. // alert.messageText = "\(filePath.lastPathComponent) \(KMLocalizedString("File Not Exist", comment: ""))"
  1383. // alert.runModal()
  1384. // return
  1385. // }
  1386. //
  1387. // guard let _url = documentURL else { return }
  1388. // guard let document = PDFDocument(url: _url) else { return }
  1389. self.mergeWindowController = KMMergeWindowController(windowNibName: "KMMergeWindowController")
  1390. // self.mergeWindowController!.password = self.listView.document.password ?? ""
  1391. // self.mergeWindowController!.oriDucumentUrl = self.listView.document?.documentURL
  1392. // self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1393. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1394. self.view.window?.endSheet(mergeWindowController!.window!)
  1395. }
  1396. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1397. self.view.window?.endSheet(mergeWindowController!.window!)
  1398. }
  1399. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1400. let file = KMFileAttribute()
  1401. file.filePath = self.listView.document?.documentURL.path ?? ""
  1402. file.password = self.listView.document?.password ?? ""
  1403. self.mergeWindowController?.files = [file]
  1404. }
  1405. }
  1406. //MARK: - Crop裁剪
  1407. func showCropController() {
  1408. if cropController == nil {
  1409. cropController = KMCropController.init()
  1410. cropController?.view.frame = infoSplitCenterView.bounds
  1411. cropController?.view.autoresizingMask = [.width, .height]
  1412. cropController?.delegate = self
  1413. infoSplitCenterView.addSubview(cropController!.view)
  1414. if viewManager.showRightSide == false {
  1415. viewManager.showRightSide = true
  1416. refreshToolbarRightViewInfo()
  1417. }
  1418. if self.alertTipViewController.view.superview != nil {
  1419. alertTipViewController.view.removeFromSuperview()
  1420. infoSplitViewTopConst.constant = 0
  1421. }
  1422. updateCropDocument()
  1423. }
  1424. }
  1425. func updateCropDocument() {
  1426. guard let controller = cropController else { return }
  1427. controller.pdfDocument = nil
  1428. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1429. let editDocument = CPDFDocument.init()
  1430. editDocument?.insertPageObject(page, at: 0)
  1431. if let editPage = editDocument?.page(at: 0) {
  1432. let mediaRect = editPage.bounds(for: .mediaBox)
  1433. editPage.setBounds(mediaRect, for: .cropBox)
  1434. if let rect = KMCropManager.defaultManager.cropRect {
  1435. controller.selectionRect = rect
  1436. } else {
  1437. if KMCropManager.defaultManager.cropSeparateOn {
  1438. let rect = KMCropTools.getPageForegroundBox(editPage)
  1439. controller.selectionRect = rect
  1440. } else if KMCropManager.defaultManager.cropAutoOn {
  1441. let rect = KMCropTools.getPageForegroundBox(editPage)
  1442. controller.selectionRect = rect
  1443. } else {
  1444. controller.selectionRect = page?.bounds(for: .cropBox) ?? .zero
  1445. }
  1446. }
  1447. if let cropVC = rightSideController?.edit_cropController {
  1448. cropVC.pageCropBounds = page?.bounds(for: .cropBox) ?? .zero
  1449. cropVC.reloadData()
  1450. }
  1451. }
  1452. controller.pdfDocument = editDocument
  1453. controller.reloadData()
  1454. }
  1455. func removeCropController() {
  1456. if cropController != nil {
  1457. cropController?.view.removeFromSuperview()
  1458. cropController = nil
  1459. KMCropManager.defaultManager.clear()
  1460. toolbarManager.edit_crop_Property.state = .normal
  1461. alertTipViewController.showInView(listView: listView, subView: infoSplitCenterView)
  1462. alertTipViewController.reloadAlertUIFrame()
  1463. }
  1464. }
  1465. // MARK: - Secure 【安全】
  1466. public func hiddenSecureLimitTip() {
  1467. }
  1468. func savePageNumberIfNeed() {
  1469. let scaleFactor = self.listView.scaleFactor
  1470. if scaleFactor <= 0 {
  1471. return
  1472. }
  1473. if self.listView.document != nil {
  1474. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1475. KMPreferenceManager.shared.setPageScale(Float(scaleFactor), forKey: self.listView.document.documentURL.path)
  1476. }
  1477. }
  1478. // MARK: - 显示加密弹窗
  1479. public func showSecureWindow() {
  1480. guard let url = self.listView.document?.documentURL else {
  1481. return
  1482. }
  1483. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1484. guard let securityWindowController = securityWindowController else { return }
  1485. securityWindowController.documentURL = self.listView.document?.documentURL
  1486. securityWindowController.batchAction = { [unowned self] controller, files in
  1487. self.view.window?.endSheet((securityWindowController.window)!)
  1488. self.showBatchWindow(type: .security, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  1489. }
  1490. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1491. let openPanel = NSOpenPanel()
  1492. openPanel.canChooseFiles = false
  1493. openPanel.canChooseDirectories = true
  1494. openPanel.canCreateDirectories = true
  1495. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1496. if result == NSApplication.ModalResponse.OK {
  1497. for fileURL in openPanel.urls {
  1498. let document = CPDFDocument(url: self.document?.documentURL)
  1499. if document != nil {
  1500. document!.setDocumentAttributes(attribute)
  1501. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1502. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1503. if success {
  1504. self.view.window?.endSheet((securityWindowController.window)!)
  1505. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1506. }
  1507. }
  1508. }
  1509. }
  1510. }
  1511. }
  1512. securityWindowController.cancelAction = { [unowned self] controller in
  1513. self.view.window?.endSheet((securityWindowController.window)!)
  1514. }
  1515. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1516. }
  1517. // MARK: - 移除文档密码
  1518. public func showRemoveSecureWindow() {
  1519. var isDocumentLocked: Bool = false
  1520. if self.document?.allowsCopying == false || self.document?.allowsPrinting == false {
  1521. isDocumentLocked = true
  1522. } else if (self.document?.password ?? "").count > 0 {
  1523. isDocumentLocked = true
  1524. }
  1525. if isDocumentLocked == false {
  1526. let alert = NSAlert()
  1527. alert.alertStyle = .warning
  1528. alert.messageText = KMLocalizedString("This document doesn’t contain any security settings and doesn‘t need to be removed.")
  1529. alert.addButton(withTitle: KMLocalizedString("OK"))
  1530. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  1531. }
  1532. } else {
  1533. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  1534. controller.pdfDocument = self.document
  1535. self.currentWindowController = controller
  1536. controller.batchAction = { [unowned self] controller, files in
  1537. self.view.window?.endSheet((self.currentWindowController.window)!)
  1538. self.currentWindowController = nil
  1539. var array: [URL] = []
  1540. for item in files {
  1541. array.append(NSURL(fileURLWithPath: item.filePath) as URL)
  1542. }
  1543. self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.security.rawValue, files: array)
  1544. }
  1545. controller.cancelAction = { [unowned self] controller in
  1546. self.view.window?.endSheet((self.currentWindowController.window)!)
  1547. self.currentWindowController = nil
  1548. }
  1549. controller.doneAction = { [unowned self] controller in
  1550. self.view.window?.endSheet((self.currentWindowController.window)!)
  1551. self.currentWindowController = nil
  1552. NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1553. if success {
  1554. let savePanel = NSSavePanel()
  1555. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  1556. savePanel.allowedFileTypes = ["pdf"]
  1557. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  1558. guard result == .OK else { return }
  1559. /// 删除安全性设置
  1560. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1561. self.model.isSaveKeyChain = false
  1562. self.listView.document.unlock(withPassword: resultPassword)
  1563. }
  1564. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  1565. guard let document = document else { return }
  1566. document.unlock(withPassword: resultPassword)
  1567. let success = document.writeDecrypt(to: savePanel.url)
  1568. if success {
  1569. self.hiddenSecureLimitTip()
  1570. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1571. } else {
  1572. self.hiddenSecureLimitTip()
  1573. }
  1574. }
  1575. }
  1576. }
  1577. }
  1578. NSWindow.currentWindow().beginSheet(controller.window!)
  1579. }
  1580. }
  1581. //MARK: - Unlock Document
  1582. func unlockPDFDocument() {
  1583. NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1584. self.listView.document.unlock(withPassword: resultPassword)
  1585. }
  1586. }
  1587. //MARK: - PopUI
  1588. func reloadPopUIWindow() {
  1589. if listView.toolMode == .CSelectToolMode {
  1590. let pageRect = listView.currentSelectionRect()
  1591. let page:CPDFPage? = listView.currentSelectionPage()
  1592. if listView.selectionRect != CGRectZero && page != nil {
  1593. let positioningRect = listView.convert(pageRect, from: page)
  1594. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1595. reloadPopUIOperation()
  1596. return
  1597. }
  1598. }
  1599. toggleClosePopUIWindow()
  1600. } else if listView.toolMode == .COCRToolMode {
  1601. let pageRect = listView.currentSelectionRect()
  1602. let page:CPDFPage? = listView.currentSelectionPage()
  1603. if listView.selectionRect != CGRectZero && page != nil {
  1604. let positioningRect = listView.convert(pageRect, from: page)
  1605. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1606. reloadPopUIOperation()
  1607. return
  1608. }
  1609. }
  1610. toggleClosePopUIWindow()
  1611. } else if(listView.isEditing() == false) {
  1612. let activeAnnotations:[CPDFAnnotation] = listView.activeAnnotations as! [CPDFAnnotation]
  1613. if(activeAnnotations.count > 0) {
  1614. if let page = activeAnnotations.first?.page {
  1615. let pageRect = listView.selectionMultipleBounds(with: activeAnnotations)
  1616. let positioningRect = listView.convert(pageRect, from: page)
  1617. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1618. reloadPopUIActiveAnnotations(activeAnnotations: activeAnnotations)
  1619. } else {
  1620. toggleClosePopUIWindow()
  1621. }
  1622. } else {
  1623. toggleClosePopUIWindow()
  1624. }
  1625. } else {
  1626. toggleClosePopUIWindow()
  1627. }
  1628. if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) { //右键菜单弹出时,或者Pop编辑框弹出时不显示Pop
  1629. toggleClosePopUIWindow()
  1630. }
  1631. } else {
  1632. let editAreas:[CPDFEditArea] = listView.km_EditingAreas()
  1633. if(editAreas.count > 0) {
  1634. if let page = editAreas.first?.page {
  1635. let pageRect = listView.selectionMultipleBounds(withEditArea: editAreas)
  1636. let positioningRect = listView.convert(pageRect, from: page)
  1637. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1638. reloadPopUIContentEdits(editAreas: editAreas)
  1639. } else {
  1640. toggleClosePopUIWindow()
  1641. }
  1642. } else {
  1643. toggleClosePopUIWindow()
  1644. }
  1645. } else {
  1646. toggleClosePopUIWindow()
  1647. }
  1648. if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) { //右键菜单弹出时,或者Pop编辑框弹出时不显示Pop
  1649. toggleClosePopUIWindow()
  1650. }
  1651. }
  1652. }
  1653. func toggleClosePopUIWindow() {
  1654. let popWindow = KMNAnnotationPopToolbarWindow.shared
  1655. if popWindow.isVisible == true {
  1656. closeAnnotationPopWindow()
  1657. }
  1658. let editPopWindow = KMNContentEditPopToolbarWindow.shared
  1659. if editPopWindow.isVisible == true {
  1660. closePopContentEditWindow()
  1661. }
  1662. let operationWindow = KMNOperationPopToolbarWindow.shared
  1663. if operationWindow.isVisible == true {
  1664. closePopOperationWindow()
  1665. }
  1666. }
  1667. func closeAnnotationPopWindow() {
  1668. KMNAnnotationPopToolbarWindow.shared.closeWindow(listView: listView)
  1669. }
  1670. func closePopContentEditWindow() {
  1671. KMNContentEditPopToolbarWindow.shared.closeWindow(listView: listView)
  1672. }
  1673. func closePopOperationWindow() {
  1674. KMNOperationPopToolbarWindow.shared.closeWindow(listView: listView)
  1675. }
  1676. func reloadPopUIOperation() {
  1677. if listView.selectionRect != CGRectZero {
  1678. let popWindow = KMNOperationPopToolbarWindow.shared
  1679. popWindow.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
  1680. self.listView.window?.addChildWindow(popWindow, ordered: .above)
  1681. let operationViewController = KMNPopOperationViewController.shared
  1682. operationViewController.listView = listView
  1683. if listView.toolMode == .CSelectToolMode {
  1684. operationViewController.popType = .crop
  1685. operationViewController.cropCurrentCallback = {[weak self] in
  1686. let rect = self?.listView.currentSelectionRect() ?? CGRect.zero
  1687. let orgPage : CPDFPage = self?.listView.currentSelectionPage() ?? CPDFPage()
  1688. self?.cropPages(atIndexs: [orgPage.pageIndex()], to: [rect])
  1689. self?.closePopOperationWindow()
  1690. }
  1691. } else if listView.toolMode == .COCRToolMode {
  1692. operationViewController.popType = .ocr
  1693. operationViewController.OCRAction = { [weak self] in
  1694. self?.convertSelectionRectOCR(rect: self?.listView.currentSelectionRect() ?? CGRectZero)
  1695. }
  1696. }
  1697. operationViewController.updatePDFViewCallback = {[weak self] in
  1698. self?.closePopOperationWindow()
  1699. self?.listView.setNeedsDisplayForVisiblePages()
  1700. }
  1701. updatePopOperationPopWinodwFrame()
  1702. } else {
  1703. closePopOperationWindow()
  1704. }
  1705. }
  1706. func reloadPopUIActiveAnnotations(activeAnnotations:[CPDFAnnotation]) {
  1707. let annotationMode = KMNAnnotationPopMode(pdfAnnotations: activeAnnotations )
  1708. let popVC = KMNPopAnnotationViewController.shared
  1709. var isCrearLineOrMeasure = false
  1710. if(listView.isClickDoubleCreatLine || listView.clickPolylineAnnotation != nil || listView.clickPolygonAnnotation != nil) {
  1711. isCrearLineOrMeasure = true
  1712. }
  1713. if annotationMode.popType == .popTypeNone || (!SettingsManager.sharedInstance.showQuickActionBar && isShowQuickBar == false) || isCrearLineOrMeasure {
  1714. closeAnnotationPopWindow()
  1715. } else {
  1716. let win = KMNAnnotationPopToolbarWindow.shared
  1717. win.annotationPopMode = annotationMode
  1718. win.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
  1719. isShowQuickBar = false
  1720. self.listView.window?.addChildWindow(win, ordered: .above)
  1721. popVC.listView = listView
  1722. popVC.annotationPopMode = annotationMode
  1723. popVC.isOpenPane = viewManager.showRightSide
  1724. updateAnnotationsPopWinodwFrame()
  1725. popVC.updatePDFViewCallback = {[weak self] in
  1726. self?.rightSideController?.reloadDataWithPDFView(pdfView: self?.listView ?? CPDFListView())
  1727. self?.listView.setNeedsDisplayMultiAnnotations(annotationMode.annotations)
  1728. NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
  1729. }
  1730. popVC.paneCallback = {[weak self] isOpen in
  1731. if isOpen == true {
  1732. self?.viewManager.showRightSide = true
  1733. } else {
  1734. self?.viewManager.showRightSide = false
  1735. }
  1736. self?.refreshToolbarRightViewInfo()
  1737. }
  1738. }
  1739. }
  1740. func reloadPopUIContentEdits(editAreas:[CPDFEditArea]) {
  1741. let editingAreas = listView.km_EditingAreas()
  1742. let editMode = KMNEditContentPopMode(currentEditAreas: editingAreas)
  1743. let popVC = KMNPopContentEditViewController.shared
  1744. if editMode.popType == .editNone || (!SettingsManager.sharedInstance.showQuickActionBar && isShowQuickBar == false) {
  1745. closePopContentEditWindow()
  1746. } else {
  1747. let win = KMNContentEditPopToolbarWindow.shared
  1748. win.editContentPopMode = editMode
  1749. win.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
  1750. self.listView.window?.addChildWindow(win, ordered: .above)
  1751. isShowQuickBar = false
  1752. popVC.listView = listView
  1753. popVC.editContentPopMode = editMode
  1754. popVC.isOpenPane = viewManager.showRightSide
  1755. popVC.editContentPopMode = editMode
  1756. updateContentEditPopWinodwFrame()
  1757. popVC.paneCallback = {[weak self] isOpen in
  1758. if isOpen == true {
  1759. self?.viewManager.showRightSide = true
  1760. } else {
  1761. self?.viewManager.showRightSide = false
  1762. }
  1763. self?.refreshToolbarRightViewInfo()
  1764. }
  1765. popVC.updatePDFViewCallback = { [weak self] in
  1766. self?.rightSideController?.reloadEditingAreas()
  1767. }
  1768. }
  1769. }
  1770. func updateAnnotationsPopWinodwFrame() {
  1771. let popWindow = KMNAnnotationPopToolbarWindow.shared
  1772. popWindow.updateFrame(listView: listView)
  1773. }
  1774. func updateContentEditPopWinodwFrame() {
  1775. let popWindow = KMNContentEditPopToolbarWindow.shared
  1776. popWindow.updateFrame(listView: listView)
  1777. }
  1778. func updatePopOperationPopWinodwFrame() {
  1779. let popWindow = KMNOperationPopToolbarWindow.shared
  1780. popWindow.updateFrame(listView: listView,page: listView.currentSelectionPage())
  1781. }
  1782. //MARK: - 安全
  1783. func removeOwnerPassword() {
  1784. guard let doc = listView.document else {
  1785. NSSound.beep()
  1786. return
  1787. }
  1788. if doc.permissionsStatus != .user {
  1789. NSSound.beep()
  1790. return
  1791. }
  1792. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1793. if result == .cancel { /// 关闭
  1794. return
  1795. }
  1796. self?.listView.document?.unlock(withPassword: password)
  1797. if doc.permissionsStatus == .owner {
  1798. self?.alertTipViewController.reloadSecureAlertUI()
  1799. self?.alertTipViewController.reloadAlertUIFrame()
  1800. }
  1801. }
  1802. }
  1803. //MARK: - Watermark水印
  1804. func showWatermarkController() {
  1805. viewManager.editType = .watermark
  1806. UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsEditFromDisplay)
  1807. if viewManager.showDisplayView == true {
  1808. viewManager.showDisplayView = false
  1809. updatePDFDisplaySettingView()
  1810. UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsEditFromDisplay)
  1811. }
  1812. showEditToolbarView()
  1813. editToolbarView?.editType = .watermark
  1814. if KMWatermarkManager.defaultManager.watermarks.count == 0 {
  1815. editToolbarView?.editSubType = .add
  1816. } else {
  1817. editToolbarView?.editSubType = .template
  1818. }
  1819. editToolbarView?.reloadData()
  1820. if watermarkViewController == nil {
  1821. watermarkViewController = KMWatermarkController.init()
  1822. }
  1823. watermarkViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1824. watermarkViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1825. watermarkViewController?.delegate = self
  1826. bottomContendBox.contentView?.addSubview(watermarkViewController!.view)
  1827. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1828. watermarkViewController?.reloadData()
  1829. updateWatermarkDocument()
  1830. watermarkViewController?.loadData()
  1831. }
  1832. func updateWatermarkDocument() {
  1833. guard let controller = watermarkViewController else { return }
  1834. if let toolbarView = self.editToolbarView {
  1835. self.kmEditToolbarViewDidPageRangeUpdate(toolbarView)
  1836. }
  1837. var editDocument = CPDFDocument.init()
  1838. if let vcDoc = controller.pdfDocument {
  1839. editDocument = vcDoc
  1840. }
  1841. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1842. editDocument?.insertPageObject(page, at: 0)
  1843. if editDocument?.pageCount == 2 {
  1844. let theIndex = IndexSet(integer: 1)
  1845. editDocument?.removePage(at: theIndex)
  1846. }
  1847. if watermarkViewController?.pdfDocument == nil {
  1848. watermarkViewController?.pdfDocument = editDocument
  1849. }
  1850. watermarkViewController?.pdfViewCurrentIndex = listView.currentPageIndex
  1851. watermarkViewController?.resetUI()
  1852. watermarkViewController?.reloadData()
  1853. watermarkViewController?.loadData()
  1854. }
  1855. //移除文档水印
  1856. func removePDFWatermark() {
  1857. if KMMemberInfo.shared.isLogin == false {
  1858. KMLoginWindowsController.shared.showWindow(nil)
  1859. return
  1860. }
  1861. let watermarks = self.listView.document.watermarks()
  1862. if (watermarks == nil || watermarks!.count <= 0) {
  1863. let alert = NSAlert()
  1864. alert.alertStyle = .warning
  1865. alert.messageText = KMLocalizedString("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: "")
  1866. alert.addButton(withTitle: KMLocalizedString("Confirm", comment: ""))
  1867. alert.runModal()
  1868. return
  1869. }
  1870. let alert = NSAlert()
  1871. alert.alertStyle = .warning
  1872. alert.messageText = KMLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  1873. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  1874. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  1875. let result = alert.runModal()
  1876. if (result == .alertFirstButtonReturn) {
  1877. for watermark in watermarks! {
  1878. listView.document.removeWatermark(watermark)
  1879. }
  1880. listView.layoutDocumentView()
  1881. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Watermark removed"),
  1882. type: .success,
  1883. fromView: bottomContendBox,
  1884. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1885. }
  1886. }
  1887. func batchAddWatermark() {
  1888. self.showBatchWindow(type: .watermark, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  1889. }
  1890. func batchRemoveWatermark() {
  1891. self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.watermark.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  1892. }
  1893. //MARK: - Background背景
  1894. func showBackgroundController() {
  1895. viewManager.editType = .background
  1896. UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsEditFromDisplay)
  1897. if viewManager.showDisplayView == true {
  1898. viewManager.showDisplayView = false
  1899. updatePDFDisplaySettingView()
  1900. UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsEditFromDisplay)
  1901. }
  1902. showEditToolbarView()
  1903. editToolbarView?.editType = .background
  1904. if KMBackgroundManager.defaultManager.datas.count == 0 {
  1905. editToolbarView?.editSubType = .add
  1906. } else {
  1907. editToolbarView?.editSubType = .template
  1908. }
  1909. editToolbarView?.reloadData()
  1910. if backgroundViewController == nil {
  1911. backgroundViewController = KMBackgroundController.init()
  1912. }
  1913. backgroundViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1914. backgroundViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1915. backgroundViewController?.delegate = self
  1916. bottomContendBox.contentView?.addSubview(backgroundViewController!.view)
  1917. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1918. backgroundViewController?.resetUI()
  1919. updateBackgroundDocument()
  1920. }
  1921. func updateBackgroundDocument() {
  1922. guard let controller = backgroundViewController else { return }
  1923. if let toolbarView = self.editToolbarView {
  1924. self.kmEditToolbarViewDidPageRangeUpdate(toolbarView)
  1925. }
  1926. controller.pdfDocument = nil
  1927. let editDocument = CPDFDocument.init()
  1928. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1929. editDocument?.insertPageObject(page, at: 0)
  1930. backgroundViewController?.pdfViewCurrentIndex = listView.currentPageIndex
  1931. backgroundViewController?.pdfDocument = editDocument
  1932. backgroundViewController?.reloadData()
  1933. }
  1934. func removePDFBackground() {
  1935. if KMMemberInfo.shared.isLogin == false {
  1936. KMLoginWindowsController.shared.showWindow(nil)
  1937. return
  1938. }
  1939. let alert = NSAlert()
  1940. alert.alertStyle = .warning
  1941. alert.messageText = KMLocalizedString("Do you want to remove the background you have added to the document?", comment: "")
  1942. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  1943. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  1944. let result = alert.runModal()
  1945. if (result == .alertFirstButtonReturn) {
  1946. let background = listView.document.background()
  1947. background?.clear()
  1948. listView.document?.refreshPageData()
  1949. listView.layoutDocumentView()
  1950. self.recordIsPDFDocumentEdited()
  1951. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Background removed"),
  1952. type: .success,
  1953. fromView: bottomContendBox,
  1954. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1955. }
  1956. }
  1957. func batchAddBackground() {
  1958. self.showBatchWindow(type: .background, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  1959. }
  1960. func batchRemoveBackground() {
  1961. self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.background.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  1962. }
  1963. //MARK: - header&footer
  1964. func showHeaderFooterController() {
  1965. viewManager.editType = .header_Footer
  1966. UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsEditFromDisplay)
  1967. if viewManager.showDisplayView == true {
  1968. viewManager.showDisplayView = false
  1969. updatePDFDisplaySettingView()
  1970. UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsEditFromDisplay)
  1971. }
  1972. showEditToolbarView()
  1973. editToolbarView?.editType = .header_Footer
  1974. if KMHeaderFooterManager.defaultManager.headFooterObjects.count == 0 {
  1975. editToolbarView?.editSubType = .add
  1976. } else {
  1977. editToolbarView?.editSubType = .template
  1978. }
  1979. editToolbarView?.reloadData()
  1980. if headerFooterViewController == nil {
  1981. headerFooterViewController = KMHeaderFooterController.init()
  1982. }
  1983. headerFooterViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1984. headerFooterViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1985. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1986. headerFooterViewController?.delegate = self
  1987. bottomContendBox.contentView?.addSubview(headerFooterViewController!.view)
  1988. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1989. updateHeaderFooterDocument()
  1990. }
  1991. func updateHeaderFooterDocument() {
  1992. guard let controller = headerFooterViewController else { return }
  1993. if let toolbarView = self.editToolbarView {
  1994. self.kmEditToolbarViewDidPageRangeUpdate(toolbarView)
  1995. }
  1996. controller.pdfDocument = nil
  1997. let editDocument = CPDFDocument.init()
  1998. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1999. editDocument?.insertPageObject(page, at: 0)
  2000. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  2001. headerFooterViewController?.pdfViewCurrentIndex = listView.currentPageIndex
  2002. headerFooterViewController?.pdfDocument = editDocument
  2003. headerFooterViewController?.resetUI()
  2004. headerFooterViewController?.reloadData()
  2005. }
  2006. func removeHeaderFooter() {
  2007. if KMMemberInfo.shared.isLogin == false {
  2008. KMLoginWindowsController.shared.showWindow(nil)
  2009. return
  2010. }
  2011. let alert = NSAlert()
  2012. alert.alertStyle = .warning
  2013. alert.messageText = KMLocalizedString("Do you want to remove the header&footer you have added to the document?", comment: "")
  2014. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  2015. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  2016. let result = alert.runModal()
  2017. if (result == .alertFirstButtonReturn) {
  2018. let headerFooter = listView.document.headerFooter()
  2019. headerFooter?.clear()
  2020. listView.document?.refreshPageData()
  2021. listView.layoutDocumentView()
  2022. self.recordIsPDFDocumentEdited()
  2023. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Header & Footer removed"),
  2024. type: .success,
  2025. fromView: bottomContendBox,
  2026. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  2027. }
  2028. }
  2029. func batchAddHeaderFooter() {
  2030. self.showBatchWindow(type: .headerAndFooter, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  2031. }
  2032. func batchRemoveHeaderFooter() {
  2033. self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.headerAndFooter.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  2034. }
  2035. //MARK: - Bates
  2036. func showBatesController() {
  2037. viewManager.editType = .bates
  2038. UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsEditFromDisplay)
  2039. if viewManager.showDisplayView == true {
  2040. viewManager.showDisplayView = false
  2041. updatePDFDisplaySettingView()
  2042. UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsEditFromDisplay)
  2043. }
  2044. showEditToolbarView()
  2045. editToolbarView?.editType = viewManager.editType
  2046. if KMBatesManager.defaultManager.datas.count == 0 {
  2047. editToolbarView?.editSubType = .add
  2048. } else {
  2049. editToolbarView?.editSubType = .template
  2050. }
  2051. editToolbarView?.reloadData()
  2052. if batesViewController == nil {
  2053. batesViewController = KMBatesController.init()
  2054. }
  2055. batesViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  2056. batesViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  2057. batesViewController?.delegate = self
  2058. batesViewController?.totalPDFCount = Int(listView.document.pageCount)
  2059. bottomContendBox.contentView?.addSubview(batesViewController!.view)
  2060. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  2061. updateBatesDocument()
  2062. batesViewController?.resetUI()
  2063. }
  2064. func updateBatesDocument() {
  2065. guard let controller = batesViewController else { return }
  2066. if let toolbarView = self.editToolbarView {
  2067. self.kmEditToolbarViewDidPageRangeUpdate(toolbarView)
  2068. }
  2069. controller.pdfDocument = nil
  2070. let editDocument = CPDFDocument.init()
  2071. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  2072. editDocument?.insertPageObject(page, at: 0)
  2073. batesViewController?.pdfDocument = editDocument
  2074. headerFooterViewController?.pdfViewCurrentIndex = listView.currentPageIndex
  2075. batesViewController?.reloadData()
  2076. }
  2077. func removePDFBates() {
  2078. if KMMemberInfo.shared.isLogin == false {
  2079. KMLoginWindowsController.shared.showWindow(nil)
  2080. return
  2081. }
  2082. let alert = NSAlert()
  2083. alert.alertStyle = .warning
  2084. alert.messageText = KMLocalizedString("Do you want to remove the Bates you have added to the document?", comment: "")
  2085. alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
  2086. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  2087. let result = alert.runModal()
  2088. if (result == .alertFirstButtonReturn) {
  2089. let bates = listView.document.bates()
  2090. bates?.clear()
  2091. listView.document?.refreshPageData()
  2092. listView.layoutDocumentView()
  2093. self.recordIsPDFDocumentEdited()
  2094. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Bates removed"),
  2095. type: .success,
  2096. fromView: bottomContendBox,
  2097. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  2098. }
  2099. }
  2100. func batchAddBates() {
  2101. self.showBatchWindow(type: .batesNumber, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  2102. }
  2103. func batchRemoveBates() {
  2104. self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.batesNumber.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  2105. }
  2106. //MARK: - Crop Action
  2107. // 白边距,统一大小
  2108. @objc func auto_cropPagesWhiteMargin(_ pageIndexs: [UInt]) {
  2109. var size = NSZeroSize
  2110. for i in pageIndexs {
  2111. let page = self.listView.document.page(at: i)
  2112. let rect = KMCropTools.getPageForegroundBox(page!)
  2113. size.width = fmax(size.width, NSWidth(rect))
  2114. size.height = fmax(size.height, NSHeight(rect))
  2115. }
  2116. var rectArray: Array<NSRect> = []
  2117. for i in pageIndexs {
  2118. progressC?.increment(by: Double(i))
  2119. progressC?.doubleValue = Double(i)
  2120. let page = self.listView.document.page(at: i)
  2121. var rect = KMCropTools.getPageForegroundBox(page!)
  2122. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  2123. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  2124. rect.origin.x = rect.maxX-size.width
  2125. }
  2126. rect.origin.y = rect.maxY-size.height
  2127. rect.size = size
  2128. if (NSWidth(rect) > NSWidth(bounds)) {
  2129. rect.size.width = NSWidth(bounds)
  2130. }
  2131. if (NSHeight(rect) > NSHeight(bounds)) {
  2132. rect.size.height = NSHeight(bounds)
  2133. }
  2134. if (NSMinX(rect) < NSMinX(bounds)) {
  2135. rect.origin.x = NSMinX(bounds)
  2136. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  2137. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  2138. }
  2139. if (NSMinY(rect) < NSMinY(bounds)) {
  2140. rect.origin.y = NSMinY(bounds)
  2141. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  2142. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  2143. }
  2144. rectArray.append(rect)
  2145. }
  2146. self.cropPages(atIndexs: pageIndexs, to: rectArray)
  2147. }
  2148. func cropPages(atIndexs pageIndexs: [UInt], to rects: Array<NSRect>) {
  2149. let currentPage = self.listView.currentPage()
  2150. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  2151. var oldRectArray: Array<NSRect> = []
  2152. let rectCount = rects.count
  2153. for i in pageIndexs {
  2154. if let page = self.listView.document.page(at: i) {
  2155. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page.bounds(for: .mediaBox)))
  2156. let oldRect = page.bounds(for: .cropBox)
  2157. oldRectArray.append(oldRect)
  2158. page.setBounds(rect, for: .cropBox)
  2159. }
  2160. let thumbnail = KMNThumbnail.init(document: document!, currentPageIndex: Int(i))
  2161. thumbnail.removeCacheImage()
  2162. }
  2163. let undoManager = self.listView.undoManager
  2164. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(atIndexs: pageIndexs, to: oldRectArray)
  2165. /// 刷新预览视图
  2166. self.listView.layoutDocumentView()
  2167. self.listView.displayBox = .cropBox
  2168. self.listView.go(to: currentPage)
  2169. self.listView.go(to: visibleRect, on: currentPage)
  2170. }
  2171. //MARK: - 文件对比
  2172. func beginCompareAction(_ index: Int) {
  2173. guard let filePath = self.document?.documentURL.path else { return }
  2174. if !FileManager.default.fileExists(atPath: filePath) {
  2175. let alert = NSAlert.init()
  2176. alert.alertStyle = .critical
  2177. alert.messageText = "\(filePath.lastPathComponent) \(KMLocalizedString("File Not Exist", comment: ""))"
  2178. alert.runModal()
  2179. return
  2180. }
  2181. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2182. self.currentWindowController = controller
  2183. controller.password = self.document?.password ?? ""
  2184. controller.filePath = (self.document?.documentURL.path)!
  2185. controller.cancelAction = { [unowned self] controller in
  2186. self.view.window?.endSheet((self.currentWindowController.window)!)
  2187. self.currentWindowController = nil
  2188. }
  2189. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  2190. self.view.window?.endSheet((self.currentWindowController.window)!)
  2191. self.currentWindowController = nil
  2192. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  2193. }
  2194. controller.coveringComplete = { [unowned self] controller, document in
  2195. self.view.window?.endSheet((self.currentWindowController.window)!)
  2196. self.currentWindowController = nil
  2197. self.openCoveringCompareVC(with: document)
  2198. }
  2199. if index == 1 {
  2200. controller.fileType = .content
  2201. } else {
  2202. controller.fileType = .coverting
  2203. }
  2204. NSWindow.currentWindow().beginSheet(controller.window!)
  2205. }
  2206. //文件对比
  2207. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  2208. self.isCompareModel = true
  2209. let compareContentView = KMCompareContentView()
  2210. compareContentView.oldDocument = oldDocument
  2211. compareContentView.document = document
  2212. compareContentView.compareResults = results
  2213. compareContentView.saveHandle = { [unowned self] view in
  2214. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2215. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  2216. self.currentWindowController = saveController
  2217. saveController.cancelHandle = { [unowned self] controller in
  2218. self.view.window!.endSheet(controller.window!)
  2219. self.currentWindowController = nil
  2220. }
  2221. saveController.saveHandle = { [unowned self] controller, saveType in
  2222. let folderPath = controller.fileSaveFolderPath
  2223. if folderPath != nil {
  2224. if !FileManager.default.fileExists(atPath: folderPath) {
  2225. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  2226. }
  2227. #if VERSION_DMG
  2228. #else
  2229. let url = URL(fileURLWithPath: folderPath)
  2230. let fileAccess = AppSandboxFileAccess()
  2231. fileAccess?.persistPermissionURL(url)
  2232. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  2233. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  2234. let urlString = url.path
  2235. let _url = URL(fileURLWithPath: urlString)
  2236. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  2237. }
  2238. #endif
  2239. var savePath: String
  2240. switch saveType {
  2241. case 0:
  2242. let filePath = oldDocument.documentURL.path
  2243. let fileName = filePath.deletingPathExtension.lastPathComponent
  2244. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2245. savePath = self.getValidFilePath(savePath)
  2246. oldDocument.write(to: URL(fileURLWithPath: savePath))
  2247. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2248. case 1:
  2249. let filePath = document.documentURL.path
  2250. let fileName = filePath.deletingPathExtension.lastPathComponent
  2251. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  2252. savePath = self.getValidFilePath(savePath)
  2253. document.write(to: URL(fileURLWithPath: savePath))
  2254. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2255. case 2:
  2256. let filePath = oldDocument.documentURL.path
  2257. let fileName = filePath.deletingPathExtension.lastPathComponent
  2258. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  2259. savePath = self.getValidFilePath(savePath)
  2260. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  2261. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  2262. default:
  2263. break
  2264. }
  2265. }
  2266. self.view.window!.endSheet(controller.window!)
  2267. self.currentWindowController = nil
  2268. }
  2269. NSWindow.currentWindow().beginSheet(saveController.window!)
  2270. }
  2271. }
  2272. compareContentView.closeHandle = { [unowned self] view in
  2273. self.isCompareModel = false
  2274. view.removeFromSuperview()
  2275. }
  2276. contendBox.addSubview(compareContentView)
  2277. compareContentView.frame = contendBox.bounds
  2278. compareContentView.autoresizingMask = [.width,.height]
  2279. }
  2280. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  2281. self.isCompareModel = true
  2282. let coveringView = KMCompareCoveringView()
  2283. coveringView.pdfDocument = pdfDocument
  2284. coveringView.closeHandle = { [unowned self] view in
  2285. self.isCompareModel = false
  2286. view.removeFromSuperview()
  2287. }
  2288. coveringView.saveHandle = { [unowned self] view in
  2289. let savePanel = NSSavePanel()
  2290. savePanel.nameFieldStringValue = "untitled"
  2291. savePanel.allowedFileTypes = ["pdf"]
  2292. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  2293. if result == .OK {
  2294. pdfDocument.write(to: savePanel.url!)
  2295. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2296. }
  2297. }
  2298. }
  2299. contendBox.addSubview(coveringView)
  2300. coveringView.frame = contendBox.bounds
  2301. coveringView.autoresizingMask = [.width,.height]
  2302. }
  2303. func getValidFilePath(_ oldPath: String) -> String {
  2304. let fileManager = FileManager.default
  2305. do {
  2306. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  2307. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  2308. return oldPath
  2309. }
  2310. var i = 1
  2311. var newPath = oldPath
  2312. while fileManager.fileExists(atPath: newPath) {
  2313. if fileType == FileAttributeType.typeDirectory.rawValue {
  2314. newPath = oldPath + "(\(i))"
  2315. } else {
  2316. let fileExtension = (oldPath as NSString).pathExtension
  2317. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  2318. }
  2319. i += 1
  2320. }
  2321. return newPath
  2322. } catch {
  2323. print("Error getting file attributes: \(error)")
  2324. return oldPath
  2325. }
  2326. }
  2327. //MARK: - TTS
  2328. @IBAction func startSpeaking(_ sender: Any?) {
  2329. self.showTTSWindow()
  2330. let ttsView = KMTTSWindowController.share
  2331. // ttsView.buttonItemClick_Play(ttsView.playButton)
  2332. }
  2333. @IBAction func stopSpeaking(_ sender: Any) {
  2334. let ttsWindowC = KMTTSWindowController.share
  2335. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  2336. if let data = ttsWindowC.window?.isVisible, data {
  2337. ttsWindowC.stopSpeaking()
  2338. ttsWindowC.close()
  2339. }
  2340. }
  2341. }
  2342. func showTTSWindow() {
  2343. var lastPDFView: CPDFView?
  2344. let ttsView = KMTTSWindowController.share
  2345. if (ttsView.window?.isVisible ?? false) {
  2346. lastPDFView = ttsView.pdfView
  2347. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  2348. lastPDFView = nil
  2349. ttsView.window?.orderOut(nil)
  2350. } else {
  2351. ttsView.pdfView = self.listView
  2352. ttsView.showWindow(nil)
  2353. }
  2354. } else {
  2355. ttsView.pdfView = self.listView
  2356. ttsView.showWindow(nil)
  2357. }
  2358. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  2359. if isCloseWindow {
  2360. }
  2361. }
  2362. if let currentSelection = self.listView.currentSelection {
  2363. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  2364. ttsView.startSpeakingPDFSelection(currentSelection)
  2365. }
  2366. }
  2367. if let lastPDFView = lastPDFView {
  2368. lastPDFView.setHighlightedSelections([])
  2369. ttsView.stopSpeaking()
  2370. }
  2371. }
  2372. //MARK: 导出图片
  2373. func extractImageAction(num: Int) {
  2374. guard let filePath = self.document?.documentURL.path else { return }
  2375. if !FileManager.default.fileExists(atPath: filePath) {
  2376. let alert = NSAlert.init()
  2377. alert.alertStyle = .critical
  2378. alert.messageText = "\(filePath.lastPathComponent) \(KMLocalizedString("File Not Exist", comment: ""))"
  2379. alert.runModal()
  2380. return
  2381. }
  2382. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2383. let alert = NSAlert()
  2384. alert.alertStyle = .critical
  2385. alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2386. alert.runModal()
  2387. return
  2388. }
  2389. let document = self.listView.document
  2390. var fileURL = document?.documentURL
  2391. if num == 1 {
  2392. let pageCount = document?.pageCount ?? 0
  2393. let indeSet = NSMutableIndexSet()
  2394. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2395. if indeSet.count == 0 {
  2396. return
  2397. }
  2398. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2399. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2400. let outputSavePanel = NSSavePanel()
  2401. outputSavePanel.title = KMLocalizedString("Save as PDF", comment: "")
  2402. outputSavePanel.allowsOtherFileTypes = true
  2403. outputSavePanel.isExtensionHidden = true
  2404. outputSavePanel.canCreateDirectories = true
  2405. outputSavePanel.nameFieldStringValue = tFileName
  2406. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2407. if result == NSApplication.ModalResponse.OK {
  2408. DispatchQueue.main.async {
  2409. self.beginProgressSheet(withMessage: KMLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2410. let tDestFile = outputSavePanel.url!.path
  2411. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2412. let pdfconverter = PDFConvertObject()
  2413. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2414. self.dismissProgressSheet()
  2415. let fileManager = FileManager.default
  2416. if fileManager.fileExists(atPath: tDestFile) {
  2417. let workspace = NSWorkspace.shared
  2418. let url = URL(fileURLWithPath: tDestFile)
  2419. workspace.activateFileViewerSelecting([url])
  2420. }
  2421. }
  2422. }
  2423. })
  2424. return
  2425. }
  2426. if fileURL != nil {
  2427. self.myDocument?.save(nil)
  2428. } else {
  2429. let myDocument = self.myDocument
  2430. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2431. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath.stringByAppendingPathComponent(str))))
  2432. if writeSuccess {
  2433. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath.stringByAppendingPathComponent(str))))
  2434. fileURL = document?.documentURL
  2435. } else {
  2436. NSSound.beep()
  2437. return
  2438. }
  2439. }
  2440. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2441. extract?.docPath = fileURL?.path ?? ""
  2442. extract?.password = document?.password ?? ""
  2443. extract?.currentPage = self.listView.currentPageIndex
  2444. extract?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
  2445. })
  2446. extract?.selectCurrentPageBtn()
  2447. }
  2448. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2449. let progress = SKProgressController()
  2450. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2451. progress.window?.contentView?.wantsLayer = true
  2452. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2453. progress.progressField.textColor = NSColor.white
  2454. progress.message = KMLocalizedString("Converting...", comment: "")
  2455. progressC = progress
  2456. progressC?.message = message
  2457. if maxValue > 0 {
  2458. progressC?.indeterminate = false
  2459. progressC?.maxValue = Double(maxValue)
  2460. progressC?.progressBar.doubleValue = 0.3
  2461. } else {
  2462. progressC?.indeterminate = true
  2463. }
  2464. progressC?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
  2465. })
  2466. }
  2467. func dismissProgressSheet() {
  2468. progressC?.stopAnimation()
  2469. progressC?.own_closeEndSheet()
  2470. progressC = nil
  2471. }
  2472. //MARK: - 打印
  2473. func validPrint() -> Bool {
  2474. if NSWindow.currentWindow() == self.view.window {
  2475. return true
  2476. }
  2477. return false
  2478. }
  2479. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2480. self.saveDocument()
  2481. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2482. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2483. if (result == .cancel) {
  2484. return
  2485. }
  2486. // 解除权限
  2487. self?.listView.document.unlock(withPassword: password)
  2488. // 隐藏提示
  2489. self?.hiddenSecureLimitTip()
  2490. // 去打印
  2491. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  2492. }
  2493. return
  2494. }
  2495. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  2496. }
  2497. //Poster
  2498. func showPosterPrintWindow() {
  2499. guard let document = self.document else { return }
  2500. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2501. if self.posterPrintWindowController == nil {
  2502. posterPrintWindowController = KMPDFPosterPrintWindowController.init(pdfDocument: pdfDocument)
  2503. }
  2504. if let window = posterPrintWindowController?.window {
  2505. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2506. })
  2507. }
  2508. }
  2509. //Multiple
  2510. func showMultiplePrintWindow() {
  2511. guard let document = self.document else { return }
  2512. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2513. if self.multiplePrintWindowController == nil {
  2514. multiplePrintWindowController = KMPDFMultiplePrintWindowController.init(pdfDocument: pdfDocument)
  2515. }
  2516. if let window = multiplePrintWindowController?.window {
  2517. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2518. })
  2519. }
  2520. }
  2521. //Booklet
  2522. func showBookletPrintWindow() {
  2523. guard let document = self.document else { return }
  2524. guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
  2525. if self.bookletWindowController == nil {
  2526. bookletWindowController = KMPDFBookletWindowController.init(document: pdfDocument)
  2527. }
  2528. if let window = bookletWindowController?.window {
  2529. NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
  2530. })
  2531. }
  2532. }
  2533. //MARK: - FileInfo
  2534. func showFileInfo() {
  2535. KMInfoWindowController.shared.showWindow(nil)
  2536. }
  2537. //MARK: - ToolTip
  2538. func showPDFViewToolTip(_ string: String) {
  2539. self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString(string))
  2540. self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
  2541. CGRectGetHeight(listView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
  2542. self.componentMessageView.properties.propertyInfo.viewWidth,
  2543. self.componentMessageView.properties.propertyInfo.viewHeight)
  2544. self.componentMessageView.reloadData()
  2545. self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
  2546. }
  2547. //MARK: - Share Action
  2548. @objc private func shareDocument(sender: NSView) {
  2549. let document = self.listView.document ?? CPDFDocument()
  2550. if document?.documentURL == nil {
  2551. return
  2552. }
  2553. var doucumentURL : URL = self.listView.document.documentURL
  2554. if doucumentURL.path.count > 0 {
  2555. let docDir = NSTemporaryDirectory()
  2556. let documentName : String = doucumentURL.path.lastPathComponent
  2557. let path = docDir.stringByAppendingPathComponent(documentName)
  2558. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2559. if writeSuccess == false {
  2560. __NSBeep()
  2561. return;
  2562. }
  2563. doucumentURL = URL(fileURLWithPath: path)
  2564. }
  2565. let array = [doucumentURL]
  2566. let picker = NSSharingServicePicker.init(items: array)
  2567. if sender.window != nil {
  2568. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2569. } else {
  2570. 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)
  2571. }
  2572. }
  2573. @objc private func shareFlatten(sender: NSView) {
  2574. if KMMemberInfo.shared.isLogin == false {
  2575. KMLoginWindowsController.shared.showWindow(nil)
  2576. return
  2577. }
  2578. let document = self.listView.document ?? CPDFDocument()
  2579. var path: String?
  2580. if document?.documentURL != nil {
  2581. path = document?.documentURL.path ?? ""
  2582. }
  2583. if path?.count ?? 0 > 0 {
  2584. let docDir = NSTemporaryDirectory()
  2585. let documentName : String = path?.lastPathComponent ?? ""
  2586. path = docDir.stringByAppendingPathComponent(documentName)
  2587. }
  2588. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2589. var tfileName = path?.deletingPathExtension.lastPathComponent
  2590. let tStdFileSuffix = "_flatten"
  2591. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2592. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2593. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2594. if success {
  2595. let url = URL(fileURLWithPath: path ?? "")
  2596. let picker = NSSharingServicePicker.init(items: [url])
  2597. if sender.window != nil {
  2598. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2599. } else {
  2600. 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)
  2601. }
  2602. }
  2603. }
  2604. @objc private func shareOriginalPDF(sender: NSView) {
  2605. guard let pdfDoc = self.listView.document else {
  2606. NSSound.beep()
  2607. return
  2608. }
  2609. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2610. let alert = NSAlert()
  2611. alert.alertStyle = .critical
  2612. alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2613. alert.runModal()
  2614. return
  2615. }
  2616. let document = self.listView.document ?? CPDFDocument()
  2617. var path: String?
  2618. if document?.documentURL != nil {
  2619. path = document?.documentURL.path ?? ""
  2620. }
  2621. if path?.count ?? 0 > 0 {
  2622. let docDir = NSTemporaryDirectory()
  2623. let documentName : String = path?.lastPathComponent ?? ""
  2624. path = docDir.stringByAppendingPathComponent(documentName)
  2625. }
  2626. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2627. if writeSuccess == false {
  2628. __NSBeep()
  2629. return;
  2630. }
  2631. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2632. let cnt = newDocument?.pageCount ?? 0
  2633. for i in 0 ..< cnt {
  2634. let page = newDocument!.page(at: i)
  2635. var annotations : [CPDFAnnotation] = []
  2636. for annotation in page!.annotations {
  2637. annotations.append(annotation)
  2638. }
  2639. for annotation in annotations {
  2640. annotation.page.removeAnnotation(annotation)
  2641. }
  2642. }
  2643. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2644. if writeSuccess ?? false {
  2645. let url = URL(fileURLWithPath: path ?? "")
  2646. let picker = NSSharingServicePicker.init(items: [url])
  2647. if sender.window != nil {
  2648. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2649. } else {
  2650. 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)
  2651. }
  2652. }
  2653. }
  2654. @objc func shareFromService(sender: NSMenuItem) {
  2655. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  2656. return
  2657. }
  2658. var string = ""
  2659. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  2660. string = freeTextAnnotation.contents ?? ""
  2661. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  2662. if let page = markupAnnotation.page {
  2663. if let selection = page.selection(for: markupAnnotation.bounds) {
  2664. string = selection.string() ?? ""
  2665. }
  2666. }
  2667. } else {
  2668. string = listView.currentSelection?.string() ?? ""
  2669. }
  2670. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  2671. let model = windowControler.browser?.tabStripModel
  2672. if let cnt = model?.count(), cnt <= 0 {
  2673. return
  2674. }
  2675. if let data = model?.activeTabContents().isHome, data {
  2676. return
  2677. }
  2678. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  2679. if string.count > 0 {
  2680. let represent : NSSharingService = sender.representedObject as! NSSharingService
  2681. represent.perform(withItems: [string])
  2682. return
  2683. }
  2684. let represent = sender.representedObject as? NSSharingService
  2685. represent?.perform(withItems: [string])
  2686. }
  2687. //MARK: - PDFView Menu
  2688. func clickPresentationMenu(point:NSPoint)->KMNMenuStruct {
  2689. var viewHeight: CGFloat = 8
  2690. var menuItemArr: [ComponentMenuitemProperty] = []
  2691. var items: [(String, String)] = []
  2692. items.append(("Next Page", PDFViewMenuIdentifier_PageNext))
  2693. items.append(("Previous Page", PDFViewMenuIdentifier_PagePrevious))
  2694. items.append(("First", PDFViewMenuIdentifier_PageFirst))
  2695. items.append(("Last", PDFViewMenuIdentifier_PageLast))
  2696. items.append(("", ""))
  2697. items.append(("Laser pointer", PDFViewMenuIdentifier_Presentation_LaserPoint))
  2698. items.append(("Brush", PDFViewMenuIdentifier_Presentation_Brush))
  2699. items.append(("", ""))
  2700. items.append(("Exit Presentation", PDFViewMenuIdentifier_Presentation_Exit))
  2701. for (i, value) in items {
  2702. if value.count == 0 {
  2703. let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
  2704. menuItemArr.append(property)
  2705. viewHeight += 8
  2706. } else {
  2707. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  2708. itemSelected: false,
  2709. isDisabled: false,
  2710. keyEquivalent: nil,
  2711. text: KMLocalizedString(i),
  2712. identifier: value,representedObject: point)
  2713. if value == PDFViewMenuIdentifier_PageNext {
  2714. properties_Menuitem.keyEquivalent = "▶"
  2715. } else if value == PDFViewMenuIdentifier_PagePrevious {
  2716. properties_Menuitem.keyEquivalent = "◀"
  2717. } else if value == PDFViewMenuIdentifier_PageFirst {
  2718. properties_Menuitem.keyEquivalent = "⌘ ◀"
  2719. } else if value == PDFViewMenuIdentifier_PageLast {
  2720. properties_Menuitem.keyEquivalent = "⌘ ▶"
  2721. } else if value == PDFViewMenuIdentifier_Presentation_Exit {
  2722. properties_Menuitem.keyEquivalent = "ESC"
  2723. }
  2724. if(value == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  2725. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2726. } else {
  2727. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2728. }
  2729. } else if value == PDFViewMenuIdentifier_Presentation_Brush {
  2730. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2731. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2732. } else {
  2733. }
  2734. }
  2735. menuItemArr.append(properties_Menuitem)
  2736. viewHeight += 36
  2737. }
  2738. }
  2739. let menuStruct = KMNMenuStruct(menuitems: menuItemArr, viewHeight: viewHeight)
  2740. return menuStruct
  2741. }
  2742. func gotoPage(_ sender: Any?) {
  2743. var pages : [String] = []
  2744. for i in 0 ..< self.listView.document.pageCount {
  2745. pages.append("\(i)")
  2746. }
  2747. self.textFieldSheet.callback = { [weak self] stringValue in
  2748. guard let index = Int(stringValue) else {
  2749. return
  2750. }
  2751. if (self?.listView == nil) {
  2752. return
  2753. }
  2754. if (index > 0 && index <= self!.listView.document.pageCount) {
  2755. self?.listView.go(toPageIndex: index-1, animated: true)
  2756. }
  2757. }
  2758. self.textFieldSheet.showWindow(nil)
  2759. self.textFieldSheet.pageBox.addItems(withObjectValues: pages)
  2760. self.textFieldSheet.stringValue = "\(self.listView.currentPageIndex+1)"
  2761. }
  2762. //MARK: - 添加书签
  2763. @objc func menuItemBookMarkClick_add(sender:NSMenuItem?) {
  2764. toggleOpenLeftSide(pdfSideBarType: .bookmark)
  2765. viewManager.pdfSideBarType = .bookmark
  2766. sideBarController?.reloadData()
  2767. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  2768. let index = self.listView.currentPageIndex
  2769. self.listView.document?.addBookmark("\(KMLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  2770. self.listView.updateRender(true)
  2771. } else {
  2772. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  2773. self.listView.updateRender(true)
  2774. }
  2775. botaViewController?.reloadData()
  2776. self.listView.undoManager?.setActionName("")//添加undo事件就可删除
  2777. }
  2778. //MARK: - 页面旋转
  2779. func rotateLeft(page:CPDFPage,listView:CPDFListView?) {
  2780. if KMMemberInfo.shared.isLogin == false {
  2781. KMLoginWindowsController.shared.showWindow(nil)
  2782. return
  2783. }
  2784. Task { @MainActor in
  2785. if viewManager.isPageEditMode {
  2786. self.pageEditViewController?.rotatePageRightAction()
  2787. } else {
  2788. let rotation = page.rotation
  2789. page.leftRotate()
  2790. listView?.layoutDocumentView()
  2791. if(listView == self.listView) {
  2792. var pageIndexes = IndexSet()
  2793. pageIndexes.insert(Int(page.pageIndex()))
  2794. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  2795. botaViewController?.reloadData()
  2796. }
  2797. }
  2798. }
  2799. }
  2800. func rotateRight(page:CPDFPage,listView:CPDFListView?) {
  2801. if KMMemberInfo.shared.isLogin == false {
  2802. KMLoginWindowsController.shared.showWindow(nil)
  2803. return
  2804. }
  2805. Task { @MainActor in
  2806. if viewManager.isPageEditMode {
  2807. self.pageEditViewController?.rotatePageRightAction()
  2808. } else {
  2809. let rotation = page.rotation
  2810. page.rightRotate()
  2811. listView?.layoutDocumentView()
  2812. if(listView == self.listView) {
  2813. var pageIndexes = IndexSet()
  2814. pageIndexes.insert(Int(page.pageIndex()))
  2815. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  2816. botaViewController?.reloadData()
  2817. }
  2818. }
  2819. }
  2820. }
  2821. //MARK: - 自动滚动
  2822. func isAutoFlowOn() -> Bool {
  2823. return listView.isAutoFlow()
  2824. }
  2825. func toggleAutoFlow(_ sender: Any?) {
  2826. if (listView.isAutoFlow()) {
  2827. listView.stopAutoFlow()
  2828. } else {
  2829. listView.startAutoFlow()
  2830. }
  2831. }
  2832. //MARK: - 高亮Form
  2833. func highlightFormFiled(_ sender: Any?) {
  2834. let enabled = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  2835. CPDFKitConfig.sharedInstance().setEnableFormFieldHighlight(!enabled)
  2836. listView.setNeedsDisplayForVisiblePages()
  2837. self.alertTipViewController.reloadFormAlertUI()
  2838. }
  2839. //MARK: - 高亮Link
  2840. func highlightLinks(_ sender: Any?) {
  2841. let enabled = CPDFKitConfig.sharedInstance().enableLinkFieldHighlight()
  2842. CPDFAnnotation.updateLinkFieldHighlight(listView, linkFieldHighlight: !enabled)
  2843. }
  2844. //MARK: - 重置Form
  2845. func resetForm(_ sender: Any?) {
  2846. listView.resetFormAnnotation()
  2847. }
  2848. //MARK: - 属性
  2849. @IBAction func menuItemAction_property(_ sender: Any?) {
  2850. showFileInfo()
  2851. }
  2852. //MARK: - 打印
  2853. @IBAction func menuItemAction_print(_ sender: Any?) {
  2854. self.showPrintWindow()
  2855. }
  2856. //MARK: - Undo,Redo
  2857. func updateUndoRedoState() {
  2858. var undo: Bool = self.listView.undoManager?.canUndo ?? false
  2859. var redo: Bool = self.listView.undoManager?.canRedo ?? false
  2860. if listView.isEditing() == true {
  2861. undo = listView.canEditTextUndo()
  2862. redo = listView.canEditTextRedo()
  2863. }
  2864. toolbarManager.undoProperty.isDisabled = undo ? false : true
  2865. toolbarManager.redoProperty.isDisabled = redo ? false : true
  2866. pdfToolbarController?.reloadUndoRedoButtonState()
  2867. }
  2868. //MARK: - Flattened
  2869. func saveAsFlattenedPDFAction() {
  2870. if KMMemberInfo.shared.isLogin == false {
  2871. KMLoginWindowsController.shared.showWindow(nil)
  2872. return
  2873. }
  2874. DispatchQueue.main.async {
  2875. NSPanel.savePanel(self.view.window!, true) { panel in
  2876. panel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_flatten" + ".pdf"
  2877. } completion: { response, url, isOpen in
  2878. if (response == .cancel) {
  2879. return
  2880. }
  2881. var result = self.listView.document.writeFlatten(to: url!)
  2882. if (!result) {
  2883. return
  2884. }
  2885. if (isOpen) {
  2886. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
  2887. }
  2888. } else {
  2889. NSWorkspace.shared.activateFileViewerSelecting([url!])
  2890. }
  2891. }
  2892. }
  2893. }
  2894. func showInFinder() {
  2895. NSWorkspace.shared.activateFileViewerSelecting([self.listView.document.documentURL])
  2896. }
  2897. //MARK: - DisplayViewMode
  2898. func getPDFViewPageLayoutType() -> pageLayoutType {
  2899. if listView.displayMode() == .singlePage {
  2900. return .singlePage
  2901. } else if listView.displayMode() == .singlePageContinuous {
  2902. return .singlePageContinue
  2903. } else if listView.displayMode() == .twoUp {
  2904. if listView.displaysAsBook == true {
  2905. return .bookMode
  2906. }
  2907. return .twoPage
  2908. } else if listView.displayMode() == .twoUpContinuous {
  2909. if listView.displaysAsBook == true {
  2910. return .bookMode
  2911. }
  2912. return .twoPageContinue
  2913. }
  2914. return .singlePage
  2915. }
  2916. func updatePDFViewDisplayMode(viewMode mode: CPDFDisplayViewMode = .singlePage, isbookMode bookMode: Bool = false, direction directionValue: CPDFDisplayDirection? = nil) {
  2917. if bookMode == true {
  2918. //书本模式
  2919. listView.displaysAsBook = true
  2920. listView.displayTwoUp = true
  2921. if let value = directionValue {
  2922. listView.displayDirection = value
  2923. }
  2924. } else {
  2925. listView.setDisplay(mode)
  2926. }
  2927. listView.layoutDocumentView()
  2928. }
  2929. //MARK: - 新增大纲
  2930. @objc func addOutLineItemAction() {
  2931. toggleOpenLeftSide(pdfSideBarType: .outline)
  2932. botaViewController?.outlineViewC.addOutline()
  2933. }
  2934. //MARK: - 搜索
  2935. @objc func searchBaiduAction() {
  2936. let label = self.listView.currentSelection?.string() ?? ""
  2937. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  2938. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  2939. NSWorkspace.shared.open(url)
  2940. }
  2941. }
  2942. //MARK: - 转档
  2943. func showConvertWindow(_ convertType: KMPDFConvertType) {
  2944. var winC: KMConvertBaseWindowController = KMConvertBaseWindowController()
  2945. let model = KMDocumentModel(url: listView.document.documentURL)
  2946. model.password = listView.document.password ?? ""
  2947. if convertType == .word {
  2948. winC = KMConvertWordWindowController()
  2949. winC.documentModel = model
  2950. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2951. } else if convertType == .ppt {
  2952. winC = KMConvertPPTsWindowController()
  2953. winC.subType = 1
  2954. winC.documentModel = model
  2955. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2956. } else if convertType == .rtf {
  2957. winC = KMConvertPPTsWindowController()
  2958. winC.subType = 2
  2959. winC.documentModel = model
  2960. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2961. } else if convertType == .text {
  2962. winC = KMConvertPPTsWindowController()
  2963. winC.subType = 4
  2964. winC.documentModel = model
  2965. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2966. } else if convertType == .csv {
  2967. winC = KMConvertCSVWindowController()
  2968. winC.subType = 5
  2969. winC.documentModel = model
  2970. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2971. } else if convertType == .excel {
  2972. winC = KMConvertExcelWindowController()
  2973. winC.documentModel = model
  2974. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2975. } else if convertType == .html {
  2976. winC = KMConvertHtmlWindowController()
  2977. winC.documentModel = model
  2978. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2979. } else if convertType == .json {
  2980. winC = KMConvertJsonWindowController()
  2981. winC.documentModel = model
  2982. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2983. } else if convertType == .jpeg ||
  2984. convertType == .jpg ||
  2985. convertType == .png ||
  2986. convertType == .gif ||
  2987. convertType == .tiff ||
  2988. convertType == .tga ||
  2989. convertType == .bmp ||
  2990. convertType == .jp2{
  2991. winC = KMConvertImageWindowController()
  2992. winC.documentModel = model
  2993. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2994. if let settingView = winC.settingView as? KMConvertImageSettingView {
  2995. settingView.selectConvertType(convertType: convertType)
  2996. }
  2997. }
  2998. winC.batchAction = { [unowned self] in
  2999. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3000. model.password = listView.document.password ?? ""
  3001. self.showBatchWindow(type: .convertPDF, subType: convertType.rawValue, files: [], fileModels: [model])
  3002. }
  3003. }
  3004. //MARK: - 选择Form注释
  3005. @objc func selectAllFormAnnotation (currentPage:CPDFPage) {
  3006. var formActiveAnnotations:[CPDFAnnotation] = []
  3007. for i in 0 ..< listView.document.pageCount {
  3008. let page = listView.document.page(at: i)
  3009. if(page?.pageIndex() == currentPage.pageIndex()) {
  3010. let annotations = page?.annotations
  3011. for j in 0 ..< (annotations?.count ?? 0) {
  3012. if let an = annotations?[j] as? CPDFAnnotation {
  3013. if (an.isKind(of: CPDFWidgetAnnotation.self) == true) {
  3014. formActiveAnnotations.append(an)
  3015. }
  3016. }
  3017. }
  3018. }
  3019. }
  3020. listView.updateActiveAnnotations(formActiveAnnotations)
  3021. }
  3022. @objc func selectAllNomerAnnotation (currentPage:CPDFPage) {
  3023. var normalActiveAnnotations:[CPDFAnnotation] = []
  3024. for i in 0 ..< listView.document.pageCount {
  3025. let page = listView.document.page(at: i)
  3026. if(page?.pageIndex() == currentPage.pageIndex()) {
  3027. let annotations = page?.annotations
  3028. for j in 0 ..< (annotations?.count ?? 0) {
  3029. if let an = annotations?[j] as? CPDFAnnotation {
  3030. if an.isKind(of: CPDFWidgetAnnotation.self) == true ||
  3031. an.isKind(of: CPDFLinkAnnotation.self) == true ||
  3032. an.isKind(of: CPDFRedactAnnotation.self) == true {
  3033. } else {
  3034. normalActiveAnnotations.append(an)
  3035. }
  3036. }
  3037. }
  3038. }
  3039. }
  3040. listView.updateActiveAnnotations(normalActiveAnnotations)
  3041. }
  3042. @objc func selectAllRedactAnnotation (currentPage:CPDFPage) {
  3043. var selectAllRedactAnnotation: [CPDFAnnotation] = []
  3044. for i in 0 ..< listView.document.pageCount {
  3045. let page = listView.document.page(at: i)
  3046. if(page?.pageIndex() == currentPage.pageIndex()) {
  3047. let annotations = page?.annotations
  3048. for j in 0 ..< (annotations?.count ?? 0) {
  3049. if let an = annotations?[j] as? CPDFAnnotation {
  3050. if an.isKind(of: CPDFRedactAnnotation.self) == true {
  3051. selectAllRedactAnnotation.append(an)
  3052. }
  3053. }
  3054. }
  3055. }
  3056. }
  3057. listView.updateActiveAnnotations(selectAllRedactAnnotation)
  3058. listView.setNeedsDisplayForVisiblePages()
  3059. }
  3060. //MARK: 搜索 & 替换
  3061. func showSearchPopWindow(type: KMNBotaSearchType, keyborad: String?, replaceText: String?, results: [KMSearchMode]) {
  3062. let handdler = KMNSearchHanddler()
  3063. handdler.type = type
  3064. handdler.searchKey = keyborad
  3065. handdler.searchKey = replaceText
  3066. self.showSearchPopWindow(hander: handdler)
  3067. }
  3068. func showSearchPopWindow(hander: KMNSearchHanddler?) {
  3069. if (self.currentWindowController != nil) && ((self.currentWindowController as? KMSearchReplaceWindowController) != nil) {
  3070. return
  3071. }
  3072. guard let hander = hander else { return }
  3073. let toolMode = self.listView.toolMode
  3074. let isEditing = self.listView.isEditing()
  3075. var winH: CGFloat = 112
  3076. if hander.type == .replace {
  3077. if toolMode == .CEditPDFToolMode && isEditing {
  3078. } else { // 进入内容编辑模式
  3079. viewManager.toolMode = .Edit
  3080. updatePDFViewAnnotationMode()
  3081. pdfToolbarController?.reloadToolbarTabsView()
  3082. pdfToolbarController?.reloadData()
  3083. }
  3084. winH = 208
  3085. }
  3086. self.view.window?.makeFirstResponder(nil)
  3087. let winC = KMSearchReplaceWindowController(with: listView, type: hander.type)
  3088. self.currentWindowController = winC
  3089. winC.replaceCallback = { [weak self] in
  3090. let toolMode = self?.listView.toolMode ?? .none
  3091. let isEditing = self?.listView.isEditing() ?? false
  3092. if toolMode == .CEditPDFToolMode && isEditing {
  3093. } else { // 进入内容编辑模式
  3094. self?.viewManager.toolMode = .Edit
  3095. self?.updatePDFViewAnnotationMode()
  3096. self?.pdfToolbarController?.reloadToolbarTabsView()
  3097. self?.pdfToolbarController?.reloadData()
  3098. }
  3099. }
  3100. winC.itemClick = { [weak self] idx, params in
  3101. if idx == 1 {
  3102. self?.toggleOpenLeftSide(pdfSideBarType: .search)
  3103. guard let handdler = params.first as? KMNSearchHanddler else {
  3104. return
  3105. }
  3106. let viewC = self?.botaViewController?.searchViewC
  3107. if handdler.type == .search {
  3108. viewC?.showSearchView()
  3109. } else if handdler.type == .replace {
  3110. viewC?.showReplaceView()
  3111. }
  3112. self?.sideBarController?.reloadData()
  3113. viewC?.handdler = winC.handdler
  3114. } else if idx == 3 {
  3115. self?.searchTypeDidChange(type: .search)
  3116. } else if idx == 4 {
  3117. self?.searchTypeDidChange(type: .replace)
  3118. }
  3119. }
  3120. winC.closeCallback = { [weak self] in
  3121. if (self?.currentWindowController != nil) {
  3122. self?.currentWindowController = nil
  3123. }
  3124. }
  3125. let targetView = self.pdfToolbarController?.leftViewButton
  3126. let point = targetView?.convert(targetView?.frame.origin ?? .zero, to: nil) ?? .zero
  3127. // 200 248
  3128. let x = point.x + (self.view.window?.frame.origin.x ?? 0) - 32
  3129. let y = point.y + (self.view.window?.frame.origin.y ?? 0) - winH - 32
  3130. let winFramePoint = NSPoint(x: x, y: y)
  3131. winC.window?.setFrameOrigin(winFramePoint)
  3132. self.view.window?.addChildWindow(winC.window!, ordered: .above)
  3133. winC.handdler = hander
  3134. }
  3135. func searchPDF() {
  3136. showSearchPopWindow(type: .search, keyborad: "", replaceText: "", results: [])
  3137. }
  3138. func find_ReplacePDF() {
  3139. showSearchPopWindow(type: .replace, keyborad: "", replaceText: "", results: [])
  3140. }
  3141. func fineNext() {
  3142. if let searchReplaceWindowController = currentWindowController as? KMSearchReplaceWindowController {
  3143. searchReplaceWindowController._nextAction(nil)
  3144. }
  3145. }
  3146. func findPrevious() {
  3147. if let searchReplaceWindowController = currentWindowController as? KMSearchReplaceWindowController {
  3148. searchReplaceWindowController._previousAction(nil)
  3149. }
  3150. }
  3151. func useSelectionForFind() {
  3152. if let currentSel = listView.currentSelection,currentSel.selectionType() == .text,currentSel.string().isEmpty != nil {
  3153. showSearchPopWindow(type: .search, keyborad: currentSel.string(), replaceText: "", results: [])
  3154. }
  3155. }
  3156. // MARK: -显示加密弹窗
  3157. }
  3158. //MARK: Compress
  3159. extension KMMainViewController {
  3160. // func showCompressController(_ url: URL) {
  3161. // let filePath = url.path
  3162. // if !FileManager.default.fileExists(atPath: filePath) {
  3163. // let alert = NSAlert.init()
  3164. // alert.alertStyle = .critical
  3165. // alert.messageText = "\(filePath.lastPathComponent) \(KMLocalizedString("File Not Exist", comment: ""))"
  3166. // alert.runModal()
  3167. // return
  3168. // }
  3169. //
  3170. // let document = CPDFDocument(url: url)
  3171. // document?.unlock(withPassword: model.password)
  3172. //
  3173. // if !document!.allowsPrinting && !document!.allowsCopying {
  3174. // KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: .owner, url: url) { [unowned self] result, password in
  3175. // if (result == .success) {
  3176. // let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3177. // model.password = password ?? ""
  3178. // model.isLock = false
  3179. // self.showCompressController(model: model)
  3180. // }
  3181. // }
  3182. // } else {
  3183. // let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3184. // self.showCompressController(model: model)
  3185. // }
  3186. // }
  3187. func showCompressController(model: KMBatchProcessingTableViewModel) {
  3188. let filePath = model.filePath
  3189. if !FileManager.default.fileExists(atPath: filePath) {
  3190. let alert = NSAlert.init()
  3191. alert.alertStyle = .critical
  3192. alert.messageText = "\(filePath.lastPathComponent) \(KMLocalizedString("File Not Exist", comment: ""))"
  3193. alert.runModal()
  3194. return
  3195. }
  3196. let document = CPDFDocument(url: model.filePath.fileURL)
  3197. document?.unlock(withPassword: model.password)
  3198. if !document!.allowsPrinting && !document!.allowsCopying {
  3199. KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: .owner, url: document!.documentURL) { [unowned self] result, password in
  3200. if (result == .success) {
  3201. // let model = KMBatchProcessingTableViewModel.initWithFilePath(url: model.filePath.fileURL)
  3202. model.password = password ?? ""
  3203. model.isLock = false
  3204. self.showCompress(model: model)
  3205. }
  3206. }
  3207. } else {
  3208. self.showCompress(model: model)
  3209. }
  3210. }
  3211. func showCompress(model: KMBatchProcessingTableViewModel) {
  3212. self.compressWindowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  3213. self.compressWindowController?.password = model.password
  3214. self.compressWindowController?.documentURL = model.filePath.fileURL
  3215. let controllerWindow = self.view.window
  3216. controllerWindow?.beginSheet(self.compressWindowController!.window!)
  3217. self.compressWindowController?.itemClick = { [unowned self] in
  3218. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  3219. }
  3220. self.compressWindowController?.batchAction = { [unowned self] view, filePaths in
  3221. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  3222. self.showBatchWindow(type: .compress, files: filePaths)
  3223. }
  3224. self.compressWindowController?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  3225. controllerWindow?.endSheet((self.compressWindowController?.window)!)
  3226. if (result) {
  3227. if (openDocument) {
  3228. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  3229. } else {
  3230. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  3231. }
  3232. } else {
  3233. let alert = NSAlert()
  3234. alert.messageText = KMLocalizedString("Compress Faild", comment: "")
  3235. alert.runModal()
  3236. }
  3237. }
  3238. }
  3239. }
  3240. //MARK: - OCR
  3241. extension KMMainViewController {
  3242. //window
  3243. func showOCRWindow() {
  3244. #if VERSION_DMG
  3245. KMResourceDownloadManager.manager.needDownloadOCRResource(complete: { [weak self] result in
  3246. if result {
  3247. KMResourceDownloadManager.manager.downLoadOCRResource(window: self?.view.window ?? NSWindow.currentWindow())
  3248. } else {
  3249. self?._showOCRWindow()
  3250. }
  3251. })
  3252. #else
  3253. self._showOCRWindow()
  3254. #endif
  3255. }
  3256. private func _showOCRWindow() {
  3257. if !IAPProductsManager.default().isAvailableAllFunction(){
  3258. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3259. winC?.showWindow(nil)
  3260. return
  3261. }
  3262. let window = KMOCRSettingWindowController(windowNibName: "KMOCRSettingWindowController")
  3263. window.OCRAction = {[unowned self] controller, model in
  3264. self.convertOCRScanFile(window: window, document: self.listView.document, model: model)
  3265. }
  3266. window.cancelAction = {[unowned self] controller in
  3267. self.view.window?.endSheet(window.window ?? NSWindow())
  3268. }
  3269. self.view.window?.beginSheet(window.window ?? NSWindow())
  3270. }
  3271. func showOCREditAlert() {
  3272. if viewManager.subToolMode != .Edit_Crop {
  3273. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
  3274. alertTipViewController.isShowOCRAlert = true
  3275. alertTipViewController.showInView(listView: listView, subView: infoSplitCenterView)
  3276. alertTipViewController.reloadOCRAlertUI()
  3277. alertTipViewController.reloadAlertUIFrame()
  3278. alertTipViewController.OCRApplyCallback = { [unowned self] in
  3279. self.showOCRWindow()
  3280. }
  3281. }
  3282. }
  3283. }
  3284. func closeOCREditAlert() {
  3285. guard let view = alertTipViewController.OCRComponentAlert else { return }
  3286. alertTipViewController.isShowOCRAlert = false
  3287. alertTipViewController.reloadOCRAlertUI()
  3288. alertTipViewController.reloadAlertUIFrame()
  3289. }
  3290. func showOCRToolAlert(_ string: String) {
  3291. let alertView = ComponentMessage()
  3292. alertView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString(string))
  3293. alertView.frame = CGRectMake((CGRectGetWidth(self.listView.frame) - alertView.properties.propertyInfo.viewWidth) / 2,
  3294. CGRectGetHeight(self.listView.frame) - alertView.properties.propertyInfo.viewHeight - 8,
  3295. alertView.properties.propertyInfo.viewWidth,
  3296. alertView.properties.propertyInfo.viewHeight)
  3297. alertView.reloadData()
  3298. self.listView.addSubview(alertView)
  3299. // 自动移除视图
  3300. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  3301. self.removeOCRToolAlert(alertView)
  3302. }
  3303. }
  3304. private func removeOCRToolAlert(_ alertView: NSView) {
  3305. // 淡出动画
  3306. NSAnimationContext.runAnimationGroup({ context in
  3307. context.duration = 0.3
  3308. alertView.animator().alphaValue = 0
  3309. }, completionHandler: {
  3310. alertView.removeFromSuperview()
  3311. })
  3312. }
  3313. //OCR
  3314. func convertOCRScanFile(window: KMOCRSettingWindowController, document: CPDFDocument, model: KMOCRModel) {
  3315. KMCompressManager.shared.showLoadingWindow(window: window.window)
  3316. KMCompressManager.shared.cancelAction = {
  3317. KMOCRManager.manager.cancelRecognition()
  3318. }
  3319. //当前页面需要提前设置
  3320. if model.pageRangeType == .current {
  3321. model.pageRange = [self.listView.currentPageIndex]
  3322. }
  3323. KMOCRManager.manager.convertScanFile(document: document, model: model, progress: { progress in
  3324. KMCompressManager.shared.updateLoadingProgress(value: progress)
  3325. }) { [weak self] document, text, error in
  3326. KMCompressManager.shared.dismissLoadiingWindow(window: window.window)
  3327. window.endLoading()
  3328. window.km_quick_endSheet()
  3329. if !model.saveAsPDF {
  3330. self?.listView.layoutDocumentView()
  3331. self?.needSave = true
  3332. }
  3333. }
  3334. }
  3335. func convertOCR(document: CPDFDocument, model: KMOCRModel) {
  3336. // self.view.window?.windowController.beginLoading()
  3337. //当前页面需要提前设置
  3338. if model.pageRangeType == .current {
  3339. model.pageRange = [self.listView.currentPageIndex]
  3340. }
  3341. KMOCRManager.manager.clearOCRTextData()
  3342. KMOCRManager.manager.convertOCR(document: document, model: model, beginProgress: { [weak self] progress in
  3343. KMCompressManager.shared.showLoadingWindow(window: self?.view.window)
  3344. }, progress: { [weak self] progress in
  3345. KMCompressManager.shared.updateLoadingProgress(value: progress)
  3346. }) { [weak self] document, text, error in
  3347. // self?.view.window?.windowController.endLoading()
  3348. // window.km_quick_endSheet()
  3349. if !model.saveAsPDF {
  3350. self?.listView.layoutDocumentView()
  3351. self?.needSave = true
  3352. }
  3353. KMCompressManager.shared.dismissLoadiingWindow(window: self?.view.window)
  3354. }
  3355. KMCompressManager.shared.cancelAction = {
  3356. KMOCRManager.manager.cancelRecognition()
  3357. }
  3358. }
  3359. func convertOCRSaveAsTXT(text: String) {
  3360. NSPanel.savePanel(NSWindow.currentWindow()) { panel in
  3361. let url: URL = self.listView.document.documentURL
  3362. panel.nameFieldStringValue = ""+url.deletingPathExtension().lastPathComponent+"_OCR"
  3363. panel.allowedFileTypes = ["txt"]
  3364. } completion: { [unowned self] response, url in
  3365. if (response == .cancel) {
  3366. return
  3367. }
  3368. let saveAsPDFFilePath = url?.path ?? ""
  3369. let outputURL = URL(fileURLWithPath: saveAsPDFFilePath)
  3370. try? text.write(to: outputURL, atomically: true, encoding: .utf8)
  3371. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: saveAsPDFFilePath)])
  3372. }
  3373. }
  3374. func convertSelectionRectOCR(rect: NSRect) {
  3375. let rect = NSIntegralRect(rect)
  3376. guard let orgPage = listView.currentSelectionPage() else { return }
  3377. if let page : CPDFPage = orgPage.copy() as? CPDFPage {
  3378. KMCompressManager.shared.showLoadingWindow(window: self.view.window)
  3379. KMCompressManager.shared.cancelAction = {
  3380. KMOCRManager.manager.cancelRecognition()
  3381. }
  3382. page.setBounds(rect, for: .cropBox)
  3383. let image = page.thumbnail(of: rect.size) ?? NSImage()
  3384. guard let model = self.rightSideController?.tool_OCRController?.model else { return }
  3385. model.pageRange = [Int(orgPage.pageIndex())]
  3386. KMOCRManager.manager.clearOCRTextData()
  3387. KMOCRManager.manager.convertOCR(images: [image], model: model, progress: { progress in
  3388. KMCompressManager.shared.updateLoadingProgress(value: progress)
  3389. }) { [weak self] document, text, error in
  3390. KMCompressManager.shared.dismissLoadiingWindow(window: self?.view.window)
  3391. self?.rightSideController?.tool_OCRController?.model.text = text ?? ""
  3392. self?.rightSideController?.tool_OCRController?.reloadData()
  3393. }
  3394. }
  3395. }
  3396. }
  3397. //MARK: Batch
  3398. extension KMMainViewController {
  3399. func showBatchWindow(type: KMBatchCollectionViewType, fileModels: [KMBatchProcessingTableViewModel]?) {
  3400. self.showBatchWindow(type: type, subType: 0, files: [], fileModels: fileModels ?? [])
  3401. }
  3402. func showBatchWindow(type: KMBatchCollectionViewType, files: [URL]?) {
  3403. self.showBatchWindow(type: type, subType: 0, files: files ?? [], fileModels: [])
  3404. }
  3405. func showBatchWindow(type: KMBatchCollectionViewType, subType: Int = 0, files: [URL] = [], fileModels: [KMBatchProcessingTableViewModel] = []) {
  3406. let batchWindowController = KMBatchWindowController.manager
  3407. batchWindowController.window?.makeKeyAndOrderFront("")
  3408. if files.count != 0 {
  3409. batchWindowController.inputData = files
  3410. }
  3411. if fileModels.count != 0 {
  3412. batchWindowController.inputDataModel = fileModels
  3413. }
  3414. batchWindowController.type = type
  3415. batchWindowController.inputSubType = subType
  3416. }
  3417. }
  3418. //MARK: - 代理方法
  3419. //MARK: - NSSplitViewDelegate
  3420. extension KMMainViewController: NSSplitViewDelegate {
  3421. func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
  3422. if splitView == infoContendSplitView {
  3423. return subview.isEqual(to: infoSplitCenterView) == false
  3424. }
  3425. return false
  3426. }
  3427. func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
  3428. if splitView == infoContendSplitView {
  3429. if(subview.isEqual(to: infoSplitLeftView)) {
  3430. } else if(subview.isEqual(to: infoSplitRightView)) {
  3431. }
  3432. }
  3433. return false
  3434. }
  3435. func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
  3436. if splitView == infoContendSplitView {
  3437. return splitView == infoContendSplitView
  3438. } else if splitView == pdfSplitView {
  3439. return splitView == pdfSplitView
  3440. }
  3441. return false
  3442. }
  3443. func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  3444. if splitView == infoContendSplitView {
  3445. if dividerIndex == 0 {
  3446. if viewManager.showDisplayView {
  3447. return MIN_SIDE_PANE_WIDTH.doubleValue
  3448. }
  3449. return infoContendSplitView.bounds.width/2
  3450. } else if (dividerIndex == 1) {
  3451. return proposedMaximumPosition - MIN_SIDE_PANE_WIDTH.doubleValue
  3452. }
  3453. }
  3454. return proposedMaximumPosition
  3455. }
  3456. func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  3457. if(splitView == infoContendSplitView && dividerIndex == 0) {
  3458. return proposedMinimumPosition + MIN_SIDE_PANE_WIDTH.doubleValue
  3459. }
  3460. return proposedMinimumPosition
  3461. }
  3462. func splitView(_ splitView: NSSplitView, shouldAdjustSizeOfSubview view: NSView) -> Bool {
  3463. if splitView == infoContendSplitView {
  3464. if view == splitView.subviews[0] || view == splitView.subviews[2] {
  3465. return false
  3466. }
  3467. }
  3468. return true
  3469. }
  3470. func splitViewDidResizeSubviews(_ notification: Notification) {
  3471. let splitView = notification.object as? NSSplitView
  3472. if(splitView == infoContendSplitView) {
  3473. leftSplitViewResizeFinish()
  3474. if(newMwcFlags.settingUpWindow == false && self.view.window?.frameAutosaveName != nil) {
  3475. let leftWidth = infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) ? 0.0 : infoSplitLeftView.frame.width
  3476. UserDefaults.standard.set(leftWidth, forKey: CPDFViewLeftSidePaneWidthKey)
  3477. UserDefaults.standard.synchronize()
  3478. }
  3479. if listView.isEditing() == false {
  3480. updateAnnotationsPopWinodwFrame()
  3481. } else {
  3482. updateContentEditPopWinodwFrame()
  3483. }
  3484. }
  3485. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(splitViewResizeFinish), object: nil)
  3486. self.perform(#selector(splitViewResizeFinish), with: nil, afterDelay: 0.15)
  3487. }
  3488. @objc func leftSplitViewResizeFinish() {
  3489. botaViewController?.changeLeftSideBounds()
  3490. }
  3491. @objc func splitViewResizeFinish() {
  3492. if infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) {
  3493. if viewManager.pdfSideBarType != .none {
  3494. viewManager.pdfSideBarType = .none
  3495. }
  3496. }
  3497. }
  3498. }
  3499. //MARK: - KMPDFSideBarControllerDelegate 左侧Sidebar代理
  3500. extension KMMainViewController: KMPDFSideBarControllerDelegate {
  3501. func kmPDFSideBarControllerDidSidebarTypeUpdated(_ view: KMPDFSideBarController) {
  3502. if viewManager.pdfSideBarType == .none {
  3503. toggleCloseLeftSide()
  3504. } else {
  3505. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  3506. }
  3507. }
  3508. func kmPDFSideBarControllerDidGotoPage(_ view: KMPDFSideBarController, _ pageIndex: Int) {
  3509. listView.go(toPageIndex: pageIndex, animated: true)
  3510. }
  3511. }
  3512. //MARK: - KMPDFToolbarControllerDelegate 工具栏代理
  3513. extension KMMainViewController: KMPDFToolbarControllerDelegate {
  3514. //MARK: -ViewTools发生变化时调用
  3515. func kmPDFToolbarControllerDidViewToolsChanged(_ controller: KMPDFToolbarController) {
  3516. let viewToolsType = viewManager.viewToolsType
  3517. if viewToolsType == .Select {
  3518. listView.toolMode = .CNoteToolMode
  3519. } else if viewToolsType == .Scroll {
  3520. listView.toolMode = .CMoveToolMode
  3521. } else if viewToolsType == .Content_Selection {
  3522. listView.toolMode = .CSelectToolMode
  3523. } else if viewToolsType == .Magnify {
  3524. listView.toolMode = .CMagnifyToolMode
  3525. } else if viewToolsType == .AreaZoom {
  3526. listView.toolMode = .CSelectZoomToolMode
  3527. }
  3528. refreshToolbarViewHeightInfo()
  3529. }
  3530. //MARK: -一级工具栏状态发生变化时调用
  3531. func kmPDFToolbarControllerDidToolModeChanged(_ controller: KMPDFToolbarController) {
  3532. refreshToolbarViewHeightInfo()
  3533. let oldToolMode = listView.toolMode
  3534. toolbarViewModeChanged()
  3535. let newToolMode = listView.toolMode
  3536. if newToolMode == .CEditPDFToolMode || oldToolMode == .CEditPDFToolMode {
  3537. updateUndoRedoState()
  3538. }
  3539. }
  3540. //MARK: -点击工具栏按钮
  3541. func kmPDFToolbarControllerDidToolbarItemClickedEnable(_ controller: KMPDFToolbarController, _ itemIdentifier: String) -> Bool {
  3542. if viewManager.subToolMode == .Edit_Crop && itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
  3543. if rightSideController?.edit_cropController?.cropEnable() == true {
  3544. let alert = NSAlert()
  3545. alert.messageText = KMLocalizedString("There are unapplied settings, do you want to apply them?", comment: "")
  3546. alert.informativeText = KMLocalizedString("If not, the changes will be lost.", comment: "")
  3547. alert.addButton(withTitle: KMLocalizedString("Apply", comment: ""))
  3548. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  3549. let result = alert.runModal()
  3550. if (result == .alertFirstButtonReturn) {
  3551. //Apply
  3552. if let button = self.rightSideController?.edit_cropController?.cropButton {
  3553. self.rightSideController?.edit_cropController?.cropButtonClicked(button)
  3554. }
  3555. } else if (result == .alertSecondButtonReturn) {
  3556. //Cancel
  3557. return true
  3558. }
  3559. return false
  3560. }
  3561. } else if itemIdentifier == KMPDFToolbar_measure_Identifier {
  3562. if KMMemberInfo.shared.isLogin == false {
  3563. KMLoginWindowsController.shared.showWindow(nil)
  3564. return false
  3565. }
  3566. } else if itemIdentifier == KMPDFToolbar_form_text_Identifier ||
  3567. itemIdentifier == KMPDFToolbar_form_checkbox_Identifier ||
  3568. itemIdentifier == KMPDFToolbar_form_radio_Identifier ||
  3569. itemIdentifier == KMPDFToolbar_form_list_Identifier ||
  3570. itemIdentifier == KMPDFToolbar_form_dropdown_Identifier ||
  3571. itemIdentifier == KMPDFToolbar_form_OK_Identifier ||
  3572. itemIdentifier == KMPDFToolbar_form_digitalSign_Identifier {
  3573. if KMMemberInfo.shared.isLogin == false {
  3574. KMLoginWindowsController.shared.showWindow(nil)
  3575. return false
  3576. }
  3577. } else if itemIdentifier == KMPDFToolbar_tools_compare_side_Identifier ||
  3578. itemIdentifier == KMPDFToolbar_tools_compare_Overlay_Identifier {
  3579. if KMMemberInfo.shared.isLogin == false {
  3580. KMLoginWindowsController.shared.showWindow(nil)
  3581. return false
  3582. }
  3583. } else if itemIdentifier == KMPDFToolbar_edit_text_Identifier ||
  3584. itemIdentifier == KMPDFToolbar_edit_image_Identifier{
  3585. if KMMemberInfo.shared.isLogin == false {
  3586. KMLoginWindowsController.shared.showWindow(nil)
  3587. return false
  3588. }
  3589. }
  3590. return true
  3591. }
  3592. func kmPDFToolbarControllerDidToolbarItemClicked(_ controller: KMPDFToolbarController, _ itemIdentifier: String) {
  3593. print("toolbar点击", itemIdentifier)
  3594. if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_PageEdit_Identifier).contains(itemIdentifier) {
  3595. //MARK: -页面编辑
  3596. if itemIdentifier == KMPDFToolbar_PageEdit_InsertFile_Identifier {
  3597. pageEditViewController?.insertFromPDFAction()
  3598. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertBlank_Identifier {
  3599. pageEditViewController?.insertFromBlankAction()
  3600. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertClip_Identifier {
  3601. pageEditViewController?.insertFromClipboardAction()
  3602. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertScanner_Identifier {
  3603. pageEditViewController?.insertFromScannerAction()
  3604. } else if itemIdentifier == KMPDFToolbar_PageEdit_Extract_Identifier {
  3605. pageEditViewController?.extractPDFAction()
  3606. } else if itemIdentifier == KMPDFToolbar_PageEdit_Replace_Identifier {
  3607. pageEditViewController?.replacePDFAction()
  3608. } else if itemIdentifier == KMPDFToolbar_PageEdit_Split_Identifier {
  3609. pageEditViewController?.splitPDFAction()
  3610. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reverse_Identifier {
  3611. pageEditViewController?.reversePDFAction()
  3612. } else if itemIdentifier == KMPDFToolbar_PageEdit_LeftRotate_Identifier {
  3613. pageEditViewController?.rotatePageLeftAction()
  3614. } else if itemIdentifier == KMPDFToolbar_PageEdit_RightRotate_Identifier{
  3615. pageEditViewController?.rotatePageRightAction()
  3616. } else if itemIdentifier == KMPDFToolbar_PageEdit_Delete_Identifier {
  3617. pageEditViewController?.deletePageAction()
  3618. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reduce_Identifier {
  3619. pageEditViewController?.zoomOutPageAction()
  3620. if(pageEditViewController?.canZoomInPageSize() == false) {
  3621. toolbarManager.page_Increase_Property.isDisabled = true
  3622. } else {
  3623. toolbarManager.page_Increase_Property.isDisabled = false
  3624. }
  3625. if(pageEditViewController?.canZoomOutPageSize() == false) {
  3626. toolbarManager.page_Reduce_Property.isDisabled = true
  3627. } else {
  3628. toolbarManager.page_Reduce_Property.isDisabled = false
  3629. }
  3630. controller.refreshSecondToolbarItemsState()
  3631. } else if itemIdentifier == KMPDFToolbar_PageEdit_Increase_Identifier {
  3632. pageEditViewController?.zoomInPageAction()
  3633. if(pageEditViewController?.canZoomInPageSize() == false) {
  3634. toolbarManager.page_Increase_Property.isDisabled = true
  3635. } else {
  3636. toolbarManager.page_Increase_Property.isDisabled = false
  3637. }
  3638. if(pageEditViewController?.canZoomOutPageSize() == false) {
  3639. toolbarManager.page_Reduce_Property.isDisabled = true
  3640. } else {
  3641. toolbarManager.page_Reduce_Property.isDisabled = false
  3642. }
  3643. controller.refreshSecondToolbarItemsState()
  3644. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_oddPage_Identifier {
  3645. pageEditViewController?.thumbnailChoosePageStyle = .odd
  3646. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3647. toolbarManager.page_pageInfo_Property.creatable = false
  3648. controller.refreshSecondToolbarItemsState()
  3649. }
  3650. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_EvenPage_Identifier {
  3651. pageEditViewController?.thumbnailChoosePageStyle = .even
  3652. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3653. toolbarManager.page_pageInfo_Property.creatable = false
  3654. controller.refreshSecondToolbarItemsState()
  3655. }
  3656. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_PortraitPage_Identifier {
  3657. pageEditViewController?.thumbnailChoosePageStyle = .horizontal
  3658. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3659. toolbarManager.page_pageInfo_Property.creatable = false
  3660. controller.refreshSecondToolbarItemsState()
  3661. }
  3662. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_LandscapePage_Identifier {
  3663. pageEditViewController?.thumbnailChoosePageStyle = .vertical
  3664. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3665. toolbarManager.page_pageInfo_Property.creatable = false
  3666. controller.refreshSecondToolbarItemsState()
  3667. }
  3668. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_AllPage_Identifier {
  3669. pageEditViewController?.thumbnailChoosePageStyle = .allPage
  3670. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  3671. toolbarManager.page_pageInfo_Property.creatable = false
  3672. controller.refreshSecondToolbarItemsState()
  3673. }
  3674. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_CustomPage_Identifier {
  3675. pageEditViewController?.thumbnailChoosePageStyle = .custom
  3676. toolbarManager.page_pageInfo_Property.text = nil
  3677. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  3678. toolbarManager.page_pageInfo_Property.creatable = true
  3679. }
  3680. controller.refreshSecondToolbarItemsState()
  3681. }
  3682. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Markup_Identifier).contains(itemIdentifier) {
  3683. //MARK: -Markup
  3684. if itemIdentifier == KMPDFToolbar_eye_Identifier {
  3685. self.showOrHideNotes()
  3686. }
  3687. if viewManager.subToolMode == .None {
  3688. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3689. viewManager.showRightSide = false
  3690. }
  3691. if itemIdentifier == KMPDFToolbar_stamp_Identifier {
  3692. viewManager.showRightSide = false
  3693. } else if itemIdentifier == KMPDFToolbar_sign_Identifier {
  3694. viewManager.showRightSide = false
  3695. }
  3696. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3697. viewManager.showRightSide = true
  3698. } else if viewManager.subToolMode == .Stamp || viewManager.subToolMode == .Sign {
  3699. viewManager.showRightSide = true
  3700. } else if viewManager.subToolMode == .Measure {
  3701. self.showPDFViewToolTip(KMLocalizedString("Double-click to finish drawing. Press ESC to exit continuous measuring mode."))
  3702. }
  3703. self.refreshToolbarRightViewInfo()
  3704. if let currentSelect = listView.currentSelection {
  3705. if(currentSelect.selectionType() == .text) {
  3706. let annotationType: CAnnotationType = KMPDFViewManager.getValidPDFAnnotationType(viewManager.subToolMode)
  3707. if annotationType != .unkown {
  3708. listView.addAnnotation(with: annotationType, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  3709. }
  3710. }
  3711. }
  3712. toolbarViewModeChanged()
  3713. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Edit_Identifier).contains(itemIdentifier) {
  3714. //MARK: -编辑
  3715. if itemIdentifier == KMPDFToolbar_edit_addWatermark_Identifier {
  3716. showWatermarkController()
  3717. } else if itemIdentifier == KMPDFToolbar_edit_removeWatermark_Identifier {
  3718. removePDFWatermark()
  3719. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddWatermark_Identifier {
  3720. batchAddWatermark()
  3721. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveWatermark_Identifier {
  3722. batchRemoveWatermark()
  3723. } else if itemIdentifier == KMPDFToolbar_edit_addBG_Identifier {
  3724. showBackgroundController()
  3725. } else if itemIdentifier == KMPDFToolbar_edit_removeBG_Identifier {
  3726. removePDFBackground()
  3727. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBG_Identifier {
  3728. batchAddBackground()
  3729. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBG_Identifier {
  3730. batchRemoveBackground()
  3731. } else if itemIdentifier == KMPDFToolbar_edit_addHF_Identifier {
  3732. showHeaderFooterController()
  3733. } else if itemIdentifier == KMPDFToolbar_edit_removeHF_Identifier {
  3734. removeHeaderFooter()
  3735. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddHF_Identifier {
  3736. batchAddHeaderFooter()
  3737. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveHF_Identifier {
  3738. batchRemoveHeaderFooter()
  3739. } else if itemIdentifier == KMPDFToolbar_edit_addBates_Identifier {
  3740. showBatesController()
  3741. } else if itemIdentifier == KMPDFToolbar_edit_removeBates_Identifier {
  3742. removePDFBates()
  3743. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBates_Identifier {
  3744. batchAddBates()
  3745. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBates_Identifier {
  3746. batchRemoveBates()
  3747. } else if itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
  3748. showCropController()
  3749. }
  3750. if viewManager.subToolMode == .None {
  3751. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3752. viewManager.showRightSide = false
  3753. }
  3754. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3755. viewManager.showRightSide = true
  3756. }
  3757. self.refreshToolbarRightViewInfo()
  3758. toolbarViewModeChanged()
  3759. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Form_Identifier).contains(itemIdentifier) {
  3760. //MARK: -Form表单
  3761. if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier {
  3762. let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  3763. CPDFAnnotation.updateHighlightFormFiled(listView, highlightFormFiled: !value)
  3764. self.toolbarManager.refreshDefaultConfigItem()
  3765. self.alertTipViewController.reloadFormAlertUI()
  3766. } else if itemIdentifier == KMPDFToolbar_form_ShowName_Identifier {
  3767. listView.showFormFieldName = !listView.showFormFieldName
  3768. if listView.showFormFieldName {
  3769. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  3770. } else {
  3771. toolbarManager.form_ShowName_Property.righticon = nil
  3772. }
  3773. listView.setNeedsDisplayForVisiblePages()
  3774. } else if itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier {
  3775. listView.resetFormAnnotation()
  3776. } else if itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier {
  3777. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  3778. listView.setNeedsDisplayForVisiblePages()
  3779. } else if itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier {
  3780. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  3781. listView.setNeedsDisplayForVisiblePages()
  3782. } else if itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier {
  3783. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  3784. listView.setNeedsDisplayForVisiblePages()
  3785. } else if itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier {
  3786. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  3787. listView.setNeedsDisplayForVisiblePages()
  3788. } else if itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier {
  3789. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  3790. listView.setNeedsDisplayForVisiblePages()
  3791. } else if itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier {
  3792. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  3793. listView.setNeedsDisplayForVisiblePages()
  3794. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier {
  3795. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  3796. listView.setNeedsDisplayForVisiblePages()
  3797. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
  3798. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  3799. listView.setNeedsDisplayForVisiblePages()
  3800. }
  3801. if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier ||
  3802. itemIdentifier == KMPDFToolbar_form_ShowName_Identifier ||
  3803. itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier ||
  3804. itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier ||
  3805. itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier ||
  3806. itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier ||
  3807. itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier ||
  3808. itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier ||
  3809. itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier ||
  3810. itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier ||
  3811. itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
  3812. } else {
  3813. toolbarViewModeChanged()
  3814. }
  3815. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Fill_Identifier).contains(itemIdentifier) {
  3816. //MARK: -填充
  3817. if viewManager.subToolMode == .None {
  3818. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3819. viewManager.showRightSide = false
  3820. }
  3821. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3822. viewManager.showRightSide = true
  3823. }
  3824. self.refreshToolbarRightViewInfo()
  3825. toolbarViewModeChanged()
  3826. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Convert_Identifier).contains(itemIdentifier) {
  3827. //MARK: -转档
  3828. if itemIdentifier == KMPDFToolbar_convert_word_Identifier {
  3829. self.showConvertWindow(.word)
  3830. } else if itemIdentifier == KMPDFToolbar_convert_ppt_Identifier {
  3831. self.showConvertWindow(.ppt)
  3832. } else if itemIdentifier == KMPDFToolbar_convert_RTF_Identifier {
  3833. self.showConvertWindow(.rtf)
  3834. } else if itemIdentifier == KMPDFToolbar_convert_Text_Identifier {
  3835. self.showConvertWindow(.text)
  3836. } else if itemIdentifier == KMPDFToolbar_convert_CSV_Identifier {
  3837. self.showConvertWindow(.csv)
  3838. } else if itemIdentifier == KMPDFToolbar_convert_excel_Identifier {
  3839. self.showConvertWindow(.excel)
  3840. } else if itemIdentifier == KMPDFToolbar_convert_HTML_Identifier {
  3841. self.showConvertWindow(.html)
  3842. } else if itemIdentifier == KMPDFToolbar_convert_Json_Identifier {
  3843. self.showConvertWindow(.json)
  3844. } else if itemIdentifier == KMPDFToolbar_convert_image_Identifier {
  3845. self.showConvertWindow(.jpeg)
  3846. } else if itemIdentifier == KMPDFToolbar_convert_imageToPDF_Identifier {
  3847. self.showBatchWindow(type: .imageToPDF, files: [])
  3848. }
  3849. self.refreshToolbarRightViewInfo()
  3850. toolbarViewModeChanged()
  3851. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Protect_Identifier).contains(itemIdentifier) {
  3852. //MARK: -Protect
  3853. if itemIdentifier == KMPDFToolbar_protect_redact_Identifier {
  3854. toolbarViewModeChanged()
  3855. alertTipViewController.resetRedactSetting()
  3856. if viewManager.showRightSide == true {
  3857. viewManager.showRightSide = false
  3858. pdfToolbarController?.reloadRightToolsView()
  3859. toggleCloseRightSide()
  3860. }
  3861. self.enterRedactAlert()
  3862. } else if itemIdentifier == KMPDFToolbar_protect_redact_Property_Identifier {
  3863. self.showRedactProperty(readactAnnotation: nil)
  3864. toolbarViewModeChanged()
  3865. } else if itemIdentifier == KMPDFToolbar_protect_redact_Apply_Identifier {
  3866. toolbarViewModeChanged()
  3867. self.redactApplyAction(needAlert: false)
  3868. } else if itemIdentifier == KMPDFToolbar_protect_redact_Exit_Identifier {
  3869. toolbarViewModeChanged()
  3870. alertTipViewController.reloadRedactAlertUI()
  3871. alertTipViewController.reloadAlertUIFrame()
  3872. } else if itemIdentifier == KMPDFToolbar_protect_security_Identifier {
  3873. self.showSecureWindow()
  3874. } else if itemIdentifier == KMPDFToolbar_protect_removeSecurity_Identifier {
  3875. self.showRemoveSecureWindow()
  3876. } else if itemIdentifier == KMPDFToolbar_protect_digitalSign_Identifier {
  3877. self.toolbarViewModeChanged()
  3878. }
  3879. alertTipViewController.reloadAlertUIFrame()
  3880. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Tools_Identifier).contains(itemIdentifier) {
  3881. //MARK: -工具
  3882. if itemIdentifier == KMPDFToolbar_tools_compress_Identifier {
  3883. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3884. model.password = listView.document.password ?? ""
  3885. self.showCompressController(model: model)
  3886. } else if itemIdentifier == KMPDFToolbar_tools_batch_compress_Identifier {
  3887. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3888. model.password = listView.document.password ?? ""
  3889. self.showBatchWindow(type: .compress, files: [], fileModels: [model])
  3890. } else if itemIdentifier == KMPDFToolbar_tools_OCR_Identifier {
  3891. self.listView.updateActiveAnnotations([])
  3892. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  3893. if viewManager.subToolMode == .Tool_OCR {
  3894. viewManager.showRightSide = true
  3895. } else {
  3896. viewManager.showRightSide = false
  3897. }
  3898. self.refreshToolbarRightViewInfo()
  3899. } else if itemIdentifier == KMPDFToolbar_tools_merge_Identifier {
  3900. self.showMergeWindow()
  3901. } else if itemIdentifier == KMPDFToolbar_tools_TTS_Identifier {
  3902. self.showTTSWindow()
  3903. } else if itemIdentifier == KMPDFToolbar_tools_extractImage_Identifier {
  3904. self.extractImageAction(num: 2)
  3905. } else if itemIdentifier == KMPDFToolbar_tools_AITools_Identifier {
  3906. self.viewManager.pdfSideBarType = .aiTools
  3907. self.sideBarController?.reloadData()
  3908. if let sideVC = self.sideBarController {
  3909. self.kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  3910. }
  3911. } else if itemIdentifier == KMPDFToolbar_tools_compare_side_Identifier {
  3912. self.beginCompareAction(1)
  3913. } else if itemIdentifier == KMPDFToolbar_tools_compare_Overlay_Identifier {
  3914. self.beginCompareAction(2)
  3915. } else if itemIdentifier == KMPDFToolbar_tools_batch_Identifier {
  3916. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3917. model.password = listView.document.password ?? ""
  3918. self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
  3919. }
  3920. if viewManager.subToolMode == .None {
  3921. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3922. viewManager.showRightSide = false
  3923. }
  3924. } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  3925. viewManager.showRightSide = true
  3926. }
  3927. self.refreshToolbarRightViewInfo()
  3928. toolbarViewModeChanged()
  3929. } else if itemIdentifier == KMPDFToolbar_ViewDisplay_Identifier {
  3930. //MARK: -Display
  3931. updatePDFDisplaySettingView()
  3932. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Right_Identifiers).contains(itemIdentifier) {
  3933. if (itemIdentifier == KMPDFToolbar_undo_Identifier) {
  3934. //MARK: -Undo
  3935. if(listView.isEditing()) {
  3936. if(listView.canEditTextUndo()){
  3937. listView.editTextUndo()
  3938. }
  3939. } else {
  3940. listView.undoManager?.undo()
  3941. self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Undo"))
  3942. self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
  3943. CGRectGetHeight(listView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
  3944. self.componentMessageView.properties.propertyInfo.viewWidth,
  3945. self.componentMessageView.properties.propertyInfo.viewHeight)
  3946. self.componentMessageView.reloadData()
  3947. self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
  3948. }
  3949. } else if(itemIdentifier == KMPDFToolbar_redo_Identifier) {
  3950. //MARK: -Redo
  3951. if(listView.isEditing()) {
  3952. if(listView.canEditTextRedo()) {
  3953. listView.editTextRedo()
  3954. }
  3955. } else {
  3956. listView.undoManager?.redo()
  3957. self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Redo"))
  3958. self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
  3959. CGRectGetHeight(listView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
  3960. self.componentMessageView.properties.propertyInfo.viewWidth,
  3961. self.componentMessageView.properties.propertyInfo.viewHeight)
  3962. self.componentMessageView.reloadData()
  3963. self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
  3964. }
  3965. } else if(itemIdentifier == KMPDFToolbar_fileInfo_Identifier) {
  3966. self.showFileInfo()
  3967. } else if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier ||
  3968. itemIdentifier == KMPDFToolbar_share_Flattened_Identifier ||
  3969. itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  3970. //MARK: -Share
  3971. if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier) {
  3972. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3973. shareDocument(sender: view)
  3974. }
  3975. } else if(itemIdentifier == KMPDFToolbar_share_Flattened_Identifier) {
  3976. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3977. shareFlatten(sender: view)
  3978. }
  3979. } else if(itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  3980. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  3981. shareOriginalPDF(sender: view)
  3982. }
  3983. }
  3984. } else if itemIdentifier == KMPDFToolbar_save_Identifier {
  3985. myDocument?.save(nil)
  3986. } else if itemIdentifier == KMPDFToolbar_print_Identifier {
  3987. self.showPrintWindow()
  3988. } else if itemIdentifier == KMPDFToolbar_tts_Identifier {
  3989. self.showTTSWindow()
  3990. } else if itemIdentifier == KMPDFToolbar_ppt_Identifier {
  3991. self.togglePresentation(nil)
  3992. } else if itemIdentifier == KMPDFToolbar_batch_Identifier {
  3993. let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
  3994. model.password = listView.document.password ?? ""
  3995. self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
  3996. }
  3997. } else if itemIdentifier == KMPDFToolbar_PageEdit_Identifier {
  3998. //MARK: -页面编辑
  3999. if viewManager.isPageEditMode == true {
  4000. enterPageEditMode()
  4001. } else {
  4002. exitPageEditMode()
  4003. }
  4004. } else if itemIdentifier == KMPDFToolbar_rightView_Identifier {
  4005. //MARK: -属性栏
  4006. self.refreshToolbarRightViewInfo()
  4007. } else {
  4008. print("click else")
  4009. }
  4010. refreshToolbarViewHeightInfo()
  4011. refreshRightSide()
  4012. }
  4013. func kmPDFToolbarControllerDidSelectTextDidBeginEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  4014. }
  4015. func kmPDFToolbarControllerDidSelectTextDidChange(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  4016. }
  4017. func kmPDFToolbarControllerDidSelectTextDidEndEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  4018. if view.properties == toolbarManager.page_pageInfo_Property {
  4019. if viewManager.isPageEditMode == true {
  4020. let fileAttribute = KMNFileAttribute()
  4021. fileAttribute.password = listView.document?.password ?? ""
  4022. fileAttribute.pdfDocument = listView.document
  4023. fileAttribute.filePath = listView.document?.documentURL.path ?? ""
  4024. fileAttribute.bAllPage = false
  4025. fileAttribute.pagesType = .PagesString
  4026. fileAttribute.pagesString = view.properties.text ?? ""
  4027. let fetchSelectPages = fileAttribute.fetchSelectPages()
  4028. if (fetchSelectPages.isEmpty) {
  4029. let alert = NSAlert()
  4030. alert.alertStyle = .critical
  4031. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  4032. alert.runModal()
  4033. toolbarManager.page_pageInfo_Property.text = ""
  4034. controller.refreshSecondToolbarItemsState()
  4035. } else {
  4036. var tIndexPaths: Set<IndexPath> = []
  4037. for i in 0 ..< fetchSelectPages.count {
  4038. tIndexPaths.insert(IndexPath(item: (fetchSelectPages[i] - 1), section: 0))
  4039. }
  4040. pageEditViewController?.selectionIndexPaths = tIndexPaths
  4041. }
  4042. }
  4043. }
  4044. }
  4045. func kmPDFToolbarControllerDidExitPageEditMode(_ controller: KMPDFToolbarController) {
  4046. exitPageEditMode()
  4047. }
  4048. }
  4049. //MARK: - KMRightSideControllerDelegate右边属性栏代理
  4050. extension KMMainViewController: KMRightSideControllerDelegate {
  4051. func kmRightSideControllerRotateLeft(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
  4052. CPDFStampAnnotation.rotateLeft(annotations, withPDFView: pdfView)
  4053. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateRight(annotations, withPDFView: pdfView)
  4054. }
  4055. func kmRightSideControllerRotateRight(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
  4056. CPDFStampAnnotation.rotateRight(annotations, withPDFView: pdfView)
  4057. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateLeft(annotations, withPDFView: pdfView)
  4058. }
  4059. func kmRightSideControllerDidContendVCUpdated(_ controller: KMRightSideController) {
  4060. //MARK: -Crop
  4061. if (controller.contentViewController is KMCropPropertyController) {
  4062. if let cropVC = rightSideController?.edit_cropController {
  4063. cropVC.pdfView = controller.pdfView
  4064. if cropVC.delegate == nil {
  4065. cropVC.delegate = cropController
  4066. }
  4067. cropVC.reloadData()
  4068. }
  4069. }
  4070. reloadPopUIWindow()
  4071. }
  4072. func kmRightSideControllerOCRShowTypeChange(_ controller: KMRightSideController, _ type: KMOCRShowType) {
  4073. if type == .area {
  4074. self.listView.toolMode = .COCRToolMode
  4075. self.showOCRToolAlert(KMLocalizedString("Please select the area that needs OCR and click the “OCR” button to start"))
  4076. } else {
  4077. self.listView.toolMode = .CTextToolMode
  4078. }
  4079. }
  4080. func kmRightSideControllerOCRDoneAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
  4081. if model.showType == .area {
  4082. self.convertOCRSaveAsTXT(text: model.text)
  4083. } else {
  4084. if model.saveAsPDF {
  4085. if model.saveType == .PDF {
  4086. } else {
  4087. }
  4088. } else {
  4089. }
  4090. self.convertOCR(document: self.listView.document, model: model)
  4091. }
  4092. }
  4093. func kmRightSideControllerOCRLanguageChangeAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
  4094. self.convertSelectionRectOCR(rect: self.listView.currentSelectionRect())
  4095. }
  4096. //测量设置界面
  4097. func kmRightSideControllerShowMeasureSetting(_ controller: KMRightSideController) {
  4098. showMeasureSettingWindow()
  4099. }
  4100. //裁剪模块
  4101. func kmRightSideControllerDidRevertCropInfo(_ controller: KMRightSideController) {
  4102. if let cropVC = cropController {
  4103. KMCropManager.defaultManager.cropAutoOn = false
  4104. KMCropManager.defaultManager.cropSeparateOn = false
  4105. cropVC.selectionRect = rightSideController?.edit_cropController?.pageBounds ?? CGRectZero
  4106. cropVC.reloadSelectionRect()
  4107. self.kmCropControllerDidChangedSelectionOrMagnification(cropVC)
  4108. }
  4109. }
  4110. }
  4111. //MARK: - KMNDisplayViewControllerDelegate代理
  4112. extension KMMainViewController: KMNDisplayViewControllerDelegate {
  4113. //Display Mode
  4114. func displayViewControllerDidDisplayModeChanged(_ controller: KMNDisplayViewController) {
  4115. listView.layoutDocumentView()
  4116. self.reloadPDFPageNumberToolbar()
  4117. }
  4118. //阅读模式
  4119. func displayViewControllerDidReadModeUpdated(_ controller: KMNDisplayViewController) {
  4120. if viewManager.isPDFReadMode {
  4121. openPDFReadMode()
  4122. } else {
  4123. exitPDFReadMode()
  4124. }
  4125. }
  4126. //PPT
  4127. func displayViewControllerDidGotoSlideShow(_ controller: KMNDisplayViewController) {
  4128. togglePresentation(nil)
  4129. }
  4130. //SplitView
  4131. func displayViewControllerDidSplitModeChanged(_ controller: KMNDisplayViewController) {
  4132. reloadPDFSplitInfo()
  4133. }
  4134. func displayViewControllerDidSplitFileChanged(_ controller: KMNDisplayViewController) {
  4135. splitPDFController?.reloadData()
  4136. }
  4137. func displayViewControllerDidToolbarStateChanged(_ controller: KMNDisplayViewController) {
  4138. splitPDFController?.refreshToolbarState()
  4139. reloadPDFPageNumberToolbar()
  4140. }
  4141. }
  4142. //MARK: - PPT
  4143. extension KMMainViewController: KMInteractionProviderProtocol {
  4144. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  4145. if(interactionMode == .presentation) {
  4146. if listView.presentationDrawView == nil {
  4147. listView.createPresentationDraw()
  4148. }
  4149. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  4150. presentationTopViewController?.pdfView = listView
  4151. presentationTopViewController?.delegate = self
  4152. presentationTopViewController?.isSelectionPre = true
  4153. listView.isPresentationMode = true
  4154. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  4155. if((presentationTopViewController) != nil) {
  4156. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  4157. }
  4158. } else {
  4159. listView.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  4160. }
  4161. fullScreenWindow.contentView?.addSubview(listView)
  4162. if(interactionMode == .presentation) {
  4163. let frame = fullScreenWindow.frame
  4164. listView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-42)
  4165. listView.autoresizingMask = [.width, .maxYMargin]
  4166. }
  4167. return view
  4168. }
  4169. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  4170. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4171. return
  4172. }
  4173. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  4174. if interactionMode == .presentation {
  4175. let backgroundColor = NSColor.black
  4176. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  4177. let wasInteractionMode = self.interactionMode
  4178. if wasInteractionMode == .normal {
  4179. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  4180. }
  4181. if wasInteractionMode == .legacyFullScreen {
  4182. self.enterPresentationMode()
  4183. self.listView.frame = (self.view.window?.contentView?.bounds)!
  4184. self.view.window?.contentView?.addSubview(listView)
  4185. // self.view.window?.backgroundColor = backgroundColor
  4186. self.view.window?.level = level
  4187. self.listView.layoutDocumentView()
  4188. self.listView.requiresDisplay()
  4189. }
  4190. } else {
  4191. KMPrint("2")
  4192. }
  4193. }
  4194. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  4195. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4196. return
  4197. }
  4198. if self.interactionMode == .presentation {
  4199. self.listView.layoutDocumentView()
  4200. self.listView.requiresDisplay()
  4201. }
  4202. }
  4203. @objc func willShowFullScreenNotification(_ sender: Notification) {
  4204. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4205. return
  4206. }
  4207. if self.interactionMode == .presentation {
  4208. let view = self.view.window?.firstResponder as? NSView
  4209. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  4210. self.view.window?.makeFirstResponder(nil)
  4211. }
  4212. }
  4213. }
  4214. @objc func didShowFullScreenNotification(_ sender: Notification) {
  4215. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  4216. return
  4217. }
  4218. if self.interactionMode == .presentation {
  4219. self.enterPresentationMode()
  4220. }
  4221. }
  4222. }
  4223. // MARK: -KMPresentationTopViewControllerDelegate (幻灯片)
  4224. extension KMMainViewController: KMPresentationTopViewControllerDelegate {
  4225. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  4226. self.exitFullScreen()
  4227. }
  4228. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  4229. listView.presentationDrawView?.clear()
  4230. }
  4231. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  4232. let presentationDrawView = listView.presentationDrawView
  4233. if presentationDrawView?.canUndo() == true {
  4234. presentationDrawView?.undo()
  4235. }
  4236. }
  4237. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  4238. listView.isPresentationMode = isSeletion
  4239. if listView.isEnterPresentationDrawMode() == true {
  4240. listView.exitPresentationDrawMode()
  4241. }
  4242. }
  4243. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  4244. if color == nil{
  4245. listView.exitPresentationDrawMode()
  4246. } else {
  4247. if listView.isEnterPresentationDrawMode() == false {
  4248. listView.enterPresentationDrawMode()
  4249. }
  4250. listView.changePresentationDrawModelColor(color)
  4251. }
  4252. }
  4253. }
  4254. //MARK: - KMSplitPDFViewControllerDelegate SplitPDFView分屏视图
  4255. extension KMMainViewController: KMSplitPDFViewControllerDelegate {
  4256. func splitPDFViewControllerDidUpdateFilePath(_ controller: KMSplitPDFViewController) {
  4257. displaySettingController?.reloadData()
  4258. }
  4259. func splitPDFViewControllerDidUpdatePDFScale(_ controller: KMSplitPDFViewController) {
  4260. if let scaleFactor = controller.pdfView?.scaleFactor {
  4261. listView.scaleFactor = scaleFactor
  4262. }
  4263. }
  4264. func splitPDFViewControllerDidUpdatePDFPageIndex(_ controller: KMSplitPDFViewController) {
  4265. if let pageIndex = controller.pdfView?.currentPageIndex {
  4266. listView.go(toPageIndex: pageIndex, animated: false)
  4267. reloadPopUIWindow()
  4268. }
  4269. }
  4270. }
  4271. //MARK: - Edit编辑相关代理
  4272. extension KMMainViewController: KMEditToolbarViewDelegate {
  4273. func kmEditToolbarViewDidPageRangeUpdate(_ view: KMEditToolbarView) {
  4274. let pageInfo = view.pageRangeSelectView.getSelectedPageIndex(listView.document)
  4275. let pageIndex = pageInfo.0
  4276. let isCurrentPage = pageInfo.1
  4277. var pageString: String?
  4278. pageString = view.pageRangeSelectView.getSelectedPageString(listView.document, pageIndex)
  4279. if isCurrentPage {
  4280. pageString = String(format: "%ld", listView.currentPageIndex)
  4281. }
  4282. if pageIndex.isEmpty {
  4283. pageString = nil
  4284. }
  4285. if view.editType == .watermark {
  4286. watermarkViewController?.validPageString = pageString
  4287. watermarkViewController?.loadData()
  4288. } else if view.editType == .background {
  4289. backgroundViewController?.validPageString = pageString
  4290. backgroundViewController?.updatePDFDocumentBackground()
  4291. } else if view.editType == .header_Footer {
  4292. headerFooterViewController?.validPageString = pageString
  4293. headerFooterViewController?.updatePDFDocumentHeaderFooter()
  4294. } else if view.editType == .bates {
  4295. batesViewController?.validPageString = pageString
  4296. batesViewController?.updatePDFDocumentBates()
  4297. }
  4298. }
  4299. func kmEditToolbarViewDidUpdateMode(_ view: KMEditToolbarView) {
  4300. if view.editType == .watermark {
  4301. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  4302. watermarkViewController?.reloadData()
  4303. watermarkViewController?.loadData()
  4304. } else if view.editType == .background {
  4305. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  4306. backgroundViewController?.resetUI()
  4307. backgroundViewController?.reloadData()
  4308. } else if view.editType == .header_Footer {
  4309. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  4310. headerFooterViewController?.resetUI()
  4311. headerFooterViewController?.reloadData()
  4312. } else if view.editType == .bates {
  4313. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  4314. batesViewController?.resetUI()
  4315. batesViewController?.reloadData()
  4316. }
  4317. }
  4318. func kmEditToolbarViewDidChooseBatch(_ view: KMEditToolbarView) {
  4319. if view.editType == .watermark {
  4320. self.showBatchWindow(type: .watermark, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  4321. } else if view.editType == .background {
  4322. self.showBatchWindow(type: .background, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  4323. } else if view.editType == .header_Footer {
  4324. self.showBatchWindow(type: .headerAndFooter, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  4325. } else if view.editType == .bates {
  4326. self.showBatchWindow(type: .batesNumber, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
  4327. }
  4328. }
  4329. func kmEditToolbarViewDidChooseApply(_ view: KMEditToolbarView) {
  4330. let pageInfo = view.pageRangeSelectView.getSelectedPageIndex(listView.document)
  4331. let pageIndex = pageInfo.0
  4332. let isCurrentPage = pageInfo.1
  4333. if pageIndex.isEmpty {
  4334. let alert = NSAlert()
  4335. alert.alertStyle = .critical
  4336. alert.messageText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
  4337. alert.runModal()
  4338. return
  4339. }
  4340. var pageString = view.pageRangeSelectView.getSelectedPageString(listView.document, pageIndex)
  4341. if isCurrentPage {
  4342. pageString = String(format: "%ld", listView.currentPageIndex)
  4343. }
  4344. if view.editType == .watermark {
  4345. if view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4346. propertyVC.showSaveEditChangeAlert(completion: { response in
  4347. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4348. //OK
  4349. propertyVC.saveDataEdit()
  4350. self.applyWatermarkInfo(pageString)
  4351. } else {
  4352. //Cancel
  4353. propertyVC.cancelDataEdit()
  4354. }
  4355. })
  4356. } else {
  4357. self.applyWatermarkInfo(pageString)
  4358. }
  4359. } else if view.editType == .background {
  4360. if view.editSubType == .edit, let propertyVC = backgroundViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4361. propertyVC.showSaveEditChangeAlert(completion: { response in
  4362. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4363. //OK
  4364. propertyVC.saveDataEdit()
  4365. self.applyBackgroundInfo(pageString)
  4366. } else {
  4367. //Cancel
  4368. propertyVC.cancelDataEdit()
  4369. }
  4370. })
  4371. } else {
  4372. self.applyBackgroundInfo(pageString)
  4373. }
  4374. } else if view.editType == .header_Footer {
  4375. if view.editSubType == .edit, let propertyVC = headerFooterViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4376. propertyVC.showSaveEditChangeAlert { response in
  4377. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4378. //OK
  4379. propertyVC.saveDataEdit()
  4380. self.applyHeaderFooterInfo(pageString)
  4381. } else {
  4382. //Cancel
  4383. propertyVC.cancelDataEdit()
  4384. }
  4385. }
  4386. } else {
  4387. self.applyHeaderFooterInfo(pageString)
  4388. }
  4389. } else if view.editType == .bates {
  4390. if view.editSubType == .edit, let propertyVC = batesViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4391. propertyVC.showSaveEditChangeAlert { response in
  4392. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4393. //OK
  4394. propertyVC.saveDataEdit()
  4395. self.applyBatesInfo(pageString)
  4396. } else {
  4397. //Cancel
  4398. propertyVC.cancelDataEdit()
  4399. }
  4400. }
  4401. } else {
  4402. self.applyBatesInfo(pageString)
  4403. }
  4404. }
  4405. }
  4406. func kmEditToolbarViewDidChooseExit(_ view: KMEditToolbarView) {
  4407. //在编辑数据时,先判断是否要保存数据。
  4408. if view.editType == .watermark, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4409. propertyVC.showSaveEditChangeAlert { response in
  4410. DispatchQueue.main.async {
  4411. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4412. //OK
  4413. propertyVC.saveDataEdit()
  4414. self.kmEditToolbarViewDidChooseExit(view)
  4415. } else {
  4416. //Cancel
  4417. propertyVC.cancelDataEdit()
  4418. }
  4419. }
  4420. }
  4421. return
  4422. } else if view.editType == .background, view.editSubType == .edit, let propertyVC = backgroundViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4423. propertyVC.showSaveEditChangeAlert { response in
  4424. DispatchQueue.main.async {
  4425. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4426. //OK
  4427. propertyVC.saveDataEdit()
  4428. self.kmEditToolbarViewDidChooseExit(view)
  4429. } else {
  4430. //Cancel
  4431. propertyVC.cancelDataEdit()
  4432. }
  4433. }
  4434. }
  4435. return
  4436. } else if view.editType == .header_Footer, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4437. propertyVC.showSaveEditChangeAlert { response in
  4438. DispatchQueue.main.async {
  4439. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4440. //OK
  4441. propertyVC.saveDataEdit()
  4442. self.kmEditToolbarViewDidChooseExit(view)
  4443. } else {
  4444. //Cancel
  4445. propertyVC.cancelDataEdit()
  4446. }
  4447. }
  4448. }
  4449. return
  4450. } else if view.editType == .bates, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
  4451. propertyVC.showSaveEditChangeAlert { response in
  4452. DispatchQueue.main.async {
  4453. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  4454. //OK
  4455. propertyVC.saveDataEdit()
  4456. self.kmEditToolbarViewDidChooseExit(view)
  4457. } else {
  4458. //Cancel
  4459. propertyVC.cancelDataEdit()
  4460. }
  4461. }
  4462. }
  4463. return
  4464. }
  4465. if view.applyEnable {
  4466. let alert = NSAlert()
  4467. alert.messageText = KMLocalizedString("If not, the changes will be lost.", comment: "")
  4468. if view.editType == .watermark {
  4469. alert.informativeText = KMLocalizedString("There are unapplied watermark settings, do you want to apply them?", comment: "")
  4470. } else if view.editType == .background {
  4471. alert.informativeText = KMLocalizedString("There are unapplied background settings, do you want to apply them?", comment: "")
  4472. } else if view.editType == .header_Footer {
  4473. alert.informativeText = KMLocalizedString("There are unapplied header&footer settings, do you want to apply them?", comment: "")
  4474. } else if view.editType == .bates {
  4475. alert.informativeText = KMLocalizedString("IThere are unapplied Bates settings, do you want to apply them?", comment: "")
  4476. }
  4477. alert.addButton(withTitle: KMLocalizedString("Apply", comment: ""))
  4478. alert.addButton(withTitle: KMLocalizedString("Don't Apply", comment: ""))
  4479. alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
  4480. let result = alert.runModal()
  4481. if (result == .alertFirstButtonReturn) {
  4482. self.kmEditToolbarViewDidChooseApply(view)
  4483. } else if (result == .alertSecondButtonReturn) {
  4484. //"Don't Apply"
  4485. exitEditToolbarView()
  4486. } else if (result == .alertThirdButtonReturn) {
  4487. //Cancel
  4488. }
  4489. } else {
  4490. exitEditToolbarView()
  4491. }
  4492. }
  4493. func applyWatermarkInfo(_ pageString: String) {
  4494. if KMMemberInfo.shared.isLogin == false {
  4495. KMLoginWindowsController.shared.showWindow(nil)
  4496. return
  4497. }
  4498. if let model = watermarkViewController?.currentWatermarkData {
  4499. let watermark = KMWatermarkModel.returnWaterMarkWith(model, listView.document)
  4500. watermark.pageString = pageString
  4501. listView.document.addWatermark(watermark)
  4502. listView.layoutDocumentView()
  4503. self.recordIsPDFDocumentEdited()
  4504. }
  4505. exitEditToolbarView()
  4506. }
  4507. func applyBackgroundInfo(_ pageString: String) {
  4508. if KMMemberInfo.shared.isLogin == false {
  4509. KMLoginWindowsController.shared.showWindow(nil)
  4510. return
  4511. }
  4512. if let model = backgroundViewController?.backgroundModel {
  4513. if let background = listView.document.background() {
  4514. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  4515. background.pageString = pageString
  4516. background.update()
  4517. listView.document?.refreshPageData()
  4518. listView.layoutDocumentView()
  4519. self.recordIsPDFDocumentEdited()
  4520. }
  4521. }
  4522. exitEditToolbarView()
  4523. }
  4524. func applyHeaderFooterInfo(_ pageString: String) {
  4525. if KMMemberInfo.shared.isLogin == false {
  4526. KMLoginWindowsController.shared.showWindow(nil)
  4527. return
  4528. }
  4529. if let model = headerFooterViewController?.headerFooterModel {
  4530. if let headerFooter = listView.document.headerFooter() {
  4531. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(listView.document.pageCount))
  4532. headerFooter.pageString = pageString
  4533. headerFooter.update()
  4534. listView.document?.refreshPageData()
  4535. listView.layoutDocumentView()
  4536. self.recordIsPDFDocumentEdited()
  4537. }
  4538. }
  4539. exitEditToolbarView()
  4540. }
  4541. func applyBatesInfo(_ pageString: String) {
  4542. if KMMemberInfo.shared.isLogin == false {
  4543. KMLoginWindowsController.shared.showWindow(nil)
  4544. return
  4545. }
  4546. if let model = batesViewController?.batesModel {
  4547. if let bates = listView.document.bates() {
  4548. KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(listView.document.pageCount))
  4549. bates.pageString = pageString
  4550. bates.update()
  4551. listView.document?.refreshPageData()
  4552. listView.layoutDocumentView()
  4553. self.recordIsPDFDocumentEdited()
  4554. }
  4555. }
  4556. exitEditToolbarView()
  4557. }
  4558. }
  4559. //MARK: - KMCropControllerDelegate 裁剪相关代理
  4560. extension KMMainViewController: KMCropControllerDelegate {
  4561. func kmCropControllerDidCrop(_ controller: KMCropController, _ cropRect: CGRect, _ view: KMPageRangeSelectView) {
  4562. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  4563. let indexs = rangeSelectResult.0
  4564. let isCurrentPage = rangeSelectResult.1
  4565. var uIndexs: [UInt] = []
  4566. for index in indexs {
  4567. if index > 0 {
  4568. uIndexs.append(UInt(index-1))
  4569. }
  4570. }
  4571. if isCurrentPage {
  4572. uIndexs = [UInt(listView.currentPageIndex)]
  4573. }
  4574. cropPages(atIndexs: uIndexs, to: [cropRect])
  4575. removeCropController()
  4576. viewManager.subToolMode = .None
  4577. if let toolbarVC = self.pdfToolbarController {
  4578. toolbarVC.refreshSecondToolbarItemsState()
  4579. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  4580. }
  4581. botaViewController?.reloadData()
  4582. botaViewController?.currentPageDidChangedAction(listView: listView)
  4583. }
  4584. func kmCropControllerDidCropSeparate(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  4585. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  4586. let indexs = rangeSelectResult.0
  4587. let isCurrentPage = rangeSelectResult.1
  4588. var rectArray: Array<NSRect> = []
  4589. var uIndexs: [UInt] = []
  4590. for index in indexs {
  4591. if index > 0 {
  4592. uIndexs.append(UInt(index-1))
  4593. let page = self.listView.document.page(at: UInt(index-1))
  4594. let rect = KMCropTools.getPageForegroundBox(page!)
  4595. rectArray.append(rect)
  4596. }
  4597. }
  4598. if isCurrentPage {
  4599. uIndexs = [UInt(listView.currentPageIndex)]
  4600. }
  4601. cropPages(atIndexs: uIndexs, to: rectArray)
  4602. removeCropController()
  4603. viewManager.subToolMode = .None
  4604. if let toolbarVC = self.pdfToolbarController {
  4605. toolbarVC.refreshSecondToolbarItemsState()
  4606. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  4607. }
  4608. }
  4609. func kmCropControllerDidCropAuto(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  4610. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  4611. let indexs = rangeSelectResult.0
  4612. let isCurrentPage = rangeSelectResult.1
  4613. var uIndexs: [UInt] = []
  4614. for index in indexs {
  4615. if index > 0 {
  4616. uIndexs.append(UInt(index-1))
  4617. }
  4618. }
  4619. if isCurrentPage {
  4620. uIndexs = [UInt(listView.currentPageIndex)]
  4621. }
  4622. auto_cropPagesWhiteMargin(uIndexs)
  4623. removeCropController()
  4624. viewManager.subToolMode = .None
  4625. if let toolbarVC = self.pdfToolbarController {
  4626. toolbarVC.refreshSecondToolbarItemsState()
  4627. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  4628. }
  4629. }
  4630. func kmCropControllerDidChangedSelectionOrMagnification(_ controller: KMCropController) {
  4631. if let cropVC = rightSideController?.edit_cropController {
  4632. if cropVC.pdfView != controller.pdfView {
  4633. cropVC.pdfView = controller.pdfView
  4634. }
  4635. cropVC.reloadData()
  4636. rightSideController?.reloadRightButtonState()
  4637. }
  4638. }
  4639. func kmCropControllerDidResetController(_ controller: KMCropController) {
  4640. kmRightSideControllerDidRevertCropInfo(rightSideController ?? KMRightSideController())
  4641. }
  4642. func kmCropControllerDidExitController(_ controller: KMCropController) {
  4643. viewManager.subToolMode = .None
  4644. if let toolbarVC = self.pdfToolbarController {
  4645. toolbarVC.refreshSecondToolbarItemsState()
  4646. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  4647. }
  4648. }
  4649. func kmCropControllerDidApplyController(_ controller: KMCropController) {
  4650. if let button = rightSideController?.edit_cropController?.cropButton {
  4651. rightSideController?.edit_cropController?.cropButtonClicked(button)
  4652. }
  4653. }
  4654. }
  4655. //MARK: - KMWatermarkControllerDelegate 水印相关代理
  4656. extension KMMainViewController: KMWatermarkControllerDelegate {
  4657. func kmWatermarkControllerDidUpdateMode(_ view: KMWatermarkController) {
  4658. editToolbarView?.editSubType = view.editSubType
  4659. editToolbarView?.reloadData()
  4660. }
  4661. func kmWatermarkControllerDidWatermarkUpdated(_ view: KMWatermarkController) {
  4662. editToolbarView?.applyEnable = view.applyEnabled()
  4663. editToolbarView?.reloadData()
  4664. }
  4665. func kmWatermarkControllerDidChooseExit(_ view: KMWatermarkController) {
  4666. if let toolbarView = self.editToolbarView {
  4667. kmEditToolbarViewDidChooseExit(toolbarView)
  4668. }
  4669. }
  4670. func kmWatermarkControllerDidChooseApply(_ view: KMWatermarkController) {
  4671. if let toolbarView = self.editToolbarView {
  4672. kmEditToolbarViewDidChooseApply(toolbarView)
  4673. }
  4674. }
  4675. }
  4676. //MARK: - KMBackgroundControllerDelegate 背景代理
  4677. extension KMMainViewController: KMBackgroundControllerDelegate {
  4678. func kmBackgroundControllerDidUpdateMode(_ view: KMBackgroundController) {
  4679. editToolbarView?.editSubType = view.editSubType
  4680. }
  4681. func kmBackgroundControllerDidBGDataUpdated(_ view: KMBackgroundController) {
  4682. editToolbarView?.applyEnable = view.applyEnabled()
  4683. editToolbarView?.reloadData()
  4684. }
  4685. func kmBackgroundControllerDidChooseExit(_ view: KMBackgroundController) {
  4686. if let toolbarView = self.editToolbarView {
  4687. kmEditToolbarViewDidChooseExit(toolbarView)
  4688. }
  4689. }
  4690. func kmBackgroundControllerDidChooseApply(_ view: KMBackgroundController) {
  4691. if let toolbarView = self.editToolbarView {
  4692. kmEditToolbarViewDidChooseApply(toolbarView)
  4693. }
  4694. }
  4695. }
  4696. //MARK: - KMHeaderFooterControllerDelegate 页眉页脚代理
  4697. extension KMMainViewController: KMHeaderFooterControllerDelegate {
  4698. func kmHeaderFooterControllerDidUpdateModeType(_ view: KMHeaderFooterController) {
  4699. editToolbarView?.editSubType = view.editSubType
  4700. }
  4701. func kmHeaderFooterControllerDidModelDataUpdated(_ view: KMHeaderFooterController) {
  4702. editToolbarView?.applyEnable = view.applyEnabled()
  4703. editToolbarView?.reloadData()
  4704. }
  4705. func kmHeaderFooterControllerDidChooseExit(_ view: KMHeaderFooterController) {
  4706. if let toolbarView = self.editToolbarView {
  4707. kmEditToolbarViewDidChooseExit(toolbarView)
  4708. }
  4709. }
  4710. func kmHeaderFooterControllerDidChooseApply(_ view: KMHeaderFooterController) {
  4711. if let toolbarView = self.editToolbarView {
  4712. kmEditToolbarViewDidChooseApply(toolbarView)
  4713. }
  4714. }
  4715. }
  4716. //MARK: - KMBatesControllerDelegate Bates贝茨码代理
  4717. extension KMMainViewController: KMBatesControllerDelegate {
  4718. func kmBatesControllerDidUpdateMode(_ view: KMBatesController) {
  4719. editToolbarView?.editSubType = view.editSubType
  4720. editToolbarView?.reloadData()
  4721. }
  4722. func kmBatesControllerDidModelDataUpdated(_ view: KMBatesController) {
  4723. editToolbarView?.applyEnable = view.applyEnabled()
  4724. editToolbarView?.reloadData()
  4725. }
  4726. func kmBatesControllerDidChooseExit(_ view: KMBatesController) {
  4727. if let toolbarView = self.editToolbarView {
  4728. kmEditToolbarViewDidChooseExit(toolbarView)
  4729. }
  4730. }
  4731. func kmBatesControllerDidChooseApply(_ view: KMBatesController) {
  4732. if let toolbarView = self.editToolbarView {
  4733. kmEditToolbarViewDidChooseApply(toolbarView)
  4734. }
  4735. }
  4736. }
  4737. //MARK: - CPDFViewDelegate PDFView代理
  4738. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  4739. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  4740. sideBarController?.reloadPageTurnerData()
  4741. documentLoadComplete()
  4742. }
  4743. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  4744. sideBarController?.reloadPageTurnerData()
  4745. botaViewController?.currentPageDidChangedAction(listView: listView)
  4746. //分屏视图
  4747. reloadPDFPageNumberToolbar()
  4748. if viewManager.splitSyncScroll {
  4749. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  4750. splitPDFController?.outPDFFirst = true
  4751. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  4752. var index = pdfView.currentPageIndex
  4753. if index > document.pageCount {
  4754. index = Int(splitPDFView.document.pageCount - 1)
  4755. }
  4756. splitPDFView.go(toPageIndex: index, animated: false)
  4757. }
  4758. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4759. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4760. } else if splitPDFController?.outPDFFirst == true {
  4761. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  4762. var index = pdfView.currentPageIndex
  4763. if index > document.pageCount {
  4764. index = Int(splitPDFView.document.pageCount - 1)
  4765. }
  4766. splitPDFView.go(toPageIndex: index, animated: false)
  4767. }
  4768. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4769. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4770. }
  4771. }
  4772. //水印
  4773. updateEditModeDocumentWhenPageChanged()
  4774. reloadPopUIWindow()
  4775. //
  4776. }
  4777. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  4778. pdfToolbarController?.reloadSelectZoomView()
  4779. reloadPDFPageNumberToolbar()
  4780. reloadPopUIWindow()
  4781. //分屏视图
  4782. if viewManager.splitSyncScroll {
  4783. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  4784. splitPDFController?.outPDFFirst = true
  4785. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4786. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4787. } else if splitPDFController?.outPDFFirst == true {
  4788. if let splitPDFView = splitPDFController?.pdfView {
  4789. splitPDFView.scaleFactor = pdfView.scaleFactor
  4790. }
  4791. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  4792. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  4793. }
  4794. }
  4795. }
  4796. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  4797. if let urlString = url, urlString == Store_Link {
  4798. //跳转订阅比较表
  4799. return
  4800. }
  4801. if url.hasPrefix("smb://") {
  4802. NSWorkspace.shared.openFile(url)
  4803. } else {
  4804. KMTools.openURL(urlString: url)
  4805. }
  4806. }
  4807. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  4808. KMPrint("pdfViewPerformURL")
  4809. if content != nil {
  4810. NSWorkspace.shared.open(URL(string: content)!)
  4811. } else {
  4812. let alert = NSAlert()
  4813. alert.alertStyle = .critical
  4814. alert.informativeText = KMLocalizedString("The hyperlink is invalid.", comment: "")
  4815. alert.messageText = ""
  4816. alert.addButton(withTitle: KMLocalizedString("OK", comment: ""))
  4817. alert.runModal()
  4818. return
  4819. }
  4820. }
  4821. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  4822. KMPrint("pdfViewPerformPrint")
  4823. self.showPrintWindow()
  4824. }
  4825. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  4826. KMPrint("pdfViewPerformGo")
  4827. }
  4828. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  4829. KMPrint("pdfViewOpenPDF")
  4830. }
  4831. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  4832. KMPrint("pdfViewPerformReset")
  4833. pdfView.document?.resetForm()
  4834. }
  4835. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  4836. KMPrint("pdfViewEditingBlockDidChanged")
  4837. }
  4838. func pdfViewAsBookBookmark() -> NSImage! {
  4839. return NSImage(named: "KMImageNameBookmarkIcon")!
  4840. }
  4841. //MARK: -PDFView内容编辑模块
  4842. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  4843. // 文本区块 选中文本已经变化
  4844. reloadPopUIWindow()
  4845. }
  4846. func pdfViewPDFSelectionAttributeDidChanged(_ pdfView: CPDFView!) {
  4847. reloadPopUIWindow()
  4848. }
  4849. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  4850. //编辑模块变化
  4851. rightSideController?.reloadDataWithPDFView(pdfView: (pdfView as! CPDFListView))
  4852. if pdfView is CPDFListView {
  4853. (pdfView as! CPDFListView).isEditImage = false
  4854. }
  4855. if let areas = pdfView.editingAreas(), areas.count > 0 {
  4856. if viewManager.showRightSide == false && SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  4857. viewManager.showRightSide = true
  4858. self.refreshToolbarRightViewInfo()
  4859. }
  4860. } else {
  4861. if viewManager.subToolMode == .None {
  4862. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  4863. viewManager.showRightSide = false
  4864. }
  4865. self.refreshToolbarRightViewInfo()
  4866. }
  4867. }
  4868. reloadPopUIWindow()
  4869. if(groupListMenuGroup?.superview != nil) {
  4870. groupListMenuGroup?.removeGroupView()
  4871. }
  4872. }
  4873. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  4874. if self.listView.cropAreas == nil && editArea != nil && (editArea is CPDFEditImageArea){
  4875. self.listView.cropAreas = editArea as? CPDFEditImageArea
  4876. }
  4877. reloadPopUIWindow()
  4878. }
  4879. //编辑PDF 创建图片区域回调
  4880. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  4881. if (pdfView as! CPDFListView).isEditImage {
  4882. return
  4883. }
  4884. if listView.editingAreas().count > 0 {
  4885. pdfView.updateEditing([])
  4886. return
  4887. }
  4888. let panel = NSOpenPanel()
  4889. panel.allowsMultipleSelection = false
  4890. panel.allowedFileTypes = ["png","jpg"]
  4891. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  4892. if response == .OK {
  4893. var filePath = panel.url?.path
  4894. let image = NSImage.init(contentsOf: panel.url!)
  4895. //图片自适应范围
  4896. if image != nil {
  4897. var imageRect = rect
  4898. let imageSize = image!.size
  4899. var previewSize = rect.size
  4900. var isChangeSize = false
  4901. if previewSize.width == 0 && previewSize.height == 0 {
  4902. previewSize = CGSize(width: 500, height: 500)
  4903. isChangeSize = true
  4904. }
  4905. var scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  4906. if scale < 1 { // 大于 500
  4907. } else {
  4908. let wh = max(imageSize.width, imageSize.height)
  4909. if wh >= 72 {
  4910. scale = min(scale, 1)
  4911. } else {
  4912. scale = min(72 / imageSize.width, 72 / imageSize.height)
  4913. }
  4914. }
  4915. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  4916. if isChangeSize {
  4917. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  4918. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  4919. } else {
  4920. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  4921. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  4922. }
  4923. imageRect.size = newSize
  4924. let limitWidth = 1920.0
  4925. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  4926. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  4927. targetSize: CGSize(width: limitWidth, height: limitWidth),
  4928. maxSizeInBytes: 1024 * 1024 * 5,
  4929. targetCompression: 1.0)
  4930. }
  4931. //自适应page
  4932. let pageRect = self.listView.currentPage().bounds ?? .zero
  4933. if imageRect.width > pageRect.width ||
  4934. imageRect.height > pageRect.height {
  4935. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  4936. imageRect = CGRect(x: imageRect.origin.x,
  4937. y: imageRect.origin.y,
  4938. width: imageRect.width * pageScale,
  4939. height: imageRect.height * pageScale)
  4940. }
  4941. if imageRect.origin.x < 0 {
  4942. imageRect.origin.x = 5
  4943. }
  4944. if imageRect.origin.y < 0 {
  4945. imageRect.origin.y = 5
  4946. }
  4947. if imageRect.origin.x + imageRect.width > pageRect.width ||
  4948. imageRect.origin.y + imageRect.height > pageRect.height {
  4949. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  4950. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  4951. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  4952. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  4953. }
  4954. DispatchQueue.main.async {
  4955. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  4956. }
  4957. }
  4958. }
  4959. }
  4960. }
  4961. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  4962. let areas = self.listView.km_EditingAreas()
  4963. if let area = areas.last {
  4964. if let data = area as? CPDFEditTextArea {
  4965. if let str = data.editTextAreaString(), str.isEmpty {
  4966. self.listView.remove(with: [area])
  4967. } else {
  4968. self.listView.updateEditing([])
  4969. return
  4970. }
  4971. }
  4972. }
  4973. var newRect = rect
  4974. if rect.size.equalTo(.zero) {
  4975. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  4976. } else {
  4977. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  4978. }
  4979. let fontSize = CPDFEditTextArea.defaultFontSize()
  4980. let fontColor = CPDFEditTextArea.defaultColor()
  4981. let fontAlign = CPDFEditTextArea.defaultFontAlignment()
  4982. NSColorPanel.shared.color = fontColor
  4983. let attri = CEditAttributes()
  4984. attri.cFont = CPDFFont(familyName: CPDFEditTextArea.defaultFontName(), fontStyle: CPDFEditTextArea.defaultFontStyle())
  4985. attri.fontColor = fontColor
  4986. attri.alignment = fontAlign
  4987. attri.fontSize = fontSize
  4988. attri.isBold = CPDFEditTextArea.defaultIsBold()
  4989. attri.isItalic = CPDFEditTextArea.defaultIsItality()
  4990. self.listView.createStringBounds(newRect, with: attri, page: page)
  4991. }
  4992. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  4993. rightSideController?.reloadEditingAreas()
  4994. toggleClosePopUIWindow()
  4995. }
  4996. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  4997. rightSideController?.reloadEditingAreas()
  4998. toggleClosePopUIWindow()
  4999. }
  5000. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  5001. rightSideController?.reloadEditingAreas()
  5002. reloadPopUIWindow()
  5003. }
  5004. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  5005. rightSideController?.reloadEditingAreas()
  5006. reloadPopUIWindow()
  5007. }
  5008. func pdfViewEditingExitCropMode(_ pdfView: CPDFView!, forEditing editingArea: CPDFEditImageArea!) {
  5009. rightSideController?.reloadEditingAreas()
  5010. toggleClosePopUIWindow()
  5011. }
  5012. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  5013. let areas = self.listView.km_editingImageAreas()
  5014. self.recordIsPDFDocumentEdited()
  5015. if areas.count == 1 {
  5016. if let data = areas.first as? CPDFEditImageArea {
  5017. let updating = self.listView.editAreaBoundUpdating
  5018. if updating {
  5019. self.listView.editAreaBoundUpdating = false
  5020. }
  5021. }
  5022. }
  5023. updateUndoRedoState()
  5024. }
  5025. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  5026. if(editArea.isImageArea()) {
  5027. listView.cropAction()
  5028. rightSideController?.reloadEditingAreas()
  5029. }
  5030. }
  5031. //MARK: - PDFView键盘事件
  5032. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  5033. let command = theEvent.modifierFlags.contains(.command)
  5034. let control = theEvent.modifierFlags.contains(.control)
  5035. let shift = theEvent.modifierFlags.contains(.shift)
  5036. let option = theEvent.modifierFlags.contains(.option)
  5037. let contentEditOffset = 5.0
  5038. KMPrint(theEvent.keyCode)
  5039. if self.listView.isEditing() == true {
  5040. if control && theEvent.keyCode == 11 { // ctr + b
  5041. self.listView.setEditingTextarea_Bold()
  5042. rightSideController?.reloadEditingAreas()
  5043. return false
  5044. } else if control && theEvent.keyCode == 34 { // ctr +i
  5045. self.listView.setEditingTextarea_Italic()
  5046. rightSideController?.reloadEditingAreas()
  5047. return false
  5048. } else if theEvent.keyCode == 36 { // enter
  5049. if self.listView.isCropMode {
  5050. self.listView.cropComfirmAction()
  5051. rightSideController?.reloadEditingAreas()
  5052. return false
  5053. }
  5054. } else if theEvent.keyCode == 53 { // Cancel
  5055. if self.listView.isCropMode {
  5056. self.listView.cropCancelAction()
  5057. rightSideController?.reloadEditingAreas()
  5058. return false
  5059. }
  5060. } else if option && command && theEvent.keyCode == 8 { // 复制样式
  5061. if self.listView.km_editingTextAreas().count == 1 {
  5062. if listView.isSelecteditAreaNotEdit() {
  5063. listView.copyEditAreaAction()
  5064. }
  5065. return false
  5066. }
  5067. } else if option && command && theEvent.keyCode == 9 { //粘贴样式
  5068. if listView.isSupportPastMatchStyle() {
  5069. listView.pasteEditAreaMatchStyleActionWith(nil)
  5070. }
  5071. return false
  5072. }
  5073. }
  5074. if self.listView.toolMode == .COCRToolMode {
  5075. if theEvent.keyCode == 53 {
  5076. self.listView.selectionRect = NSZeroRect
  5077. self.listView.selectionPageIndex = UInt(NSNotFound)
  5078. self.closePopOperationWindow()
  5079. self.listView.setNeedsDisplayForVisiblePages()
  5080. return false
  5081. } else if theEvent.keyCode == 36 { // enter
  5082. self.convertSelectionRectOCR(rect: self.listView.currentSelectionRect())
  5083. return false
  5084. }
  5085. }
  5086. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  5087. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  5088. return false
  5089. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  5090. return false
  5091. } else if (command && option && theEvent.keyCode == 0) { // command + opt + A [全选注释]
  5092. if(listView.toolMode == .CFormToolMode) {
  5093. selectAllFormAnnotation(currentPage: listView.currentPage())
  5094. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  5095. } else if listView.toolMode == .CNoteToolMode || listView.toolMode == .CTextToolMode || listView.toolMode == .CNoteToolMode {
  5096. selectAllNomerAnnotation(currentPage: listView.currentPage())
  5097. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  5098. } else if listView.toolMode == .CRedactToolMode{
  5099. selectAllRedactAnnotation(currentPage: listView.currentPage())
  5100. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  5101. }
  5102. return false
  5103. } else if (theEvent.keyCode == 123) { // 向左
  5104. if(self.listView.isEditing()) {
  5105. let editingAreas = listView.km_EditingAreas()
  5106. if(editingAreas.count > 0) {
  5107. var isEditSelect = false
  5108. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  5109. isEditSelect = true
  5110. } else {
  5111. let editState = listView.editStatus()
  5112. if (editState == .editSelectText) {// 选择文本
  5113. isEditSelect = true
  5114. }
  5115. }
  5116. if isEditSelect {
  5117. var editingLoction:CEditingLocation = .loadTypePreCharPlace
  5118. if(shift && option) { //上一个字符(opt+shift+左)
  5119. editingLoction = .loadTypePreWord
  5120. } else if (shift && command) {
  5121. editingLoction = CEditingLocation(rawValue: 0)
  5122. } else if (option) {
  5123. editingLoction = .loadTypePreWord
  5124. } else if command {
  5125. editingLoction = CEditingLocation(rawValue: 0)
  5126. }
  5127. for editEdit in editingAreas {
  5128. if let editTextEdit = editEdit as? CPDFEditTextArea {
  5129. listView.jumpEditingLoction(editingLoction, with: editTextEdit, isSelectRanage: false)
  5130. }
  5131. }
  5132. return false
  5133. } else {
  5134. let point = NSPoint(x: -contentEditOffset, y: 0)
  5135. for editEdit in editingAreas {
  5136. listView.move(editEdit, point: point)
  5137. }
  5138. return false
  5139. }
  5140. } else {
  5141. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  5142. self.listView.goToPreviousPage(nil)
  5143. return false
  5144. }
  5145. }
  5146. return false
  5147. } else {
  5148. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  5149. self.listView.goToPreviousPage(nil)
  5150. return false
  5151. }
  5152. }
  5153. } else if (theEvent.keyCode == 126) { // 向上
  5154. if(self.listView.isEditing()) {
  5155. let editingAreas = listView.km_EditingAreas()
  5156. if(editingAreas.count > 0) {
  5157. var isEditSelect = false
  5158. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  5159. isEditSelect = true
  5160. } else {
  5161. let editState = listView.editStatus()
  5162. if (editState == .editSelectText) {// 选择文本
  5163. isEditSelect = true
  5164. }
  5165. }
  5166. if isEditSelect {
  5167. var editingLoction:CEditingLocation = .loadTypeUpCharPlace
  5168. if(command && shift && option) { //文本开头(cmd+opt+shift+上)
  5169. editingLoction = .loadTypeSectionBegin
  5170. } else if (command) { // 跳到行首 (cmd+上)
  5171. if shift {
  5172. } else {
  5173. editingLoction = CEditingLocation(rawValue: 0)
  5174. }
  5175. }
  5176. for editEdit in editingAreas {
  5177. if let editTextEdit = editEdit as? CPDFEditTextArea {
  5178. listView.jumpEditingLoction(editingLoction, with: editTextEdit, isSelectRanage: false)
  5179. }
  5180. }
  5181. return false
  5182. } else {
  5183. let point = NSPoint(x: 0, y: contentEditOffset)
  5184. for editEdit in editingAreas {
  5185. listView.move(editEdit, point: point)
  5186. }
  5187. return false
  5188. }
  5189. } else {
  5190. if (self.listView.isContinousScroll()) {
  5191. return true
  5192. }
  5193. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  5194. self.listView.goToPreviousPage(nil)
  5195. return false
  5196. }
  5197. }
  5198. } else {
  5199. if (self.listView.isContinousScroll()) {
  5200. return true
  5201. }
  5202. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  5203. self.listView.goToPreviousPage(nil)
  5204. return false
  5205. }
  5206. }
  5207. } else if (theEvent.keyCode == 124) { // 向右
  5208. if(self.listView.isEditing()) {
  5209. let editingAreas = listView.km_EditingAreas()
  5210. if(editingAreas.count > 0) {
  5211. var isEditSelect = false
  5212. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  5213. isEditSelect = true
  5214. } else {
  5215. let editState = listView.editStatus()
  5216. if (editState == .editSelectText) {// 选择文本
  5217. isEditSelect = true
  5218. }
  5219. }
  5220. if isEditSelect {
  5221. var editingLoction:CEditingLocation = .loadTypeNextCharPlace
  5222. if(shift && option) { //上一个字符(opt+shift+左)
  5223. editingLoction = .loadTypeNextWord
  5224. } else if (shift && command) {
  5225. editingLoction = .loadTypeLineEnd
  5226. } else if (option) {
  5227. editingLoction = .loadTypeNextWord
  5228. } else if command {
  5229. editingLoction = .loadTypeLineEnd
  5230. }
  5231. for editEdit in editingAreas {
  5232. if let editTextEdit = editEdit as? CPDFEditTextArea {
  5233. listView.jumpEditingLoction(editingLoction, with: editTextEdit, isSelectRanage: false)
  5234. }
  5235. }
  5236. return false
  5237. } else {
  5238. let point = NSPoint(x: contentEditOffset, y: 0)
  5239. for editEdit in editingAreas {
  5240. listView.move(editEdit, point: point)
  5241. }
  5242. return false
  5243. }
  5244. } else {
  5245. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  5246. self.listView.goToNextPage(nil)
  5247. return false
  5248. }
  5249. }
  5250. return false
  5251. } else {
  5252. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  5253. self.listView.goToNextPage(nil)
  5254. return false
  5255. }
  5256. }
  5257. } else if (theEvent.keyCode == 125) { // 向下
  5258. if(self.listView.isEditing()) {
  5259. let editingAreas = listView.km_EditingAreas()
  5260. if(editingAreas.count > 0) {
  5261. var isEditSelect = false
  5262. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  5263. isEditSelect = true
  5264. } else {
  5265. let editState = listView.editStatus()
  5266. if (editState == .editSelectText) {// 选择文本
  5267. isEditSelect = true
  5268. }
  5269. }
  5270. if isEditSelect {
  5271. var editingLoction:CEditingLocation = .loadTypeDownCharPlace
  5272. if(command && shift && option) { //文本末尾(cmd+opt+shift+下)
  5273. editingLoction = .loadTypeSectionEnd
  5274. } else if (command) { // 跳到行尾 (cmd+下)
  5275. if shift {
  5276. } else {
  5277. editingLoction = .loadTypeLineEnd
  5278. }
  5279. }
  5280. for editEdit in editingAreas {
  5281. if let editTextEdit = editEdit as? CPDFEditTextArea {
  5282. listView.jumpEditingLoction(editingLoction, with: editTextEdit, isSelectRanage: false)
  5283. }
  5284. }
  5285. return false
  5286. } else {
  5287. let point = NSPoint(x: 0, y: -contentEditOffset)
  5288. for editEdit in editingAreas {
  5289. listView.move(editEdit, point: point)
  5290. }
  5291. return false
  5292. }
  5293. } else {
  5294. if (self.listView.isContinousScroll()) {
  5295. return true
  5296. } else {
  5297. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  5298. self.listView.goToNextPage(nil)
  5299. return false
  5300. }
  5301. }
  5302. }
  5303. return false
  5304. } else {
  5305. if (self.listView.isContinousScroll()) {
  5306. return true
  5307. }
  5308. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  5309. self.listView.goToNextPage(nil)
  5310. return false
  5311. }
  5312. }
  5313. } else if (theEvent.keyCode == 36) {
  5314. if self.listView.shouAddEditAreaType() == .image || self.listView.shouAddEditAreaType() == .text {
  5315. if self.listView.isEditImage {
  5316. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  5317. }
  5318. } else if command && shift && theEvent.keyCode == 36 {
  5319. //PPT,从头放映
  5320. listView.go(toPageIndex: 0, animated: false)
  5321. togglePresentation(nil)
  5322. } else if command && theEvent.keyCode == 36 {
  5323. //PPT,从当前页放映
  5324. togglePresentation(nil)
  5325. }
  5326. } else if option && theEvent.keyCode == 18 {
  5327. //option + 1
  5328. updatePDFViewToolsType(.Select)
  5329. } else if option && theEvent.keyCode == 19 {
  5330. //option + 2
  5331. updatePDFViewToolsType(.Scroll)
  5332. } else if option && theEvent.keyCode == 20 {
  5333. //option + 3
  5334. updatePDFViewToolsType(.Content_Selection)
  5335. } else if option && theEvent.keyCode == 21 {
  5336. //option + 4
  5337. updatePDFViewToolsType(.Magnify)
  5338. } else if option && theEvent.keyCode == 23 {
  5339. //option + 5
  5340. updatePDFViewToolsType(.AreaZoom)
  5341. } else if theEvent.keyCode == 53 {
  5342. //ESC
  5343. self.exitFullScreen()
  5344. self.toggleClosePopUIWindow()
  5345. if viewManager.isPDFReadMode {
  5346. self.exitPDFReadMode()
  5347. }
  5348. self.leftSideViewCancelSelect()
  5349. } else if theEvent.keyCode == 49 {
  5350. //空格
  5351. if (self.listView.canGoToNextPage()) {
  5352. self.listView.goToNextPage(nil)
  5353. }
  5354. } else if control && command && theEvent.keyCode == 4 {
  5355. //ctrl + com + H
  5356. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.highlightProperty)
  5357. } else if control && command && theEvent.keyCode == 32 {
  5358. //ctrl + com + U
  5359. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.UnderlineProperty)
  5360. } else if control && command && theEvent.keyCode == 9 {
  5361. //ctrl + com + V
  5362. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.wavelineProperty)
  5363. } else if control && command && theEvent.keyCode == 1 {
  5364. //ctrl + com + S
  5365. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.strikethroughProperty)
  5366. } else if control && command && theEvent.keyCode == 17 {
  5367. //ctrl + com + T
  5368. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.textProperty)
  5369. } else if control && command && theEvent.keyCode == 45 {
  5370. //ctrl + com + N
  5371. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.noteProperty)
  5372. } else if control && command && theEvent.keyCode == 35 {
  5373. //ctrl + com + P
  5374. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.penProperty)
  5375. } else if control && command && theEvent.keyCode == 14 {
  5376. //ctrl + com + E
  5377. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.eraserProperty)
  5378. } else if control && command && theEvent.keyCode == 15 {
  5379. //ctrl + com + R
  5380. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.rectangleProperty)
  5381. } else if control && command && theEvent.keyCode == 31 {
  5382. //ctrl + com + O
  5383. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.circleProperty)
  5384. } else if control && command && theEvent.keyCode == 0 {
  5385. //ctrl + com + A
  5386. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.arrowProperty)
  5387. } else if control && command && theEvent.keyCode == 37 {
  5388. //ctrl + com + L
  5389. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.lineProperty)
  5390. } else if control && command && theEvent.keyCode == 43 {
  5391. //ctrl + com + ,
  5392. if viewManager.subToolMode != .Measure {
  5393. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.measureProperty)
  5394. }
  5395. if let measureVC = rightSideController?.contentViewController as? KMMeasureController {
  5396. measureVC.segmentedDidSelected(itemProperty: measureVC.line_Property)
  5397. }
  5398. } else if control && command && theEvent.keyCode == 47 {
  5399. //ctrl + com + .
  5400. if viewManager.subToolMode != .Measure {
  5401. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.measureProperty)
  5402. }
  5403. if let measureVC = rightSideController?.contentViewController as? KMMeasureController {
  5404. measureVC.segmentedDidSelected(itemProperty: measureVC.polygon_Property)
  5405. }
  5406. } else if control && command && theEvent.keyCode == 44 {
  5407. //ctrl + com + /
  5408. if viewManager.subToolMode != .Measure {
  5409. pdfToolbarController?.secondToolBar.buttonClickedWithProperty(toolbarManager.measureProperty)
  5410. }
  5411. if let measureVC = rightSideController?.contentViewController as? KMMeasureController {
  5412. measureVC.segmentedDidSelected(itemProperty: measureVC.rectangle_Property)
  5413. }
  5414. } else if shift && command && theEvent.keyCode == 17 {
  5415. //shift + com + T
  5416. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_text_Identifier)
  5417. } else if shift && command && theEvent.keyCode == 34 {
  5418. //shift + com + I
  5419. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_image_Identifier)
  5420. } else if shift && command && theEvent.keyCode == 37 {
  5421. //shift + com + L
  5422. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_link_Identifier)
  5423. }
  5424. return true
  5425. }
  5426. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  5427. guard let action = menuItem.action else {
  5428. isTakesEffect.pointee = false
  5429. return false
  5430. }
  5431. isTakesEffect.pointee = false
  5432. return false
  5433. }
  5434. //MARK: - CPDFListViewDelegate
  5435. func pdfListViewChangedToolMode(_ pdfListView: CPDFListView!, for toolMode: CToolMode) {
  5436. reloadPopUIWindow()
  5437. }
  5438. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  5439. if(annotationType == .unkown) {
  5440. if viewManager.showRightSide == false {
  5441. toggleCloseRightSide()
  5442. }
  5443. var itemIdentifier = ""
  5444. if viewManager.subToolMode != .None {
  5445. if viewManager.subToolMode == .Stamp || viewManager.subToolMode == .Sign {
  5446. itemIdentifier = "KMPDFToolbar_stamp_Identifier"
  5447. }
  5448. viewManager.subToolMode = .None
  5449. pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
  5450. pdfToolbarController?.refreshSecondToolbarItemsState()
  5451. }
  5452. if viewManager.subToolMode == .None {
  5453. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  5454. viewManager.showRightSide = false
  5455. }
  5456. if itemIdentifier == KMPDFToolbar_stamp_Identifier {
  5457. viewManager.showRightSide = false
  5458. }
  5459. refreshToolbarRightViewInfo()
  5460. }
  5461. cancelMeasureType()
  5462. } else if annotationType == .measureLine ||
  5463. annotationType == .measurePolyLine ||
  5464. annotationType == .measurePolyGon ||
  5465. annotationType == .measureSquare {
  5466. refreshMeasureInfo()
  5467. } else {
  5468. cancelMeasureType()
  5469. }
  5470. }
  5471. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  5472. self.view.window?.makeFirstResponder(self.listView)
  5473. reloadPopUIWindow()
  5474. if isRightMenu {
  5475. } else if annotations.count > 0 {
  5476. if self.viewManager.isPDFReadMode {
  5477. toggleCloseRightSide()
  5478. } else {
  5479. let isMultiAnnotations = pdfListView.isMultiAnnotation(annotations)
  5480. if isMultiAnnotations == true, SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  5481. viewManager.showRightSide = false
  5482. } else {
  5483. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  5484. viewManager.showRightSide = true
  5485. }
  5486. }
  5487. refreshToolbarRightViewInfo()
  5488. }
  5489. } else if (annotations.count == 0){
  5490. if pdfListView.annotationType == .unkown {
  5491. if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
  5492. viewManager.showRightSide = false
  5493. }
  5494. } else {
  5495. if self.viewManager.isPDFReadMode {
  5496. viewManager.showRightSide = false
  5497. } else {
  5498. }
  5499. }
  5500. refreshToolbarRightViewInfo()
  5501. }
  5502. self.refreshMeasureInfo()
  5503. //
  5504. pdfToolbarController?.pdfViewActiveAnnotationsChanged()
  5505. }
  5506. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  5507. toggleClosePopUIWindow()
  5508. self.view.window?.orderFront(nil)
  5509. var pagePoint = CGPoint.zero
  5510. let point = self.view.convert(theEvent.locationInWindow, from: nil)
  5511. let isShowPopUI:Bool = true
  5512. if let page = pdfListView.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  5513. if view.window?.interactionMode == .presentation {
  5514. let menuStruct = clickPresentationMenu(point: pagePoint)
  5515. groupListMenuGroup?.pagePoint = pagePoint
  5516. groupListMenuGroup?.groupDelegate = self
  5517. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  5518. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  5519. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil, withWindow: listView.window)
  5520. } else {
  5521. var menuStringArr: [String] = []
  5522. let activeAnnotations = pdfListView.activeAnnotations as? [CPDFAnnotation]
  5523. if activeAnnotations?.count ?? 0 > 1 {
  5524. var isSameAnnotation = true
  5525. let firstAnnotation = activeAnnotations?.first
  5526. var isContainMark = false
  5527. if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
  5528. isContainMark = true
  5529. }
  5530. for i in 1..<(activeAnnotations?.count ?? 1) {
  5531. //Form 注释不能用这个判断
  5532. if firstAnnotation?.type != activeAnnotations?[i].type {
  5533. isSameAnnotation = false
  5534. }
  5535. if activeAnnotations?[i].isKind(of: CPDFMarkupAnnotation.self) == true {
  5536. isContainMark = true
  5537. }
  5538. }
  5539. if isSameAnnotation {
  5540. if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
  5541. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  5542. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5543. if(isShowPopUI){
  5544. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5545. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5546. }
  5547. } else if firstAnnotation?.isKind(of: CPDFRedactAnnotation.self) == true {
  5548. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5549. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5550. menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
  5551. menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
  5552. } else {
  5553. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5554. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5555. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5556. if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true {
  5557. } else {
  5558. if(isShowPopUI){
  5559. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5560. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5561. }
  5562. }
  5563. }
  5564. if firstAnnotation?.isKind(of: CPDFRedactAnnotation.self) == true {
  5565. } else {
  5566. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5567. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  5568. }
  5569. if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true || firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  5570. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5571. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  5572. }
  5573. } else {
  5574. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5575. if isContainMark == false {
  5576. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5577. }
  5578. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5579. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5580. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  5581. if firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  5582. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  5583. }
  5584. }
  5585. } else if activeAnnotations?.count == 1 {
  5586. let activeAnnotation = pdfListView.activeAnnotation!
  5587. if activeAnnotation.isKind(of: CPDFMarkupAnnotation.self) {
  5588. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  5589. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5590. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5591. menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
  5592. if(isShowPopUI){
  5593. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5594. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5595. }
  5596. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5597. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  5598. } else if activeAnnotation.isKind(of: CPDFRedactAnnotation.self) {
  5599. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5600. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5601. menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
  5602. menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
  5603. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5604. menuStringArr.append(PDFViewMenuIdentifier_Normal_RedactProperties)
  5605. menuStringArr.append(PDFViewMenuIdentifier_Redact_Default)
  5606. } else if activeAnnotation.isKind(of: CPDFLinkAnnotation.self) {
  5607. let link = activeAnnotation as? CPDFLinkAnnotation
  5608. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5609. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5610. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5611. if(isShowPopUI){
  5612. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5613. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5614. }
  5615. } else {
  5616. if activeAnnotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
  5617. let signatureWidgetAnnotation = activeAnnotation as? CPDFSignatureWidgetAnnotation
  5618. if(signatureWidgetAnnotation?.isSigned() == true) {
  5619. return
  5620. }
  5621. }
  5622. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5623. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5624. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5625. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5626. if activeAnnotation.isKind(of: CPDFTextAnnotation.self) ||
  5627. activeAnnotation.isKind(of: CPDFFreeTextAnnotation.self) ||
  5628. activeAnnotation.isKind(of: CSelfSignAnnotation.self) ||
  5629. activeAnnotation.isKind(of: CPDFWidgetAnnotation.self) {
  5630. } else {
  5631. menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
  5632. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5633. }
  5634. if(isShowPopUI){
  5635. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5636. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5637. }
  5638. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  5639. }
  5640. } else {
  5641. let currentSelection = pdfListView.currentSelection
  5642. if currentSelection != nil {
  5643. if currentSelection?.selectionType() == .text && pdfListView == self.listView {
  5644. #if VERSION_BETA
  5645. #else
  5646. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  5647. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5648. #endif
  5649. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5650. if pdfListView.canPaste() {
  5651. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  5652. }
  5653. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5654. menuStringArr.append(PDFViewMenuIdentifier_Normal_Hight)
  5655. menuStringArr.append(PDFViewMenuIdentifier_Normal_Underline)
  5656. menuStringArr.append(PDFViewMenuIdentifier_Normal_StrikeOut)
  5657. menuStringArr.append(PDFViewMenuIdentifier_Normal_Squiggly)
  5658. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  5659. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  5660. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5661. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddOutLine)
  5662. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  5663. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5664. menuStringArr.append(PDFViewMenuIdentifier_Normal_TTS)
  5665. menuStringArr.append(PDFViewMenuIdentifier_Normal_SearchText)
  5666. } else if currentSelection?.selectionType() == .image && pdfListView == self.listView {
  5667. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5668. if pdfListView.canPaste() {
  5669. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  5670. }
  5671. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5672. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  5673. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5674. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  5675. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  5676. }
  5677. } else {
  5678. if(pdfListView == self.listView) {
  5679. if pdfListView.toolMode == .CFormToolMode {
  5680. if pdfListView.canPaste() {
  5681. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  5682. }
  5683. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5684. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllForm)
  5685. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5686. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  5687. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowFormName)
  5688. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  5689. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5690. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  5691. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5692. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  5693. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5694. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  5695. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5696. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  5697. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5698. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  5699. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5700. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  5701. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5702. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  5703. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  5704. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  5705. } else if pdfListView.toolMode == .CRedactToolMode {
  5706. } else {
  5707. if(listView.viewSplitMode != .disable) {
  5708. menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
  5709. menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
  5710. menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
  5711. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5712. } else {
  5713. #if VERSION_BETA
  5714. #else
  5715. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  5716. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5717. #endif
  5718. if pdfListView == listView {
  5719. if pdfListView.canPaste() {
  5720. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  5721. }
  5722. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
  5723. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllAnnotation)
  5724. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5725. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowAnnotation)
  5726. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5727. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  5728. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5729. }
  5730. }
  5731. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  5732. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5733. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  5734. if(listView.viewSplitMode != .disable) {
  5735. } else {
  5736. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  5737. }
  5738. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5739. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  5740. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5741. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  5742. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5743. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  5744. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5745. menuStringArr.append(PDFViewMenuIdentifier_Normal_AutoScroll)
  5746. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5747. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  5748. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  5749. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  5750. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5751. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  5752. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  5753. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  5754. }
  5755. }
  5756. }
  5757. }
  5758. if(menuStringArr.count > 0) {
  5759. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  5760. groupListMenuGroup?.pagePoint = pagePoint
  5761. groupListMenuGroup?.groupDelegate = self
  5762. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  5763. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  5764. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil, withWindow: self.view.window)
  5765. }
  5766. }
  5767. } else {
  5768. if(pdfListView == self.listView) {
  5769. var menuStringArr: [String] = []
  5770. if(listView.viewSplitMode != .disable) {
  5771. menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
  5772. menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
  5773. menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
  5774. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5775. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  5776. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5777. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  5778. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5779. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  5780. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  5781. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  5782. } else {
  5783. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  5784. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  5785. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5786. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  5787. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5788. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  5789. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  5790. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  5791. }
  5792. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  5793. groupListMenuGroup?.pagePoint = pagePoint
  5794. groupListMenuGroup?.groupDelegate = self
  5795. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  5796. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  5797. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil, withWindow: self.view.window)
  5798. }
  5799. }
  5800. }
  5801. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  5802. toggleClosePopUIWindow()
  5803. var windowPoint = listView.convert(point, from: page)
  5804. let view: NSView? = nil
  5805. windowPoint = listView.convert(windowPoint, to: view)
  5806. if self.view.window?.interactionMode == .presentation {
  5807. let menuStruct = clickPresentationMenu(point: point)
  5808. groupListMenuGroup?.pagePoint = point
  5809. groupListMenuGroup?.groupDelegate = self
  5810. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  5811. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  5812. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: nil, withWindow: listView.window)
  5813. } else {
  5814. let isShowPopUI:Bool = true
  5815. var menuStringArr: [String] = []
  5816. let editingAreas = listView.km_EditingAreas()
  5817. let firstEditingArea = editingAreas.first
  5818. if editingAreas.count > 1 {
  5819. var isSameEditingArea = true
  5820. if(firstEditingArea?.isTextArea() == true) {
  5821. for i in 1..<(editingAreas.count) {
  5822. if !editingAreas[i].isTextArea() {
  5823. isSameEditingArea = false
  5824. break
  5825. }
  5826. }
  5827. } else if (firstEditingArea?.isImageArea() == true) {
  5828. for i in 1..<(editingAreas.count) {
  5829. if !editingAreas[i].isImageArea() {
  5830. isSameEditingArea = false
  5831. break
  5832. }
  5833. }
  5834. }
  5835. if(isSameEditingArea) {
  5836. if (firstEditingArea?.isTextArea() == true) {
  5837. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5838. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5839. if listView.isSupportPastMatchStyle() {
  5840. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  5841. }
  5842. if listView.isSupportPast() {
  5843. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  5844. }
  5845. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5846. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5847. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  5848. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  5849. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  5850. if(isShowPopUI){
  5851. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5852. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5853. }
  5854. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5855. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  5856. } else if (firstEditingArea?.isImageArea() == true) {
  5857. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5858. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5859. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5860. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5861. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  5862. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  5863. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  5864. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  5865. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5866. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  5867. if(isShowPopUI){
  5868. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5869. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5870. }
  5871. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5872. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  5873. }
  5874. } else {
  5875. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5876. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5877. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5878. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5879. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  5880. }
  5881. } else if editingAreas.count == 1 {
  5882. if firstEditingArea?.isTextArea() == true {
  5883. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  5884. if listView.isSupportPast() {
  5885. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  5886. }
  5887. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  5888. } else {
  5889. let editState = listView.editStatus()
  5890. if (editState == .editSelectText) {// 选择文本
  5891. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5892. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5893. if listView.isSupportPast() {
  5894. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  5895. }
  5896. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  5897. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5898. } else {
  5899. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5900. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5901. if listView.isSupportPastMatchStyle() {
  5902. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  5903. }
  5904. if listView.isSupportPast() {
  5905. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  5906. }
  5907. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  5908. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5909. }
  5910. }
  5911. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5912. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  5913. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  5914. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  5915. if(isShowPopUI){
  5916. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5917. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5918. }
  5919. } else if firstEditingArea?.isImageArea() == true {
  5920. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  5921. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  5922. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  5923. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5924. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  5925. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  5926. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  5927. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  5928. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5929. menuStringArr.append(PDFViewMenuIdentifier_Edit_Crop)
  5930. menuStringArr.append(PDFViewMenuIdentifier_Edit_Replace)
  5931. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  5932. if(isShowPopUI){
  5933. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5934. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  5935. }
  5936. }
  5937. } else {
  5938. if(listView.isSupportPast()) {
  5939. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  5940. }
  5941. if(listView.isSupportPastMatchStyle()) {
  5942. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  5943. }
  5944. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  5945. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5946. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddText)
  5947. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddImage)
  5948. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddLink)
  5949. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5950. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  5951. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5952. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  5953. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5954. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  5955. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5956. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  5957. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5958. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  5959. menuStringArr.append(PDFViewMenuIdentifier_Space)
  5960. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  5961. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  5962. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  5963. }
  5964. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: nil, listView: listView)
  5965. groupListMenuGroup?.pagePoint = point
  5966. groupListMenuGroup?.groupDelegate = self
  5967. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  5968. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  5969. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: nil, withWindow: listView.window)
  5970. }
  5971. return []
  5972. }
  5973. func pdfListViewMobileAnnotationBegan(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  5974. toggleClosePopUIWindow()
  5975. }
  5976. func pdfListViewMobileAnnotationMove(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  5977. toggleClosePopUIWindow()
  5978. }
  5979. func pdfListViewMobileAnnotationEnd(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  5980. reloadPopUIWindow()
  5981. }
  5982. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  5983. var pageIndexes = IndexSet()
  5984. pageIndexes.insert(Int(pdfPage.pageIndex()))
  5985. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  5986. botaViewController?.reloadData()
  5987. var isContainsForm = false
  5988. for annotation in annotations {
  5989. if annotation is CPDFWidgetAnnotation {
  5990. isContainsForm = true
  5991. break
  5992. }
  5993. }
  5994. if(isContainsForm == true) {
  5995. alertTipViewController.resetFormSetting()
  5996. }
  5997. alertTipViewController.reloadFormAlertUI()
  5998. alertTipViewController.reloadDigitalAlertUI()
  5999. alertTipViewController.reloadAlertUIFrame()
  6000. //标记密文
  6001. if self.listView.toolMode == .CRedactToolMode {
  6002. self.pdfToolbarController?.redactToolbar.applyButton.properties.isDisabled = !self.isExistRedactAnnotation()
  6003. self.pdfToolbarController?.redactToolbar.applyButton.reloadData()
  6004. }
  6005. }
  6006. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  6007. var pageIndexes = IndexSet()
  6008. pageIndexes.insert(Int(pdfPage.pageIndex()))
  6009. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
  6010. botaViewController?.reloadData()
  6011. alertTipViewController.reloadFormAlertUI()
  6012. alertTipViewController.reloadAlertUIFrame()
  6013. if(groupListMenuGroup?.superview != nil) {
  6014. groupListMenuGroup?.removeGroupView()
  6015. }
  6016. //标记密文
  6017. if self.listView.toolMode == .CRedactToolMode {
  6018. self.pdfToolbarController?.redactToolbar.applyButton.properties.isDisabled = !self.isExistRedactAnnotation()
  6019. self.pdfToolbarController?.redactToolbar.applyButton.reloadData()
  6020. }
  6021. }
  6022. func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  6023. if anotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
  6024. if let signatureWidgetAnnotation = anotation as? CPDFSignatureWidgetAnnotation {
  6025. let signature = signatureWidgetAnnotation.signature()
  6026. if ((signature) != nil) {
  6027. popUpSignatureWidgetState(signature!, listView)
  6028. } else {
  6029. let widget = CPDFSignatureWidgetAnnotation.init(PDFListViewNoteWith: listView.document)
  6030. widget.bounds = NSMakeRect(-1000, -1000, 545, 178);
  6031. anotation.page.addAnnotation(widget)
  6032. let configWindowVC = DSignatureConfigWindowController.init(windowNibName: "DSignatureConfigWindowController")
  6033. configWindowVC.viewType = .fileList;
  6034. configWindowVC.appearanceWidget = widget;
  6035. configWindowVC.isCreatDS = false
  6036. configWindowVC.complentionHandle = {[weak self] isSign, dic, config, isLock in
  6037. widget.page.removeAnnotation(widget)
  6038. if isSign {
  6039. if (dic.object(forKey: SAVEFILEPATH_KEY) != nil) {
  6040. let p12Path = dic.object(forKey: SAVEFILEPATH_KEY) as! String
  6041. let password = dic.object(forKey: PASSWORD_KEY)
  6042. if p12Path.count > 0 {
  6043. self?.writeSignatureToWidget(signatureWidgetAnnotation, p12Path, password as! String, config, isLock)
  6044. }
  6045. }
  6046. } else {
  6047. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  6048. self?.listView.remove(anotation)
  6049. }
  6050. }
  6051. }
  6052. configWindowVC.actionBlock = {[weak self] controller, type in
  6053. if (type == .cancel) {
  6054. NSApplication.shared.stopModal()
  6055. controller.window?.orderOut(nil)
  6056. controller.window?.close()
  6057. widget.page.removeAnnotation(widget)
  6058. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  6059. self?.listView.remove(anotation)
  6060. } else {
  6061. self?.listView.setNeedsDisplayAnnotationViewFor(anotation.page)
  6062. }
  6063. } else if (type == .confirm) {
  6064. NSApplication.shared.stopModal()
  6065. controller.window?.orderOut(nil)
  6066. controller.window?.close()
  6067. }
  6068. }
  6069. configWindowVC.window?.center()
  6070. NSApplication.shared.runModal(for: configWindowVC.window!)
  6071. }
  6072. }
  6073. } else if anotation.isKind(of: CPDFRedactAnnotation.self) {
  6074. if let redactAnnotation = anotation as? CPDFRedactAnnotation {
  6075. let properties = KMRedactPropertiesWindowController()
  6076. properties.readactAnnotation = redactAnnotation
  6077. properties.own_beginSheetModal(for: self.view.window) { result in
  6078. }
  6079. properties.callback = { [weak self] annotation in
  6080. if let page = annotation?.page {
  6081. self?.listView.setNeedsDisplayAnnotationViewFor(page)
  6082. }
  6083. }
  6084. }
  6085. }
  6086. }
  6087. func pdfListViewSplitModeShowBar() -> Bool {
  6088. return viewManager.splitShowBottomBar
  6089. }
  6090. func pdfListViewSyncSplitView() -> Bool {
  6091. return viewManager.splitSyncScroll
  6092. }
  6093. func pdfListViewEndEditMode(_ pdfListView: CPDFListView!) {
  6094. let document = listView.document
  6095. if(document != nil) {
  6096. for i in 0..<document!.pageCount {
  6097. let thumbnail = KMNThumbnail.init(document: document!, currentPageIndex: Int(i))
  6098. thumbnail.removeCacheImage()
  6099. }
  6100. }
  6101. botaViewController?.reloadData()
  6102. }
  6103. func pdfListViewAddEditAreaTypeChanged(_ pdfListView: CPDFListView!) {
  6104. if self.listView.shouAddEditAreaType() != .text && self.listView.shouAddEditAreaType() != .image {
  6105. if viewManager.subToolMode != .None {
  6106. viewManager.subToolMode = .None
  6107. pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
  6108. pdfToolbarController?.refreshSecondToolbarItemsState()
  6109. }
  6110. }
  6111. }
  6112. //MARK: -Crop
  6113. func pdfListViewChangedSelectionOrMagnification(_ pdfListView: CPDFListView!) {
  6114. reloadPopUIWindow()
  6115. }
  6116. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  6117. if (!self.listView.isEqual(to: pdfListView)) {
  6118. return
  6119. }
  6120. if (self.listView.toolMode != .CSelectToolMode) {
  6121. return
  6122. }
  6123. reloadPopUIWindow()
  6124. }
  6125. func pdfListViewHaveDocumentAttribute() -> Bool {
  6126. if(!self.listView.document.allowsCopying) {
  6127. self.removeOwnerPassword()
  6128. return false
  6129. }
  6130. return true
  6131. }
  6132. func pdfListViewShowTipView() -> Bool {
  6133. let popWindow = KMNAnnotationPopToolbarWindow.shared
  6134. if popWindow.isVisible == true {
  6135. return true
  6136. }
  6137. return false
  6138. }
  6139. func pdfListViewIsSupportSelecton(_ theEvent: NSEvent!, mouseType: KMPDFViewMouseType) -> Bool {
  6140. let subToolMode = viewManager.subToolMode
  6141. if subToolMode == .Tool_OCR {
  6142. if (rightSideController?.tool_OCRController?.model.showType == .area) {
  6143. if(mouseType == .down) {
  6144. return true;
  6145. }
  6146. }
  6147. return false
  6148. }
  6149. return true
  6150. }
  6151. func pdfListViewAnnotationEditModeChange(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  6152. reloadPopUIWindow()
  6153. }
  6154. func pdfListViewAnnotationChange(_ color: NSColor!, forActiveAnnotation annotation: CPDFAnnotation!) {
  6155. rightSideController?.reloadData()
  6156. NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
  6157. }
  6158. //MARK: - 测量Measure
  6159. func pdfListViewAnnotationMeasureInfoChange(_ pdfListView: CPDFListView!, with annotation: CPDFAnnotation!) {
  6160. guard let _ = annotation else {
  6161. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  6162. distanceMeasureInfoWindowController?.clearData()
  6163. }
  6164. return
  6165. }
  6166. if let lineAnnotation = annotation as? CPDFLineAnnotation {
  6167. handleLineAnnotation(lineAnnotation)
  6168. } else if let polylineAnnotation = annotation as? CPDFPolylineAnnotation {
  6169. handlePolylineAnnotation(polylineAnnotation)
  6170. } else if let polygonAnnotation = annotation as? CPDFPolygonAnnotation {
  6171. handlePolygonAnnotation(polygonAnnotation)
  6172. }
  6173. reloadPopUIWindow()
  6174. }
  6175. func pdfListViewMeasureCancel(_ pdfListView: CPDFListView!) {
  6176. cancelMeasureType()
  6177. }
  6178. func pdfListViewInkAnnotationInfoChanged(_ pdfListView: CPDFListView!) {
  6179. self.rightSideController?.reloadData()
  6180. }
  6181. private func handleLineAnnotation(_ annotation: CPDFLineAnnotation) {
  6182. if let window = perimeterMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6183. self.view.window?.removeChildWindow(window)
  6184. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  6185. }
  6186. if let window = areaMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6187. self.view.window?.removeChildWindow(window)
  6188. areaMeasureInfoWindowController?.hideFloatingWindow()
  6189. }
  6190. if let window = distanceMeasureInfoWindowController?.window {
  6191. self.view.window?.addChildWindow(window, ordered: .above)
  6192. let selfRect = self.view.window!.frame
  6193. var rect = window.frame
  6194. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6195. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6196. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6197. }
  6198. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6199. window.setFrame(rect, display: true)
  6200. }
  6201. if let measureInfo = annotation.measureInfo {
  6202. let startPoint = annotation.startPoint
  6203. let endPoint = annotation.endPoint
  6204. let angle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) * (180.0 / .pi)
  6205. distanceMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  6206. distanceMeasureInfoWindowController?.xLabel.stringValue = String(format: "%.0f", abs(endPoint.x - startPoint.x))
  6207. distanceMeasureInfoWindowController?.yLabel.stringValue = String(format: "%.0f", abs(endPoint.y - startPoint.y))
  6208. distanceMeasureInfoWindowController?.reloadData(with: measureInfo)
  6209. }
  6210. }
  6211. private func handlePolylineAnnotation(_ annotation: CPDFPolylineAnnotation) {
  6212. if let window = distanceMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6213. self.view.window?.removeChildWindow(window)
  6214. distanceMeasureInfoWindowController?.hideFloatingWindow()
  6215. }
  6216. if let window = areaMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6217. self.view.window?.removeChildWindow(window)
  6218. areaMeasureInfoWindowController?.hideFloatingWindow()
  6219. }
  6220. if let window = perimeterMeasureInfoWindowController?.window {
  6221. self.view.window?.addChildWindow(window, ordered: .above)
  6222. let selfRect = self.view.window!.frame
  6223. var rect = window.frame
  6224. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6225. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6226. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6227. }
  6228. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6229. window.setFrame(rect, display: true)
  6230. }
  6231. if let measureInfo = annotation.measureInfo {
  6232. let savePoints = annotation.savePoints
  6233. var angle: CGFloat = 0
  6234. if savePoints.count >= 3 {
  6235. let count = savePoints.count
  6236. let startPoint = (savePoints[count - 3] as AnyObject).pointValue
  6237. let midPoint = (savePoints[count - 2] as AnyObject).pointValue
  6238. let endPoint = (savePoints.last! as AnyObject).pointValue
  6239. angle = angleBetweenPoints(startPoint ?? CGPointZero, midPoint ?? CGPointZero, endPoint ?? CGPointZero)
  6240. }
  6241. angle = 180 - angle
  6242. perimeterMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  6243. perimeterMeasureInfoWindowController?.reloadData(with: measureInfo)
  6244. }
  6245. }
  6246. private func handlePolygonAnnotation(_ annotation: CPDFPolygonAnnotation) {
  6247. if let window = distanceMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6248. self.view.window?.removeChildWindow(window)
  6249. distanceMeasureInfoWindowController?.hideFloatingWindow()
  6250. }
  6251. if let window = perimeterMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6252. self.view.window?.removeChildWindow(window)
  6253. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  6254. }
  6255. if let window = areaMeasureInfoWindowController?.window {
  6256. self.view.window?.addChildWindow(window, ordered: .above)
  6257. let selfRect = self.view.window!.frame
  6258. var rect = window.frame
  6259. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6260. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6261. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6262. }
  6263. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6264. window.setFrame(rect, display: true)
  6265. }
  6266. if let measureInfo = annotation.measureInfo {
  6267. let savePoints = annotation.savePoints
  6268. var angle: CGFloat = 0
  6269. if savePoints.count >= 3 {
  6270. let count = savePoints.count
  6271. let startPoint = (savePoints[count - 3] as AnyObject).pointValue
  6272. let midPoint = (savePoints[count - 2] as AnyObject).pointValue
  6273. let endPoint = (savePoints.last as AnyObject).pointValue
  6274. angle = angleBetweenPoints(startPoint!, midPoint!, endPoint!)
  6275. }
  6276. angle = 180 - angle
  6277. areaMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  6278. areaMeasureInfoWindowController?.reloadData(measureInfo)
  6279. }
  6280. }
  6281. func refreshMeasureInfo() {
  6282. if distanceMeasureInfoWindowController == nil {
  6283. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  6284. }
  6285. if perimeterMeasureInfoWindowController == nil {
  6286. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  6287. }
  6288. if areaMeasureInfoWindowController == nil {
  6289. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  6290. }
  6291. showMeasureFloatingWindowsIfNeed()
  6292. }
  6293. @objc func cancelMeasureType() {
  6294. self.hideMeasureFloatingWindows()
  6295. }
  6296. func hideMeasureFloatingWindows() {
  6297. if let window = distanceMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6298. distanceMeasureInfoWindowController?.hideFloatingWindow()
  6299. self.view.window?.removeChildWindow(window)
  6300. }
  6301. if let window = perimeterMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6302. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  6303. self.view.window?.removeChildWindow(window)
  6304. }
  6305. if let window = areaMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6306. areaMeasureInfoWindowController?.hideFloatingWindow()
  6307. self.view.window?.removeChildWindow(window)
  6308. }
  6309. }
  6310. func showMeasureFloatingWindowsIfNeed() {
  6311. cancelMeasureType()
  6312. let toolMode = self.listView.toolMode
  6313. if toolMode != .CNoteToolMode {
  6314. return
  6315. }
  6316. if let _ = self.listView.activeAnnotation as? CPDFPolylineAnnotation {
  6317. } else if let _ = self.listView.activeAnnotation as? CPDFPolygonAnnotation {
  6318. } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
  6319. } else {
  6320. let type = self.listView.annotationType
  6321. if type == .measureLine {
  6322. distanceMeasureInfoWindowController?.measureInfo = listView.distanceMeasureInfo
  6323. if let window = distanceMeasureInfoWindowController?.window {
  6324. self.view.window?.addChildWindow(window, ordered: .above)
  6325. let selfRect = self.view.window!.frame
  6326. var rect = window.frame
  6327. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6328. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6329. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6330. }
  6331. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6332. window.setFrame(rect, display: true)
  6333. }
  6334. } else if type == .measurePolyLine {
  6335. perimeterMeasureInfoWindowController?.measureInfo = listView.perimeterMeasureInfo
  6336. if let window = perimeterMeasureInfoWindowController?.window {
  6337. self.view.window?.addChildWindow(window, ordered: .above)
  6338. let selfRect = self.view.window!.frame
  6339. var rect = window.frame
  6340. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6341. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6342. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6343. }
  6344. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6345. window.setFrame(rect, display: true)
  6346. }
  6347. } else if type == .measurePolyGon {
  6348. areaMeasureInfoWindowController?.measureInfo = listView.polygonAreaMeasureInfo
  6349. if let window = areaMeasureInfoWindowController?.window {
  6350. self.view.window?.addChildWindow(window, ordered: .above)
  6351. let selfRect = self.view.window!.frame
  6352. var rect = window.frame
  6353. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6354. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6355. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6356. }
  6357. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6358. window.setFrame(rect, display: true)
  6359. }
  6360. } else if type == .measureSquare {
  6361. areaMeasureInfoWindowController?.measureInfo = listView.squareAreaMeasureInfo
  6362. areaMeasureInfoWindowController?.measureInfo = listView.polygonAreaMeasureInfo
  6363. if let window = areaMeasureInfoWindowController?.window {
  6364. self.view.window?.addChildWindow(window, ordered: .above)
  6365. let selfRect = self.view.window!.frame
  6366. var rect = window.frame
  6367. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16
  6368. if viewManager.showRightSide == true, let rightVC = self.rightSideController {
  6369. rect.origin.x = CGRectGetMaxX(selfRect) - rect.size.width - 16 - rightVC.view.frame.size.width
  6370. }
  6371. rect.origin.y = CGRectGetMinY(selfRect) + 16
  6372. window.setFrame(rect, display: true)
  6373. }
  6374. } else {
  6375. cancelMeasureType()
  6376. }
  6377. }
  6378. }
  6379. func showMeasureSettingWindow() {
  6380. if let window = distanceMeasureInfoWindowController?.window, let childWindows = self.view.window?.childWindows, childWindows.contains(window) {
  6381. self.view.window?.removeChildWindow(window)
  6382. distanceMeasureInfoWindowController?.hideFloatingWindow()
  6383. }
  6384. let distanceSettingWC = CDistanceSettingWindowController(measureInfo: self.listView.distanceMeasureInfo)
  6385. distanceSettingWC.delegate = self
  6386. distanceSettingWC.own_beginSheetModal(for: self.view.window) { string in
  6387. }
  6388. }
  6389. private func angleBetweenPoints(_ startPoint: CGPoint, _ midPoint: CGPoint, _ endPoint: CGPoint) -> CGFloat {
  6390. let vector1 = CGPoint(x: midPoint.x - startPoint.x, y: midPoint.y - startPoint.y)
  6391. let vector2 = CGPoint(x: endPoint.x - midPoint.x, y: endPoint.y - midPoint.y)
  6392. let dotProduct = vector1.x * vector2.x + vector1.y * vector2.y
  6393. let magnitude1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
  6394. let magnitude2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
  6395. return acos(dotProduct / (magnitude1 * magnitude2)) * (180.0 / .pi)
  6396. }
  6397. @objc func pdfUpdatedFinish() {
  6398. splitPDFController?.inPDFFirst = false
  6399. splitPDFController?.outPDFFirst = false
  6400. }
  6401. //MARK: - Notification
  6402. @objc private func pdfViewScrollViewDidScroll(_ noti: Notification) {
  6403. if let documentView = noti.object as? NSScrollView {
  6404. if documentView == listView.documentView() {
  6405. reloadPopUIWindow()
  6406. if listView.popOver?.isShown == true {
  6407. listView.popOver?.close()
  6408. }
  6409. }
  6410. }
  6411. }
  6412. func pageCountChangedNotification(_ sender: Notification) {
  6413. guard let document = sender.object as? CPDFDocument else {
  6414. return
  6415. }
  6416. botaViewController?.pageCountChangedAction(document: document)
  6417. }
  6418. func annotationsAttributeHasChange(_ sender: Notification) {
  6419. guard let dict = sender.object as? [String : Any] else {
  6420. return
  6421. }
  6422. if let anno = dict["object"] as? CPDFAnnotation {
  6423. if let page = anno.page {
  6424. if(page.document == listView.document) {
  6425. let value = dict["keyPath"] as? String ?? ""
  6426. let didEnd = dict["didEnd"] as? Bool ?? false
  6427. if didEnd {
  6428. if value == CPDFAnnotationBoundsKey {
  6429. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  6430. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  6431. }
  6432. }
  6433. if anno.km_isMeasure() && anno.contents == nil {
  6434. anno.contents = anno.string() ?? ""
  6435. }
  6436. var pageIndexes = IndexSet()
  6437. pageIndexes.insert(Int(anno.page.pageIndex()))
  6438. reloadIfThumData(pageIndexs: pageIndexes)
  6439. reloadPopUIWindow()
  6440. } else {
  6441. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  6442. var pageIndexes = IndexSet()
  6443. pageIndexes.insert(Int(anno.page.pageIndex()))
  6444. reloadIfThumData(pageIndexs: pageIndexes)
  6445. reloadPopUIWindow()
  6446. }
  6447. }
  6448. }
  6449. }
  6450. }
  6451. }
  6452. func reloadThumData(pageIndexs: IndexSet) {
  6453. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(reloadIfThumData), object: pageIndexs)
  6454. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  6455. self.reloadIfThumData(pageIndexs: pageIndexs)
  6456. }
  6457. }
  6458. func reloadIfThumData(pageIndexs: IndexSet) {
  6459. KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexs)
  6460. botaViewController?.reloadData()
  6461. }
  6462. @objc fileprivate func signatureStateChangeNoti(_ sender: Notification) {
  6463. guard let objecListView = sender.object as? CPDFListView else {
  6464. return
  6465. }
  6466. if listView == objecListView {
  6467. reloadDigitalSigns()
  6468. alertTipViewController.reloadDigitalAlertUI()
  6469. alertTipViewController.reloadAlertUIFrame()
  6470. let signatureWidget = listView.editAnnotation
  6471. if let signatureWidgetAnnotation = signatureWidget as? CPDFSignatureWidgetAnnotation {
  6472. let signature = signatureWidgetAnnotation.signature()
  6473. if signature == nil {
  6474. return
  6475. }
  6476. signaturestateVC.signature = signature
  6477. signaturestateVC.reloadData()
  6478. }
  6479. }
  6480. }
  6481. @objc private func redoChangeNotification(_ noti: Notification) {
  6482. updateUndoRedoState()
  6483. }
  6484. }
  6485. //MARK: - KMNThumbnailBaseViewDelegate
  6486. extension KMMainViewController: KMNThumbnailBaseViewDelegate {
  6487. func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int) {
  6488. if listView.currentPageIndex != currentIndex {
  6489. listView.go(toPageIndex: currentIndex, animated: false)
  6490. }
  6491. exitPageEditMode()
  6492. viewManager.isPageEditMode = false
  6493. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_PageEdit_Identifier)
  6494. }
  6495. func insertPDFThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, pdfDocment: CPDFDocument?) {
  6496. if(pdfDocment != nil) {
  6497. insertDocuments.insert(pdfDocment!)
  6498. }
  6499. }
  6500. func changeIndexPathsThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, selectionIndexPaths: Set<IndexPath>, selectionStrings: String) {
  6501. toolbarManager.page_pageInfo_Property.text = selectionStrings
  6502. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  6503. toolbarManager.page_pageInfo_Property.creatable = true
  6504. }
  6505. pdfToolbarController?.refreshSecondToolbarItemsState()
  6506. }
  6507. func leftSideViewControllerThumbnailHaveChange(leftSideViewController: KMNLeftSideViewController) {
  6508. if(self.pageEditViewController?.view.superview == nil) { //当页面编辑不显示时,undo还会继续,所以需要刷新PDFView,如果页面编辑视图存在时,在退出页面编辑时一次性刷新
  6509. listView.layoutDocumentView()
  6510. botaViewController?.reloadData()
  6511. }
  6512. }
  6513. func thumbnailViewControlleHaveChange(pageEditVC: KMNThumbnailBaseViewController) {
  6514. if(self.pageEditViewController?.view.superview == nil) { //当页面编辑不显示时,undo还会继续,所以需要刷新PDFView,如果页面编辑视图存在时,在退出页面编辑时一次性刷新
  6515. listView.layoutDocumentView()
  6516. botaViewController?.reloadData()
  6517. }
  6518. }
  6519. }
  6520. //MARK: - KMNLeftSideViewControllerDelegate
  6521. extension KMMainViewController: KMNLeftSideViewControllerDelegate {
  6522. func enterPageEditLeftSideViewController(leftSideViewController: KMNLeftSideViewController) {
  6523. if viewManager.isPageEditMode == false {
  6524. viewManager.isPageEditMode = true
  6525. if(pdfToolbarController != nil) {
  6526. kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_PageEdit_Identifier)
  6527. pdfToolbarController?.resetSecondToolbar()
  6528. pageEditViewController?.selectionIndexPaths = leftSideViewController.thumnailViewController?.collectionView.selectionIndexPaths ?? []
  6529. }
  6530. }
  6531. }
  6532. func changeSelectePageLeftSideViewController(leftSideViewController: KMNLeftSideViewController, pageIndex: Int) {
  6533. if(listView.currentPageIndex != pageIndex) {
  6534. listView.go(toPageIndex: pageIndex, animated: true)
  6535. }
  6536. }
  6537. func addBookmarkForLeftC(controller: KMNLeftSideViewController, bookmark: CPDFBookmark?, info: [String : Any]?) {
  6538. if let result = info?["result"] as? Bool {
  6539. if result == false {
  6540. if let targetV = listView.superview {
  6541. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("This page has been bookmarked"), type: .normal_custom, fromView: targetV, point:CGPointMake(targetV.frame.size.width/2, targetV.bounds.size.height-24))
  6542. }
  6543. }
  6544. }
  6545. }
  6546. func switchSearchPopWindow(controller: KMNLeftSideViewController) {
  6547. if(viewManager.pdfSideBarType == .search) {
  6548. viewManager.pdfSideBarType = .none
  6549. sideBarController?.reloadData()
  6550. toggleCloseLeftSide()
  6551. }
  6552. let handdler = controller.searchViewC.handdler
  6553. showSearchPopWindow(hander: handdler)
  6554. }
  6555. func searchTypeDidChange(controller: KMNLeftSideViewController) {
  6556. let handdler = controller.searchViewC.handdler
  6557. self.searchTypeDidChange(type: handdler.type)
  6558. }
  6559. func searchTypeDidChange(type: KMNBotaSearchType) {
  6560. if type == .replace {
  6561. if viewManager.toolMode != .Edit {
  6562. viewManager.toolMode = .Edit
  6563. updatePDFViewAnnotationMode()
  6564. pdfToolbarController?.reloadToolbarTabsView()
  6565. pdfToolbarController?.reloadData()
  6566. refreshToolbarViewHeightInfo()
  6567. }
  6568. } else if type == .search {
  6569. if viewManager.toolMode == .Edit {
  6570. viewManager.toolMode = .None
  6571. updatePDFViewAnnotationMode()
  6572. pdfToolbarController?.reloadToolbarTabsView()
  6573. pdfToolbarController?.reloadData()
  6574. refreshToolbarViewHeightInfo()
  6575. }
  6576. }
  6577. }
  6578. }
  6579. //MARK: - ComponentGroupDelegate
  6580. extension KMMainViewController: ComponentGroupDelegate {
  6581. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  6582. if menuItemProperty?.identifier == PDFViewMenuIdentifier_PageNext {
  6583. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6584. if objectListView.canGoToNextPage() {
  6585. objectListView.goToNextPage(nil)
  6586. }
  6587. }
  6588. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PagePrevious) {
  6589. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6590. if objectListView.canGoToPreviousPage() {
  6591. objectListView.goToPreviousPage(nil)
  6592. }
  6593. }
  6594. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageFirst) {
  6595. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6596. if objectListView.canGoToFirstPage() {
  6597. objectListView.goToFirstPage(nil)
  6598. }
  6599. }
  6600. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageLast) {
  6601. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6602. if objectListView.canGoToLastPage() {
  6603. objectListView.goToLastPage(nil)
  6604. }
  6605. }
  6606. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  6607. listView.exitPresentationDrawMode()
  6608. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Brush) {
  6609. listView.enterPresentationDrawMode()
  6610. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Exit) {
  6611. self.exitFullScreen()
  6612. } else if menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIRewrite {
  6613. viewManager.pdfSideBarType = .aiTools
  6614. sideBarController?.reloadData()
  6615. if let sideVC = sideBarController {
  6616. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  6617. }
  6618. if(listView.currentSelection != nil) {
  6619. botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
  6620. }
  6621. botaViewController?.chooseAIFunctionWithType(.reWriting)
  6622. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIProofread) {
  6623. viewManager.pdfSideBarType = .aiTools
  6624. sideBarController?.reloadData()
  6625. if let sideVC = sideBarController {
  6626. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  6627. }
  6628. if(listView.currentSelection != nil) {
  6629. botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
  6630. }
  6631. botaViewController?.chooseAIFunctionWithType(.proofreading)
  6632. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AITranslate) {
  6633. viewManager.pdfSideBarType = .aiTools
  6634. sideBarController?.reloadData()
  6635. if let sideVC = sideBarController {
  6636. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  6637. }
  6638. if(listView.currentSelection != nil) {
  6639. botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
  6640. }
  6641. botaViewController?.chooseAIFunctionWithType(.translate)
  6642. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Past) {
  6643. let theEvent = menuItemProperty?.representedObject
  6644. if let currentEvent = theEvent as? NSEvent {
  6645. var pagePoint = CGPoint.zero
  6646. if let page = listView.pageAndPoint(&pagePoint, for: currentEvent, nearest: false) {
  6647. listView.menuPointPaste(pagePoint, page: page, isRightPaste: true)
  6648. }
  6649. }
  6650. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllText) {
  6651. if self.listView.toolMode == .CRedactToolMode {
  6652. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  6653. let objectListView = dic["Object"] as? CPDFListView
  6654. let theEvent = dic["theEvent"] as? NSEvent
  6655. if(objectListView != nil && theEvent != nil) {
  6656. var pagePoint = CGPoint.zero
  6657. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  6658. self.selectAllRedactAnnotation(currentPage: page)
  6659. }
  6660. }
  6661. }
  6662. } else {
  6663. listView.selectAll(nil)
  6664. }
  6665. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddBook) {
  6666. menuItemBookMarkClick_add(sender: nil)
  6667. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TextTool) {
  6668. listView.toolMode = .CSelectToolMode
  6669. listView.annotationType = .unkown
  6670. viewManager.viewToolsType = .Content_Selection
  6671. pdfToolbarController?.reloadToolsView()
  6672. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MoveTool) {
  6673. listView.toolMode = .CMoveToolMode
  6674. listView.annotationType = .unkown
  6675. viewManager.viewToolsType = .Scroll
  6676. pdfToolbarController?.viewManager?.toolMode = .None
  6677. pdfToolbarController?.viewManager?.subToolMode = .None
  6678. refreshToolbarViewHeightInfo()
  6679. pdfToolbarController?.reloadData()
  6680. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectTool) {
  6681. listView.toolMode = .CNoteToolMode
  6682. listView.annotationType = .unkown
  6683. viewManager.viewToolsType = .Select
  6684. pdfToolbarController?.viewManager?.toolMode = .None
  6685. pdfToolbarController?.viewManager?.subToolMode = .None
  6686. refreshToolbarViewHeightInfo()
  6687. pdfToolbarController?.reloadData()
  6688. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MagnifyTool) {
  6689. listView.toolMode = .CMagnifyToolMode
  6690. listView.annotationType = .unkown
  6691. viewManager.viewToolsType = .Magnify
  6692. pdfToolbarController?.viewManager?.toolMode = .None
  6693. pdfToolbarController?.viewManager?.subToolMode = .None
  6694. refreshToolbarViewHeightInfo()
  6695. pdfToolbarController?.reloadData()
  6696. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectZoomTool) {
  6697. listView.toolMode = .CSelectZoomToolMode
  6698. listView.annotationType = .unkown
  6699. viewManager.viewToolsType = .AreaZoom
  6700. pdfToolbarController?.viewManager?.toolMode = .None
  6701. pdfToolbarController?.viewManager?.subToolMode = .None
  6702. refreshToolbarViewHeightInfo()
  6703. pdfToolbarController?.reloadData()
  6704. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Single) {
  6705. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6706. objectListView.menuItemClick_SinglePage(nil)
  6707. displaySettingController?.reloadData()
  6708. }
  6709. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SingleContinuous) {
  6710. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6711. objectListView.menuItemClick_SinglePagesContinuous(nil)
  6712. displaySettingController?.reloadData()
  6713. }
  6714. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPages) {
  6715. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6716. objectListView.menuItemClick_TwoPages(nil)
  6717. displaySettingController?.reloadData()
  6718. }
  6719. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPagesContinuous) {
  6720. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6721. objectListView.menuItemClick_TwoPagesContinuous(nil)
  6722. displaySettingController?.reloadData()
  6723. }
  6724. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BookMode) {
  6725. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6726. objectListView.menuItemClick_BookMode(nil)
  6727. displaySettingController?.reloadData()
  6728. }
  6729. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ReadMode) {
  6730. viewManager.isPDFReadMode = !viewManager.isPDFReadMode
  6731. if viewManager.isPDFReadMode {
  6732. openPDFReadMode()
  6733. } else {
  6734. exitPDFReadMode()
  6735. }
  6736. displaySettingController?.reloadData()
  6737. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleWidth) {
  6738. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6739. objectListView.autoScales = true
  6740. }
  6741. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScalePage) {
  6742. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6743. let pageHeight = objectListView.currentPage()!.size.height
  6744. let pdfviewHeight = objectListView.bounds.size.height
  6745. objectListView.scaleFactor = pdfviewHeight/pageHeight
  6746. objectListView.autoScales = false
  6747. }
  6748. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleOrg) {
  6749. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6750. if objectListView.scaleFactor != 1.0 {
  6751. objectListView.scaleFactor = 1.0
  6752. objectListView.autoScales = false
  6753. }
  6754. }
  6755. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomIn) {
  6756. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6757. var scale = objectListView.scaleFactor
  6758. switch scale {
  6759. case 0...0.25:
  6760. scale += 0.25
  6761. case 0.25...3:
  6762. scale += 0.25
  6763. case 3.1...10:
  6764. scale += 0.4
  6765. case 10.1...100:
  6766. scale += 1
  6767. default:
  6768. scale += 1
  6769. }
  6770. objectListView.scaleFactor = scale
  6771. }
  6772. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomOut) {
  6773. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6774. var scale = objectListView.scaleFactor
  6775. switch scale {
  6776. case 0...0.25:
  6777. scale = 0
  6778. case 0.25...3:
  6779. scale -= 0.25
  6780. case 3.1...10:
  6781. scale -= 0.4
  6782. case 10.1...100:
  6783. scale -= 1
  6784. default:
  6785. scale -= 1
  6786. }
  6787. objectListView.scaleFactor = scale
  6788. }
  6789. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateLeft) {
  6790. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  6791. let objectListView = dic["Object"] as? CPDFListView
  6792. let theEvent = dic["theEvent"] as? NSEvent
  6793. if(objectListView != nil && theEvent != nil) {
  6794. var pagePoint = CGPoint.zero
  6795. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  6796. rotateLeft(page: page, listView: objectListView)
  6797. }
  6798. }
  6799. }
  6800. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateRight) {
  6801. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  6802. let objectListView = dic["Object"] as? CPDFListView
  6803. let theEvent = dic["theEvent"] as? NSEvent
  6804. if(objectListView != nil && theEvent != nil) {
  6805. var pagePoint = CGPoint.zero
  6806. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  6807. rotateRight(page: page, listView: objectListView)
  6808. }
  6809. }
  6810. }
  6811. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_EnterPageNum) {
  6812. gotoPage(nil)
  6813. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageBack) {
  6814. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6815. if(objectListView.km_canGoBack() == true) {
  6816. objectListView.km_goBack(nil)
  6817. }
  6818. }
  6819. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageForward) {
  6820. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  6821. if(objectListView.km_canGoForward() == true) {
  6822. objectListView.km_goForward(nil)
  6823. }
  6824. }
  6825. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AutoScroll) {
  6826. toggleAutoFlow(nil)
  6827. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightForm) {
  6828. highlightFormFiled(nil)
  6829. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightLink) {
  6830. highlightLinks(nil)
  6831. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RestForm) {
  6832. resetForm(nil)
  6833. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Search) {
  6834. if botaViewController != nil {
  6835. switchSearchPopWindow(controller: botaViewController!)
  6836. }
  6837. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Print) {
  6838. menuItemAction_print(nil)
  6839. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Properties) {
  6840. menuItemAction_property(nil)
  6841. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Copy) {
  6842. if(listView.isEditing() == true) {
  6843. listView.copyEditAreaAction()
  6844. } else {
  6845. listView.copy(nil)
  6846. }
  6847. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Hight) {
  6848. if let currentSelect = listView.currentSelection {
  6849. if(currentSelect.selectionType() == .text) {
  6850. listView.addAnnotation(with: .highlight, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  6851. listView.currentSelection = nil;
  6852. }
  6853. }
  6854. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Underline) {
  6855. if let currentSelect = listView.currentSelection {
  6856. if(currentSelect.selectionType() == .text) {
  6857. listView.addAnnotation(with: .underline, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  6858. listView.currentSelection = nil;
  6859. }
  6860. }
  6861. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Squiggly) {
  6862. if let currentSelect = listView.currentSelection {
  6863. if(currentSelect.selectionType() == .text) {
  6864. listView.addAnnotation(with: .squiggly, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  6865. listView.currentSelection = nil;
  6866. }
  6867. }
  6868. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_StrikeOut) {
  6869. if let currentSelect = listView.currentSelection {
  6870. if(currentSelect.selectionType() == .text) {
  6871. listView.addAnnotation(with: .strikeOut, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  6872. listView.currentSelection = nil;
  6873. }
  6874. }
  6875. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Square) {
  6876. if let currentSelect = listView.currentSelection {
  6877. listView.addAnnotation(with: .square, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  6878. listView.currentSelection = nil;
  6879. }
  6880. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Circle) {
  6881. if let currentSelect = listView.currentSelection {
  6882. listView.addAnnotation(with: .circle, selection: currentSelect, page: currentSelect.page, bounds: listView.currentSelection.bounds)
  6883. listView.currentSelection = nil;
  6884. }
  6885. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddOutLine) {
  6886. addOutLineItemAction()
  6887. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TTS) {
  6888. startSpeaking(nil)
  6889. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SearchText) {
  6890. searchBaiduAction()
  6891. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllForm) {
  6892. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  6893. let objectListView = dic["Object"] as? CPDFListView
  6894. let theEvent = dic["theEvent"] as? NSEvent
  6895. if(objectListView != nil && theEvent != nil) {
  6896. var pagePoint = CGPoint.zero
  6897. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  6898. selectAllFormAnnotation(currentPage: page)
  6899. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6900. }
  6901. }
  6902. }
  6903. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowFormName) {
  6904. if(listView.showFormFieldName == true) {
  6905. listView.showFormFieldName = false
  6906. } else {
  6907. listView.showFormFieldName = true
  6908. }
  6909. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6910. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllAnnotation) {
  6911. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  6912. let objectListView = dic["Object"] as? CPDFListView
  6913. let theEvent = dic["theEvent"] as? NSEvent
  6914. if(objectListView != nil && theEvent != nil) {
  6915. var pagePoint = CGPoint.zero
  6916. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  6917. selectAllNomerAnnotation(currentPage: page)
  6918. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6919. }
  6920. }
  6921. }
  6922. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowAnnotation) {
  6923. if(pdfToolbarController != nil) {
  6924. if(toolbarManager.eyeProperty.state == .normal) {
  6925. toolbarManager.eyeProperty.state = .pressed
  6926. } else {
  6927. toolbarManager.eyeProperty.state = .normal
  6928. }
  6929. self.kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_eye_Identifier)
  6930. pdfToolbarController?.resetSecondToolbar()
  6931. }
  6932. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_CopyText) {
  6933. var copyText:String = ""
  6934. let annotations = listView.activeAnnotations
  6935. for i in 0 ..< (annotations?.count ?? 0){
  6936. if let an = annotations?[i] as? CPDFMarkupAnnotation {
  6937. let markupContent = an.markupContent()
  6938. if markupContent.isEmpty == false {
  6939. if copyText.isEmpty == true {
  6940. copyText = markupContent
  6941. } else {
  6942. copyText = copyText + "\n" + markupContent
  6943. }
  6944. }
  6945. }
  6946. }
  6947. let pboard = NSPasteboard.general
  6948. if copyText.isEmpty == false {
  6949. pboard.clearContents()
  6950. pboard.writeObjects([copyText as NSPasteboardWriting])
  6951. }
  6952. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Cut) {
  6953. if(listView.isEditing() == true) {
  6954. listView.cutEditAreaAction()
  6955. } else {
  6956. listView.cut(nil)
  6957. }
  6958. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Delete) {
  6959. if(listView.isEditing() == true) {
  6960. listView.deleteEditAreaAction()
  6961. } else {
  6962. listView.delete(nil)
  6963. }
  6964. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowPopUI) {
  6965. self.isShowQuickBar = true
  6966. reloadPopUIWindow()
  6967. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortFirstAnnotation) {
  6968. let activeAnnotations = listView.activeAnnotations
  6969. for i in 0 ..< (activeAnnotations?.count ?? 0){
  6970. let object = activeAnnotations?[i]
  6971. if let an = object as? CPDFAnnotation {
  6972. listView.bringAnnotationFront(an, page: an.page)
  6973. }
  6974. }
  6975. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6976. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortTopAnnotation) {
  6977. let activeAnnotations = listView.activeAnnotations
  6978. for i in 0 ..< (activeAnnotations?.count ?? 0){
  6979. let object = activeAnnotations?[i]
  6980. if let an = object as? CPDFAnnotation {
  6981. listView.bringAnnotationForward(an, page: an.page)
  6982. }
  6983. }
  6984. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6985. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortBottomAnnotation) {
  6986. let activeAnnotations = listView.activeAnnotations
  6987. for i in 0 ..< (activeAnnotations?.count ?? 0){
  6988. let object = activeAnnotations?[i]
  6989. if let an = object as? CPDFAnnotation {
  6990. listView.sendAnnotationBackward(an, page: an.page)
  6991. }
  6992. }
  6993. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  6994. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortLastAnnotation) {
  6995. let activeAnnotations = listView.activeAnnotations
  6996. for i in 0 ..< (activeAnnotations?.count ?? 0){
  6997. let object = activeAnnotations?[i]
  6998. if let an = object as? CPDFAnnotation {
  6999. listView.sendAnnotationBack(an, page: an.page)
  7000. }
  7001. }
  7002. listView.setNeedsDisplayAnnotationViewForVisiblePages()
  7003. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Content) {
  7004. if let activeAnnotation = listView.activeAnnotation {
  7005. listView.edit(activeAnnotation)
  7006. }
  7007. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Apply) {
  7008. redactApplyAction()
  7009. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Multipage) {
  7010. redactMultipageAction(redactAnnotations: listView.activeAnnotations as! [CPDFRedactAnnotation])
  7011. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Default) {
  7012. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
  7013. setPropertiesDefault(annotation: redactAnnotation)
  7014. }
  7015. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewSingleMode) {
  7016. listView.viewSplitMode = .disable
  7017. reloadPDFSplitInfo()
  7018. displaySettingController?.reloadData()
  7019. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewVerticalMode) {
  7020. listView.viewSplitMode = .vertical
  7021. displaySettingController?.reloadData()
  7022. reloadPDFSplitInfo()
  7023. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewHorizontalMode) {
  7024. listView.viewSplitMode = .horizontal
  7025. displaySettingController?.reloadData()
  7026. reloadPDFSplitInfo()
  7027. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_Sync) {
  7028. viewManager.splitSyncScroll = !viewManager.splitSyncScroll
  7029. displaySettingController?.reloadData()
  7030. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ShowBar) {
  7031. viewManager.splitShowBottomBar = !viewManager.splitShowBottomBar
  7032. splitPDFController?.refreshToolbarState()
  7033. reloadPDFPageNumberToolbar()
  7034. displaySettingController?.reloadData()
  7035. if(listView.isEditing()) {
  7036. listView.changeEditingAreas(.left)
  7037. } else {
  7038. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  7039. }
  7040. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_VerticallyAlight) {
  7041. if(listView.isEditing()) {
  7042. listView.changeEditingAreas(.vertical)
  7043. } else {
  7044. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  7045. }
  7046. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RightAlight) {
  7047. if(listView.isEditing()) {
  7048. listView.changeEditingAreas(.right)
  7049. } else {
  7050. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  7051. }
  7052. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TopAlight) {
  7053. if(listView.isEditing()) {
  7054. listView.changeEditingAreas(.top)
  7055. } else {
  7056. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  7057. }
  7058. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HorizontallyAlight) {
  7059. if(listView.isEditing()) {
  7060. listView.changeEditingAreas(.horizontally)
  7061. } else {
  7062. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  7063. }
  7064. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BottomAlight) {
  7065. if(listView.isEditing()) {
  7066. listView.changeEditingAreas(.bottom)
  7067. } else {
  7068. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  7069. }
  7070. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeHorizontally) {
  7071. if(listView.isEditing()) {
  7072. listView.changeEditingAreas(.disHorizontally)
  7073. } else {
  7074. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  7075. }
  7076. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeVertically) {
  7077. if(listView.isEditing()) {
  7078. listView.changeEditingAreas(.disVertical)
  7079. } else {
  7080. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  7081. }
  7082. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportJPG) {
  7083. if KMMemberInfo.shared.isLogin == false {
  7084. KMLoginWindowsController.shared.showWindow(nil)
  7085. return
  7086. }
  7087. if(listView.isEditing() == true) {
  7088. listView.exportEditingImageAreasAction(format: "jpg")
  7089. } else {
  7090. if let currentSelection = listView.currentSelection {
  7091. if(currentSelection.selectionType() == .image) {
  7092. listView.exprotSelection(currentSelection, type: 1)
  7093. }
  7094. }
  7095. }
  7096. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPNG) {
  7097. if KMMemberInfo.shared.isLogin == false {
  7098. KMLoginWindowsController.shared.showWindow(nil)
  7099. return
  7100. }
  7101. if(listView.isEditing() == true) {
  7102. listView.exportEditingImageAreasAction(format: "png")
  7103. } else {
  7104. if let currentSelection = listView.currentSelection {
  7105. if(currentSelection.selectionType() == .image) {
  7106. listView.exprotSelection(currentSelection, type: 0)
  7107. }
  7108. }
  7109. }
  7110. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPDF) {
  7111. if KMMemberInfo.shared.isLogin == false {
  7112. KMLoginWindowsController.shared.showWindow(nil)
  7113. return
  7114. }
  7115. if(listView.isEditing() == true) {
  7116. listView.exportEditingImageAreasAction(format: "pdf")
  7117. } else {
  7118. if let currentSelection = listView.currentSelection {
  7119. if(currentSelection.selectionType() == .image) {
  7120. listView.exprotSelection(currentSelection, type: 2)
  7121. }
  7122. }
  7123. }
  7124. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Paste) {
  7125. let pointValue = NSValue(point: group?.pagePoint ?? CGPointZero)
  7126. listView.pasteEditAreaMatchStyleActionWith(pointValue)
  7127. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_NoStylePaste) {
  7128. let pointValue = NSValue(point: group?.pagePoint ?? CGPointZero)
  7129. listView.pasteEditAreaActionWith(pointValue)
  7130. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_SelectAll) {
  7131. if listView.km_EditingAreas().count <= 0 {
  7132. listView.selectAllAreaAction()
  7133. } else {
  7134. listView.selectAllAction(with: listView.km_EditingAreas().first)
  7135. }
  7136. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddLink) {
  7137. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_link_Identifier)
  7138. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddText) {
  7139. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_text_Identifier)
  7140. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddImage) {
  7141. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_image_Identifier)
  7142. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontBold) {
  7143. listView.setEditingTextarea_Bold()
  7144. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontItalic) {
  7145. listView.setEditingTextarea_Italic()
  7146. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontUnderline) {
  7147. listView.setEditingTextarea_Under()
  7148. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontStrikeout) {
  7149. listView.setEditingTextarea_Strikeout()
  7150. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomIn) {
  7151. listView.zoomInEditTextFontSize()
  7152. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomOut) {
  7153. listView.zoomOutEditTextFontSize()
  7154. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontColor) {
  7155. let colorPanel = NSColorPanel.shared
  7156. colorPanel.setTarget(self)
  7157. colorPanel.setAction(#selector(editFontColorItemPanelAction(_:)))
  7158. colorPanel.orderFront(nil)
  7159. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH1Name) {
  7160. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h1)
  7161. self.updateEditPDFTextFontModel(model)
  7162. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH2Name) {
  7163. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h2)
  7164. self.updateEditPDFTextFontModel(model)
  7165. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH3Name) {
  7166. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h3)
  7167. self.updateEditPDFTextFontModel(model)
  7168. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB1Name) {
  7169. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b1)
  7170. self.updateEditPDFTextFontModel(model)
  7171. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB2Name) {
  7172. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b2)
  7173. self.updateEditPDFTextFontModel(model)
  7174. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB3Name) {
  7175. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b3)
  7176. self.updateEditPDFTextFontModel(model)
  7177. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontLeftAlight) {
  7178. listView.setEditingTextarea_Alignment(align:.left)
  7179. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontCenterAlight) {
  7180. listView.setEditingTextarea_Alignment(align:.center)
  7181. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontRightAlight) {
  7182. listView.setEditingTextarea_Alignment(align:.right)
  7183. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontJustAlight) {
  7184. listView.setEditingTextarea_Alignment(align:.justified)
  7185. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateLeft) {
  7186. listView.leftRotateAction()
  7187. rightSideController?.reloadEditingAreas()
  7188. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateRight) {
  7189. listView.rightRotateAction()
  7190. rightSideController?.reloadEditingAreas()
  7191. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_HorizontalMirror) {
  7192. listView.reverseXAction()
  7193. rightSideController?.reloadEditingAreas()
  7194. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_VerticalMirror) {
  7195. listView.reverseYAction()
  7196. rightSideController?.reloadEditingAreas()
  7197. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Crop) {
  7198. listView.cropAction()
  7199. rightSideController?.reloadEditingAreas()
  7200. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Replace) {
  7201. listView.replaceImageEdit()
  7202. rightSideController?.reloadEditingAreas()
  7203. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RedactProperties) {
  7204. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation{
  7205. showRedactProperty(readactAnnotation: redactAnnotation)
  7206. }
  7207. }
  7208. }
  7209. func componentGroupDidDismiss(group: ComponentGroup?) {
  7210. }
  7211. func updateEditPDFTextFontModel(_ model: KMEditPDFTextFontModel) {
  7212. let fontName = model.fontName
  7213. let fontStyle = model.fontStyle
  7214. let fontSize = model.fontSize
  7215. let bold = model.bold
  7216. let italic = model.italic
  7217. let alignment = model.alignment
  7218. let font = CPDFFont(familyName: fontName, fontStyle: fontStyle)
  7219. listView.setEditingTextarea_font(font: font)
  7220. listView.setEditingTextarea_FontSize(size: fontSize)
  7221. listView.setEditingTextarea(isBold: bold)
  7222. listView.setEditingTextarea(isItalic: italic)
  7223. listView.setEditingTextarea_Alignment(align: alignment)
  7224. }
  7225. }
  7226. // MARK: - KMSnapshotWindowControllerDelegate
  7227. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  7228. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  7229. }
  7230. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  7231. return CGRectZero
  7232. }
  7233. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  7234. }
  7235. }
  7236. // MARK: - CPDFDocumentDelegate
  7237. extension KMMainViewController: CPDFDocumentDelegate {
  7238. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  7239. }
  7240. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  7241. }
  7242. }
  7243. // MARK: - 测量代理CDistanceSettingWindowControllerDelegate
  7244. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  7245. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, updateMeasureInfo measureInfo: CPDFMeasureInfo?) {
  7246. if measureInfo != nil {
  7247. if self.listView.activeAnnotations.count > 0 {
  7248. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  7249. self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo, withNewMeasure: measureInfo)
  7250. self.handlePolylineAnnotation((self.listView.activeAnnotation as! CPDFPolylineAnnotation))
  7251. } else if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  7252. self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo, withNewMeasure: measureInfo)
  7253. self.handlePolygonAnnotation(self.listView.activeAnnotation as! CPDFPolygonAnnotation)
  7254. } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
  7255. self.updateMeasureInfo(data.measureInfo, withNewMeasure: measureInfo)
  7256. self.handleLineAnnotation(data)
  7257. }
  7258. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  7259. }
  7260. self.updateMeasureInfo(self.listView.distanceMeasureInfo, withNewMeasure: measureInfo)
  7261. self.updateMeasureInfo(self.listView.perimeterMeasureInfo, withNewMeasure: measureInfo)
  7262. self.updateMeasureInfo(self.listView.polygonAreaMeasureInfo, withNewMeasure: measureInfo)
  7263. self.updateMeasureInfo(self.listView.squareAreaMeasureInfo, withNewMeasure: measureInfo)
  7264. }
  7265. }
  7266. func updateMeasureInfo(_ measureInfo: CPDFMeasureInfo?, withNewMeasure newMeasure: CPDFMeasureInfo?) {
  7267. guard let measureInfo = measureInfo else { return }
  7268. guard let newMeasure = newMeasure else { return }
  7269. measureInfo.rulerBase = newMeasure.rulerBase
  7270. measureInfo.rulerTranslate = newMeasure.rulerTranslate
  7271. measureInfo.rulerBaseUnit = newMeasure.rulerBaseUnit
  7272. measureInfo.rulerTranslateUnit = newMeasure.rulerTranslateUnit
  7273. measureInfo.factor = newMeasure.factor
  7274. measureInfo.precision = newMeasure.precision
  7275. }
  7276. }
  7277. //MARK: - Redact密文
  7278. extension KMMainViewController {
  7279. func showRedactProperty(readactAnnotation: CPDFRedactAnnotation?) {
  7280. let properties = KMRedactPropertiesWindowController()
  7281. properties.readactAnnotation = readactAnnotation
  7282. properties.own_beginSheetModal(for: self.view.window) { result in
  7283. }
  7284. }
  7285. func redactApplyAction(needAlert: Bool = true) {
  7286. if KMMemberInfo.shared.isLogin == false {
  7287. KMLoginWindowsController.shared.showWindow(nil)
  7288. return
  7289. }
  7290. if needAlert {
  7291. DispatchQueue.main.async { [weak self] in
  7292. guard let self = self else {
  7293. return
  7294. }
  7295. if UserDefaults.standard.object(forKey: "kApplyRedactAlert") != nil {
  7296. self.listView.document.applyRedactions()
  7297. self.listView.layoutDocumentView()
  7298. return
  7299. }
  7300. let alert = NSAlert()
  7301. alert.alertStyle = .informational
  7302. alert.messageText = KMLocalizedString("This action will permanently remove the redacted information from this document.")
  7303. alert.informativeText = KMLocalizedString("""
  7304. After you save this document, you will not be able to retrieve the redacted information.
  7305. """)
  7306. alert.addButton(withTitle: KMLocalizedString("Apply"))
  7307. alert.addButton(withTitle: KMLocalizedString("Cancel"))
  7308. alert.showsSuppressionButton = true
  7309. let response = alert.runModal()
  7310. if response.rawValue == 1000 {
  7311. if alert.suppressionButton?.state == .on {
  7312. UserDefaults.standard.set("YES", forKey: "kApplyRedactAlert")
  7313. UserDefaults.standard.synchronize()
  7314. }
  7315. self.listView.document.applyRedactions()
  7316. self.listView.layoutDocumentView()
  7317. self.documentLoadComplete()
  7318. } else if response.rawValue == 1001 {
  7319. //取消
  7320. }
  7321. }
  7322. } else {
  7323. self.listView.document.applyRedactions()
  7324. self.listView.updateActiveAnnotations([])
  7325. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  7326. self.listView.updateRenderItemVisibleCell(true)
  7327. }
  7328. }
  7329. func redactMultipageAction(redactAnnotations: [CPDFRedactAnnotation]) {
  7330. let pagesWindowController = KMRedactSelectPagesWindowController(document: listView.document)
  7331. pagesWindowController.own_beginSheetModal(for: self.view.window) { result in
  7332. }
  7333. pagesWindowController.callback = { [weak self] pages in
  7334. if pages.count > 0 {
  7335. self?.listView.redactAddAnnotationPages(pages, redactAnnotations: redactAnnotations)
  7336. }
  7337. }
  7338. }
  7339. func setPropertiesDefault(annotation:CPDFRedactAnnotation) {
  7340. CPDFRedactAnnotation.update_defaultOutlineColor(annotation.borderColor())
  7341. CPDFRedactAnnotation.update_defaultFillColor(annotation.interiorColor())
  7342. CPDFRedactAnnotation.update_defaultTextColor(annotation.fontColor())
  7343. CPDFRedactAnnotation.update_defaultFontSize(annotation.fontSize)
  7344. CPDFRedactAnnotation.update_defaultFontAlignment(annotation.alignment())
  7345. CPDFRedactAnnotation.update_defaultOverlayText(annotation.overlayText())
  7346. }
  7347. func enterRedactAlert() {
  7348. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  7349. if UserDefaults.standard.object(forKey: "kRedact") != nil {
  7350. return
  7351. }
  7352. let alert = NSAlert()
  7353. alert.alertStyle = .informational
  7354. alert.informativeText = KMLocalizedString("Redaction allows you to permanently mask and remove sensitive content.")
  7355. alert.messageText = KMLocalizedString("""
  7356. Redaction requires two steps:
  7357. 1. Mark for Redaction
  7358. 2. Apply Redactions
  7359. Note: Redactions are not applied permanently until you select Apply Redactions.
  7360. """)
  7361. alert.addButton(withTitle: KMLocalizedString("OK"))
  7362. alert.showsSuppressionButton = true
  7363. let response = alert.runModal()
  7364. if response.rawValue == 1000 {
  7365. if alert.suppressionButton?.state == .on {
  7366. UserDefaults.standard.set("YES", forKey: "kRedact")
  7367. UserDefaults.standard.synchronize()
  7368. }
  7369. }
  7370. //标记密文
  7371. if self.listView.toolMode == .CRedactToolMode {
  7372. self.pdfToolbarController?.redactToolbar.applyButton.properties.isDisabled = !self.isExistRedactAnnotation()
  7373. self.pdfToolbarController?.redactToolbar.applyButton.reloadData()
  7374. }
  7375. }
  7376. }
  7377. //判断是否存在标记密文
  7378. func isExistRedactAnnotation() -> Bool {
  7379. var isContainsRedact = false
  7380. for i in 0..<(listView.document?.pageCount ?? 0) {
  7381. guard i < listView.document?.pageCount ?? 0 else { continue }
  7382. let page = listView.document.page(at: i)
  7383. if let annotations = page?.annotations, !annotations.isEmpty {
  7384. for annotation in annotations {
  7385. if annotation is CPDFRedactAnnotation {
  7386. isContainsRedact = true
  7387. break
  7388. }
  7389. }
  7390. }
  7391. if isContainsRedact {
  7392. break
  7393. }
  7394. }
  7395. return isContainsRedact
  7396. }
  7397. }
  7398. //MARK: - extension
  7399. extension KMMainViewController {
  7400. func removeAllAnnotations() {
  7401. let alert = NSAlert()
  7402. alert.messageText = KMLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  7403. alert.addButton(withTitle: KMLocalizedString("Yes", comment:""))
  7404. alert.addButton(withTitle: KMLocalizedString("No", comment:""))
  7405. if (alert.runModal() != .alertFirstButtonReturn) {
  7406. return
  7407. }
  7408. DispatchQueue.main.async {
  7409. self.removeAllAnnotationsStore.store(t: self.listView)
  7410. }
  7411. }
  7412. //MARK: - AI
  7413. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  7414. if (self.document != nil) {
  7415. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  7416. } else {
  7417. AIChatInfoManager.defaultManager.currentFilePath = ""
  7418. }
  7419. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  7420. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  7421. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  7422. let documentArray = NSDocumentController.shared.documents
  7423. var didFileEdit: Bool = false
  7424. var curDoc: KMMainDocument!
  7425. for document in documentArray {
  7426. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  7427. didFileEdit = document.isDocumentEdited
  7428. curDoc = document as! KMMainDocument
  7429. break
  7430. }
  7431. }
  7432. if didFileEdit {
  7433. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  7434. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  7435. do {
  7436. try FileManager.default.removeItem(at: tempFileURL)
  7437. } catch {
  7438. }
  7439. }
  7440. if curDoc != nil {
  7441. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  7442. }
  7443. }
  7444. windowVC.window?.becomeMain()
  7445. }
  7446. }
  7447. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  7448. } else {
  7449. var windowRect = windowVC.window?.frame
  7450. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  7451. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  7452. windowVC.window?.setFrame(windowRect!, display: true)
  7453. windowVC.didSetOriginFrame = true
  7454. }
  7455. windowVC.eventLabel = "AITools_Tbr"
  7456. windowVC.showWindow(nil)
  7457. if (aiConfigType != .none) {
  7458. windowVC.eventLabel = "AITools_Start"
  7459. if self.listView.currentSelection?.string()?.isEmpty == false {
  7460. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  7461. }
  7462. windowVC.chooseAIFunctionWithType(aiConfigType)
  7463. }
  7464. }
  7465. @objc func aiTipIconViewShowStateChangeNoti() {
  7466. }
  7467. //MARK: - 引导
  7468. func loadFunctionGuide() -> Void {
  7469. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  7470. if self.view.window != nil {
  7471. self.loadOpenFileFunctionGuide(.openFileNormal)
  7472. }
  7473. }
  7474. }
  7475. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  7476. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  7477. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  7478. guard let guideWC = self.guideInfoWindowController else { return }
  7479. guideWC.type = .openFileNormal
  7480. // guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  7481. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  7482. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  7483. }
  7484. guideWC.finishHandle = { [weak self] windowVC, type in
  7485. if type == .windowNewFinish ||
  7486. type == . windowDigitalFinish {
  7487. self?.checkFirstTrialController()
  7488. }
  7489. }
  7490. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  7491. self?.checkFirstTrialController()
  7492. }
  7493. var rect = self.view.window!.frame
  7494. rect.size.height -= 20
  7495. guideWC.window?.setFrame(rect, display: false)
  7496. guideWC.window?.minSize = rect.size
  7497. guideWC.window?.maxSize = rect.size
  7498. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  7499. guideWC.show()
  7500. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  7501. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  7502. guard let guideWC = self.guideInfoWindowController else { return }
  7503. guideWC.type = .digitalSignGuide
  7504. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  7505. guideWC.finishHandle = { [weak self] windowVC, type in
  7506. self?.checkFirstTrialController()
  7507. }
  7508. var rect = self.view.window!.frame
  7509. rect.size.height -= 20
  7510. guideWC.window?.setFrame(rect, display: false)
  7511. guideWC.window?.minSize = rect.size
  7512. guideWC.window?.maxSize = rect.size
  7513. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  7514. guideWC.show()
  7515. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  7516. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  7517. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  7518. guard let guideWC = self.guideInfoWindowController else { return }
  7519. guideWC.type = .pdfCompareGuide
  7520. guard let win = self.view.window else {
  7521. return
  7522. }
  7523. guideWC.finishHandle = { [weak self] winC, type in
  7524. if type == .windowNewFinish {
  7525. DispatchQueue.main.async {
  7526. self?.loadOpenFileFunctionGuide(.measureGuide)
  7527. }
  7528. return
  7529. }
  7530. }
  7531. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  7532. var rect = self.view.window!.frame
  7533. rect.size.height -= 20
  7534. guideWC.window?.setFrame(rect, display: false)
  7535. guideWC.window?.minSize = rect.size
  7536. guideWC.window?.maxSize = rect.size
  7537. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  7538. guideWC.show()
  7539. }
  7540. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  7541. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  7542. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  7543. guard let guideWC = self.guideInfoWindowController else { return }
  7544. guard let _ = self.view.window else {
  7545. return
  7546. }
  7547. guideWC.type = .measureGuide
  7548. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  7549. var rect = self.view.window?.frame ?? .zero
  7550. rect.size.height -= 20
  7551. guideWC.window?.setFrame(rect, display: false)
  7552. guideWC.window?.minSize = rect.size
  7553. guideWC.window?.maxSize = rect.size
  7554. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  7555. guideWC.show()
  7556. }
  7557. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  7558. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  7559. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  7560. guard let guideWC = self.guideInfoWindowController else { return }
  7561. guideWC.type = .convertGuide
  7562. guard let win = self.view.window else {
  7563. return
  7564. }
  7565. guideWC.purchaseHandle = { [weak self] windowVC in
  7566. #if VERSION_DMG
  7567. if IAPProductsManager.default().isAvailableAllFunction() {
  7568. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  7569. //Convert:
  7570. } else {
  7571. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  7572. limitWC.continueBlock = { windowController in
  7573. }
  7574. limitWC.window?.center()
  7575. limitWC.showWindow(nil)
  7576. }
  7577. } else {
  7578. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  7579. }
  7580. #else
  7581. if IAPProductsManager.default().isAvailableAllFunction() {
  7582. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  7583. //Convert:
  7584. } else {
  7585. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  7586. vc.showWindow(nil)
  7587. }
  7588. } else {
  7589. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  7590. }
  7591. #endif
  7592. }
  7593. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  7594. var rect = self.view.window?.frame ?? .zero
  7595. rect.size.height -= 20
  7596. guideWC.window?.setFrame(rect, display: false)
  7597. guideWC.window?.minSize = rect.size
  7598. guideWC.window?.maxSize = rect.size
  7599. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  7600. guideWC.show()
  7601. }
  7602. } else {
  7603. }
  7604. }
  7605. func checkFirstTrialController() -> Void {
  7606. #if VERSION_DMG
  7607. //打开文档后引导相关
  7608. if VerificationManager.default().status == .none {
  7609. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  7610. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  7611. if lastVersion.isEmpty || lastVersion != appVersion {
  7612. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  7613. UserDefaults.standard.synchronize()
  7614. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  7615. }
  7616. }
  7617. #endif
  7618. }
  7619. // MARK: - Private Methods
  7620. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  7621. let url = URL(fileURLWithPath: filePath)
  7622. guard let document = PDFDocument(url: url) else {
  7623. return false
  7624. }
  7625. let pageCount = document.pageCount
  7626. return pageCount > 30
  7627. }
  7628. // MARK: - 保存文档
  7629. internal func needSaveDocument() -> Bool {
  7630. if (self.isPDFDocumentEdited) {
  7631. return self.isPDFDocumentEdited
  7632. }
  7633. if (self.needSave) {
  7634. return self.needSave
  7635. }
  7636. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  7637. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  7638. return false
  7639. }
  7640. return true
  7641. }
  7642. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  7643. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  7644. if (overlook) {
  7645. document?.save(nil)
  7646. return
  7647. }
  7648. if (self.isPDFDocumentEdited) {
  7649. self.needSave = false
  7650. document?.save(nil)
  7651. return
  7652. }
  7653. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  7654. return
  7655. }
  7656. document?.save(nil)
  7657. }
  7658. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  7659. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  7660. if (overlook) {
  7661. DispatchQueue.main.async {
  7662. document?.save(nil)
  7663. callback()
  7664. }
  7665. return
  7666. }
  7667. if (self.isPDFDocumentEdited) {
  7668. self.needSave = false
  7669. DispatchQueue.main.async {
  7670. document?.save(nil)
  7671. callback()
  7672. }
  7673. return
  7674. }
  7675. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  7676. callback()
  7677. return
  7678. }
  7679. DispatchQueue.main.async {
  7680. document?.save(nil)
  7681. callback()
  7682. }
  7683. }
  7684. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  7685. // 显示进度
  7686. AutoSaveManager.manager.isSaving = true
  7687. self.showProgressWindow(message: KMLocalizedString("Save", comment: "") + "PDF")
  7688. self.progressC?.maxValue = 3.0
  7689. self.progressC?.increment(by: 1.0)
  7690. // 保存文档
  7691. self.asyncSaveDocument { [weak self] params in
  7692. // 执行进度 [假进度]
  7693. self?.progressC?.increment(by: 1.0)
  7694. self?.progressC?.increment(by: 1.0)
  7695. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  7696. // 隐藏进度
  7697. self?.hiddenProgressWindow()
  7698. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  7699. AutoSaveManager.manager.isSaving = false
  7700. }
  7701. // 回调
  7702. callback()
  7703. }
  7704. }
  7705. }
  7706. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  7707. self.document?.write(toFile: tempPath)
  7708. }
  7709. // MARK: - 定时保存
  7710. func addAutoSaveEvent() {
  7711. if (self.autoSaveTimer != nil) {
  7712. self.autoSaveTimer?.invalidate()
  7713. self.autoSaveTimer = nil
  7714. }
  7715. if self.document != nil, SettingsManager.sharedInstance.autoSaveFile == true {
  7716. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  7717. self?.autoSaveTimerAction(timer)
  7718. })
  7719. }
  7720. self.checkAutoSaveInfo()
  7721. }
  7722. func checkAutoSaveInfo() {
  7723. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  7724. return
  7725. }
  7726. if AutoSaveManager.manager.autoSaveAlertShow {
  7727. return
  7728. }
  7729. AutoSaveManager.manager.autoSaveDidEndAction = false
  7730. AutoSaveManager.manager.autoSaveAlertShow = true
  7731. blockSaveWindow.cancelHandle = { [weak self] windowController in
  7732. AutoSaveManager.manager.autoSaveDidEndAction = true
  7733. AutoSaveManager.manager.clearCache()
  7734. self?.view.window?.endSheet(windowController.window!)
  7735. }
  7736. blockSaveWindow.confirmHandle = { [weak self] windowController in
  7737. self?.view.window?.endSheet(windowController.window!)
  7738. self?.saveAutoSaveInfo()
  7739. }
  7740. self.view.window?.beginSheet(blockSaveWindow.window!)
  7741. }
  7742. func saveAutoSaveInfo() {
  7743. let openPanel = NSOpenPanel()
  7744. openPanel.canChooseDirectories = true
  7745. openPanel.canChooseFiles = false
  7746. openPanel.allowsMultipleSelection = false
  7747. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  7748. openPanel.beginSheetModal(for: win!) { result in
  7749. if (result == .OK) {
  7750. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  7751. for path in AutoSaveManager.manager.opendPaths ?? [] {
  7752. let _path = path as? String
  7753. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  7754. newPath = self.getValidFilePath(newPath)
  7755. do {
  7756. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  7757. } catch {
  7758. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  7759. }
  7760. }
  7761. AutoSaveManager.manager.clearCache()
  7762. }
  7763. AutoSaveManager.manager.autoSaveDidEndAction = true
  7764. }
  7765. }
  7766. func autoSaveTimerAction(_ timer: Timer) {
  7767. if (self.document == nil || self.listView.document?.documentURL.path == nil) {
  7768. return
  7769. }
  7770. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  7771. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  7772. return
  7773. }
  7774. if let data = self.document?.isLocked, data {
  7775. return
  7776. }
  7777. if SettingsManager.sharedInstance.autoSaveFile == false {
  7778. return
  7779. }
  7780. let documentArray = NSDocumentController.shared.documents
  7781. var didFileEdit = false
  7782. for doc in documentArray {
  7783. if doc.fileURL?.path == self.document?.documentURL.path {
  7784. didFileEdit = doc.isDocumentEdited
  7785. break
  7786. }
  7787. }
  7788. if (didFileEdit == false) {
  7789. return
  7790. }
  7791. AutoSaveManager.manager.isSaving = true
  7792. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView.document?.documentURL.path ?? "")
  7793. if (!self.document!.isLocked) {
  7794. self.document?.write(to: URL(fileURLWithPath: savePath))
  7795. }
  7796. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  7797. AutoSaveManager.manager.isSaving = false
  7798. }
  7799. }
  7800. func removeAutoSaveInfo() {
  7801. if self.autoSaveTimer != nil {
  7802. self.autoSaveTimer?.invalidate()
  7803. self.autoSaveTimer = nil
  7804. }
  7805. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  7806. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  7807. return
  7808. }
  7809. if SettingsManager.sharedInstance.autoSaveFile == false {
  7810. return
  7811. }
  7812. if self.document == nil || self.listView.document?.documentURL.path == nil {
  7813. return
  7814. }
  7815. AutoSaveManager.manager.removeAutoSavePath(self.listView.document?.documentURL.path ?? "")
  7816. }
  7817. // MARK: - 选择缩放模式
  7818. @objc public func selectZoom(_ type: KMPDFZoomType) {
  7819. switch type {
  7820. case .width:
  7821. self.listView.autoScales = true
  7822. break
  7823. case .fit:
  7824. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  7825. let pdfviewHeight = self.listView.bounds.size.height
  7826. self.listView.scaleFactor = pdfviewHeight/pageHeight
  7827. self.listView.autoScales = false
  7828. }
  7829. break
  7830. case .actualSize:
  7831. if self.listView.scaleFactor != 1.0 {
  7832. self.listView.scaleFactor = 1.0
  7833. self.listView.autoScales = false
  7834. }
  7835. break
  7836. case .zoom_In:
  7837. self.doZoomIn(nil)
  7838. break
  7839. case .zoom_Out:
  7840. self.doZoomOut(nil)
  7841. break
  7842. }
  7843. }
  7844. func doZoomIn(_ sender: Any?) {
  7845. if (self.listView.canZoomIn) {
  7846. self.listView.zoomIn(nil)
  7847. }
  7848. }
  7849. func doZoomOut(_ sender: Any?) {
  7850. if (self.listView.canZoomOut) {
  7851. self.listView.zoomOut(nil)
  7852. }
  7853. }
  7854. // MARK: - Event 监听
  7855. private func addEventMonitor() {
  7856. if (self.eventMonitor != nil) {
  7857. self.removeEventMonitor()
  7858. }
  7859. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown, .leftMouseUp]) { [weak self] event in
  7860. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  7861. self?.listView.magnifyWheel(event)
  7862. return nil
  7863. } else if event.type == .leftMouseDown {
  7864. let point = event.locationInView(self?.listView ?? NSView())
  7865. let presentationDrawView = self?.listView.presentationDrawView
  7866. if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true { // 幻灯片模式下
  7867. if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
  7868. let can = self?.listView.canGoToNextPage() ?? false
  7869. if can {
  7870. self?.listView.goToNextPage(nil)
  7871. }
  7872. } else {
  7873. let can = self?.listView.canGoToPreviousPage() ?? false
  7874. if can {
  7875. self?.listView.goToPreviousPage(nil)
  7876. }
  7877. }
  7878. return nil
  7879. }
  7880. }
  7881. return event
  7882. }
  7883. }
  7884. private func removeEventMonitor() {
  7885. if (self.eventMonitor != nil) {
  7886. KMPrint("已移除事件监听")
  7887. NSEvent.removeMonitor(self.eventMonitor as Any)
  7888. self.eventMonitor = nil
  7889. }
  7890. }
  7891. func addKeyEventMonitor() {
  7892. if (self.keyEventMonitor != nil) {
  7893. self.removeKeyEventMonitor()
  7894. }
  7895. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  7896. if event.window != self?.view.window {
  7897. return event
  7898. }
  7899. if event.keyCode == 53 {
  7900. self?.listView.keyDown(with: event)
  7901. return nil
  7902. } else {
  7903. }
  7904. return event
  7905. }
  7906. }
  7907. func removeKeyEventMonitor() {
  7908. if (self.keyEventMonitor != nil) {
  7909. KMPrint("removeKeyEventMonitor 已移除事件监听")
  7910. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  7911. self.keyEventMonitor = nil
  7912. }
  7913. }
  7914. //MARK: - Mouse Event
  7915. override func mouseMoved(with event: NSEvent) {
  7916. self.view.window?.mouseMoved(with: event)
  7917. }
  7918. override func keyDown(with event: NSEvent) {
  7919. listView.keyDown(with: event)
  7920. }
  7921. func keyDownEditCmdDown(){
  7922. let editingAreas = listView.km_EditingAreas()
  7923. if(editingAreas.count > 0) {
  7924. var isEditSelect = false
  7925. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  7926. isEditSelect = true
  7927. } else {
  7928. let editState = listView.editStatus()
  7929. if (editState == .editSelectText) {// 选择文本
  7930. isEditSelect = true
  7931. }
  7932. }
  7933. if isEditSelect {
  7934. for editEdit in editingAreas {
  7935. if let editTextEdit = editEdit as? CPDFEditTextArea {
  7936. listView.jumpEditingLoction(.loadTypeSectionEnd, with: editTextEdit, isSelectRanage: false)
  7937. }
  7938. }
  7939. } else {
  7940. listView.goToLastPage(nil)
  7941. }
  7942. } else {
  7943. listView.goToLastPage(nil)
  7944. }
  7945. }
  7946. func keyDownEditCmdUp(){
  7947. let editingAreas = listView.km_EditingAreas()
  7948. if(editingAreas.count > 0) {
  7949. var isEditSelect = false
  7950. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  7951. isEditSelect = true
  7952. } else {
  7953. let editState = listView.editStatus()
  7954. if (editState == .editSelectText) {// 选择文本
  7955. isEditSelect = true
  7956. }
  7957. }
  7958. if isEditSelect {
  7959. for editEdit in editingAreas {
  7960. if let editTextEdit = editEdit as? CPDFEditTextArea {
  7961. listView.jumpEditingLoction(.loadTypeSectionBegin, with: editTextEdit, isSelectRanage: false)
  7962. }
  7963. }
  7964. } else {
  7965. listView.goToFirstPage(nil)
  7966. }
  7967. } else {
  7968. listView.goToFirstPage(nil)
  7969. }
  7970. }
  7971. func keyDownEditCmdLeft(){
  7972. let editingAreas = listView.km_EditingAreas()
  7973. if(editingAreas.count > 0) {
  7974. var isEditSelect = false
  7975. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  7976. isEditSelect = true
  7977. } else {
  7978. let editState = listView.editStatus()
  7979. if (editState == .editSelectText) {// 选择文本
  7980. isEditSelect = true
  7981. }
  7982. }
  7983. if isEditSelect {
  7984. for editEdit in editingAreas {
  7985. if let editTextEdit = editEdit as? CPDFEditTextArea {
  7986. listView.jumpEditingLoction(CEditingLocation(rawValue: 0), with: editTextEdit, isSelectRanage: false)
  7987. }
  7988. }
  7989. } else {
  7990. if (listView.canGoToPreviousPage()) {
  7991. listView.goToPreviousPage(nil)
  7992. }
  7993. }
  7994. } else {
  7995. if (listView.canGoToPreviousPage()) {
  7996. listView.goToPreviousPage(nil)
  7997. }
  7998. }
  7999. }
  8000. func keyDownEditCmdRight(){
  8001. let editingAreas = listView.km_EditingAreas()
  8002. if(editingAreas.count > 0) {
  8003. var isEditSelect = false
  8004. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  8005. isEditSelect = true
  8006. } else {
  8007. let editState = listView.editStatus()
  8008. if (editState == .editSelectText) {// 选择文本
  8009. isEditSelect = true
  8010. }
  8011. }
  8012. if isEditSelect {
  8013. for editEdit in editingAreas {
  8014. if let editTextEdit = editEdit as? CPDFEditTextArea {
  8015. listView.jumpEditingLoction(.loadTypeLineEnd, with: editTextEdit, isSelectRanage: false)
  8016. }
  8017. }
  8018. } else {
  8019. if (listView.canGoToNextPage()) {
  8020. listView.goToNextPage(nil)
  8021. }
  8022. }
  8023. } else {
  8024. if (listView.canGoToNextPage()) {
  8025. listView.goToNextPage(nil)
  8026. }
  8027. }
  8028. }
  8029. // MARK: - Tools
  8030. func pdfViewCanHorizontalScroll() -> Bool {
  8031. let scroll = self.listView.scroll()
  8032. if (scroll == nil) {
  8033. return false
  8034. }
  8035. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  8036. }
  8037. func pdfViewCanVerticalScroll() -> Bool {
  8038. let scroll = self.listView.scroll()
  8039. if (scroll == nil) {
  8040. return false
  8041. }
  8042. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  8043. }
  8044. // MARK: - Public Methods
  8045. // 清理数据 [eg. 通知]
  8046. public func clearData() {
  8047. self.hideMeasureFloatingWindows()
  8048. KMThumbnailCache.shared.clearCache()
  8049. self.removeNotifications()
  8050. if (self.listView.spellingTag() > 0) {
  8051. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  8052. }
  8053. self.removeAutoSaveInfo()
  8054. self.myDocument = nil
  8055. if textFieldSheet.window?.isVisible == true {
  8056. textFieldSheet.close()
  8057. }
  8058. if NSColorPanel.shared.isVisible == true {
  8059. NSColorPanel.shared.close()
  8060. }
  8061. if KMInfoWindowController.shared.window?.isVisible == true {
  8062. KMInfoWindowController.shared.close()
  8063. }
  8064. }
  8065. public func clearSecureOptions() {
  8066. self._secureOptions = nil
  8067. self.documentAttribute = nil
  8068. }
  8069. public func clearRemoveSecureFlag() {
  8070. self._removeSecureFlag = false
  8071. }
  8072. public func recordIsPDFDocumentEdited() {
  8073. km_synchronized(self) {
  8074. self.model.isPDFDocumentEdited = true
  8075. if let _document = self.myDocument {
  8076. KMTools.setDocumentEditedState(document: _document)
  8077. }
  8078. }
  8079. }
  8080. public func clearIsPDFDocumentEdited() {
  8081. km_synchronized(self) {
  8082. self.model.isPDFDocumentEdited = false
  8083. }
  8084. }
  8085. func showSnapshots(setups: NSArray?) {
  8086. if self.listView.document != nil {
  8087. for setup in setups ?? [] {
  8088. let swc = KMSnapshotWindowController()
  8089. swc.delegate = self
  8090. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  8091. swc.setForceOnTop(self.interactionMode != .normal)
  8092. self.myDocument?.addWindowController(swc)
  8093. }
  8094. }
  8095. }
  8096. // MARK: - Noti Actions
  8097. internal func documentDidUnlockNotification(_ sender: Notification) {
  8098. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  8099. if (self.myDocument == nil) {
  8100. return
  8101. }
  8102. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  8103. self.hiddenSecureLimitTip()
  8104. }
  8105. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  8106. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  8107. return
  8108. }
  8109. let type = SettingsManager.sharedInstance.keychainType
  8110. if (type == .never) {
  8111. return
  8112. }
  8113. if (type == .always) {
  8114. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  8115. return
  8116. }
  8117. // 保存到钥匙串
  8118. let alert = NSAlert()
  8119. alert.messageText = KMLocalizedString("Remember Password?", comment: "")
  8120. if #available(macOS 15.0, *) {
  8121. alert.informativeText = KMLocalizedString("Do you want to save this password in your Passwords?", comment: "")
  8122. } else {
  8123. alert.informativeText = KMLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  8124. }
  8125. alert.addButton(withTitle: KMLocalizedString("Yes", comment: ""))
  8126. alert.addButton(withTitle: KMLocalizedString("No", comment: ""))
  8127. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  8128. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  8129. return
  8130. }
  8131. }
  8132. }
  8133. internal func applicationWillTerminateNotification(_ sender: Notification) {
  8134. self.savePageNumberIfNeed()
  8135. self.saveDocument()
  8136. }
  8137. internal func pdfViewHighlightFormFiledUpdateNoti(_ sender: Notification) {
  8138. self.alertTipViewController.reloadFormAlertUI()
  8139. self.listView.setNeedsDisplayForVisiblePages()
  8140. }
  8141. func rename(_ sender: NSNotification) -> Void {
  8142. if (self.view.window == nil || self.view.window!.isVisible == false) {
  8143. return
  8144. }
  8145. let tabController = sender.object as? CTTabController
  8146. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  8147. if let doc = self.myDocument, doc.isDocumentEdited {
  8148. Task {
  8149. let resp = await KMAlertTool.runModel(message: KMLocalizedString("File Updated", comment: ""), buttons: [KMLocalizedString("Save", comment: ""), KMLocalizedString("Cancel", comment: "")])
  8150. if resp != .alertFirstButtonReturn { // 取消
  8151. return
  8152. }
  8153. doc.updateChangeCount(.changeCleared)
  8154. self.document?.write(to: doc.fileURL)
  8155. Task { @MainActor in
  8156. self._renameForSavePanel(tabController)
  8157. }
  8158. }
  8159. return
  8160. }
  8161. self._renameForSavePanel(tabController)
  8162. }
  8163. }
  8164. func savePdfAlertView() {
  8165. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  8166. return
  8167. }
  8168. AutoSaveManager.manager.isSaveNoti = true
  8169. var num = 0
  8170. if self.listView.document != nil{
  8171. num = Int(self.listView.document.pageCount)
  8172. }
  8173. if Thread.current.isMainThread {
  8174. self.beginProgressSheet(withMessage: KMLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  8175. } else {
  8176. DispatchQueue.main.async {
  8177. self.beginProgressSheet(withMessage: KMLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  8178. }
  8179. }
  8180. }
  8181. func savePdfFinishAlertView() {
  8182. if !AutoSaveManager.manager.isSaveNoti{
  8183. return
  8184. }
  8185. AutoSaveManager.manager.isSaveNoti = false
  8186. if Thread.current.isMainThread {
  8187. self.dismissProgressSheet()
  8188. } else {
  8189. DispatchQueue.main.async {
  8190. self.dismissProgressSheet()
  8191. }
  8192. }
  8193. }
  8194. private func _renameForSavePanel(_ tabC: CTTabController?) {
  8195. let outputSavePanel = NSSavePanel()
  8196. outputSavePanel.title = KMLocalizedString("Rename", comment: "")
  8197. outputSavePanel.allowedFileTypes = ["pdf"]
  8198. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  8199. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  8200. let resp = outputSavePanel.runModal()
  8201. if resp == .OK {
  8202. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  8203. let fileURL = pdfDocument?.documentURL
  8204. let fileManager = FileManager.default
  8205. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  8206. var result = true
  8207. do {
  8208. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  8209. } catch {
  8210. result = false
  8211. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  8212. }
  8213. if (result) {
  8214. tabC?.title = outputSavePanel.url!.lastPathComponent
  8215. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  8216. self.model.isSaveKeyChain = false
  8217. newPdfDocument.unlock(withPassword: self.document?.password)
  8218. if (newPdfDocument.pageCount > 0) {
  8219. self.setDocument = newPdfDocument
  8220. }
  8221. }
  8222. }
  8223. } else {
  8224. outputSavePanel.close()
  8225. }
  8226. }
  8227. func showInFinder(_ sender: Any) -> Void {
  8228. if sender is NSNotification {
  8229. let tabController = (sender as! NSNotification).object as? CTTabController
  8230. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  8231. if tabController?.title == path {
  8232. if let file = self.myDocument?.fileURL {
  8233. if FileManager.default.fileExists(atPath: file.path) {
  8234. NSWorkspace.shared.activateFileViewerSelecting([file])
  8235. }
  8236. }
  8237. }
  8238. } else {
  8239. guard let url = self.myDocument?.fileURL else { return }
  8240. let file: URL = url
  8241. if FileManager.default.fileExists(atPath: file.path) {
  8242. NSWorkspace.shared.activateFileViewerSelecting([file])
  8243. }
  8244. }
  8245. }
  8246. }
  8247. extension KMMainViewController {
  8248. func cut(_ sender: Any?) {
  8249. if viewManager.isPageEditMode {
  8250. self.pageEditViewController?.cutMenuItemAciton()
  8251. }
  8252. }
  8253. func copy(_ sender: Any?) {
  8254. if viewManager.isPageEditMode {
  8255. self.pageEditViewController?.copyMenuItemAciton()
  8256. }
  8257. }
  8258. func paste(_ sender: Any?) {
  8259. if viewManager.isPageEditMode {
  8260. pageEditViewController?.pastMenuItemAciton(menuitemProperty: nil)
  8261. }
  8262. }
  8263. func delete(_ sender: Any?) {
  8264. if viewManager.isPageEditMode {
  8265. self.pageEditViewController?.deleteMenuItemAciton()
  8266. }
  8267. }
  8268. }