KMMainViewController.swift 426 KB

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