KMMainViewController.swift 297 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790
  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. struct KMNMWCFlags {
  13. var settingUpWindow: Bool = true
  14. }
  15. @objcMembers class KMMainViewController: KMNBaseViewController, NSTextFieldDelegate {
  16. @IBOutlet var contendBox: NSBox!
  17. @IBOutlet var toolbarBox: NSBox! //工具栏Box
  18. @IBOutlet var bottomContendBox: NSBox! //
  19. @IBOutlet var sidebarBox: NSBox! //左侧边栏Box
  20. @IBOutlet var infoContendSplitView: NSSplitView!
  21. @IBOutlet var infoSplitLeftView: NSView!
  22. @IBOutlet var infoSplitRightView: NSView!
  23. @IBOutlet var infoSplitCenterView: NSView!
  24. @IBOutlet var pdfSplitView: NSSplitView!
  25. @IBOutlet var pdfSplitTopView: NSView!
  26. @IBOutlet var pdfSplitBottomView: NSView!
  27. @IBOutlet var toolbarBoxHeightConst: NSLayoutConstraint!
  28. @IBOutlet var infoSplitViewLeftConst: NSLayoutConstraint!
  29. @IBOutlet var infoSplitViewRightConst: NSLayoutConstraint!
  30. var viewManager: KMPDFViewManager = KMPDFViewManager.init()
  31. var toolbarManager: KMPDFToolbarManager = KMPDFToolbarManager.init()
  32. var listView: CPDFListView = CPDFListView.init()
  33. var document: CPDFDocument?
  34. var myDocument: NSDocument?
  35. var isFirstOpen: Bool = true
  36. var insertDocuments: Set<CPDFDocument> = [] //插入新文档时,SDK会出现崩溃,临时记录
  37. //工具栏
  38. private var pdfToolbarController: KMPDFToolbarController?
  39. //BOTA SideBar
  40. private var sideBarController: KMPDFSideBarController?
  41. //页面编辑
  42. private var pageEditViewController: KMNPageEditViewController?
  43. //DisplaySetting
  44. private var displaySettingController: KMNDisplayViewController?
  45. //SPlitPDF分屏视图
  46. private var splitPDFController: KMSplitPDFViewController?
  47. private var pageNumberToolbar: KMPageNumberPromptView?
  48. //PPT操作界面
  49. var presentationTopViewController: KMPresentationTopViewController?
  50. //Edit
  51. var editToolbarView: KMEditToolbarView?
  52. //水印
  53. var watermarkViewController: KMWatermarkController?
  54. //背景
  55. var backgroundViewController: KMBackgroundController?
  56. //Header&Footer
  57. var headerFooterViewController: KMHeaderFooterController?
  58. //Bates
  59. var batesViewController: KMBatesController?
  60. //Crop
  61. var cropController: KMCropController?
  62. //左边
  63. var botaViewController: KMNLeftSideViewController?
  64. //右边
  65. var rightSideController: KMRightSideController?
  66. let alertTipViewController: KMNAlertTipViewController = KMNAlertTipViewController(nibName: "KMNAlertTipViewController", bundle: nil)
  67. //合并
  68. var mergeWindowController: KMMergeWindowController?
  69. //春季活动
  70. var recommondPopWindowVC: KMRecommondPopWindow?
  71. //数字签名状态
  72. var signaturestateVC: CDSignatureCertificateStateViewController = CDSignatureCertificateStateViewController.init()
  73. //PDFView右键菜单
  74. private var groupListMenuGroup: ComponentGroup? = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  75. //MARK: - 旧代码,有需要用到的拿出来,写好备注
  76. @IBOutlet weak var leftView: NSView!
  77. var model = KMMainModel()
  78. //自动滚动
  79. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  80. //Search
  81. var searchIndex: Int = 0
  82. //Secure
  83. var secureAlertView: KMSecureAlertView?
  84. //对比
  85. var isCompareModel: Bool = false {
  86. didSet {
  87. }
  88. }
  89. //密码弹窗
  90. var passwordWindow: KMPasswordInputWindow?
  91. //对比
  92. var compressWindowController: KMCompressWindowController?
  93. //
  94. var securityWindowController: KMSecurityWindowController?
  95. //引导
  96. var guideInfoWindowController: KMGuideInfoWindowController?
  97. //测量
  98. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  99. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  100. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  101. var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  102. private var _needSave = false
  103. var needSave: Bool {
  104. set {
  105. _needSave = newValue
  106. if (_needSave == false) {
  107. self.clearIsPDFDocumentEdited()
  108. }
  109. }
  110. get {
  111. return _needSave
  112. }
  113. }
  114. var isPDFDocumentEdited: Bool {
  115. get {
  116. return self.model.isPDFDocumentEdited
  117. }
  118. }
  119. var newMwcFlags = KMNMWCFlags(settingUpWindow: true)
  120. var searchResults: [KMSearchMode] = []
  121. var mwcFlags: MwcFlags = MwcFlags()
  122. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  123. var currentWindowController: NSWindowController!
  124. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  125. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  126. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  127. var extract: KMExtractImageWindowController?
  128. var functionWidth: Double {
  129. get {
  130. if self.viewManager.isPDFReadMode {
  131. if !self.model.isShowBOTA {
  132. return 0
  133. }
  134. }
  135. return 48-4
  136. }
  137. }
  138. var pageNumber: UInt?
  139. var autoSaveTimer: Timer?
  140. private var _documentFirstLoad: Bool = true
  141. var eventMonitor: Any?
  142. var keyEventMonitor: Any?
  143. var mouseRightMenuEvent: NSEvent?
  144. lazy private var homeVC: KMNHomeViewController? = {
  145. let vc = KMNHomeViewController()
  146. return vc
  147. }()
  148. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  149. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  150. get {
  151. return self._secureOptions
  152. }
  153. }
  154. var documentAttribute: [CPDFDocumentAttribute : Any]?
  155. fileprivate var _removeSecureFlag = false
  156. var removeSecureFlag: Bool {
  157. get {
  158. return self._removeSecureFlag
  159. }
  160. }
  161. fileprivate var _saveWatermarkFlag = false
  162. var saveWatermarkFlag: Bool {
  163. get {
  164. return self._saveWatermarkFlag
  165. }
  166. }
  167. private var mainWindow_: NSWindow?
  168. var mainWindow: NSWindow? {
  169. get {
  170. return self.mainWindow_
  171. }
  172. set {
  173. self.mainWindow_ = newValue
  174. }
  175. }
  176. var setDocument: CPDFDocument? {
  177. get {
  178. return document
  179. }
  180. set {
  181. if document != newValue {
  182. document = newValue
  183. }
  184. listView.document = document
  185. botaViewController?.changeDocument(document: document)
  186. }
  187. }
  188. var setPageNumber: UInt {
  189. get {
  190. return pageNumber!
  191. }
  192. set {
  193. let pageCount = listView.document?.pageCount ?? 0
  194. var value = newValue
  195. if value > pageCount {
  196. value = pageCount
  197. }
  198. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  199. listView.go(to: listView.document?.page(at: value-1))
  200. }
  201. if pageNumber != value {
  202. pageNumber = value
  203. }
  204. }
  205. }
  206. //MARK: - func
  207. deinit {
  208. NotificationCenter.default.removeObserver(self)
  209. self.listView.delegate = nil
  210. self.listView.document?.delegate = nil
  211. self.removeEventMonitor()
  212. self.removeKeyEventMonitor()
  213. }
  214. override func viewDidLoad() {
  215. super.viewDidLoad()
  216. // Do view setup here.
  217. setupData()
  218. setupUI()
  219. NotificationCenter.default.addObserver(self, selector: #selector(pdfViewScrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: listView.documentView())
  220. NotificationCenter.default.addObserver(self, selector: #selector(pageCountChangedNotification), name: NSNotification.Name.CPDFDocumentPageCountChanged, object: listView.document)
  221. loadUserDefaultsData()
  222. }
  223. override func viewDidAppear() {
  224. super.viewDidAppear()
  225. reloadPopUIWindow()
  226. }
  227. override func viewDidDisappear() {
  228. super.viewDidDisappear()
  229. toggleClosePopUIWindow()
  230. }
  231. override func initContentView() {
  232. super.initContentView()
  233. }
  234. override func updateUIThemeColor() {
  235. super.updateUIThemeColor()
  236. }
  237. override func updateUILanguage() {
  238. super.updateUILanguage()
  239. }
  240. //MARK: - private
  241. func setupUI() {
  242. initPDFView()
  243. initToolbar()
  244. initSideBar()
  245. setUpSplitView()
  246. }
  247. func setupData() {
  248. toolbarManager.pdfViewManager = viewManager
  249. if (UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) != nil) {
  250. UserDefaults.standard.set(MIN_SIDE_PANE_WIDTH, forKey: CPDFViewLeftSidePaneWidthKey)
  251. UserDefaults.standard.synchronize()
  252. }
  253. newMwcFlags.settingUpWindow = true
  254. }
  255. //MARK: - document load成功
  256. private func documentLoadComplete() {
  257. loadUserDefaultsData()
  258. initLeftSideController()
  259. addNotificationCenter()
  260. activityLoadMethod()
  261. let readModel = UserDefaults.standard.bool(forKey: CPDFViewIsReadModeKey)
  262. if readModel == true {
  263. self.openPDFReadMode()
  264. }
  265. toggleCloseLeftSide() //根据偏好设置显示左边栏状态
  266. reloadDigitalSigns()
  267. alertTipViewController.showInView(listView)
  268. alertTipViewController.formFieldHighlightCallback = { [weak self] in
  269. CPDFWidgetAnnotation.updateHighlightFormFiled(self?.listView)
  270. self?.toolbarManager.refreshDefaultConfigItem()
  271. }
  272. alertTipViewController.enterPasswordCallback = { [weak self] in
  273. self?.removeOwnerPassword()
  274. }
  275. alertTipViewController.digitalDetailsCallback = { [weak self] in
  276. }
  277. alertTipViewController.redactApplyCallback = { [weak self] in
  278. self?.redactApplyAction()
  279. }
  280. newMwcFlags.settingUpWindow = false
  281. }
  282. private func saveAsPath() {
  283. let saveAccessCtr = KMSavePanelAccessoryController()
  284. var fileName = listView.document.documentURL.deletingPathExtension().lastPathComponent
  285. fileName = String(format: "%@_%@.pdf", fileName, "Redact")
  286. let outputSavePanel = NSSavePanel()
  287. outputSavePanel.allowedFileTypes = ["pdf"]
  288. outputSavePanel.nameFieldStringValue = fileName
  289. outputSavePanel.accessoryView = saveAccessCtr.view
  290. outputSavePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  291. if result == .OK {
  292. self.listView.document.applyRedactions()
  293. self.showProgressWindow(message: KMLocalizedString("Save") + "PDF")
  294. self.progressC?.maxValue = 3.0
  295. self.progressC?.increment(by: 1.0)
  296. let savePDFPath = outputSavePanel.url!.path
  297. // 执行进度 [假进度]
  298. self.progressC?.increment(by: 1.0)
  299. self.progressC?.increment(by: 1.0)
  300. let isSuccess = self.listView.document.write(toFile: savePDFPath)
  301. if (isSuccess) {
  302. if (saveAccessCtr.openAutomaticButton.state == .on) {
  303. NSDocumentController.shared.km_safe_openDocument(withContentsOf: outputSavePanel.url!, display: true) { _, _, _ in
  304. }
  305. } else {
  306. let url = URL(fileURLWithPath: savePDFPath)
  307. NSWorkspace.shared.activateFileViewerSelecting([url])
  308. }
  309. }
  310. self.hiddenProgressWindow()
  311. }
  312. }
  313. }
  314. private func reloadDigitalSigns() {
  315. let signatures = listView.document.signatures()
  316. for i in 0 ..< (signatures?.count ?? 0) {
  317. let signature:CPDFSignature = signatures?[i] ?? CPDFSignature()
  318. if signature.signers.count > 0 {
  319. signature.verifySignature(with: listView.document)//耗时,注意
  320. }
  321. }
  322. listView.signatures = signatures
  323. }
  324. //MARK: - 活动加载相关
  325. private func activityLoadMethod() {
  326. }
  327. private func addNotificationCenter() {
  328. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  329. NotificationCenter.default.addObserver(self, selector: #selector(signatureStateChangeNoti), name: NSNotification.Name(rawValue: "CSignatureTrustCerDidChangeNotification"), object: nil)
  330. }
  331. private func loadUserDefaultsData() {
  332. applyLeftSideWidth(0, rightSideWidth: 0) //初始打开左边栏
  333. }
  334. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  335. infoContendSplitView.setPosition(infoContendSplitView.maxPossiblePositionOfDivider(at: 1) - infoContendSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  336. infoContendSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  337. }
  338. //MARK: - PDFView
  339. func initPDFView() {
  340. listView.autoresizingMask = [.width, .height]
  341. listView.autoScales = true
  342. listView.delegate = self
  343. listView.pdfListViewDelegate = self
  344. listView.document = self.document
  345. listView.pageBreakMargins = NSEdgeInsetsMake(10, 0, 10, 10)
  346. reloadPDFSplitInfo()
  347. }
  348. func updatePDFViewAnnotationMode() {
  349. let toolbarMode = viewManager.toolMode
  350. let subToolMode = viewManager.subToolMode
  351. listView.isHidden = false
  352. if toolbarMode == .None {
  353. listView.annotationType = .unkown
  354. } else if toolbarMode == .Markup {
  355. if subToolMode == .None {
  356. listView.toolMode = .CTextToolMode
  357. } else {
  358. listView.toolMode = .CNoteToolMode
  359. }
  360. //MARK: -Markup
  361. if subToolMode == .None {
  362. listView.annotationType = .unkown
  363. } else if subToolMode == .Highlight {
  364. listView.annotationType = .highlight
  365. } else if subToolMode == .Underline {
  366. listView.annotationType = .underline
  367. } else if subToolMode == .Waveline {
  368. listView.annotationType = .squiggly
  369. } else if subToolMode == .Strikethrough {
  370. listView.annotationType = .strikeOut
  371. } else if subToolMode == .Text {
  372. listView.annotationType = .freeText
  373. } else if subToolMode == .Note {
  374. listView.annotationType = .anchored
  375. } else if subToolMode == .Pen {
  376. listView.annotationType = .ink
  377. } else if subToolMode == .Eraser {
  378. listView.annotationType = .eraser
  379. } else if subToolMode == .Rectangle {
  380. listView.annotationType = .square
  381. } else if subToolMode == .Circle {
  382. listView.annotationType = .circle
  383. } else if subToolMode == .Arrow {
  384. listView.annotationType = .arrow
  385. } else if subToolMode == .Line {
  386. listView.annotationType = .line
  387. } else if subToolMode == .Measure {
  388. listView.annotationType = CPDFMeasureDefaultInfo.default_measureType()
  389. } else if subToolMode == .Stamp {
  390. listView.annotationType = .stamp
  391. } else if subToolMode == .Sign {
  392. listView.annotationType = .signSignature
  393. }
  394. } else if toolbarMode == .Edit {
  395. //MARK: -编辑
  396. if subToolMode == .None {
  397. if listView.toolMode != .CEditPDFToolMode {
  398. listView.toolMode = .CEditPDFToolMode
  399. listView.configPDFEditingInfo()
  400. }
  401. listView.setShouAddEdit([])
  402. listView.change([.text, .image])
  403. } else if subToolMode == .Edit_text {
  404. if listView.toolMode != .CEditPDFToolMode {
  405. listView.toolMode = .CEditPDFToolMode
  406. listView.configPDFEditingInfo()
  407. }
  408. listView.setShouAddEdit([.text])
  409. listView.change(.text)
  410. } else if subToolMode == .Edit_Image {
  411. if listView.toolMode != .CEditPDFToolMode {
  412. listView.toolMode = .CEditPDFToolMode
  413. listView.configPDFEditingInfo()
  414. }
  415. listView.setShouAddEdit([.image])
  416. listView.change(.image)
  417. } else if subToolMode == .Edit_Link {
  418. listView.toolMode = .CEditLinkToolMode
  419. listView.annotationType = .link
  420. } else if subToolMode == .Edit_Crop {
  421. listView.isHidden = true
  422. listView.toolMode = .CCropToolMode
  423. }
  424. if viewManager.editType == .watermark ||
  425. viewManager.editType == .background ||
  426. viewManager.editType == .header_Footer ||
  427. viewManager.editType == .bates {
  428. listView.isHidden = true
  429. listView.toolMode = .CTextToolMode
  430. }
  431. if subToolMode != .Edit_Crop {
  432. removeCropController()
  433. }
  434. self.showOCREditAlert()
  435. } else if toolbarMode == .Form {
  436. //MARK: -Form表单
  437. listView.toolMode = .CFormToolMode
  438. if subToolMode == .None {
  439. listView.annotationType = .unkown
  440. } else if subToolMode == .Form_text {
  441. listView.annotationType = .textField
  442. } else if subToolMode == .Form_checkbox {
  443. listView.annotationType = .checkBox
  444. } else if subToolMode == .Form_radio {
  445. listView.annotationType = .radioButton
  446. } else if subToolMode == .Form_list {
  447. listView.annotationType = .listMenu
  448. } else if subToolMode == .Form_dropdown {
  449. listView.annotationType = .comboBox
  450. } else if subToolMode == .Form_OK {
  451. listView.annotationType = .actionButton
  452. } else if subToolMode == .Form_digitalSign {
  453. listView.annotationType = .signature
  454. }
  455. } else if toolbarMode == .Fill {
  456. //MARK: -填充
  457. if subToolMode == .None {
  458. listView.toolMode = .CTextToolMode
  459. } else {
  460. listView.toolMode = .CNoteToolMode
  461. }
  462. if subToolMode == .None {
  463. } else if subToolMode == .Fill_tick {
  464. listView.annotationType = .signTure
  465. } else if subToolMode == .fill_fork {
  466. listView.annotationType = .signFalse
  467. } else if subToolMode == .fill_rectangle {
  468. listView.annotationType = .signCircle
  469. } else if subToolMode == .fill_line {
  470. listView.annotationType = .signLine
  471. } else if subToolMode == .fill_dot {
  472. listView.annotationType = .signDot
  473. } else if subToolMode == .fill_date {
  474. listView.annotationType = .signDate
  475. } else if subToolMode == .fill_sign {
  476. listView.annotationType = .signSignature
  477. }
  478. } else if toolbarMode == .Convert {
  479. //MARK: -转档
  480. listView.toolMode = .CTextToolMode
  481. } else if toolbarMode == .Protect {
  482. //MARK: -Protect
  483. listView.toolMode = .CTextToolMode
  484. if subToolMode == .Redact {
  485. //密文
  486. listView.annotationType = .redact
  487. listView.toolMode = .CRedactToolMode
  488. } else if subToolMode == .Digital_Sign {
  489. //数字签名
  490. listView.annotationType = .digitalSign
  491. listView.toolMode = .CDigitalSignToolMode
  492. }
  493. } else if toolbarMode == .Tools {
  494. //MARK: -工具
  495. // if subToolMode == .Tool_OCR {
  496. // listView.toolMode = .COCRToolMode
  497. // } else {
  498. // listView.toolMode = .CTextToolMode
  499. // }
  500. }
  501. if (toolbarMode != .Edit) {
  502. self.closeOCREditAlert()
  503. }
  504. }
  505. func showOrHideNotes() {
  506. self.listView.hideNotes = !self.listView.hideNotes
  507. if self.listView.hideNotes {
  508. listView.annotationType = .unkown
  509. }
  510. }
  511. //MARK: - SplitView
  512. func setUpSplitView() {
  513. infoContendSplitView.wantsLayer = true
  514. infoContendSplitView.layer?.backgroundColor = NSColor.clear.cgColor
  515. infoContendSplitView.delegate = self
  516. infoContendSplitView.layer?.masksToBounds = true
  517. }
  518. func setupSplitPDFController() {
  519. if splitPDFController == nil {
  520. splitPDFController = KMSplitPDFViewController.init()
  521. }
  522. splitPDFController?.view.frame = pdfSplitBottomView.bounds
  523. splitPDFController?.view.autoresizingMask = [.height, .width]
  524. splitPDFController?.viewManager = self.viewManager
  525. splitPDFController?.delegate = self
  526. splitPDFController?.pdfView?.pdfListViewDelegate = self
  527. splitPDFController?.reloadData()
  528. pdfSplitBottomView.addSubview(splitPDFController!.view)
  529. }
  530. //MARK: - 工具栏
  531. func initToolbar() {
  532. toolbarBox.borderWidth = 0
  533. if pdfToolbarController == nil {
  534. pdfToolbarController = KMPDFToolbarController.init()
  535. }
  536. pdfToolbarController?.view.frame = toolbarBox.bounds
  537. pdfToolbarController?.view.autoresizingMask = [.width, .height]
  538. pdfToolbarController?.delegate = self
  539. toolbarBox.contentView = pdfToolbarController?.view
  540. pdfToolbarController?.viewManager = viewManager
  541. pdfToolbarController?.toolbarManager = toolbarManager
  542. pdfToolbarController?.pdfView = listView
  543. pdfToolbarController?.setUpData()
  544. refreshToolbarViewHeightInfo()
  545. if listView.showFormFieldName {
  546. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  547. } else {
  548. toolbarManager.form_ShowName_Property.righticon = nil
  549. }
  550. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
  551. self.pdfToolbarController?.clickWithIdentify(KMPDFToolbar_Markup_Identifier)
  552. }
  553. }
  554. func refreshToolbarViewHeightInfo() {
  555. let _viewManager = viewManager
  556. if viewManager.isPageEditMode {
  557. toolbarBoxHeightConst.constant = 80
  558. } else if viewManager.editType == .watermark ||
  559. viewManager.editType == .background ||
  560. viewManager.editType == .header_Footer ||
  561. viewManager.editType == .bates {
  562. toolbarBoxHeightConst.constant = 40
  563. } else if _viewManager.toolMode == .Markup ||
  564. _viewManager.toolMode == .Edit ||
  565. _viewManager.toolMode == .Form ||
  566. _viewManager.toolMode == .Fill ||
  567. _viewManager.toolMode == .Convert ||
  568. _viewManager.toolMode == .Protect ||
  569. _viewManager.toolMode == .Tools {
  570. toolbarBoxHeightConst.constant = 80
  571. if _viewManager.subToolMode == .Redact {
  572. toolbarBoxHeightConst.constant = 40
  573. }
  574. } else {
  575. toolbarBoxHeightConst.constant = 40
  576. }
  577. }
  578. func toolbarViewModeChanged() {
  579. updatePDFViewAnnotationMode()
  580. refreshToolbarRightViewInfo()
  581. if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
  582. removeCropController()
  583. }
  584. }
  585. //MARK: - 右边属性栏
  586. func refreshToolbarRightViewInfo() {
  587. //统一刷新viewManager.showRightSide, 由这个参数控制右边属性边框的展开与隐藏
  588. if viewManager.showRightSide == true {
  589. toolbarManager.rightViewProperty.state = .pressed
  590. toggleOpenRightSide()
  591. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  592. } else {
  593. toggleCloseRightSide()
  594. }
  595. if viewManager.showRightSide == true {
  596. toolbarManager.rightViewProperty.state = .pressed
  597. } else {
  598. toolbarManager.rightViewProperty.state = .normal
  599. }
  600. pdfToolbarController?.reloadRightToolsView()
  601. }
  602. //MARK: - 侧边工具栏
  603. func initSideBar() {
  604. sidebarBox.borderWidth = 0
  605. if sideBarController == nil {
  606. sideBarController = KMPDFSideBarController.init()
  607. }
  608. sideBarController?.view.frame = sidebarBox.bounds
  609. sideBarController?.view.autoresizingMask = [.width, .height]
  610. sidebarBox.contentView = sideBarController?.view
  611. sideBarController?.pdfView = listView
  612. sideBarController?.delegate = self
  613. sideBarController?.pdfViewManager = viewManager
  614. sideBarController?.reloadData()
  615. }
  616. //MARK: - 左边侧边栏
  617. func initLeftSideController() {
  618. if botaViewController == nil {
  619. botaViewController = KMNLeftSideViewController(listView.document)
  620. }
  621. botaViewController?.leftSideViewDelegate = self
  622. botaViewController?.view.frame = infoSplitLeftView.bounds
  623. botaViewController?.view.autoresizingMask = [.width, .height]
  624. if botaViewController != nil {
  625. infoSplitLeftView?.addSubview(botaViewController!.view)
  626. }
  627. }
  628. private func leftSidePaneIsOpen() -> Bool {
  629. return !infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) //第一次点击时存在问题,待解决
  630. }
  631. private func toggleOpenLeftSide(pdfSideBarType: KMPDFSidebarType) {
  632. if(leftSidePaneIsOpen() == false) {
  633. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) as? NSNumber ?? MIN_SIDE_PANE_WIDTH
  634. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0) //暂时无法记录上一次打开的宽度
  635. }
  636. if pdfSideBarType == .search {
  637. botaViewController?.searchViewC.handdler.pdfView = listView
  638. botaViewController?.leftsideType = .search
  639. } else if pdfSideBarType == .thumbnail {
  640. botaViewController?.leftsideType = pdfSideBarType
  641. botaViewController?.thumnailViewController?.reloadDatas()
  642. botaViewController?.currentPageDidChangedAction(listView: listView)
  643. } else if pdfSideBarType == .outline {
  644. botaViewController?.outlineViewC.handdler.pdfView = listView
  645. botaViewController?.leftsideType = pdfSideBarType
  646. } else if pdfSideBarType == .bookmark {
  647. botaViewController?.bookmarkViewC.handdler.pdfView = listView
  648. botaViewController?.leftsideType = pdfSideBarType
  649. } else if pdfSideBarType == .annotation {
  650. // botaViewController?.annoController.handdler.pdfView = listView
  651. // botaViewController?.leftsideType = .annotation
  652. }
  653. }
  654. private func toggleCloseLeftSide() {
  655. if(leftSidePaneIsOpen() == true) {
  656. infoContendSplitView.setPosition(0, ofDividerAt: 0)
  657. }
  658. }
  659. //MARK: - 右侧属性栏
  660. func initRightSideController() {
  661. if rightSideController == nil {
  662. rightSideController = KMRightSideController.init()
  663. rightSideController?.delegate = self
  664. }
  665. rightSideController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, 680)
  666. rightSideController?.view.autoresizingMask = [.height, .maxXMargin]
  667. }
  668. func removeRightSideController() {
  669. rightSideController?.view.removeFromSuperview()
  670. rightSideController = nil
  671. }
  672. @objc func toggleOpenRightSide() -> Void {
  673. if rightSideController != nil {
  674. return
  675. }
  676. initRightSideController()
  677. rightSideController?.view.frame = infoSplitRightView.bounds
  678. rightSideController?.view.autoresizingMask = [.width, .height]
  679. infoSplitRightView.addSubview(rightSideController!.view)
  680. infoContendSplitView.setPosition(CGRectGetWidth(view.frame)-MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 1)
  681. rightSideController?.viewManager = self.viewManager
  682. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  683. }
  684. @objc func toggleCloseRightSide() -> Void {
  685. removeRightSideController()
  686. infoContendSplitView.setPosition(CGRectGetWidth(view.frame), ofDividerAt: 1)
  687. }
  688. func refreshRightSide() -> Void {
  689. if let rightVC = rightSideController, let _ = rightSideController?.view.superview {
  690. rightVC.reloadDataWithPDFView(pdfView: listView)
  691. }
  692. }
  693. //MARK: - PDFDisplayView
  694. func updatePDFDisplaySettingView() {
  695. if viewManager.showDisplayView {
  696. infoSplitViewLeftConst.constant = MIN_SIDE_PANE_WIDTH.doubleValue
  697. } else {
  698. infoSplitViewLeftConst.constant = 44
  699. }
  700. if viewManager.showDisplayView {
  701. if displaySettingController == nil {
  702. displaySettingController = KMNDisplayViewController.init()
  703. }
  704. displaySettingController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, CGRectGetHeight(bottomContendBox.frame))
  705. displaySettingController?.view.autoresizingMask = [.height, .maxXMargin]
  706. bottomContendBox.addSubview(displaySettingController!.view)
  707. displaySettingController?.pdfView = self.listView
  708. displaySettingController?.viewManager = self.viewManager
  709. displaySettingController?.delegate = self
  710. displaySettingController?.reloadData()
  711. } else {
  712. displaySettingController?.view.removeFromSuperview()
  713. displaySettingController = nil
  714. }
  715. }
  716. //MARK: - 页面编辑
  717. func enterPageEditMode() {
  718. pageEditViewController = KMNPageEditViewController(self.document)
  719. if(pageEditViewController != nil) {
  720. bottomContendBox.addSubview(pageEditViewController!.view)
  721. pageEditViewController?.view.frame = bottomContendBox.bounds
  722. pageEditViewController?.thumbnailBaseViewDelegate = self
  723. pageEditViewController?.selectionIndexPaths = [IndexPath(item: listView.currentPageIndex, section: 0)]
  724. pageEditViewController?.view.autoresizingMask = [.width,.height]
  725. pageEditViewController?.currentUndoManager = listView.undoManager
  726. toolbarManager.page_pageInfo_Property.text = String(listView.currentPageIndex + 1)
  727. pdfToolbarController?.refreshSecondToolbarItemsState()
  728. listView.isHidden = true
  729. }
  730. }
  731. func exitPageEditMode() {
  732. if pageEditViewController != nil {
  733. pageEditViewController?.view.removeFromSuperview()
  734. pageEditViewController = nil
  735. }
  736. listView.isHidden = false
  737. if listView.document?.isModified() == true {
  738. listView.layoutDocumentView()
  739. botaViewController?.thumnailViewController?.reloadDatas()
  740. }
  741. }
  742. //MARK: - 阅读模式
  743. func openPDFReadMode() {
  744. if viewManager.showDisplayView {
  745. viewManager.showDisplayView = false
  746. pdfToolbarController?.reloadLeftIconView()
  747. updatePDFDisplaySettingView()
  748. }
  749. infoSplitViewLeftConst.constant = 0
  750. toolbarBoxHeightConst.constant = 0
  751. view.window?.makeFirstResponder(listView)
  752. let readModeMessage: ComponentMessage = ComponentMessage()
  753. readModeMessage.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode On"))
  754. readModeMessage.frame = CGRectMake((CGRectGetWidth(self.view.frame) - readModeMessage.properties.propertyInfo.viewWidth)/2,
  755. CGRectGetHeight(self.view.frame) - readModeMessage.properties.propertyInfo.viewHeight - 8,
  756. readModeMessage.properties.propertyInfo.viewWidth,
  757. readModeMessage.properties.propertyInfo.viewHeight)
  758. readModeMessage.reloadData()
  759. readModeMessage.show(inView: self.view, autoHideSeconde: 2)
  760. setUpPDFPageNumberToolbar()
  761. }
  762. func exitPDFReadMode() {
  763. viewManager.isPDFReadMode = false
  764. if viewManager.showDisplayView == false {
  765. viewManager.showDisplayView = true
  766. pdfToolbarController?.reloadLeftIconView()
  767. }
  768. updatePDFDisplaySettingView()
  769. refreshToolbarViewHeightInfo()
  770. reloadPDFPageNumberToolbar()
  771. let readModeMessage: ComponentMessage = ComponentMessage()
  772. readModeMessage.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode Off"))
  773. readModeMessage.frame = CGRectMake((CGRectGetWidth(self.view.frame) - readModeMessage.properties.propertyInfo.viewWidth)/2,
  774. CGRectGetHeight(self.view.frame) - readModeMessage.properties.propertyInfo.viewHeight - 8,
  775. readModeMessage.properties.propertyInfo.viewWidth,
  776. readModeMessage.properties.propertyInfo.viewHeight)
  777. readModeMessage.reloadData()
  778. readModeMessage.show(inView: self.view, autoHideSeconde: 2)
  779. }
  780. //MARK: - PPT
  781. func togglePresentation(_ sender: Any?) {
  782. if self.canExitPresentation() {
  783. exitFullScreen()
  784. } else if self.canEnterPresentation() {
  785. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  786. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  787. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  788. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  789. view.window?.enterPresentation(provider: self)
  790. }
  791. }
  792. func enterPresentationMode() {
  793. let scrollView = listView.documentView().enclosingScrollView
  794. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  795. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  796. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  797. listView.backgroundColor = NSColor.clear
  798. listView.setDisplay(.singlePage)
  799. listView.autoScales = true
  800. listView.displayBox = .cropBox
  801. listView.displaysPageBreaks = false
  802. scrollView?.autohidesScrollers = true
  803. scrollView?.hasHorizontalScroller = false
  804. scrollView?.hasVerticalScroller = false
  805. listView.setCurrentSelection(nil, animate: true)
  806. }
  807. func exitPresentationMode() {
  808. NotificationCenter.default.removeObserver(self, name: NSWindow.willEnterInteractionModeNotification, object: nil)
  809. NotificationCenter.default.removeObserver(self, name: NSWindow.didEnterInteractionModeNotification, object: nil)
  810. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  811. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  812. }
  813. func exitFullScreen() {
  814. if self.canExitPresentation() == true {
  815. let mainDocument = self.myDocument as? KMMainDocument
  816. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  817. browserWindowController?.exitFullscreen()
  818. }
  819. }
  820. func exitFullscreenMode() {
  821. if self.interactionMode == .presentation {
  822. self.exitPresentationMode()
  823. }
  824. self.applyPDFSettings(self.savedNormalSetup)
  825. self.savedNormalSetup.removeAllObjects()
  826. listView.layoutDocumentView()
  827. listView.requiresDisplay()
  828. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  829. listView.backgroundColor = backgroundColor
  830. }
  831. }
  832. func applyPDFSettings(_ setup: NSDictionary) {
  833. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  834. self.listView.autoScales = data.boolValue
  835. }
  836. if self.listView.autoScales == false {
  837. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  838. self.listView.scaleFactor = data.floatValue.cgFloat
  839. }
  840. }
  841. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  842. self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
  843. }
  844. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  845. self.listView.displaysAsBook = data.boolValue
  846. }
  847. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  848. self.listView.displaysPageBreaks = data.boolValue
  849. }
  850. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  851. }
  852. self.listView.layoutDocumentView()
  853. }
  854. func currentPDFSettings() -> NSDictionary {
  855. let setup = NSMutableDictionary()
  856. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  857. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  858. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  859. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  860. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  861. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
  862. return setup
  863. }
  864. func canEnterFullscreen() -> Bool {
  865. if (mwcFlags.isSwitchingFullScreen != 0) {
  866. return false
  867. }
  868. if useNativeFullScreen() {
  869. return interactionMode == .normal || interactionMode == .presentation
  870. } else {
  871. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  872. }
  873. }
  874. override func canEnterPresentation() -> Bool {
  875. let can = super.canEnterPresentation()
  876. if can == false {
  877. return false
  878. }
  879. guard let doc = self.listView.document, doc.isLocked == false else {
  880. return false
  881. }
  882. return can
  883. }
  884. func fadeOutFullScreenWindow() {
  885. guard let fullScreenWindow = self.view.window as? KMFullScreenWindow else {
  886. NSSound.beep()
  887. return
  888. }
  889. let mainWindow = fullScreenWindow.interactionParent
  890. let collectionBehavior = mainWindow?.collectionBehavior
  891. mainWindow?.alphaValue = 0
  892. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  893. mainWindow?.animationBehavior = .none
  894. }
  895. // trick to make sure the main window shows up in the same space as the fullscreen window
  896. fullScreenWindow.addChildWindow(mainWindow!, ordered: .below)
  897. fullScreenWindow.removeChildWindow(mainWindow!)
  898. fullScreenWindow.level = .popUpMenu
  899. // these can change due to the child window trick
  900. mainWindow?.level = .normal
  901. mainWindow?.alphaValue = 1.0
  902. mainWindow?.collectionBehavior = collectionBehavior!
  903. mainWindow?.display()
  904. mainWindow?.makeFirstResponder(self.listView)
  905. mainWindow?.recalculateKeyViewLoop()
  906. // mainWindow?.delegate = self
  907. mainWindow?.makeKey()
  908. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  909. mainWindow?.animationBehavior = .default
  910. }
  911. NSApp.removeWindowsItem(fullScreenWindow)
  912. fullScreenWindow.fadeOut()
  913. }
  914. //MARK: - PDF分屏视图
  915. func reloadPDFSplitInfo() {
  916. if listView.viewSplitMode == .disable {
  917. pdfSplitView.isHidden = true
  918. listView.frame = infoSplitCenterView.bounds
  919. infoSplitCenterView.addSubview(listView)
  920. if splitPDFController != nil {
  921. splitPDFController = nil
  922. }
  923. } else {
  924. pdfSplitView.isHidden = false
  925. listView.frame = pdfSplitTopView.bounds
  926. pdfSplitTopView.addSubview(listView)
  927. setUpPDFPageNumberToolbar()
  928. setupSplitPDFController()
  929. if listView.viewSplitMode == .horizontal {
  930. pdfSplitView.isVertical = false
  931. } else if listView.viewSplitMode == .vertical {
  932. pdfSplitView.isVertical = true
  933. }
  934. }
  935. }
  936. func setUpPDFPageNumberToolbar() {
  937. if pageNumberToolbar != nil {
  938. pageNumberToolbar?.removeFromSuperview()
  939. pageNumberToolbar = nil
  940. }
  941. if pageNumberToolbar == nil {
  942. pageNumberToolbar = KMPageNumberPromptView.init()
  943. }
  944. pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-144, 20, 288, 40)
  945. pageNumberToolbar?.autoresizingMask = [.minXMargin, .maxXMargin, .maxYMargin]
  946. pageNumberToolbar?.pdfView = self.listView
  947. pageNumberToolbar?.reloadData()
  948. pageNumberToolbar?.isHidden = true
  949. listView.addSubview(pageNumberToolbar!)
  950. reloadPDFPageNumberToolbar()
  951. }
  952. func reloadPDFPageNumberToolbar() {
  953. if viewManager.isPDFReadMode == true ||
  954. (viewManager.splitShowBottomBar && listView.viewSplitMode != .disable) {
  955. pageNumberToolbar?.isHidden = false
  956. pageNumberToolbar?.reloadData()
  957. } else {
  958. pageNumberToolbar?.isHidden = true
  959. }
  960. }
  961. //MARK: - Edit模式
  962. func showEditToolbarView() {
  963. if editToolbarView == nil {
  964. editToolbarView = KMEditToolbarView()
  965. }
  966. editToolbarView?.frame = toolbarBox.bounds
  967. editToolbarView?.delegate = self
  968. editToolbarView?.autoresizingMask = [.width, .height]
  969. toolbarBox.contentView = editToolbarView
  970. }
  971. func exitEditToolbarView() {
  972. viewManager.editType = .none
  973. viewManager.subToolMode = .None
  974. editToolbarView?.removeFromSuperview()
  975. editToolbarView = nil
  976. watermarkViewController?.view.removeFromSuperview()
  977. watermarkViewController = nil
  978. backgroundViewController?.view.removeFromSuperview()
  979. backgroundViewController = nil
  980. headerFooterViewController?.view.removeFromSuperview()
  981. headerFooterViewController = nil
  982. batesViewController?.view.removeFromSuperview()
  983. batesViewController = nil
  984. refreshToolbarViewHeightInfo()
  985. toolbarBox.contentView = pdfToolbarController?.view
  986. updatePDFViewAnnotationMode()
  987. }
  988. func updateEditModeDocumentWhenPageChanged() {
  989. if viewManager.editType == .watermark {
  990. updateWatermarkDocument()
  991. } else if viewManager.editType == .background {
  992. updateBackgroundDocument()
  993. } else if viewManager.editType == .header_Footer {
  994. updateHeaderFooterDocument()
  995. } else if viewManager.editType == .bates {
  996. updateBatesDocument()
  997. } else if viewManager.subToolMode == .Edit_Crop {
  998. updateCropDocument()
  999. }
  1000. }
  1001. //MARK: - 数字签名
  1002. func writeSignatureToWidget(_ widget: CPDFSignatureWidgetAnnotation, _ path: String, _ password: String, _ config: CPDFSignatureConfig, _ isLock: Bool) ->() {
  1003. let fileName = listView.document.documentURL?.lastPathComponent
  1004. let fileNameWithoutExtension = URL(fileURLWithPath: fileName!).deletingPathExtension().lastPathComponent
  1005. let outputSavePanel = NSSavePanel()
  1006. outputSavePanel.directoryURL = listView.document.documentURL.deletingLastPathComponent()
  1007. outputSavePanel.title = NSLocalizedString("", comment: "Save as PDF")
  1008. outputSavePanel.allowedFileTypes = ["pdf"]
  1009. outputSavePanel.nameFieldStringValue = fileNameWithoutExtension + "_" + NSLocalizedString("Signed", comment: "")
  1010. let result = outputSavePanel.runModal()
  1011. if result == .OK {
  1012. let contentArr = NSMutableArray()
  1013. var locationStr = ""
  1014. var reasonStr = NSLocalizedString("none", comment: "")
  1015. for item in config.contents {
  1016. if item.key == NSLocalizedString("Reason", comment: "") {
  1017. if item.value == NSLocalizedString("<your signing reason here>", comment: "") {
  1018. item.value = " " + NSLocalizedString("none", comment: "")
  1019. }
  1020. reasonStr = item.value
  1021. } else if item.key == NSLocalizedString("Location", comment: "") {
  1022. if item.value == NSLocalizedString("<your signing location here>", comment: "") {
  1023. item.value = " "
  1024. }
  1025. locationStr = item.value
  1026. }
  1027. contentArr.add(item)
  1028. }
  1029. config.contents = contentArr as? [CPDFSignatureConfigItem]
  1030. widget.setFieldName(widget.getValidName(inPage: widget.page))
  1031. widget.signAppearanceConfig(config)
  1032. let success = listView.document.writeSignature(to: outputSavePanel.url, withWidget: widget, pkcs12Cert: path, password: password, location: locationStr, reason: reasonStr, permissions: .forbidChange)
  1033. widget.removeSignature()
  1034. if success {
  1035. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1036. NSDocumentController.shared.openDocument(withContentsOf: outputSavePanel.url!, display: true) { document, documentWasAlreadyOpen, error in
  1037. if error != nil {
  1038. NSApp.presentError(error!)
  1039. return
  1040. }
  1041. }
  1042. }
  1043. } else {
  1044. let alert = NSAlert.init()
  1045. alert.messageText = NSLocalizedString("Save failed!", comment: "")
  1046. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  1047. alert.runModal()
  1048. }
  1049. widget.page.removeAnnotation(widget)
  1050. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1051. } else {
  1052. widget.page.removeAnnotation(widget)
  1053. listView.setNeedsDisplayAnnotationViewFor(widget.page)
  1054. }
  1055. }
  1056. func popUpSignatureWidgetState(_ signature: CPDFSignature, _ pdfListView: CPDFListView) ->(){
  1057. signaturestateVC.signature = signature
  1058. signaturestateVC.pdfListView = pdfListView
  1059. signaturestateVC.actionBlock = { [weak self, weak signaturestateVC] stateVCSelf, actionType in
  1060. guard let weakSelf = self, let stateVC = signaturestateVC else { return }
  1061. if actionType == .cancel {
  1062. stateVC.dismiss(stateVCSelf)
  1063. } else if actionType == .confirm {
  1064. if let signer = signature.signers.first, let data = signer.certificates {
  1065. let signatureDetail = DSignatureDetailsViewController.init()
  1066. signatureDetail.certificates = data
  1067. signatureDetail.signature = signature
  1068. signatureDetail.pdfListView = pdfListView
  1069. stateVCSelf.presentAsSheet(signatureDetail)
  1070. } else {
  1071. NSSound.beep()
  1072. }
  1073. }
  1074. }
  1075. self.presentAsSheet(signaturestateVC)
  1076. signaturestateVC.reloadData()
  1077. }
  1078. // MARK: - 显示合并窗口
  1079. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1080. DispatchQueue.main.async {
  1081. var documentURL = url
  1082. if documentURL == nil {
  1083. documentURL = self.listView.document?.documentURL
  1084. }
  1085. guard let _url = documentURL else { return }
  1086. guard let document = PDFDocument(url: _url) else { return }
  1087. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  1088. self.mergeWindowController!.oriDucumentUrl = self.listView.document?.documentURL
  1089. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1090. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1091. self.view.window?.endSheet(mergeWindowController!.window!)
  1092. }
  1093. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1094. self.view.window?.endSheet(mergeWindowController!.window!)
  1095. }
  1096. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1097. }
  1098. }
  1099. //MARK: - Crop裁剪
  1100. func showCropController() {
  1101. if cropController == nil {
  1102. cropController = KMCropController.init()
  1103. cropController?.view.frame = infoSplitCenterView.bounds
  1104. cropController?.view.autoresizingMask = [.width, .height]
  1105. cropController?.delegate = self
  1106. infoSplitCenterView.addSubview(cropController!.view)
  1107. updateCropDocument()
  1108. if viewManager.showRightSide == false {
  1109. viewManager.showRightSide = true
  1110. refreshToolbarRightViewInfo()
  1111. }
  1112. }
  1113. }
  1114. func updateCropDocument() {
  1115. guard let controller = cropController else { return }
  1116. controller.pdfDocument = nil
  1117. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1118. let editDocument = CPDFDocument.init()
  1119. editDocument?.insertPageObject(page, at: 0)
  1120. if let editPage = editDocument?.page(at: 0) {
  1121. editPage.setBounds(CGRectMake(0, 0, editPage.bounds(for: .mediaBox).size.width, editPage.bounds(for: .mediaBox).size.height), for: .cropBox)
  1122. controller.selectionRect = page?.bounds(for: .cropBox) ?? .zero
  1123. }
  1124. controller.pdfDocument = editDocument
  1125. controller.reloadData()
  1126. }
  1127. func removeCropController() {
  1128. if cropController != nil {
  1129. cropController?.view.removeFromSuperview()
  1130. cropController = nil
  1131. toolbarManager.edit_crop_Property.state = .normal
  1132. }
  1133. }
  1134. // MARK: - Secure 【安全】
  1135. public func hiddenSecureLimitTip() {
  1136. self.secureAlertView?.removeFromSuperview()
  1137. self.secureAlertView = nil
  1138. }
  1139. func savePageNumberIfNeed() {
  1140. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1141. let scaleFactor = self.listView.scaleFactor ?? 0
  1142. if scaleFactor <= 0 {
  1143. return
  1144. }
  1145. if self.listView.document != nil {
  1146. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1147. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1148. }
  1149. }
  1150. }
  1151. // MARK: -显示加密弹窗
  1152. public func showSecureWindow() {
  1153. guard let url = self.listView.document?.documentURL else {
  1154. return
  1155. }
  1156. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1157. guard let securityWindowController = securityWindowController else { return }
  1158. securityWindowController.documentURL = self.listView.document?.documentURL
  1159. securityWindowController.batchAction = { [unowned self] controller, files in
  1160. self.view.window?.endSheet((securityWindowController.window)!)
  1161. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1162. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1163. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1164. batchWindowController.window?.makeKeyAndOrderFront("")
  1165. }
  1166. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1167. let openPanel = NSOpenPanel()
  1168. openPanel.canChooseFiles = false
  1169. openPanel.canChooseDirectories = true
  1170. openPanel.canCreateDirectories = true
  1171. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1172. if result == NSApplication.ModalResponse.OK {
  1173. for fileURL in openPanel.urls {
  1174. let document = CPDFDocument(url: self.document?.documentURL)
  1175. if document != nil {
  1176. document!.setDocumentAttributes(attribute)
  1177. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1178. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1179. if success {
  1180. self.view.window?.endSheet((securityWindowController.window)!)
  1181. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. securityWindowController.cancelAction = { [unowned self] controller in
  1189. self.view.window?.endSheet((securityWindowController.window)!)
  1190. }
  1191. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1192. }
  1193. public func showRemoveSecureWindow() {
  1194. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  1195. let alert = NSAlert()
  1196. alert.alertStyle = .warning
  1197. alert.messageText = NSLocalizedString("Warning", comment: "")
  1198. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1199. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  1200. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  1201. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  1202. if returnCode == .alertSecondButtonReturn {
  1203. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  1204. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  1205. if success {
  1206. self.document?.unlock(withPassword: resultPassword)
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. } else {
  1213. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  1214. controller.pdfDocument = self.document
  1215. self.currentWindowController = controller
  1216. controller.batchAction = { [unowned self] controller, files in
  1217. self.view.window?.endSheet((self.currentWindowController.window)!)
  1218. self.currentWindowController = nil
  1219. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1220. if #available(macOS 10.13, *) {
  1221. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1222. } else {
  1223. baseWindowController.showWindow(nil)
  1224. }
  1225. let arr = NSMutableArray()
  1226. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  1227. file.password = document?.password ?? ""
  1228. arr.add(file)
  1229. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  1230. }
  1231. controller.cancelAction = { [unowned self] controller in
  1232. self.view.window?.endSheet((self.currentWindowController.window)!)
  1233. self.currentWindowController = nil
  1234. }
  1235. controller.doneAction = { [unowned self] controller in
  1236. self.view.window?.endSheet((self.currentWindowController.window)!)
  1237. self.currentWindowController = nil
  1238. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  1239. if success {
  1240. let savePanel = NSSavePanel()
  1241. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  1242. savePanel.allowedFileTypes = ["pdf"]
  1243. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  1244. guard result == .OK else { return }
  1245. /// 删除安全性设置
  1246. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1247. self.model.isSaveKeyChain = false
  1248. self.listView.document.unlock(withPassword: resultPassword)
  1249. }
  1250. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  1251. guard let document = document else { return }
  1252. document.unlock(withPassword: resultPassword)
  1253. let success = document.writeDecrypt(to: savePanel.url)
  1254. if success {
  1255. self.hiddenSecureLimitTip()
  1256. let tip = KMRemovePasswordResultTipView()
  1257. tip.result = .success
  1258. tip.showInView(superView: (self.listView.superview)!)
  1259. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1260. } else {
  1261. self.hiddenSecureLimitTip()
  1262. let tip = KMRemovePasswordResultTipView()
  1263. tip.result = .failure
  1264. tip.showInView(superView: (self.listView.superview)!)
  1265. }
  1266. }
  1267. }
  1268. }
  1269. }
  1270. NSWindow.currentWindow().beginSheet(controller.window!)
  1271. }
  1272. }
  1273. //MARK: - 测量
  1274. @objc func cancelMeasureType() {
  1275. self.hideMeasureFloatingWindows()
  1276. }
  1277. func hideMeasureFloatingWindows() {
  1278. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1279. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1280. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1281. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1282. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1283. areaMeasureInfoWindowController?.hideFloatingWindow()
  1284. }
  1285. }
  1286. func showMeasureFloatingWindowsIfNeed() {
  1287. let toolMode = self.listView.toolMode
  1288. if toolMode != .CNoteToolMode {
  1289. return
  1290. }
  1291. let type = self.listView.annotationType
  1292. if type == .measureLine {
  1293. self.distanceMeasureInfoWindowController?.window?.orderFront(nil)
  1294. } else if type == .measurePolyLine {
  1295. self.perimeterMeasureInfoWindowController?.window?.orderFront(nil)
  1296. } else if type == .measurePolyGon {
  1297. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  1298. } else if type == .measureSquare {
  1299. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  1300. }
  1301. }
  1302. //MARK: - Watermark水印
  1303. func showWatermarkController() {
  1304. viewManager.editType = .watermark
  1305. showEditToolbarView()
  1306. editToolbarView?.editType = .watermark
  1307. if KMWatermarkManager.defaultManager.watermarks.count == 0 {
  1308. editToolbarView?.editSubType = .add
  1309. } else {
  1310. editToolbarView?.editSubType = .template
  1311. }
  1312. editToolbarView?.reloadData()
  1313. if watermarkViewController == nil {
  1314. watermarkViewController = KMWatermarkController.init()
  1315. }
  1316. watermarkViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1317. watermarkViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1318. watermarkViewController?.delegate = self
  1319. bottomContendBox.contentView?.addSubview(watermarkViewController!.view)
  1320. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1321. updateWatermarkDocument()
  1322. }
  1323. func updateWatermarkDocument() {
  1324. guard let controller = watermarkViewController else { return }
  1325. var editDocument = CPDFDocument.init()
  1326. if let vcDoc = controller.pdfDocument {
  1327. editDocument = vcDoc
  1328. }
  1329. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1330. editDocument?.insertPageObject(page, at: 0)
  1331. if editDocument?.pageCount == 2 {
  1332. let theIndex = IndexSet(integer: 1)
  1333. editDocument?.removePage(at: theIndex)
  1334. }
  1335. if watermarkViewController?.pdfDocument == nil {
  1336. watermarkViewController?.pdfDocument = editDocument
  1337. }
  1338. watermarkViewController?.resetUI()
  1339. watermarkViewController?.reloadData()
  1340. }
  1341. //移除文档水印
  1342. func removePDFWatermark() {
  1343. let watermarks = self.listView.document.watermarks()
  1344. if (watermarks == nil || watermarks!.count <= 0) {
  1345. let alert = NSAlert()
  1346. alert.alertStyle = .warning
  1347. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  1348. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  1349. alert.runModal()
  1350. return
  1351. }
  1352. let alert = NSAlert()
  1353. alert.alertStyle = .warning
  1354. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  1355. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1356. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1357. let result = alert.runModal()
  1358. if (result == .alertFirstButtonReturn) {
  1359. for watermark in watermarks! {
  1360. listView.document.removeWatermark(watermark)
  1361. }
  1362. listView.layoutDocumentView()
  1363. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Watermark removed"),
  1364. type: .success,
  1365. fromView: bottomContendBox,
  1366. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1367. }
  1368. }
  1369. func batchAddWatermark() {
  1370. }
  1371. func batchRemoveWatermark() {
  1372. }
  1373. //MARK: - PopUI
  1374. func reloadPopUIWindow() {
  1375. if listView.toolMode == .CSelectToolMode {
  1376. let pageRect = listView.currentSelectionRect()
  1377. let page:CPDFPage? = listView.currentSelectionPage()
  1378. if listView.selectionRect != CGRectZero && page != nil {
  1379. let positioningRect = listView.convert(pageRect, from: page)
  1380. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1381. reloadPopUIOperation()
  1382. return
  1383. }
  1384. }
  1385. toggleClosePopUIWindow()
  1386. } else if listView.toolMode == .COCRToolMode {
  1387. let pageRect = listView.currentSelectionRect()
  1388. let page:CPDFPage? = listView.currentSelectionPage()
  1389. if listView.selectionRect != CGRectZero && page != nil {
  1390. let positioningRect = listView.convert(pageRect, from: page)
  1391. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1392. reloadPopUIOperation()
  1393. return
  1394. }
  1395. }
  1396. toggleClosePopUIWindow()
  1397. } else if(listView.isEditing() == false) {
  1398. let activeAnnotations:[CPDFAnnotation] = listView.activeAnnotations as! [CPDFAnnotation]
  1399. if(activeAnnotations.count > 0) {
  1400. if let page = activeAnnotations.first?.page {
  1401. let pageRect = listView.selectionMultipleBounds(with: activeAnnotations)
  1402. let positioningRect = listView.convert(pageRect, from: page)
  1403. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1404. reloadPopUIActiveAnnotations(activeAnnotations: activeAnnotations)
  1405. return
  1406. }
  1407. }
  1408. }
  1409. toggleClosePopUIWindow()
  1410. } else {
  1411. let editAreas:[CPDFEditArea] = listView.km_EditingAreas()
  1412. if(editAreas.count > 0) {
  1413. if let page = editAreas.first?.page {
  1414. let pageRect = listView.selectionMultipleBounds(withEditArea: editAreas)
  1415. let positioningRect = listView.convert(pageRect, from: page)
  1416. if (CGRectIntersectsRect(positioningRect, listView.frame)) {
  1417. reloadPopUIContentEdits(editAreas: editAreas)
  1418. return
  1419. }
  1420. }
  1421. }
  1422. toggleClosePopUIWindow()
  1423. }
  1424. }
  1425. func toggleClosePopUIWindow() {
  1426. let popWindow = KMNPopAnnotationWindowController.shared
  1427. if popWindow.window?.isVisible == true {
  1428. closeAnnotationPopWindow()
  1429. }
  1430. let editPopWindow = KMNPopContentEditWindowController.shared
  1431. if editPopWindow.window?.isVisible == true {
  1432. closePopContentEditWindow()
  1433. }
  1434. let operationWindow = KMNPopOperationWindowController.shared
  1435. if operationWindow.window?.isVisible == true {
  1436. closePopOperationWindow()
  1437. }
  1438. }
  1439. func closeAnnotationPopWindow() {
  1440. KMNPopAnnotationWindowController.shared.closeWindow(listView: listView)
  1441. }
  1442. func closePopContentEditWindow() {
  1443. KMNPopContentEditWindowController.shared.closeWindow(listView: listView)
  1444. }
  1445. func closePopOperationWindow() {
  1446. KMNPopOperationWindowController.shared.closeWindow(listView: listView)
  1447. }
  1448. func reloadPopUIOperation() {
  1449. if listView.selectionRect != CGRectZero {
  1450. let popWindow = KMNPopOperationWindowController.shared
  1451. if popWindow.window?.isVisible == false {
  1452. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1453. }
  1454. popWindow.listView = listView
  1455. if listView.toolMode == .CSelectToolMode {
  1456. popWindow.popType = .crop
  1457. popWindow.cropCurrentCallback = {[weak self] in
  1458. let rect = self?.listView.currentSelectionRect() ?? CGRect.zero
  1459. let orgPage : CPDFPage = self?.listView.currentSelectionPage() ?? CPDFPage()
  1460. self?.cropPages(atIndexs: [orgPage.pageIndex()], to: [rect])
  1461. self?.closePopOperationWindow()
  1462. }
  1463. } else if listView.toolMode == .COCRToolMode {
  1464. popWindow.popType = .ocr
  1465. popWindow.OCRAction = { [weak self] in
  1466. // let rect = self?.listView.currentSelectionRect() ?? CGRect.zero
  1467. // let orgPage : CPDFPage = self?.listView.currentSelectionPage() ?? CPDFPage()
  1468. // self?.cropPages(atIndexs: [orgPage.pageIndex()], to: [rect])
  1469. // self?.closePopOperationWindow()
  1470. }
  1471. }
  1472. popWindow.updatePDFViewCallback = {[weak self] in
  1473. self?.closePopOperationWindow()
  1474. self?.listView.setNeedsDisplayForVisiblePages()
  1475. }
  1476. updatePopOperationPopWinodwFrame()
  1477. } else {
  1478. closePopOperationWindow()
  1479. }
  1480. }
  1481. func reloadPopUIActiveAnnotations(activeAnnotations:[CPDFAnnotation]) {
  1482. let annotationMode = KMNAnnotationPopMode(pdfAnnotations: activeAnnotations )
  1483. let popWindow = KMNPopAnnotationWindowController.shared
  1484. if annotationMode.popType == .popTypeNone {
  1485. closeAnnotationPopWindow()
  1486. } else {
  1487. if popWindow.window?.isVisible == false {
  1488. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1489. }
  1490. popWindow.listView = listView
  1491. popWindow.annotationPopMode = annotationMode
  1492. popWindow.isOpenPane = viewManager.showRightSide
  1493. updateAnnotationsPopWinodwFrame()
  1494. popWindow.updatePDFViewCallback = {[weak self] in
  1495. self?.rightSideController?.reloadDataWithPDFView(pdfView: self?.listView ?? CPDFListView())
  1496. self?.listView.setNeedsDisplayMultiAnnotations(annotationMode.annotations)
  1497. }
  1498. popWindow.paneCallback = {[weak self] isOpen in
  1499. if isOpen == true && self?.viewManager.showRightSide == false {
  1500. self?.viewManager.showRightSide = false
  1501. } else {
  1502. self?.viewManager.showRightSide = true
  1503. }
  1504. self?.refreshToolbarRightViewInfo()
  1505. }
  1506. }
  1507. }
  1508. func reloadPopUIContentEdits(editAreas:[CPDFEditArea]) {
  1509. let editingAreas = listView.km_EditingAreas()
  1510. let editMode = KMNEditContentPopMode(currentEditAreas: editingAreas)
  1511. let popWindow = KMNPopContentEditWindowController.shared
  1512. if editMode.popType == .editNone {
  1513. closePopContentEditWindow()
  1514. } else {
  1515. listView.window?.addChildWindow(popWindow.window ?? NSWindow(), ordered: .above)
  1516. popWindow.listView = listView
  1517. popWindow.editContentPopMode = editMode
  1518. popWindow.isOpenPane = viewManager.showRightSide
  1519. updateContentEditPopWinodwFrame()
  1520. popWindow.paneCallback = {[weak self] isOpen in
  1521. if isOpen == true && self?.viewManager.showRightSide == false {
  1522. self?.viewManager.showRightSide = false
  1523. } else {
  1524. self?.viewManager.showRightSide = true
  1525. }
  1526. self?.refreshToolbarRightViewInfo()
  1527. }
  1528. }
  1529. }
  1530. func updateAnnotationsPopWinodwFrame() {
  1531. let popWindow = KMNPopAnnotationWindowController.shared
  1532. if popWindow.window?.isVisible == true {
  1533. popWindow.updateFrame(listView: listView)
  1534. }
  1535. }
  1536. func updateContentEditPopWinodwFrame() {
  1537. let popWindow = KMNPopContentEditWindowController.shared
  1538. if popWindow.window?.isVisible == true {
  1539. popWindow.updateFrame(listView: listView)
  1540. }
  1541. }
  1542. func updatePopOperationPopWinodwFrame() {
  1543. let popWindow = KMNPopOperationWindowController.shared
  1544. if popWindow.window?.isVisible == true {
  1545. popWindow.updateFrame(listView: listView,page: listView.currentSelectionPage())
  1546. }
  1547. }
  1548. //MARK: - 安全
  1549. func removeOwnerPassword() {
  1550. guard let doc = listView.document else {
  1551. NSSound.beep()
  1552. return
  1553. }
  1554. if doc.permissionsStatus != .user {
  1555. NSSound.beep()
  1556. return
  1557. }
  1558. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1559. if result == .cancel { /// 关闭
  1560. return
  1561. }
  1562. self?.listView.document?.unlock(withPassword: password)
  1563. if doc.permissionsStatus == .owner {
  1564. self?.alertTipViewController.reloadSecureAlertUI()
  1565. self?.alertTipViewController.reloadAlertUIFrame()
  1566. }
  1567. }
  1568. }
  1569. //MARK: - Background背景
  1570. func showBackgroundController() {
  1571. viewManager.editType = .background
  1572. showEditToolbarView()
  1573. editToolbarView?.editType = .background
  1574. if KMBackgroundManager.defaultManager.datas.count == 0 {
  1575. editToolbarView?.editSubType = .add
  1576. } else {
  1577. editToolbarView?.editSubType = .template
  1578. }
  1579. editToolbarView?.reloadData()
  1580. if backgroundViewController == nil {
  1581. backgroundViewController = KMBackgroundController.init()
  1582. }
  1583. backgroundViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1584. backgroundViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1585. backgroundViewController?.delegate = self
  1586. bottomContendBox.contentView?.addSubview(backgroundViewController!.view)
  1587. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1588. backgroundViewController?.resetUI()
  1589. updateBackgroundDocument()
  1590. }
  1591. func updateBackgroundDocument() {
  1592. guard let controller = backgroundViewController else { return }
  1593. controller.pdfDocument = nil
  1594. let editDocument = CPDFDocument.init()
  1595. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1596. editDocument?.insertPageObject(page, at: 0)
  1597. backgroundViewController?.pdfDocument = editDocument
  1598. backgroundViewController?.reloadData()
  1599. }
  1600. func removePDFBackground() {
  1601. let alert = NSAlert()
  1602. alert.alertStyle = .warning
  1603. alert.messageText = NSLocalizedString("Are you sure you want to remove the background?", comment: "")
  1604. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1605. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1606. let result = alert.runModal()
  1607. if (result == .alertFirstButtonReturn) {
  1608. let background = listView.document.background()
  1609. background?.clear()
  1610. listView.document?.refreshPageData()
  1611. listView.layoutDocumentView()
  1612. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Background removed"),
  1613. type: .success,
  1614. fromView: bottomContendBox,
  1615. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1616. }
  1617. }
  1618. func batchAddBackground() {
  1619. }
  1620. func batchRemoveBackground() {
  1621. }
  1622. //MARK: - header&footer
  1623. func showHeaderFooterController() {
  1624. viewManager.editType = .header_Footer
  1625. showEditToolbarView()
  1626. editToolbarView?.editType = .header_Footer
  1627. if KMHeaderFooterManager.defaultManager.headFooterObjects.count == 0 {
  1628. editToolbarView?.editSubType = .add
  1629. } else {
  1630. editToolbarView?.editSubType = .template
  1631. }
  1632. editToolbarView?.reloadData()
  1633. if headerFooterViewController == nil {
  1634. headerFooterViewController = KMHeaderFooterController.init()
  1635. }
  1636. headerFooterViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1637. headerFooterViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1638. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1639. headerFooterViewController?.delegate = self
  1640. bottomContendBox.contentView?.addSubview(headerFooterViewController!.view)
  1641. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1642. updateHeaderFooterDocument()
  1643. }
  1644. func updateHeaderFooterDocument() {
  1645. guard let controller = headerFooterViewController else { return }
  1646. controller.pdfDocument = nil
  1647. let editDocument = CPDFDocument.init()
  1648. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1649. editDocument?.insertPageObject(page, at: 0)
  1650. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1651. headerFooterViewController?.pdfDocument = editDocument
  1652. headerFooterViewController?.resetUI()
  1653. headerFooterViewController?.reloadData()
  1654. }
  1655. func removeHeaderFooter() {
  1656. let alert = NSAlert()
  1657. alert.alertStyle = .warning
  1658. alert.messageText = NSLocalizedString("Are you sure you want to remove the Header & Footer?", comment: "")
  1659. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1660. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1661. let result = alert.runModal()
  1662. if (result == .alertFirstButtonReturn) {
  1663. let headerFooter = listView.document.headerFooter()
  1664. headerFooter?.clear()
  1665. listView.document?.refreshPageData()
  1666. listView.layoutDocumentView()
  1667. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Header & Footer removed"),
  1668. type: .success,
  1669. fromView: bottomContendBox,
  1670. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1671. }
  1672. }
  1673. func batchAddHeaderFooter() {
  1674. }
  1675. func batchRemoveHeaderFooter() {
  1676. }
  1677. //MARK: - Bates
  1678. func showBatesController() {
  1679. viewManager.editType = .bates
  1680. showEditToolbarView()
  1681. editToolbarView?.editType = viewManager.editType
  1682. if KMBatesManager.defaultManager.datas.count == 0 {
  1683. editToolbarView?.editSubType = .add
  1684. } else {
  1685. editToolbarView?.editSubType = .template
  1686. }
  1687. editToolbarView?.reloadData()
  1688. if batesViewController == nil {
  1689. batesViewController = KMBatesController.init()
  1690. }
  1691. batesViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1692. batesViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1693. batesViewController?.delegate = self
  1694. batesViewController?.totalPDFCount = Int(listView.document.pageCount)
  1695. bottomContendBox.contentView?.addSubview(batesViewController!.view)
  1696. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1697. updateBatesDocument()
  1698. batesViewController?.resetUI()
  1699. }
  1700. func updateBatesDocument() {
  1701. guard let controller = batesViewController else { return }
  1702. controller.pdfDocument = nil
  1703. let editDocument = CPDFDocument.init()
  1704. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1705. editDocument?.insertPageObject(page, at: 0)
  1706. batesViewController?.pdfDocument = editDocument
  1707. batesViewController?.reloadData()
  1708. }
  1709. func removePDFBates() {
  1710. let alert = NSAlert()
  1711. alert.alertStyle = .warning
  1712. alert.messageText = NSLocalizedString("Are you sure you want to remove the Bates?", comment: "")
  1713. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1714. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1715. let result = alert.runModal()
  1716. if (result == .alertFirstButtonReturn) {
  1717. let bates = listView.document.bates()
  1718. bates?.clear()
  1719. listView.document?.refreshPageData()
  1720. listView.layoutDocumentView()
  1721. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Bates removed"),
  1722. type: .success,
  1723. fromView: bottomContendBox,
  1724. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1725. }
  1726. }
  1727. func batchAddBates() {
  1728. }
  1729. func batchRemoveBates() {
  1730. }
  1731. //MARK: - Crop Action
  1732. // 白边距,统一大小
  1733. @objc func auto_cropPagesWhiteMargin(_ pageIndexs: [UInt]) {
  1734. var size = NSZeroSize
  1735. for i in pageIndexs {
  1736. let page = self.listView.document.page(at: i)
  1737. let rect = KMCropTools.getPageForegroundBox(page!)
  1738. size.width = fmax(size.width, NSWidth(rect))
  1739. size.height = fmax(size.height, NSHeight(rect))
  1740. }
  1741. var rectArray: Array<NSRect> = []
  1742. for i in pageIndexs {
  1743. progressC?.increment(by: Double(i))
  1744. progressC?.doubleValue = Double(i)
  1745. let page = self.listView.document.page(at: i)
  1746. var rect = KMCropTools.getPageForegroundBox(page!)
  1747. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1748. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1749. rect.origin.x = rect.maxX-size.width
  1750. }
  1751. rect.origin.y = rect.maxY-size.height
  1752. rect.size = size
  1753. if (NSWidth(rect) > NSWidth(bounds)) {
  1754. rect.size.width = NSWidth(bounds)
  1755. }
  1756. if (NSHeight(rect) > NSHeight(bounds)) {
  1757. rect.size.height = NSHeight(bounds)
  1758. }
  1759. if (NSMinX(rect) < NSMinX(bounds)) {
  1760. rect.origin.x = NSMinX(bounds)
  1761. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1762. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1763. }
  1764. if (NSMinY(rect) < NSMinY(bounds)) {
  1765. rect.origin.y = NSMinY(bounds)
  1766. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1767. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1768. }
  1769. rectArray.append(rect)
  1770. }
  1771. self.cropPages(atIndexs: pageIndexs, to: rectArray)
  1772. }
  1773. func cropPages(atIndexs pageIndexs: [UInt], to rects: Array<NSRect>) {
  1774. let currentPage = self.listView.currentPage()
  1775. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1776. var oldRectArray: Array<NSRect> = []
  1777. let rectCount = rects.count
  1778. for i in pageIndexs {
  1779. if let page = self.listView.document.page(at: i) {
  1780. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page.bounds(for: .mediaBox)))
  1781. let oldRect = page.bounds(for: .cropBox)
  1782. oldRectArray.append(oldRect)
  1783. page.setBounds(rect, for: .cropBox)
  1784. }
  1785. }
  1786. let undoManager = self.listView.undoManager
  1787. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(atIndexs: pageIndexs, to: oldRectArray)
  1788. /// 刷新预览视图
  1789. self.listView.layoutDocumentView()
  1790. self.listView.displayBox = .cropBox
  1791. self.listView.go(to: currentPage)
  1792. self.listView.go(to: visibleRect, on: currentPage)
  1793. }
  1794. //MARK: - TTS
  1795. @IBAction func startSpeaking(_ sender: Any?) {
  1796. self.showTTSWindow()
  1797. let ttsView = KMTTSWindowController.share
  1798. // ttsView.buttonItemClick_Play(ttsView.playButton)
  1799. }
  1800. @IBAction func stopSpeaking(_ sender: Any) {
  1801. let ttsWindowC = KMTTSWindowController.share
  1802. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  1803. if let data = ttsWindowC.window?.isVisible, data {
  1804. ttsWindowC.stopSpeaking()
  1805. ttsWindowC.close()
  1806. }
  1807. }
  1808. }
  1809. func showTTSWindow() {
  1810. var lastPDFView: CPDFView?
  1811. let ttsView = KMTTSWindowController.share
  1812. if (ttsView.window?.isVisible ?? false) {
  1813. lastPDFView = ttsView.pdfView
  1814. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  1815. lastPDFView = nil
  1816. ttsView.window?.orderOut(nil)
  1817. } else {
  1818. ttsView.pdfView = self.listView
  1819. ttsView.showWindow(nil)
  1820. }
  1821. } else {
  1822. ttsView.pdfView = self.listView
  1823. ttsView.showWindow(nil)
  1824. }
  1825. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  1826. if isCloseWindow {
  1827. }
  1828. }
  1829. if let currentSelection = self.listView.currentSelection {
  1830. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  1831. ttsView.startSpeakingPDFSelection(currentSelection)
  1832. }
  1833. }
  1834. if let lastPDFView = lastPDFView {
  1835. lastPDFView.setHighlightedSelections([])
  1836. ttsView.stopSpeaking()
  1837. }
  1838. }
  1839. //MARK: 导出图片
  1840. func extractImageAction(num: Int) {
  1841. if !IAPProductsManager.default().isAvailableAllFunction(){
  1842. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1843. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  1844. winC?.showWindow(nil)
  1845. return
  1846. }
  1847. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1848. let alert = NSAlert()
  1849. alert.alertStyle = .critical
  1850. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1851. alert.runModal()
  1852. return
  1853. }
  1854. let document = self.listView.document
  1855. var fileURL = document?.documentURL
  1856. if num == 1 {
  1857. let pageCount = document?.pageCount ?? 0
  1858. let indeSet = NSMutableIndexSet()
  1859. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1860. if indeSet.count == 0 {
  1861. return
  1862. }
  1863. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  1864. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  1865. let outputSavePanel = NSSavePanel()
  1866. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  1867. outputSavePanel.allowsOtherFileTypes = true
  1868. outputSavePanel.isExtensionHidden = true
  1869. outputSavePanel.canCreateDirectories = true
  1870. outputSavePanel.nameFieldStringValue = tFileName
  1871. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  1872. if result == NSApplication.ModalResponse.OK {
  1873. DispatchQueue.main.async {
  1874. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  1875. let tDestFile = outputSavePanel.url!.path
  1876. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  1877. let pdfconverter = PDFConvertObject()
  1878. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  1879. self.dismissProgressSheet()
  1880. let fileManager = FileManager.default
  1881. if fileManager.fileExists(atPath: tDestFile) {
  1882. let workspace = NSWorkspace.shared
  1883. let url = URL(fileURLWithPath: tDestFile)
  1884. workspace.activateFileViewerSelecting([url])
  1885. }
  1886. }
  1887. }
  1888. })
  1889. return
  1890. }
  1891. if fileURL != nil {
  1892. self.myDocument?.save(nil)
  1893. } else {
  1894. let myDocument = self.myDocument
  1895. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  1896. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1897. if writeSuccess {
  1898. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1899. fileURL = document?.documentURL
  1900. } else {
  1901. NSSound.beep()
  1902. return
  1903. }
  1904. }
  1905. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  1906. extract?.docPath = fileURL?.path ?? ""
  1907. extract?.password = document?.password ?? ""
  1908. extract?.currentPage = self.listView.currentPageIndex
  1909. self.km_beginSheet(windowC: extract!)
  1910. extract?.selectCurrentPageBtn()
  1911. }
  1912. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  1913. let progress = SKProgressController()
  1914. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1915. progress.window?.contentView?.wantsLayer = true
  1916. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1917. progress.progressField.textColor = NSColor.white
  1918. progress.message = NSLocalizedString("Converting...", comment: "")
  1919. progressC = progress
  1920. progressC?.message = message
  1921. if maxValue > 0 {
  1922. progressC?.indeterminate = false
  1923. progressC?.maxValue = Double(maxValue)
  1924. progressC?.progressBar.doubleValue = 0.3
  1925. } else {
  1926. progressC?.indeterminate = true
  1927. }
  1928. self.view.km_beginSheet(windowC: progressC!)
  1929. }
  1930. func dismissProgressSheet() {
  1931. progressC?.stopAnimation()
  1932. self.view.km_endSheet()
  1933. progressC = nil
  1934. }
  1935. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  1936. let newArr = NSMutableArray()
  1937. for item in files {
  1938. newArr.add(item.filePath)
  1939. }
  1940. return newArr as! [String]
  1941. }
  1942. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1943. self.saveDocument()
  1944. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1945. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1946. if (result == .cancel) {
  1947. return
  1948. }
  1949. // 解除权限
  1950. self?.listView.document.unlock(withPassword: password)
  1951. // 隐藏提示
  1952. self?.hiddenSecureLimitTip()
  1953. // 去打印
  1954. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1955. }
  1956. return
  1957. }
  1958. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  1959. }
  1960. //MARK: - FileInfo
  1961. func showFileInfo() {
  1962. KMInfoWindowController.shared.showWindow(nil)
  1963. }
  1964. //MARK: - Share Action
  1965. @objc private func shareDocument(sender: NSView) {
  1966. let document = self.listView.document ?? CPDFDocument()
  1967. if document?.documentURL == nil {
  1968. return
  1969. }
  1970. var doucumentURL : URL = self.listView.document.documentURL
  1971. if doucumentURL.path.count > 0 {
  1972. let docDir = NSTemporaryDirectory()
  1973. let documentName : String = doucumentURL.path.lastPathComponent
  1974. let path = docDir.stringByAppendingPathComponent(documentName)
  1975. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1976. if writeSuccess == false {
  1977. __NSBeep()
  1978. return;
  1979. }
  1980. doucumentURL = URL(fileURLWithPath: path)
  1981. }
  1982. let array = [doucumentURL]
  1983. let picker = NSSharingServicePicker.init(items: array)
  1984. if sender.window != nil {
  1985. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  1986. } else {
  1987. 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)
  1988. }
  1989. }
  1990. @objc private func shareFlatten(sender: NSView) {
  1991. let document = self.listView.document ?? CPDFDocument()
  1992. var path: String?
  1993. if document?.documentURL != nil {
  1994. path = document?.documentURL.path ?? ""
  1995. }
  1996. if path?.count ?? 0 > 0 {
  1997. let docDir = NSTemporaryDirectory()
  1998. let documentName : String = path?.lastPathComponent ?? ""
  1999. path = docDir.stringByAppendingPathComponent(documentName)
  2000. }
  2001. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  2002. var tfileName = path?.deletingPathExtension.lastPathComponent
  2003. let tStdFileSuffix = "_flatten"
  2004. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  2005. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  2006. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  2007. if success {
  2008. let url = URL(fileURLWithPath: path ?? "")
  2009. let picker = NSSharingServicePicker.init(items: [url])
  2010. if sender.window != nil {
  2011. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2012. } else {
  2013. 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)
  2014. }
  2015. }
  2016. }
  2017. @objc private func shareOriginalPDF(sender: NSView) {
  2018. guard let pdfDoc = self.listView.document else {
  2019. NSSound.beep()
  2020. return
  2021. }
  2022. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  2023. let alert = NSAlert()
  2024. alert.alertStyle = .critical
  2025. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2026. alert.runModal()
  2027. return
  2028. }
  2029. let document = self.listView.document ?? CPDFDocument()
  2030. var path: String?
  2031. if document?.documentURL != nil {
  2032. path = document?.documentURL.path ?? ""
  2033. }
  2034. if path?.count ?? 0 > 0 {
  2035. let docDir = NSTemporaryDirectory()
  2036. let documentName : String = path?.lastPathComponent ?? ""
  2037. path = docDir.stringByAppendingPathComponent(documentName)
  2038. }
  2039. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  2040. if writeSuccess == false {
  2041. __NSBeep()
  2042. return;
  2043. }
  2044. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  2045. let cnt = newDocument?.pageCount ?? 0
  2046. for i in 0 ..< cnt {
  2047. let page = newDocument!.page(at: i)
  2048. var annotations : [CPDFAnnotation] = []
  2049. for annotation in page!.annotations {
  2050. annotations.append(annotation)
  2051. }
  2052. for annotation in annotations {
  2053. annotation.page.removeAnnotation(annotation)
  2054. }
  2055. }
  2056. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  2057. if writeSuccess ?? false {
  2058. let url = URL(fileURLWithPath: path ?? "")
  2059. let picker = NSSharingServicePicker.init(items: [url])
  2060. if sender.window != nil {
  2061. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  2062. } else {
  2063. 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)
  2064. }
  2065. }
  2066. }
  2067. @objc func shareFromService(sender: NSMenuItem) {
  2068. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  2069. return
  2070. }
  2071. var string = ""
  2072. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  2073. string = freeTextAnnotation.contents ?? ""
  2074. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  2075. if let page = markupAnnotation.page {
  2076. if let selection = page.selection(for: markupAnnotation.bounds) {
  2077. string = selection.string() ?? ""
  2078. }
  2079. }
  2080. } else {
  2081. string = listView.currentSelection?.string() ?? ""
  2082. }
  2083. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  2084. let model = windowControler.browser?.tabStripModel
  2085. if let cnt = model?.count(), cnt <= 0 {
  2086. return
  2087. }
  2088. if let data = model?.activeTabContents().isHome, data {
  2089. return
  2090. }
  2091. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  2092. if string.count > 0 {
  2093. let represent : NSSharingService = sender.representedObject as! NSSharingService
  2094. represent.perform(withItems: [string])
  2095. return
  2096. }
  2097. let represent = sender.representedObject as? NSSharingService
  2098. represent?.perform(withItems: [string])
  2099. }
  2100. //MARK: - PDFView Menu
  2101. func clickPresentationMenu(point:NSPoint)->KMNMenuStruct {
  2102. var viewHeight: CGFloat = 8
  2103. var menuItemArr: [ComponentMenuitemProperty] = []
  2104. var items: [(String, String)] = []
  2105. items.append(("Next Page", PDFViewMenuIdentifier_PageNext))
  2106. items.append(("Previous Page", PDFViewMenuIdentifier_PagePrevious))
  2107. items.append(("First", PDFViewMenuIdentifier_PageFirst))
  2108. items.append(("Last", PDFViewMenuIdentifier_PageLast))
  2109. items.append(("", ""))
  2110. items.append(("Laser pointer", PDFViewMenuIdentifier_Presentation_LaserPoint))
  2111. items.append(("Brush", PDFViewMenuIdentifier_Presentation_Brush))
  2112. items.append(("", ""))
  2113. items.append(("Exit Presentation", PDFViewMenuIdentifier_Presentation_Exit))
  2114. for (i, value) in items {
  2115. if value.count == 0 {
  2116. let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
  2117. menuItemArr.append(property)
  2118. viewHeight += 8
  2119. } else {
  2120. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  2121. itemSelected: false,
  2122. isDisabled: false,
  2123. keyEquivalent: nil,
  2124. text: KMLocalizedString(i),
  2125. identifier: value,representedObject: point)
  2126. if value == PDFViewMenuIdentifier_PageNext {
  2127. properties_Menuitem.keyEquivalent = "▶"
  2128. } else if value == PDFViewMenuIdentifier_PagePrevious {
  2129. properties_Menuitem.keyEquivalent = "◀"
  2130. } else if value == PDFViewMenuIdentifier_PageFirst {
  2131. properties_Menuitem.keyEquivalent = "⌘ ◀"
  2132. } else if value == PDFViewMenuIdentifier_PageLast {
  2133. properties_Menuitem.keyEquivalent = "⌘ ▶"
  2134. } else if value == PDFViewMenuIdentifier_Presentation_Exit {
  2135. properties_Menuitem.keyEquivalent = "ESC"
  2136. }
  2137. if(value == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  2138. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2139. } else {
  2140. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2141. }
  2142. } else if value == PDFViewMenuIdentifier_Presentation_Brush {
  2143. if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
  2144. properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
  2145. } else {
  2146. }
  2147. }
  2148. menuItemArr.append(properties_Menuitem)
  2149. viewHeight += 36
  2150. }
  2151. }
  2152. let menuStruct = KMNMenuStruct(menuitems: menuItemArr, viewHeight: viewHeight)
  2153. return menuStruct
  2154. }
  2155. //MARK: - 添加书签
  2156. @objc func menuItemBookMarkClick_add(sender:NSMenuItem?) {
  2157. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  2158. let index = self.listView.currentPageIndex
  2159. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  2160. self.listView.setNeedsDisplayForVisiblePages()
  2161. } else {
  2162. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  2163. self.listView.setNeedsDisplayForVisiblePages()
  2164. }
  2165. self.listView.undoManager?.setActionName("")//添加undo事件就可删除
  2166. }
  2167. //MARK: - 页面旋转
  2168. func rotateLeft(page:CPDFPage,listView:CPDFListView?) {
  2169. Task { @MainActor in
  2170. let rotation = page.rotation
  2171. page.leftRotate()
  2172. listView?.layoutDocumentView()
  2173. if(listView == self.listView) {
  2174. var pageIndexes = IndexSet()
  2175. pageIndexes.insert(Int(page.pageIndex()))
  2176. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  2177. }
  2178. }
  2179. }
  2180. func rotateRight(page:CPDFPage,listView:CPDFListView?) {
  2181. Task { @MainActor in
  2182. let rotation = page.rotation
  2183. page.rightRotate()
  2184. listView?.layoutDocumentView()
  2185. if(listView == self.listView) {
  2186. var pageIndexes = IndexSet()
  2187. pageIndexes.insert(Int(page.pageIndex()))
  2188. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  2189. }
  2190. }
  2191. }
  2192. //MARK: - 自动滚动
  2193. @IBAction func toggleAutoFlow(_ sender: Any?) {
  2194. if (listView.isAutoFlow()) {
  2195. listView.stopAutoFlow()
  2196. } else {
  2197. listView.startAutoFlow()
  2198. }
  2199. }
  2200. //MARK: - 高亮Form
  2201. func highlightFormFiled(_ sender: Any?) {
  2202. let enabled = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
  2203. CPDFKitConfig.sharedInstance().setEnableFormFieldHighlight(!enabled)
  2204. listView.setNeedsDisplayForVisiblePages()
  2205. }
  2206. //MARK: - 高亮Link
  2207. func highlightLinks(_ sender: Any?) {
  2208. let enabled = CPDFKitConfig.sharedInstance().enableLinkFieldHighlight()
  2209. CPDFKitConfig.sharedInstance().setEnableLinkFieldHighlight(!enabled)
  2210. listView.setNeedsDisplayForVisiblePages()
  2211. }
  2212. //MARK: - 重置Form
  2213. func resetForm(_ sender: Any?) {
  2214. listView.resetFormAnnotation()
  2215. }
  2216. //MARK: - 属性
  2217. @IBAction func menuItemAction_property(_ sender: Any?) {
  2218. KMInfoWindowController.shared.showWindow(sender)
  2219. }
  2220. //MARK: - 打印
  2221. @IBAction func menuItemAction_print(_ sender: Any?) {
  2222. self.showPrintWindow()
  2223. }
  2224. //MARK: - 新增大纲
  2225. @objc func addOutLineItemAction() {
  2226. botaViewController?.outlineViewC.addOutline()
  2227. }
  2228. //MARK: - 搜索
  2229. @objc func searchBaiduAction() {
  2230. let label = self.listView.currentSelection?.string() ?? ""
  2231. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  2232. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  2233. NSWorkspace.shared.open(url)
  2234. }
  2235. }
  2236. //MARK: - 选择Form注释
  2237. @objc func selectAllFormAnnotation () {
  2238. var formActiveAnnotations:[CPDFAnnotation] = []
  2239. for i in 0 ..< listView.document.pageCount {
  2240. let page = listView.document.page(at: i)
  2241. let annotations = page?.annotations
  2242. for j in 0 ..< (annotations?.count ?? 0) {
  2243. if let an = annotations?[j] as? CPDFAnnotation {
  2244. if (an.isKind(of: CPDFWidgetAnnotation.self) == true) {
  2245. formActiveAnnotations.append(an)
  2246. }
  2247. }
  2248. }
  2249. }
  2250. listView.updateActiveAnnotations(formActiveAnnotations)
  2251. }
  2252. @objc func selectAllNomerAnnotation () {
  2253. var normalActiveAnnotations:[CPDFAnnotation] = []
  2254. for i in 0 ..< listView.document.pageCount {
  2255. let page = listView.document.page(at: i)
  2256. let annotations = page?.annotations
  2257. for j in 0 ..< (annotations?.count ?? 0) {
  2258. if let an = annotations?[j] as? CPDFAnnotation {
  2259. if an.isKind(of: CPDFWidgetAnnotation.self) == true ||
  2260. an.isKind(of: CPDFLinkAnnotation.self) == true ||
  2261. an.isKind(of: CPDFRedactAnnotation.self) == true {
  2262. } else {
  2263. normalActiveAnnotations.append(an)
  2264. }
  2265. }
  2266. }
  2267. }
  2268. listView.updateActiveAnnotations(normalActiveAnnotations)
  2269. }
  2270. //MARK: 搜索 & 替换
  2271. func showSearchPopWindow(type: KMNBotaSearchType, keyborad: String?, replaceText: String?, results: [KMSearchMode]) {
  2272. let toolMode = self.listView.toolMode
  2273. let isEditing = self.listView.isEditing()
  2274. var winH: CGFloat = 112
  2275. if type == .replace {
  2276. if IAPProductsManager.default().isAvailableAllFunction() == false {
  2277. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2278. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  2279. winC?.showWindow(nil)
  2280. return
  2281. }
  2282. if toolMode == .CEditPDFToolMode && isEditing {
  2283. } else { // 进入内容编辑模式
  2284. viewManager.toolMode = .Edit
  2285. updatePDFViewAnnotationMode()
  2286. }
  2287. winH = 208
  2288. }
  2289. self.view.window?.makeFirstResponder(nil)
  2290. let winC = KMSearchReplaceWindowController(with: listView, type: type)
  2291. self.currentWindowController = winC
  2292. winC.replaceCallback = { [weak self] in
  2293. let toolMode = self?.listView.toolMode ?? .none
  2294. let isEditing = self?.listView.isEditing() ?? false
  2295. if toolMode == .CEditPDFToolMode && isEditing {
  2296. } else { // 进入内容编辑模式
  2297. self?.viewManager.toolMode = .Edit
  2298. self?.updatePDFViewAnnotationMode()
  2299. }
  2300. }
  2301. winC.itemClick = { [weak self] idx, params in
  2302. if idx == 1 {
  2303. self?.toggleOpenLeftSide(pdfSideBarType: .search)
  2304. guard let handdler = params.first as? KMNSearchHanddler else {
  2305. return
  2306. }
  2307. let viewC = self?.botaViewController?.searchViewC
  2308. viewC?.update(keyborad: handdler.searchKey, replaceKey: handdler.replaceKey, results: handdler.searchSectionResults)
  2309. }
  2310. }
  2311. let targetView = self.pdfToolbarController?.leftViewButton
  2312. let point = targetView?.convert(targetView?.frame.origin ?? .zero, to: nil) ?? .zero
  2313. // 200 248
  2314. let x = point.x + (self.view.window?.frame.origin.x ?? 0) - 32
  2315. let y = point.y + (self.view.window?.frame.origin.y ?? 0) - winH - 32
  2316. let winFramePoint = NSPoint(x: x, y: y)
  2317. winC.window?.setFrameOrigin(winFramePoint)
  2318. winC.update(keyborad: keyborad, replaceKey: replaceText, results: results)
  2319. self.view.window?.addChildWindow(winC.window!, ordered: .above)
  2320. }
  2321. }
  2322. //MARK: Compress
  2323. extension KMMainViewController {
  2324. func showCompressController(_ url: URL) {
  2325. self.compressWindowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  2326. self.compressWindowController?.password = self.listView.document?.password ?? ""
  2327. self.compressWindowController?.documentURL = url
  2328. self.view.window?.beginSheet(self.compressWindowController!.window!)
  2329. self.compressWindowController?.itemClick = { [unowned self] in
  2330. self.view.window?.endSheet((self.compressWindowController?.window)!)
  2331. }
  2332. self.compressWindowController?.batchAction = { [unowned self] view, filePaths in
  2333. self.view.window?.endSheet((self.compressWindowController?.window)!)
  2334. self.showBatchCompressController(filePaths)
  2335. }
  2336. self.compressWindowController?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  2337. self.view.window?.endSheet((self.compressWindowController?.window)!)
  2338. if (result) {
  2339. if (openDocument) {
  2340. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2341. } else {
  2342. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2343. }
  2344. } else {
  2345. let alert = NSAlert()
  2346. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2347. alert.runModal()
  2348. }
  2349. }
  2350. }
  2351. func showBatchCompressController(_ filePaths: [URL]) {
  2352. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2353. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2354. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2355. batchWindowController.window?.makeKeyAndOrderFront("")
  2356. }
  2357. }
  2358. //MARK: - OCR
  2359. extension KMMainViewController {
  2360. func showOCRWindow() {
  2361. if !IAPProductsManager.default().isAvailableAllFunction(){
  2362. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2363. winC?.showWindow(nil)
  2364. return
  2365. }
  2366. let window = KMOCRSettingWindowController(windowNibName: "KMOCRSettingWindowController")
  2367. window.OCRAction = {[unowned self] controller, model in
  2368. self.convertOCRScanFile(window: window, document: self.listView.document, model: model)
  2369. }
  2370. self.km_beginSheet(windowC: window)
  2371. }
  2372. func showOCREditAlert() {
  2373. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
  2374. alertTipViewController.isShowOCRAlert = true
  2375. alertTipViewController.showInView(listView)
  2376. alertTipViewController.reloadOCRAlertUI()
  2377. alertTipViewController.reloadAlertUIFrame()
  2378. alertTipViewController.OCRApplyCallback = { [unowned self] in
  2379. self.showOCRWindow()
  2380. }
  2381. }
  2382. }
  2383. func closeOCREditAlert() {
  2384. alertTipViewController.isShowOCRAlert = false
  2385. alertTipViewController.reloadOCRAlertUI()
  2386. // alertTipViewController.reloadAlertUIFrame()
  2387. }
  2388. func showOCRToolAlert(_ string: String) {
  2389. let alertView = ComponentMessage()
  2390. alertView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString(string))
  2391. alertView.frame = CGRectMake((CGRectGetWidth(self.listView.frame) - alertView.properties.propertyInfo.viewWidth) / 2,
  2392. CGRectGetHeight(self.listView.frame) - alertView.properties.propertyInfo.viewHeight - 8,
  2393. alertView.properties.propertyInfo.viewWidth,
  2394. alertView.properties.propertyInfo.viewHeight)
  2395. alertView.reloadData()
  2396. self.listView.addSubview(alertView)
  2397. // 自动移除视图
  2398. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  2399. self.removeOCRToolAlert(alertView)
  2400. }
  2401. }
  2402. private func removeOCRToolAlert(_ alertView: NSView) {
  2403. // 淡出动画
  2404. NSAnimationContext.runAnimationGroup({ context in
  2405. context.duration = 0.3
  2406. alertView.animator().alphaValue = 0
  2407. }, completionHandler: {
  2408. alertView.removeFromSuperview()
  2409. })
  2410. }
  2411. //OCR
  2412. func convertOCRScanFile(window: KMOCRSettingWindowController, document: CPDFDocument, model: KMOCRModel) {
  2413. window.beginLoading()
  2414. //当前页面需要提前设置
  2415. if model.pageRangeType == .current {
  2416. model.pageRange = [self.listView.currentPageIndex]
  2417. }
  2418. KMOCRManager.manager.convertScanFile(document: document, model: model, progress: { progress in
  2419. }) { [weak self] document, error in
  2420. window.endLoading()
  2421. window.km_quick_endSheet()
  2422. if !model.saveAsPDF {
  2423. self?.listView.layoutDocumentView()
  2424. }
  2425. }
  2426. }
  2427. func convertOCR(document: CPDFDocument, model: KMOCRModel) {
  2428. // self.view.window?.windowController.beginLoading()
  2429. //当前页面需要提前设置
  2430. if model.pageRangeType == .current {
  2431. model.pageRange = [self.listView.currentPageIndex]
  2432. }
  2433. KMOCRManager.manager.convertOCR(document: document, model: model, progress: { progress in
  2434. }) { [weak self] document, error in
  2435. // self?.view.window?.windowController.endLoading()
  2436. // window.km_quick_endSheet()
  2437. if !model.saveAsPDF {
  2438. self?.listView.layoutDocumentView()
  2439. }
  2440. }
  2441. }
  2442. // MARK: -显示加密弹窗
  2443. //MARK: - Redact密文
  2444. func showRedactProperty() {
  2445. let properties = KMRedactPropertiesWindowController()
  2446. self.km_beginSheet(windowC: properties)
  2447. }
  2448. //MARK: - 测量
  2449. func refreshMeasureInfo() {
  2450. if let annotation = listView.activeAnnotation {
  2451. if (listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self)) {
  2452. if (!(listView.activeAnnotation as! CPDFLineAnnotation).isMeasure) {
  2453. cancelMeasureType()
  2454. } else {
  2455. if distanceMeasureInfoWindowController == nil {
  2456. let measureInfo = CPDFDistanceMeasureInfo()
  2457. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2458. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2459. distanceMeasureInfoWindowController?.delegate = self
  2460. }
  2461. }
  2462. } else if (!listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) && !listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self)) {
  2463. cancelMeasureType()
  2464. } else if (listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) || listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self)) {
  2465. if perimeterMeasureInfoWindowController == nil {
  2466. let measureInfo = CPDFPerimeterMeasureInfo()
  2467. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2468. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2469. perimeterMeasureInfoWindowController?.delegate = self
  2470. }
  2471. if areaMeasureInfoWindowController == nil {
  2472. let measureInfo = CPDFAreaMeasureInfo()
  2473. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2474. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2475. areaMeasureInfoWindowController?.delegate = self
  2476. }
  2477. }
  2478. } else {
  2479. cancelMeasureType()
  2480. }
  2481. }
  2482. }
  2483. //MARK: - 代理方法
  2484. //MARK: - NSSplitViewDelegate
  2485. extension KMMainViewController: NSSplitViewDelegate {
  2486. func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
  2487. if splitView == infoContendSplitView {
  2488. return subview.isEqual(to: infoSplitCenterView) == false
  2489. }
  2490. return false
  2491. }
  2492. func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
  2493. if splitView == infoContendSplitView {
  2494. if(subview.isEqual(to: infoSplitLeftView)) {
  2495. } else if(subview.isEqual(to: infoSplitRightView)) {
  2496. }
  2497. }
  2498. return false
  2499. }
  2500. func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
  2501. if splitView == infoContendSplitView {
  2502. return splitView == infoContendSplitView
  2503. } else if splitView == pdfSplitView {
  2504. return splitView == pdfSplitView
  2505. }
  2506. return false
  2507. }
  2508. func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  2509. if(splitView == infoContendSplitView && dividerIndex == 1) {
  2510. return proposedMaximumPosition - MIN_SIDE_PANE_WIDTH.doubleValue
  2511. }
  2512. return proposedMaximumPosition
  2513. }
  2514. func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  2515. if(splitView == infoContendSplitView && dividerIndex == 0) {
  2516. return proposedMinimumPosition + MIN_SIDE_PANE_WIDTH.doubleValue
  2517. }
  2518. return proposedMinimumPosition
  2519. }
  2520. func splitViewDidResizeSubviews(_ notification: Notification) {
  2521. let splitView = notification.object as? NSSplitView
  2522. if(splitView == infoContendSplitView) {
  2523. leftSplitViewResizeFinish()
  2524. if(newMwcFlags.settingUpWindow == false && self.view.window?.frameAutosaveName != nil) {
  2525. let leftWidth = infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) ? 0.0 : infoSplitLeftView.frame.width
  2526. UserDefaults.standard.set(leftWidth, forKey: CPDFViewLeftSidePaneWidthKey)
  2527. UserDefaults.standard.synchronize()
  2528. }
  2529. if listView.isEditing() == false {
  2530. updateAnnotationsPopWinodwFrame()
  2531. } else {
  2532. updateContentEditPopWinodwFrame()
  2533. }
  2534. }
  2535. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(splitViewResizeFinish), object: nil)
  2536. self.perform(#selector(splitViewResizeFinish), with: nil, afterDelay: 0.15)
  2537. }
  2538. @objc func leftSplitViewResizeFinish() {
  2539. botaViewController?.changeLeftSideBounds()
  2540. }
  2541. @objc func splitViewResizeFinish() {
  2542. if infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) {
  2543. if viewManager.pdfSideBarType != .none {
  2544. viewManager.pdfSideBarType = .none
  2545. sideBarController?.reloadBOTAData()
  2546. }
  2547. }
  2548. }
  2549. }
  2550. //MARK: - KMPDFSideBarControllerDelegate 左侧Sidebar代理
  2551. extension KMMainViewController: KMPDFSideBarControllerDelegate {
  2552. func kmPDFSideBarControllerDidSidebarTypeUpdated(_ view: KMPDFSideBarController) {
  2553. if viewManager.pdfSideBarType == .none {
  2554. toggleCloseLeftSide()
  2555. } else {
  2556. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  2557. }
  2558. }
  2559. func kmPDFSideBarControllerDidGotoPage(_ view: KMPDFSideBarController, _ pageIndex: Int) {
  2560. listView.go(toPageIndex: pageIndex, animated: true)
  2561. }
  2562. }
  2563. //MARK: - KMPDFToolbarControllerDelegate 工具栏代理
  2564. extension KMMainViewController: KMPDFToolbarControllerDelegate {
  2565. //MARK: -ViewTools发生变化时调用
  2566. func kmPDFToolbarControllerDidViewToolsChanged(_ controller: KMPDFToolbarController) {
  2567. let viewToolsType = viewManager.viewToolsType
  2568. if viewToolsType == .Select {
  2569. listView.toolMode = .CNoteToolMode
  2570. } else if viewToolsType == .Scroll {
  2571. listView.toolMode = .CMoveToolMode
  2572. } else if viewToolsType == .Content_Selection {
  2573. listView.toolMode = .CSelectToolMode
  2574. } else if viewToolsType == .Magnify {
  2575. listView.toolMode = .CMagnifyToolMode
  2576. } else if viewToolsType == .AreaZoom {
  2577. listView.toolMode = .CSelectZoomToolMode
  2578. }
  2579. refreshToolbarViewHeightInfo()
  2580. }
  2581. //MARK: -一级工具栏状态发生变化时调用
  2582. func kmPDFToolbarControllerDidToolModeChanged(_ controller: KMPDFToolbarController) {
  2583. refreshToolbarViewHeightInfo()
  2584. toolbarViewModeChanged()
  2585. }
  2586. //MARK: -点击工具栏按钮
  2587. func kmPDFToolbarControllerDidToolbarItemClicked(_ controller: KMPDFToolbarController, _ itemIdentifier: String) {
  2588. print("toolbar点击", itemIdentifier)
  2589. if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_PageEdit_Identifier).contains(itemIdentifier) {
  2590. //MARK: -页面编辑
  2591. if itemIdentifier == KMPDFToolbar_PageEdit_InsertFile_Identifier {
  2592. pageEditViewController?.insertFromPDFAction()
  2593. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertBlank_Identifier {
  2594. pageEditViewController?.insertFromBlankAction()
  2595. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertClip_Identifier {
  2596. pageEditViewController?.insertFromClipboardAction()
  2597. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertScanner_Identifier {
  2598. pageEditViewController?.insertFromScannerAction()
  2599. } else if itemIdentifier == KMPDFToolbar_PageEdit_Extract_Identifier {
  2600. pageEditViewController?.extractPDFAction()
  2601. } else if itemIdentifier == KMPDFToolbar_PageEdit_Replace_Identifier {
  2602. pageEditViewController?.replacePDFAction()
  2603. } else if itemIdentifier == KMPDFToolbar_PageEdit_Split_Identifier {
  2604. pageEditViewController?.splitPDFAction()
  2605. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reverse_Identifier {
  2606. pageEditViewController?.reversePDFAction()
  2607. } else if itemIdentifier == KMPDFToolbar_PageEdit_LeftRotate_Identifier {
  2608. pageEditViewController?.rotatePageLeftAction()
  2609. } else if itemIdentifier == KMPDFToolbar_PageEdit_RightRotate_Identifier{
  2610. pageEditViewController?.rotatePageRightAction()
  2611. } else if itemIdentifier == KMPDFToolbar_PageEdit_Delete_Identifier {
  2612. pageEditViewController?.deletePageAction()
  2613. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reduce_Identifier {
  2614. pageEditViewController?.zoomOutPageAction()
  2615. if(pageEditViewController?.canZoomInPageSize() == false) {
  2616. toolbarManager.page_Increase_Property.isDisabled = true
  2617. } else {
  2618. toolbarManager.page_Increase_Property.isDisabled = false
  2619. }
  2620. if(pageEditViewController?.canZoomOutPageSize() == false) {
  2621. toolbarManager.page_Reduce_Property.isDisabled = true
  2622. } else {
  2623. toolbarManager.page_Reduce_Property.isDisabled = false
  2624. }
  2625. controller.refreshSecondToolbarItemsState()
  2626. } else if itemIdentifier == KMPDFToolbar_PageEdit_Increase_Identifier {
  2627. pageEditViewController?.zoomInPageAction()
  2628. if(pageEditViewController?.canZoomInPageSize() == false) {
  2629. toolbarManager.page_Increase_Property.isDisabled = true
  2630. } else {
  2631. toolbarManager.page_Increase_Property.isDisabled = false
  2632. }
  2633. if(pageEditViewController?.canZoomOutPageSize() == false) {
  2634. toolbarManager.page_Reduce_Property.isDisabled = true
  2635. } else {
  2636. toolbarManager.page_Reduce_Property.isDisabled = false
  2637. }
  2638. controller.refreshSecondToolbarItemsState()
  2639. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_oddPage_Identifier {
  2640. pageEditViewController?.thumbnailChoosePageStyle = .odd
  2641. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  2642. toolbarManager.page_pageInfo_Property.creatable = false
  2643. controller.refreshSecondToolbarItemsState()
  2644. }
  2645. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_EvenPage_Identifier {
  2646. pageEditViewController?.thumbnailChoosePageStyle = .even
  2647. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  2648. toolbarManager.page_pageInfo_Property.creatable = false
  2649. controller.refreshSecondToolbarItemsState()
  2650. }
  2651. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_PortraitPage_Identifier {
  2652. pageEditViewController?.thumbnailChoosePageStyle = .horizontal
  2653. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  2654. toolbarManager.page_pageInfo_Property.creatable = false
  2655. controller.refreshSecondToolbarItemsState()
  2656. }
  2657. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_LandscapePage_Identifier {
  2658. pageEditViewController?.thumbnailChoosePageStyle = .vertical
  2659. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  2660. toolbarManager.page_pageInfo_Property.creatable = false
  2661. controller.refreshSecondToolbarItemsState()
  2662. }
  2663. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_AllPage_Identifier {
  2664. pageEditViewController?.thumbnailChoosePageStyle = .allPage
  2665. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  2666. toolbarManager.page_pageInfo_Property.creatable = false
  2667. controller.refreshSecondToolbarItemsState()
  2668. }
  2669. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_CustomPage_Identifier {
  2670. pageEditViewController?.thumbnailChoosePageStyle = .custom
  2671. toolbarManager.page_pageInfo_Property.text = nil
  2672. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  2673. toolbarManager.page_pageInfo_Property.creatable = true
  2674. }
  2675. controller.refreshSecondToolbarItemsState()
  2676. }
  2677. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Markup_Identifier).contains(itemIdentifier) {
  2678. //MARK: -Markup
  2679. if itemIdentifier == KMPDFToolbar_eye_Identifier {
  2680. self.showOrHideNotes()
  2681. }
  2682. if viewManager.subToolMode == .None {
  2683. viewManager.showRightSide = false
  2684. } else {
  2685. viewManager.showRightSide = true
  2686. }
  2687. self.refreshToolbarRightViewInfo()
  2688. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Edit_Identifier).contains(itemIdentifier) {
  2689. //MARK: -编辑
  2690. if itemIdentifier == KMPDFToolbar_edit_addWatermark_Identifier {
  2691. showWatermarkController()
  2692. } else if itemIdentifier == KMPDFToolbar_edit_removeWatermark_Identifier {
  2693. removePDFWatermark()
  2694. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddWatermark_Identifier {
  2695. batchAddWatermark()
  2696. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveWatermark_Identifier {
  2697. batchRemoveWatermark()
  2698. } else if itemIdentifier == KMPDFToolbar_edit_addBG_Identifier {
  2699. showBackgroundController()
  2700. } else if itemIdentifier == KMPDFToolbar_edit_removeBG_Identifier {
  2701. removePDFBackground()
  2702. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBG_Identifier {
  2703. batchAddBackground()
  2704. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBG_Identifier {
  2705. batchRemoveBackground()
  2706. } else if itemIdentifier == KMPDFToolbar_edit_addHF_Identifier {
  2707. showHeaderFooterController()
  2708. } else if itemIdentifier == KMPDFToolbar_edit_removeHF_Identifier {
  2709. removeHeaderFooter()
  2710. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddHF_Identifier {
  2711. batchAddHeaderFooter()
  2712. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveHF_Identifier {
  2713. batchRemoveHeaderFooter()
  2714. } else if itemIdentifier == KMPDFToolbar_edit_addBates_Identifier {
  2715. showBatesController()
  2716. } else if itemIdentifier == KMPDFToolbar_edit_removeBates_Identifier {
  2717. removePDFBates()
  2718. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBates_Identifier {
  2719. batchAddBates()
  2720. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBates_Identifier {
  2721. batchRemoveBates()
  2722. } else if itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
  2723. showCropController()
  2724. }
  2725. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Form_Identifier).contains(itemIdentifier) {
  2726. //MARK: -Form表单
  2727. if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier {
  2728. CPDFWidgetAnnotation.updateHighlightFormFiled(listView)
  2729. self.toolbarManager.refreshDefaultConfigItem()
  2730. } else if itemIdentifier == KMPDFToolbar_form_ShowName_Identifier {
  2731. listView.showFormFieldName = !listView.showFormFieldName
  2732. if listView.showFormFieldName {
  2733. toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
  2734. } else {
  2735. toolbarManager.form_ShowName_Property.righticon = nil
  2736. }
  2737. listView.setNeedsDisplayForVisiblePages()
  2738. } else if itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier {
  2739. listView.resetFormAnnotation()
  2740. } else if itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier {
  2741. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  2742. } else if itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier {
  2743. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  2744. } else if itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier {
  2745. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  2746. } else if itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier {
  2747. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  2748. } else if itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier {
  2749. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  2750. } else if itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier {
  2751. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  2752. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier {
  2753. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  2754. } else if itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
  2755. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  2756. }
  2757. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Fill_Identifier).contains(itemIdentifier) {
  2758. //MARK: -填充
  2759. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Convert_Identifier).contains(itemIdentifier) {
  2760. //MARK: -转档
  2761. if itemIdentifier == KMPDFToolbar_convert_word_Identifier {
  2762. let winC = KMConvertWordWindowController()
  2763. let model = KMDocumentModel(url: listView.document.documentURL)
  2764. winC.documentModel = model
  2765. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2766. } else if itemIdentifier == KMPDFToolbar_convert_ppt_Identifier {
  2767. let winC = KMConvertPPTsWindowController()
  2768. winC.subType = 1
  2769. let model = KMDocumentModel(url: listView.document.documentURL)
  2770. winC.documentModel = model
  2771. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2772. } else if itemIdentifier == KMPDFToolbar_convert_RTF_Identifier {
  2773. let winC = KMConvertPPTsWindowController()
  2774. winC.subType = 2
  2775. let model = KMDocumentModel(url: listView.document.documentURL)
  2776. winC.documentModel = model
  2777. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2778. } else if itemIdentifier == KMPDFToolbar_convert_Text_Identifier {
  2779. let winC = KMConvertPPTsWindowController()
  2780. winC.subType = 4
  2781. let model = KMDocumentModel(url: listView.document.documentURL)
  2782. winC.documentModel = model
  2783. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2784. } else if itemIdentifier == KMPDFToolbar_convert_CSV_Identifier {
  2785. let winC = KMConvertPPTsWindowController()
  2786. winC.subType = 5
  2787. let model = KMDocumentModel(url: listView.document.documentURL)
  2788. winC.documentModel = model
  2789. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2790. } else if itemIdentifier == KMPDFToolbar_convert_excel_Identifier {
  2791. let winC = KMConvertExcelWindowController()
  2792. let model = KMDocumentModel(url: listView.document.documentURL)
  2793. winC.documentModel = model
  2794. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2795. } else if itemIdentifier == KMPDFToolbar_convert_HTML_Identifier {
  2796. let winC = KMConvertHtmlWindowController()
  2797. let model = KMDocumentModel(url: listView.document.documentURL)
  2798. winC.documentModel = model
  2799. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  2800. } else if itemIdentifier == KMPDFToolbar_convert_Json_Identifier {
  2801. let winC = KMConvertJsonWindowController()
  2802. let model = KMDocumentModel(url: listView.document.documentURL)
  2803. winC.documentModel = model
  2804. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2805. } else if itemIdentifier == KMPDFToolbar_convert_image_Identifier {
  2806. let winC = KMConvertImageWindowController()
  2807. let model = KMDocumentModel(url: listView.document.documentURL)
  2808. winC.documentModel = model
  2809. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  2810. } else if itemIdentifier == KMPDFToolbar_convert_imageToPDF_Identifier {
  2811. NSApplication.ShowImageToPDFWindow()
  2812. }
  2813. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Protect_Identifier).contains(itemIdentifier) {
  2814. //MARK: -Protect
  2815. if itemIdentifier == KMPDFToolbar_protect_redact_Identifier {
  2816. } else if itemIdentifier == KMPDFToolbar_protect_redact_Property_Identifier {
  2817. self.showRedactProperty()
  2818. } else if itemIdentifier == KMPDFToolbar_protect_redact_Apply_Identifier {
  2819. } else if itemIdentifier == KMPDFToolbar_protect_redact_Exit_Identifier {
  2820. } else if itemIdentifier == KMPDFToolbar_protect_security_Identifier {
  2821. self.showSecureWindow()
  2822. } else if itemIdentifier == KMPDFToolbar_protect_removeSecurity_Identifier {
  2823. self.showRemoveSecureWindow()
  2824. } else if itemIdentifier == KMPDFToolbar_protect_digitalSign_Identifier {
  2825. }
  2826. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Tools_Identifier).contains(itemIdentifier) {
  2827. //MARK: -工具
  2828. if itemIdentifier == KMPDFToolbar_tools_compress_Identifier {
  2829. self.showCompressController(self.listView.document.documentURL)
  2830. } else if itemIdentifier == KMPDFToolbar_tools_batch_compress_Identifier {
  2831. self.showBatchCompressController([self.listView.document.documentURL])
  2832. } else if itemIdentifier == KMPDFToolbar_tools_OCR_Identifier {
  2833. viewManager.showRightSide = !viewManager.showRightSide
  2834. self.refreshToolbarRightViewInfo()
  2835. } else if itemIdentifier == KMPDFToolbar_tools_merge_Identifier {
  2836. self.showMergeWindow(self.listView.document.password)
  2837. } else if itemIdentifier == KMPDFToolbar_tools_TTS_Identifier {
  2838. self.showTTSWindow()
  2839. } else if itemIdentifier == KMPDFToolbar_tools_extractImage_Identifier {
  2840. self.extractImageAction(num: 2)
  2841. } else if itemIdentifier == KMPDFToolbar_tools_AITools_Identifier {
  2842. self.viewManager.pdfSideBarType = .aiTools
  2843. self.sideBarController?.reloadData()
  2844. if let sideVC = self.sideBarController {
  2845. self.kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  2846. }
  2847. }
  2848. } else if itemIdentifier == KMPDFToolbar_ViewDisplay_Identifier {
  2849. //MARK: -Display
  2850. updatePDFDisplaySettingView()
  2851. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Right_Identifiers).contains(itemIdentifier) {
  2852. if itemIdentifier == KMPDFToolbar_rightView_Identifier {
  2853. //MARK: -属性栏
  2854. } else if itemIdentifier == KMPDFToolbar_PageEdit_Identifier {
  2855. //MARK: -页面编辑
  2856. if viewManager.isPageEditMode == true {
  2857. enterPageEditMode()
  2858. } else {
  2859. exitPageEditMode()
  2860. }
  2861. } else if(itemIdentifier == KMPDFToolbar_undo_Identifier) {
  2862. //MARK: -Undo
  2863. listView.undoManager?.undo()
  2864. } else if(itemIdentifier == KMPDFToolbar_redo_Identifier) {
  2865. //MARK: -Redo
  2866. listView.undoManager?.redo()
  2867. } else if(itemIdentifier == KMPDFToolbar_fileInfo_Identifier) {
  2868. self.showFileInfo()
  2869. } else if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier ||
  2870. itemIdentifier == KMPDFToolbar_share_Flattened_Identifier ||
  2871. itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  2872. //MARK: -Share
  2873. if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier) {
  2874. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  2875. shareDocument(sender: view)
  2876. }
  2877. } else if(itemIdentifier == KMPDFToolbar_share_Flattened_Identifier) {
  2878. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  2879. shareFlatten(sender: view)
  2880. }
  2881. } else if(itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  2882. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  2883. shareOriginalPDF(sender: view)
  2884. }
  2885. }
  2886. }
  2887. } else {
  2888. print("click else")
  2889. }
  2890. refreshToolbarViewHeightInfo()
  2891. toolbarViewModeChanged()
  2892. refreshRightSide()
  2893. }
  2894. func kmPDFToolbarControllerDidSelectTextDidBeginEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  2895. }
  2896. func kmPDFToolbarControllerDidSelectTextDidChange(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  2897. }
  2898. func kmPDFToolbarControllerDidSelectTextDidEndEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  2899. if view.properties == toolbarManager.page_pageInfo_Property {
  2900. if viewManager.isPageEditMode == true {
  2901. let fileAttribute = KMNFileAttribute()
  2902. fileAttribute.password = listView.document?.password ?? ""
  2903. fileAttribute.pdfDocument = listView.document
  2904. fileAttribute.filePath = listView.document?.documentURL.path ?? ""
  2905. fileAttribute.bAllPage = false
  2906. fileAttribute.pagesType = .PagesString
  2907. fileAttribute.pagesString = view.properties.text ?? ""
  2908. let fetchSelectPages = fileAttribute.fetchSelectPages()
  2909. if (fetchSelectPages.isEmpty) {
  2910. let alert = NSAlert()
  2911. alert.alertStyle = .critical
  2912. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  2913. alert.runModal()
  2914. toolbarManager.page_pageInfo_Property.text = ""
  2915. controller.refreshSecondToolbarItemsState()
  2916. } else {
  2917. var tIndexPaths: Set<IndexPath> = []
  2918. for i in 0 ..< fetchSelectPages.count {
  2919. tIndexPaths.insert(IndexPath(item: (fetchSelectPages[i] - 1), section: 0))
  2920. }
  2921. pageEditViewController?.selectionIndexPaths = tIndexPaths
  2922. }
  2923. }
  2924. }
  2925. }
  2926. func kmPDFToolbarControllerDidExitPageEditMode(_ controller: KMPDFToolbarController) {
  2927. exitPageEditMode()
  2928. }
  2929. }
  2930. //MARK: - KMRightSideControllerDelegate右边属性栏代理
  2931. extension KMMainViewController: KMRightSideControllerDelegate {
  2932. func kmRightSideControllerDidContendVCUpdated(_ controller: KMRightSideController) {
  2933. //MARK: -Crop
  2934. if (controller.contentViewController is KMCropPropertyController) {
  2935. if let cropVC = rightSideController?.edit_cropController {
  2936. cropVC.pdfView = controller.pdfView
  2937. if cropVC.delegate == nil {
  2938. cropVC.delegate = cropController
  2939. }
  2940. cropVC.reloadData()
  2941. }
  2942. }
  2943. }
  2944. func kmRightSideControllerOCRShowTypeChange(_ controller: KMRightSideController, _ type: KMOCRShowType) {
  2945. if type == .area {
  2946. self.listView.toolMode = .COCRToolMode
  2947. self.showOCRToolAlert(KMLocalizedString("Please select the area that needs OCR and click the “OCR” button to start"))
  2948. } else {
  2949. self.listView.toolMode = .CTextToolMode
  2950. }
  2951. }
  2952. func kmRightSideControllerOCRDoneAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
  2953. if model.showType == .area {
  2954. } else {
  2955. if model.saveAsPDF {
  2956. if model.saveType == .PDF {
  2957. } else {
  2958. }
  2959. } else {
  2960. }
  2961. self.convertOCR(document: self.listView.document, model: model)
  2962. }
  2963. }
  2964. }
  2965. //MARK: - KMNDisplayViewControllerDelegate代理
  2966. extension KMMainViewController: KMNDisplayViewControllerDelegate {
  2967. //Display Mode
  2968. func displayViewControllerDidDisplayModeChanged(_ controller: KMNDisplayViewController) {
  2969. listView.layoutDocumentView()
  2970. }
  2971. //阅读模式
  2972. func displayViewControllerDidReadModeUpdated(_ controller: KMNDisplayViewController) {
  2973. if viewManager.isPDFReadMode {
  2974. openPDFReadMode()
  2975. } else {
  2976. exitPDFReadMode()
  2977. }
  2978. }
  2979. //PPT
  2980. func displayViewControllerDidGotoSlideShow(_ controller: KMNDisplayViewController) {
  2981. togglePresentation(nil)
  2982. }
  2983. //SplitView
  2984. func displayViewControllerDidSplitModeChanged(_ controller: KMNDisplayViewController) {
  2985. reloadPDFSplitInfo()
  2986. }
  2987. func displayViewControllerDidSplitFileChanged(_ controller: KMNDisplayViewController) {
  2988. splitPDFController?.reloadData()
  2989. }
  2990. func displayViewControllerDidToolbarStateChanged(_ controller: KMNDisplayViewController) {
  2991. splitPDFController?.refreshToolbarState()
  2992. reloadPDFPageNumberToolbar()
  2993. }
  2994. }
  2995. //MARK: - PPT
  2996. extension KMMainViewController: KMInteractionProviderProtocol {
  2997. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  2998. if(interactionMode == .presentation) {
  2999. if listView.presentationDrawView == nil {
  3000. listView.createPresentationDraw()
  3001. }
  3002. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  3003. presentationTopViewController?.pdfView = listView
  3004. presentationTopViewController?.delegate = self
  3005. presentationTopViewController?.isSelectionPre = true
  3006. listView.isPresentationMode = true
  3007. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  3008. if((presentationTopViewController) != nil) {
  3009. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  3010. }
  3011. } else {
  3012. listView.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  3013. }
  3014. fullScreenWindow.contentView?.addSubview(listView)
  3015. if(interactionMode == .presentation) {
  3016. let frame = fullScreenWindow.frame
  3017. listView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-42)
  3018. listView.autoresizingMask = [.width, .maxYMargin]
  3019. }
  3020. return view
  3021. }
  3022. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  3023. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3024. return
  3025. }
  3026. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  3027. if interactionMode == .presentation {
  3028. let backgroundColor = NSColor.black
  3029. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  3030. let wasInteractionMode = self.interactionMode
  3031. if wasInteractionMode == .normal {
  3032. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  3033. }
  3034. if wasInteractionMode == .legacyFullScreen {
  3035. self.enterPresentationMode()
  3036. self.listView.frame = (self.view.window?.contentView?.bounds)!
  3037. self.view.window?.contentView?.addSubview(listView)
  3038. // self.view.window?.backgroundColor = backgroundColor
  3039. self.view.window?.level = level
  3040. self.listView.layoutDocumentView()
  3041. self.listView.requiresDisplay()
  3042. self.forceSubwindowsOnTop(false)
  3043. }
  3044. } else {
  3045. KMPrint("2")
  3046. }
  3047. }
  3048. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  3049. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3050. return
  3051. }
  3052. if self.interactionMode == .presentation {
  3053. self.listView.layoutDocumentView()
  3054. self.listView.requiresDisplay()
  3055. }
  3056. }
  3057. @objc func willShowFullScreenNotification(_ sender: Notification) {
  3058. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3059. return
  3060. }
  3061. if self.interactionMode == .presentation {
  3062. let view = self.view.window?.firstResponder as? NSView
  3063. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  3064. self.view.window?.makeFirstResponder(nil)
  3065. }
  3066. }
  3067. }
  3068. @objc func didShowFullScreenNotification(_ sender: Notification) {
  3069. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3070. return
  3071. }
  3072. if self.interactionMode == .presentation {
  3073. self.enterPresentationMode()
  3074. }
  3075. }
  3076. }
  3077. // MARK: -KMPresentationTopViewControllerDelegate (幻灯片)
  3078. extension KMMainViewController: KMPresentationTopViewControllerDelegate {
  3079. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3080. self.exitFullScreen()
  3081. }
  3082. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3083. listView.presentationDrawView?.clear()
  3084. }
  3085. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  3086. let presentationDrawView = listView.presentationDrawView
  3087. if presentationDrawView?.canUndo() == true {
  3088. presentationDrawView?.undo()
  3089. }
  3090. }
  3091. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  3092. listView.isPresentationMode = isSeletion
  3093. if listView.isEnterPresentationDrawMode() == true {
  3094. listView.exitPresentationDrawMode()
  3095. }
  3096. }
  3097. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  3098. if color == nil{
  3099. listView.exitPresentationDrawMode()
  3100. } else {
  3101. if listView.isEnterPresentationDrawMode() == false {
  3102. listView.enterPresentationDrawMode()
  3103. }
  3104. listView.changePresentationDrawModelColor(color)
  3105. }
  3106. }
  3107. }
  3108. //MARK: - KMSplitPDFViewControllerDelegate SplitPDFView分屏视图
  3109. extension KMMainViewController: KMSplitPDFViewControllerDelegate {
  3110. func splitPDFViewControllerDidUpdateFilePath(_ controller: KMSplitPDFViewController) {
  3111. displaySettingController?.reloadData()
  3112. }
  3113. func splitPDFViewControllerDidUpdatePDFScale(_ controller: KMSplitPDFViewController) {
  3114. if let scaleFactor = controller.pdfView?.scaleFactor {
  3115. listView.scaleFactor = scaleFactor
  3116. }
  3117. }
  3118. func splitPDFViewControllerDidUpdatePDFPageIndex(_ controller: KMSplitPDFViewController) {
  3119. if let pageIndex = controller.pdfView?.currentPageIndex {
  3120. listView.go(toPageIndex: pageIndex, animated: false)
  3121. }
  3122. }
  3123. }
  3124. //MARK: - Edit编辑相关代理
  3125. extension KMMainViewController: KMEditToolbarViewDelegate {
  3126. func kmEditToolbarViewDidUpdateMode(_ view: KMEditToolbarView) {
  3127. if view.editType == .watermark {
  3128. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3129. watermarkViewController?.resetUI()
  3130. watermarkViewController?.reloadData()
  3131. } else if view.editType == .background {
  3132. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3133. backgroundViewController?.resetUI()
  3134. backgroundViewController?.reloadData()
  3135. } else if view.editType == .header_Footer {
  3136. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3137. headerFooterViewController?.resetUI()
  3138. headerFooterViewController?.reloadData()
  3139. } else if view.editType == .bates {
  3140. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  3141. batesViewController?.resetUI()
  3142. batesViewController?.reloadData()
  3143. }
  3144. }
  3145. func kmEditToolbarViewDidChooseBatch(_ view: KMEditToolbarView) {
  3146. }
  3147. func kmEditToolbarViewDidChooseApply(_ view: KMEditToolbarView) {
  3148. // let pageIndex = view.getSelectedPageIndex(listView.document)
  3149. // if pageIndex.isEmpty {
  3150. // let alert = NSAlert()
  3151. // alert.alertStyle = .critical
  3152. // alert.messageText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
  3153. // alert.runModal()
  3154. // return
  3155. // }
  3156. // let pageString = view.getSelectedPageString(listView.document, pageIndex)
  3157. //
  3158. // if view.editType == .watermark {
  3159. // if let model = watermarkViewController?.currentWatermarkData {
  3160. // let watermark = KMPDFWatermarkData.returnWaterMarkWith(model, listView.document)
  3161. // watermark.pageString = pageString
  3162. // listView.document.addWatermark(watermark)
  3163. // listView.layoutDocumentView()
  3164. // }
  3165. // exitEditToolbarView()
  3166. // } else if view.editType == .background {
  3167. // if let model = backgroundViewController?.backgroundModel {
  3168. // if let background = listView.document.background() {
  3169. // KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  3170. // background.pageString = pageString
  3171. // background.update()
  3172. //
  3173. // listView.document?.refreshPageData()
  3174. // listView.layoutDocumentView()
  3175. // }
  3176. // }
  3177. // exitEditToolbarView()
  3178. //
  3179. // } else if view.editType == .header_Footer {
  3180. // if let model = headerFooterViewController?.headerFooterModel {
  3181. // if let headerFooter = listView.document.headerFooter() {
  3182. // KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(listView.document.pageCount))
  3183. // headerFooter.pageString = pageString
  3184. // headerFooter.update()
  3185. //
  3186. // listView.document?.refreshPageData()
  3187. // listView.layoutDocumentView()
  3188. // }
  3189. // }
  3190. //
  3191. // exitEditToolbarView()
  3192. //
  3193. // } else if view.editType == .bates {
  3194. // exitEditToolbarView()
  3195. //
  3196. // }
  3197. }
  3198. func kmEditToolbarViewDidChooseExit(_ view: KMEditToolbarView) {
  3199. if view.applyEnable {
  3200. let alert = NSAlert()
  3201. if view.editType == .watermark {
  3202. alert.messageText = NSLocalizedString("There are unapplied Watermark settings, do you want to apply them?", comment: "")
  3203. } else if view.editType == .background {
  3204. alert.messageText = NSLocalizedString("There are unapplied Background settings, do you want to apply them?", comment: "")
  3205. } else if view.editType == .header_Footer {
  3206. alert.messageText = NSLocalizedString("There are unapplied Header & Footer settings, do you want to apply them?", comment: "")
  3207. } else if view.editType == .bates {
  3208. alert.messageText = NSLocalizedString("There are unapplied Bates settings, do you want to apply them?", comment: "")
  3209. }
  3210. alert.informativeText = NSLocalizedString("If not, the changes will be lost.", comment: "")
  3211. alert.addButton(withTitle: NSLocalizedString("Apply", comment: ""))
  3212. alert.addButton(withTitle: NSLocalizedString("Don't Apply", comment: ""))
  3213. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3214. let result = alert.runModal()
  3215. if (result == .alertFirstButtonReturn) {
  3216. self.kmEditToolbarViewDidChooseApply(view)
  3217. } else if (result == .alertSecondButtonReturn) {
  3218. //"Don't Apply"
  3219. exitEditToolbarView()
  3220. } else if (result == .alertThirdButtonReturn) {
  3221. //Cancel
  3222. }
  3223. } else {
  3224. exitEditToolbarView()
  3225. }
  3226. }
  3227. }
  3228. //MARK: - KMCropControllerDelegate 裁剪相关代理
  3229. extension KMMainViewController: KMCropControllerDelegate {
  3230. func kmCropControllerDidCrop(_ controller: KMCropController, _ cropRect: CGRect, _ view: KMPageRangeSelectView) {
  3231. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3232. let indexs = rangeSelectResult.0
  3233. let isCurrentPage = rangeSelectResult.1
  3234. var uIndexs: [UInt] = []
  3235. for index in indexs {
  3236. if index > 0 {
  3237. uIndexs.append(UInt(index-1))
  3238. }
  3239. }
  3240. if isCurrentPage {
  3241. uIndexs = [UInt(listView.currentPageIndex)]
  3242. }
  3243. cropPages(atIndexs: uIndexs, to: [cropRect])
  3244. removeCropController()
  3245. viewManager.subToolMode = .None
  3246. if let toolbarVC = self.pdfToolbarController {
  3247. toolbarVC.refreshSecondToolbarItemsState()
  3248. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3249. }
  3250. }
  3251. func kmCropControllerDidCropSeparate(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  3252. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3253. let indexs = rangeSelectResult.0
  3254. let isCurrentPage = rangeSelectResult.1
  3255. var rectArray: Array<NSRect> = []
  3256. var uIndexs: [UInt] = []
  3257. for index in indexs {
  3258. if index > 0 {
  3259. uIndexs.append(UInt(index-1))
  3260. let page = self.listView.document.page(at: UInt(index-1))
  3261. let rect = KMCropTools.getPageForegroundBox(page!)
  3262. rectArray.append(rect)
  3263. }
  3264. }
  3265. if isCurrentPage {
  3266. uIndexs = [UInt(listView.currentPageIndex)]
  3267. }
  3268. cropPages(atIndexs: uIndexs, to: rectArray)
  3269. removeCropController()
  3270. viewManager.subToolMode = .None
  3271. if let toolbarVC = self.pdfToolbarController {
  3272. toolbarVC.refreshSecondToolbarItemsState()
  3273. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3274. }
  3275. }
  3276. func kmCropControllerDidCropAuto(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  3277. let rangeSelectResult = view.getSelectedPageIndex(listView.document)
  3278. let indexs = rangeSelectResult.0
  3279. let isCurrentPage = rangeSelectResult.1
  3280. var uIndexs: [UInt] = []
  3281. for index in indexs {
  3282. if index > 0 {
  3283. uIndexs.append(UInt(index-1))
  3284. }
  3285. }
  3286. if isCurrentPage {
  3287. uIndexs = [UInt(listView.currentPageIndex)]
  3288. }
  3289. auto_cropPagesWhiteMargin(uIndexs)
  3290. removeCropController()
  3291. viewManager.subToolMode = .None
  3292. if let toolbarVC = self.pdfToolbarController {
  3293. toolbarVC.refreshSecondToolbarItemsState()
  3294. self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
  3295. }
  3296. }
  3297. func kmCropControllerDidChangedSelectionOrMagnification(_ controller: KMCropController) {
  3298. if let cropVC = rightSideController?.edit_cropController {
  3299. if cropVC.pdfView != controller.pdfView {
  3300. cropVC.pdfView = controller.pdfView
  3301. }
  3302. cropVC.cropSeparateOn = false
  3303. cropVC.cropAutoOn = false
  3304. cropVC.reloadData()
  3305. }
  3306. }
  3307. }
  3308. //MARK: - KMWatermarkControllerDelegate 水印相关代理
  3309. extension KMMainViewController: KMWatermarkControllerDelegate {
  3310. func kmWatermarkControllerDidUpdateMode(_ view: KMWatermarkController) {
  3311. editToolbarView?.editSubType = view.editSubType
  3312. editToolbarView?.reloadData()
  3313. }
  3314. func kmWatermarkControllerDidWatermarkUpdated(_ view: KMWatermarkController) {
  3315. var applyEnable = true
  3316. if let model = view.currentWatermarkData {
  3317. if model.watermarkType == .text {
  3318. if model.text == nil || model.text?.count == 0 {
  3319. applyEnable = false
  3320. }
  3321. } else if model.watermarkType == .image {
  3322. if model.imagePath == nil {
  3323. applyEnable = false
  3324. }
  3325. }
  3326. } else {
  3327. applyEnable = false
  3328. }
  3329. editToolbarView?.applyEnable = applyEnable
  3330. editToolbarView?.reloadData()
  3331. }
  3332. }
  3333. //MARK: - KMBackgroundControllerDelegate 背景代理
  3334. extension KMMainViewController: KMBackgroundControllerDelegate {
  3335. func kmBackgroundControllerDidUpdateMode(_ view: KMBackgroundController) {
  3336. editToolbarView?.editSubType = view.editSubType
  3337. }
  3338. func kmBackgroundControllerDidWatermarkUpdated(_ view: KMBackgroundController) {
  3339. var applyEnable = true
  3340. if let model = view.backgroundModel {
  3341. if model.type == .image {
  3342. if model.imagePath == nil {
  3343. applyEnable = false
  3344. }
  3345. }
  3346. } else {
  3347. applyEnable = false
  3348. }
  3349. editToolbarView?.applyEnable = applyEnable
  3350. editToolbarView?.reloadData()
  3351. }
  3352. }
  3353. //MARK: - KMHeaderFooterControllerDelegate 页眉页脚代理
  3354. extension KMMainViewController: KMHeaderFooterControllerDelegate {
  3355. func kmHeaderFooterControllerDidUpdateModeType(_ view: KMHeaderFooterController) {
  3356. editToolbarView?.editSubType = view.editSubType
  3357. }
  3358. func kmHeaderFooterControllerDidModelDataUpdated(_ view: KMHeaderFooterController) {
  3359. var applyEnable = true
  3360. if let model = view.headerFooterModel {
  3361. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  3362. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  3363. applyEnable = false
  3364. }
  3365. } else {
  3366. applyEnable = false
  3367. }
  3368. editToolbarView?.applyEnable = applyEnable
  3369. editToolbarView?.reloadData()
  3370. }
  3371. }
  3372. //MARK: - KMBatesControllerDelegate Bates贝茨码代理
  3373. extension KMMainViewController: KMBatesControllerDelegate {
  3374. func kmBatesControllerDidUpdateMode(_ view: KMBatesController) {
  3375. editToolbarView?.editSubType = view.editSubType
  3376. editToolbarView?.reloadData()
  3377. }
  3378. func kmBatesControllerDidModelDataUpdated(_ view: KMBatesController) {
  3379. var applyEnable = true
  3380. if let model = view.batesModel {
  3381. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  3382. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  3383. applyEnable = false
  3384. }
  3385. } else {
  3386. applyEnable = false
  3387. }
  3388. editToolbarView?.applyEnable = applyEnable
  3389. editToolbarView?.reloadData()
  3390. }
  3391. }
  3392. //MARK: - CPDFViewDelegate PDFView代理
  3393. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  3394. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  3395. sideBarController?.reloadPageTurnerData()
  3396. documentLoadComplete()
  3397. }
  3398. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  3399. sideBarController?.reloadPageTurnerData()
  3400. botaViewController?.currentPageDidChangedAction(listView: listView)
  3401. //分屏视图
  3402. reloadPDFPageNumberToolbar()
  3403. if viewManager.splitSyncScroll {
  3404. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  3405. splitPDFController?.outPDFFirst = true
  3406. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  3407. var index = pdfView.currentPageIndex
  3408. if index > document.pageCount {
  3409. index = Int(splitPDFView.document.pageCount - 1)
  3410. }
  3411. splitPDFView.go(toPageIndex: index, animated: false)
  3412. }
  3413. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  3414. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  3415. } else if splitPDFController?.outPDFFirst == true {
  3416. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  3417. var index = pdfView.currentPageIndex
  3418. if index > document.pageCount {
  3419. index = Int(splitPDFView.document.pageCount - 1)
  3420. }
  3421. splitPDFView.go(toPageIndex: index, animated: false)
  3422. }
  3423. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  3424. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  3425. }
  3426. }
  3427. //水印
  3428. updateEditModeDocumentWhenPageChanged()
  3429. //
  3430. }
  3431. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  3432. pdfToolbarController?.reloadSelectZoomView()
  3433. reloadPDFPageNumberToolbar()
  3434. reloadPopUIWindow()
  3435. //分屏视图
  3436. if viewManager.splitSyncScroll {
  3437. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  3438. splitPDFController?.outPDFFirst = true
  3439. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  3440. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  3441. } else if splitPDFController?.outPDFFirst == true {
  3442. if let splitPDFView = splitPDFController?.pdfView {
  3443. splitPDFView.scaleFactor = pdfView.scaleFactor
  3444. }
  3445. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  3446. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  3447. }
  3448. }
  3449. }
  3450. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  3451. if let urlString = url, urlString == kKMPurchaseProductURLString {
  3452. //跳转订阅比较表
  3453. return
  3454. }
  3455. if url.hasPrefix("smb://") {
  3456. NSWorkspace.shared.openFile(url)
  3457. } else {
  3458. KMTools.openURL(urlString: url)
  3459. }
  3460. }
  3461. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  3462. KMPrint("pdfViewPerformURL")
  3463. if content != nil {
  3464. NSWorkspace.shared.open(URL(string: content)!)
  3465. } else {
  3466. let alert = NSAlert()
  3467. alert.alertStyle = .critical
  3468. alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
  3469. alert.messageText = ""
  3470. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3471. alert.runModal()
  3472. return
  3473. }
  3474. }
  3475. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  3476. KMPrint("pdfViewPerformPrint")
  3477. self.showPrintWindow()
  3478. }
  3479. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  3480. KMPrint("pdfViewPerformGo")
  3481. }
  3482. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  3483. KMPrint("pdfViewOpenPDF")
  3484. }
  3485. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  3486. KMPrint("pdfViewPerformReset")
  3487. pdfView.document?.resetForm()
  3488. }
  3489. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  3490. KMPrint("pdfViewEditingBlockDidChanged")
  3491. }
  3492. func pdfViewAsBookBookmark() -> NSImage! {
  3493. return NSImage(named: "KMImageNameBookmarkIcon")!
  3494. }
  3495. //MARK: -编辑模块
  3496. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  3497. // 文本区块 选中文本已经变化
  3498. reloadPopUIWindow()
  3499. }
  3500. func pdfViewPDFSelectionAttributeDidChanged(_ pdfView: CPDFView!) {
  3501. reloadPopUIWindow()
  3502. }
  3503. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  3504. //编辑模块变化
  3505. rightSideController?.reloadDataWithPDFView(pdfView: (pdfView as! CPDFListView))
  3506. if pdfView is CPDFListView {
  3507. (pdfView as! CPDFListView).isEditImage = false
  3508. }
  3509. reloadPopUIWindow()
  3510. }
  3511. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  3512. if editArea != nil && (editArea is CPDFEditImageArea){
  3513. self.listView.cropAreas = editArea as? CPDFEditImageArea
  3514. }
  3515. reloadPopUIWindow()
  3516. }
  3517. //编辑PDF 创建图片区域回调
  3518. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  3519. if (pdfView as! CPDFListView).isEditImage {
  3520. return
  3521. }
  3522. if rect.size.width < 5 && rect.size.height < 5 {
  3523. pdfView.updateEditing([])
  3524. return
  3525. }
  3526. let panel = NSOpenPanel()
  3527. panel.allowsMultipleSelection = false
  3528. panel.allowedFileTypes = ["png","jpg"]
  3529. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  3530. if response == .OK {
  3531. var filePath = panel.url?.path
  3532. let image = NSImage.init(contentsOf: panel.url!)
  3533. //图片自适应范围
  3534. if image != nil {
  3535. var imageRect = rect
  3536. let imageSize = image!.size
  3537. var previewSize = rect.size
  3538. var isChangeSize = false
  3539. if previewSize.width == 0 && previewSize.height == 0 {
  3540. previewSize = CGSize(width: 500, height: 500)
  3541. isChangeSize = true
  3542. }
  3543. var scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  3544. if scale < 1 { // 大于 500
  3545. } else {
  3546. let wh = max(imageSize.width, imageSize.height)
  3547. if wh >= 72 {
  3548. scale = min(scale, 1)
  3549. } else {
  3550. scale = min(72 / imageSize.width, 72 / imageSize.height)
  3551. }
  3552. }
  3553. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  3554. if isChangeSize {
  3555. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  3556. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  3557. } else {
  3558. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  3559. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  3560. }
  3561. imageRect.size = newSize
  3562. let limitWidth = 1920.0
  3563. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  3564. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  3565. targetSize: CGSize(width: limitWidth, height: limitWidth),
  3566. maxSizeInBytes: 1024 * 1024 * 5,
  3567. targetCompression: 1.0)
  3568. }
  3569. //自适应page
  3570. let pageRect = self.listView.currentPage().bounds ?? .zero
  3571. if imageRect.width > pageRect.width ||
  3572. imageRect.height > pageRect.height {
  3573. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  3574. imageRect = CGRect(x: imageRect.origin.x,
  3575. y: imageRect.origin.y,
  3576. width: imageRect.width * pageScale,
  3577. height: imageRect.height * pageScale)
  3578. }
  3579. if imageRect.origin.x < 0 {
  3580. imageRect.origin.x = 5
  3581. }
  3582. if imageRect.origin.y < 0 {
  3583. imageRect.origin.y = 5
  3584. }
  3585. if imageRect.origin.x + imageRect.width > pageRect.width ||
  3586. imageRect.origin.y + imageRect.height > pageRect.height {
  3587. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  3588. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  3589. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  3590. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  3591. }
  3592. DispatchQueue.main.async {
  3593. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  3594. }
  3595. }
  3596. }
  3597. }
  3598. }
  3599. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  3600. if rect.size.width < 5 && rect.size.height < 5 {
  3601. let areas = self.listView.km_EditingAreas()
  3602. if let area = areas.last {
  3603. if let data = area as? CPDFEditTextArea {
  3604. if let str = data.editTextAreaString(), str.isEmpty {
  3605. self.listView.remove(with: area)
  3606. } else {
  3607. self.listView.updateEditing([])
  3608. }
  3609. }
  3610. }
  3611. return
  3612. }
  3613. var newRect = rect
  3614. if rect.size.equalTo(.zero) {
  3615. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  3616. } else {
  3617. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  3618. }
  3619. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  3620. let fontSize = model.fontSize
  3621. let fontColor = model.color
  3622. let fontAlign = model.alignment
  3623. NSColorPanel.shared.color = fontColor
  3624. let attri = CEditAttributes()
  3625. attri.cFont = CPDFFont(familyName: model.fontName, fontStyle: model.fontStyle)
  3626. attri.fontColor = fontColor
  3627. attri.alignment = fontAlign
  3628. attri.isBold = model.bold
  3629. attri.isItalic = model.italic
  3630. self.listView.createStringBounds(newRect, with: attri, page: page)
  3631. }
  3632. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  3633. rightSideController?.reloadEditingAreas()
  3634. toggleClosePopUIWindow()
  3635. }
  3636. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  3637. rightSideController?.reloadEditingAreas()
  3638. toggleClosePopUIWindow()
  3639. }
  3640. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  3641. rightSideController?.reloadEditingAreas()
  3642. reloadPopUIWindow()
  3643. }
  3644. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  3645. rightSideController?.reloadEditingAreas()
  3646. reloadPopUIWindow()
  3647. }
  3648. func pdfViewEditingExitCropMode(_ pdfView: CPDFView!, forEditing editingArea: CPDFEditImageArea!) {
  3649. rightSideController?.reloadEditingAreas()
  3650. toggleClosePopUIWindow()
  3651. }
  3652. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  3653. let areas = self.listView.km_editingImageAreas()
  3654. if areas.count == 1 {
  3655. if let data = areas.first as? CPDFEditImageArea {
  3656. let updating = self.listView.editAreaBoundUpdating
  3657. if updating {
  3658. self.listView.editAreaBoundUpdating = false
  3659. }
  3660. }
  3661. }
  3662. }
  3663. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  3664. }
  3665. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  3666. let command = theEvent.modifierFlags.contains(.command)
  3667. let control = theEvent.modifierFlags.contains(.control)
  3668. KMPrint(theEvent.keyCode)
  3669. if self.listView.isEditing() == true {
  3670. if control && theEvent.keyCode == 11 { // ctr + b
  3671. self.listView.setEditingTextarea_Bold()
  3672. rightSideController?.reloadEditingAreas()
  3673. return false
  3674. } else if control && theEvent.keyCode == 34 { // ctr +i
  3675. self.listView.setEditingTextarea_Italic()
  3676. rightSideController?.reloadEditingAreas()
  3677. return false
  3678. } else if theEvent.keyCode == 36 { // enter
  3679. if self.listView.isCropMode {
  3680. self.listView.cropComfirmAction()
  3681. rightSideController?.reloadEditingAreas()
  3682. return false
  3683. }
  3684. } else if theEvent.keyCode == 53 { // Cancel
  3685. if self.listView.isCropMode {
  3686. self.listView.cropCancelAction()
  3687. rightSideController?.reloadEditingAreas()
  3688. return false
  3689. }
  3690. }
  3691. }
  3692. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  3693. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  3694. return false
  3695. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  3696. return false
  3697. } else if (theEvent.keyCode == 123) { // 向左
  3698. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  3699. return false
  3700. } else {
  3701. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  3702. self.listView.goToPreviousPage(nil)
  3703. return false
  3704. }
  3705. }
  3706. } else if (theEvent.keyCode == 126) { // 向上
  3707. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  3708. return false
  3709. } else {
  3710. if (self.listView.isContinousScroll()) {
  3711. return true
  3712. }
  3713. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  3714. self.listView.goToPreviousPage(nil)
  3715. return false
  3716. }
  3717. }
  3718. } else if (theEvent.keyCode == 124) { // 向右
  3719. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  3720. return false
  3721. } else {
  3722. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  3723. self.listView.goToNextPage(nil)
  3724. return false
  3725. }
  3726. }
  3727. } else if (theEvent.keyCode == 125) { // 向下
  3728. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  3729. return false
  3730. } else {
  3731. if (self.listView.isContinousScroll()) {
  3732. return true
  3733. }
  3734. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  3735. self.listView.goToNextPage(nil)
  3736. return false
  3737. }
  3738. }
  3739. } else if (theEvent.keyCode == 36) {
  3740. if self.listView.shouAddEditAreaType() == .image || self.listView.shouAddEditAreaType() == .text {
  3741. if self.listView.isEditImage {
  3742. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  3743. }
  3744. }
  3745. }
  3746. if theEvent.keyCode == 53 {
  3747. //ESC
  3748. self.exitFullScreen()
  3749. if viewManager.isPDFReadMode {
  3750. self.exitPDFReadMode()
  3751. }
  3752. self.leftSideViewCancelSelect()
  3753. }
  3754. return true
  3755. }
  3756. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  3757. guard let action = menuItem.action else {
  3758. isTakesEffect.pointee = false
  3759. return false
  3760. }
  3761. if (KMSystemMenu.isEditSelector(sel: action)) {
  3762. if (KMSystemMenu.Edit.deleteSelector == action) {
  3763. isTakesEffect.pointee = true
  3764. return self.listView.activeAnnotations.count > 0
  3765. } else if (KMSystemMenu.Edit.copySelector == action) {
  3766. isTakesEffect.pointee = true
  3767. return true//self.listView.canCopy()
  3768. } else if (KMSystemMenu.Edit.cutSelector == action) {
  3769. isTakesEffect.pointee = true
  3770. return self.listView.canCopy()
  3771. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  3772. isTakesEffect.pointee = true
  3773. return self.listView.canPaste()
  3774. }
  3775. }
  3776. isTakesEffect.pointee = false
  3777. return false
  3778. }
  3779. //MARK: - CPDFListViewDelegate
  3780. func pdfListViewChangedToolMode(_ pdfListView: CPDFListView!, for toolMode: CToolMode) {
  3781. reloadPopUIWindow()
  3782. }
  3783. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  3784. self.view.window?.makeFirstResponder(self.listView)
  3785. reloadPopUIWindow()
  3786. if isRightMenu {
  3787. } else if annotations.count > 0 {
  3788. if self.viewManager.isPDFReadMode {
  3789. toggleCloseRightSide()
  3790. } else {
  3791. let isMultiAnnotations = pdfListView.isMultiAnnotation(annotations)
  3792. if isMultiAnnotations == true {
  3793. viewManager.showRightSide = false
  3794. } else {
  3795. viewManager.showRightSide = true
  3796. }
  3797. refreshToolbarRightViewInfo()
  3798. }
  3799. } else if (annotations.count == 0){
  3800. if pdfListView.annotationType == .unkown {
  3801. viewManager.showRightSide = false
  3802. } else {
  3803. if self.viewManager.isPDFReadMode {
  3804. viewManager.showRightSide = false
  3805. } else {
  3806. viewManager.showRightSide = true
  3807. }
  3808. }
  3809. refreshToolbarRightViewInfo()
  3810. }
  3811. self.refreshMeasureInfo()
  3812. //
  3813. pdfToolbarController?.pdfViewActiveAnnotationsChanged()
  3814. }
  3815. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  3816. var pagePoint = CGPoint.zero
  3817. let point = theEvent.locationInWindow
  3818. let isShowPopUI:Bool = false
  3819. if let page = listView.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  3820. if view.window?.interactionMode == .presentation {
  3821. let menuStruct = clickPresentationMenu(point: pagePoint)
  3822. groupListMenuGroup?.groupDelegate = self
  3823. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  3824. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  3825. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: pdfListView)
  3826. } else {
  3827. var menuStringArr: [String] = []
  3828. let activeAnnotations = pdfListView.activeAnnotations as? [CPDFAnnotation]
  3829. if activeAnnotations?.count ?? 0 > 1 {
  3830. var isSameAnnotation = true
  3831. let firstAnnotation = activeAnnotations?.first
  3832. for i in 1..<(activeAnnotations?.count ?? 1) {
  3833. if firstAnnotation?.type != activeAnnotations?[i].type {
  3834. isSameAnnotation = false
  3835. break
  3836. }
  3837. }
  3838. if isSameAnnotation {
  3839. if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
  3840. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  3841. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3842. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3843. } else {
  3844. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3845. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  3846. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3847. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3848. }
  3849. if(isShowPopUI){
  3850. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  3851. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3852. }
  3853. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  3854. if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true || firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  3855. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3856. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  3857. }
  3858. } else {
  3859. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3860. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  3861. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3862. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3863. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  3864. if firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
  3865. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  3866. }
  3867. }
  3868. } else if activeAnnotations?.count == 1 {
  3869. if pdfListView.activeAnnotation.isKind(of: CPDFMarkupAnnotation.self) {
  3870. menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
  3871. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3872. if(isShowPopUI){
  3873. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3874. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  3875. }
  3876. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3877. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  3878. } else if pdfListView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self) {
  3879. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3880. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3881. menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
  3882. menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
  3883. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3884. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  3885. menuStringArr.append(PDFViewMenuIdentifier_Redact_Default)
  3886. } else if listView.activeAnnotation.isKind(of: CPDFLinkAnnotation.self) {
  3887. let link = listView.activeAnnotation as? CPDFLinkAnnotation
  3888. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3889. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  3890. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3891. if link?.destination() != nil || ((link?.url()) != nil) {
  3892. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3893. menuStringArr.append(PDFViewMenuIdentifier_Normal_LinkReade)
  3894. }
  3895. if(isShowPopUI){
  3896. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3897. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  3898. }
  3899. } else if pdfListView.activeAnnotation.isKind(of: CPDFWidgetAnnotation.self) {
  3900. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3901. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  3902. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3903. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3904. if(isShowPopUI){
  3905. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  3906. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3907. }
  3908. menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
  3909. } else {
  3910. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3911. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  3912. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  3913. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3914. if pdfListView.activeAnnotation.isKind(of: CPDFTextAnnotation.self) ||
  3915. pdfListView.activeAnnotation.isKind(of: CPDFFreeTextAnnotation.self) {
  3916. } else {
  3917. menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
  3918. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3919. }
  3920. if(isShowPopUI){
  3921. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  3922. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3923. }
  3924. }
  3925. } else {
  3926. let currentSelection = pdfListView.currentSelection
  3927. if currentSelection != nil {
  3928. if currentSelection?.selectionType() == .text {
  3929. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  3930. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3931. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3932. if pdfListView.canPaste() {
  3933. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  3934. }
  3935. menuStringArr.append(PDFViewMenuIdentifier_Normal_Hight)
  3936. menuStringArr.append(PDFViewMenuIdentifier_Normal_Underline)
  3937. menuStringArr.append(PDFViewMenuIdentifier_Normal_StrikeOut)
  3938. menuStringArr.append(PDFViewMenuIdentifier_Normal_Squiggly)
  3939. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  3940. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  3941. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3942. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddOutLine)
  3943. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  3944. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3945. menuStringArr.append(PDFViewMenuIdentifier_Normal_TTS)
  3946. menuStringArr.append(PDFViewMenuIdentifier_Normal_SearchText)
  3947. } else if currentSelection?.selectionType() == .image {
  3948. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  3949. if pdfListView.canPaste() {
  3950. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  3951. }
  3952. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3953. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  3954. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3955. menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
  3956. menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
  3957. }
  3958. } else {
  3959. if pdfListView.toolMode == .CFormToolMode {
  3960. if pdfListView.canPaste() {
  3961. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  3962. }
  3963. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3964. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllForm)
  3965. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3966. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  3967. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowFormName)
  3968. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  3969. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3970. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  3971. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3972. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  3973. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3974. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  3975. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3976. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  3977. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3978. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  3979. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3980. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  3981. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3982. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  3983. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  3984. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  3985. } else if pdfListView.toolMode == .CRedactToolMode {
  3986. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
  3987. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3988. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  3989. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3990. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  3991. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3992. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  3993. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3994. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  3995. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3996. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  3997. menuStringArr.append(PDFViewMenuIdentifier_Space)
  3998. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  3999. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4000. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4001. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4002. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4003. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4004. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4005. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4006. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4007. } else {
  4008. if(listView.viewSplitMode != .disable) {
  4009. menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
  4010. menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
  4011. menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
  4012. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4013. } else {
  4014. menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
  4015. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4016. if pdfListView == listView {
  4017. if pdfListView.canPaste() {
  4018. menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
  4019. }
  4020. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
  4021. menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllAnnotation)
  4022. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4023. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowAnnotation)
  4024. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4025. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4026. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4027. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4028. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4029. }
  4030. }
  4031. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4032. if(listView.viewSplitMode != .disable) {
  4033. } else {
  4034. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  4035. }
  4036. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4037. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4038. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4039. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4040. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4041. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4042. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4043. menuStringArr.append(PDFViewMenuIdentifier_Normal_AutoScroll)
  4044. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4045. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4046. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4047. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4048. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4049. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4050. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4051. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4052. }
  4053. }
  4054. }
  4055. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  4056. groupListMenuGroup?.groupDelegate = self
  4057. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4058. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4059. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: pdfListView)
  4060. }
  4061. } else {
  4062. var menuStringArr: [String] = []
  4063. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4064. menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
  4065. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4066. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4067. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4068. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
  4069. menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
  4070. menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
  4071. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
  4072. groupListMenuGroup?.groupDelegate = self
  4073. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4074. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4075. groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: pdfListView)
  4076. }
  4077. }
  4078. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  4079. var windowPoint = listView.convert(point, from: page)
  4080. let view: NSView? = nil
  4081. windowPoint = listView.convert(windowPoint, to: view)
  4082. if self.view.window?.interactionMode == .presentation {
  4083. let menuStruct = clickPresentationMenu(point: point)
  4084. groupListMenuGroup?.groupDelegate = self
  4085. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4086. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4087. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: listView)
  4088. } else {
  4089. let isShowPopUI:Bool = false
  4090. var menuStringArr: [String] = []
  4091. let editingAreas = listView.km_EditingAreas()
  4092. let firstEditingArea = editingAreas.first
  4093. if editingAreas.count > 1 {
  4094. var isSameEditingArea = true
  4095. if(firstEditingArea?.isTextArea() == true) {
  4096. for i in 1..<(editingAreas.count) {
  4097. if !editingAreas[i].isTextArea() {
  4098. isSameEditingArea = false
  4099. break
  4100. }
  4101. }
  4102. } else if (firstEditingArea?.isImageArea() == true) {
  4103. for i in 1..<(editingAreas.count) {
  4104. if !editingAreas[i].isImageArea() {
  4105. isSameEditingArea = false
  4106. break
  4107. }
  4108. }
  4109. }
  4110. if(isSameEditingArea) {
  4111. if (firstEditingArea?.isTextArea() == true) {
  4112. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4113. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4114. if listView.isSupportPastMatchStyle() {
  4115. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4116. }
  4117. if listView.isSupportPast() {
  4118. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4119. }
  4120. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4121. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4122. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4123. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  4124. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  4125. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  4126. if(isShowPopUI){
  4127. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4128. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4129. }
  4130. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4131. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4132. } else if (firstEditingArea?.isImageArea() == true) {
  4133. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4134. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4135. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4136. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4137. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  4138. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  4139. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  4140. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  4141. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4142. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  4143. if(isShowPopUI){
  4144. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4145. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4146. }
  4147. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4148. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4149. }
  4150. } else {
  4151. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4152. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4153. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4154. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4155. menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
  4156. }
  4157. } else if editingAreas.count == 1 {
  4158. if firstEditingArea?.isTextArea() == true {
  4159. if !listView.isSelecteditAreaNotEdit() { //光标输入状态
  4160. if listView.isSupportPast() {
  4161. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4162. }
  4163. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4164. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4165. } else {
  4166. let editState = listView.editStatus()
  4167. if (editState == .editSelectText) {// 选择文本
  4168. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4169. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4170. if listView.isSupportPast() {
  4171. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4172. }
  4173. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4174. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4175. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4176. } else {
  4177. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4178. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4179. if listView.isSupportPastMatchStyle() {
  4180. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4181. }
  4182. if listView.isSupportPast() {
  4183. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4184. }
  4185. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4186. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4187. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4188. }
  4189. menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
  4190. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
  4191. menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
  4192. if(isShowPopUI){
  4193. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4194. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4195. }
  4196. }
  4197. } else if firstEditingArea?.isImageArea() == true {
  4198. menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
  4199. menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
  4200. menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
  4201. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4202. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
  4203. menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
  4204. menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
  4205. menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
  4206. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4207. menuStringArr.append(PDFViewMenuIdentifier_Edit_Crop)
  4208. menuStringArr.append(PDFViewMenuIdentifier_Edit_Replace)
  4209. menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
  4210. if(isShowPopUI){
  4211. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4212. menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
  4213. }
  4214. }
  4215. } else {
  4216. if(listView.isSupportPastMatchStyle()) {
  4217. menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
  4218. }
  4219. if(listView.isSupportPast()) {
  4220. menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
  4221. }
  4222. menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
  4223. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4224. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddText)
  4225. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddImage)
  4226. menuStringArr.append(PDFViewMenuIdentifier_Edit_AddLink)
  4227. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4228. menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
  4229. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4230. menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
  4231. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4232. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
  4233. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4234. menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
  4235. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4236. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
  4237. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4238. menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
  4239. menuStringArr.append(PDFViewMenuIdentifier_Space)
  4240. menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
  4241. menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
  4242. menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
  4243. }
  4244. let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: nil, listView: listView)
  4245. groupListMenuGroup?.groupDelegate = self
  4246. groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
  4247. groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
  4248. groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: listView)
  4249. }
  4250. return []
  4251. }
  4252. func pdfListViewMobileAnnotationBegan(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4253. toggleClosePopUIWindow()
  4254. }
  4255. func pdfListViewMobileAnnotationMove(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4256. toggleClosePopUIWindow()
  4257. }
  4258. func pdfListViewMobileAnnotationEnd(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
  4259. reloadPopUIWindow()
  4260. }
  4261. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  4262. if(annotationType == .unkown) {
  4263. toggleCloseRightSide()
  4264. }
  4265. }
  4266. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  4267. var pageIndexes = IndexSet()
  4268. pageIndexes.insert(Int(pdfPage.pageIndex()))
  4269. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  4270. }
  4271. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  4272. var pageIndexes = IndexSet()
  4273. pageIndexes.insert(Int(pdfPage.pageIndex()))
  4274. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  4275. }
  4276. func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  4277. if anotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
  4278. if let signatureWidgetAnnotation = anotation as? CPDFSignatureWidgetAnnotation {
  4279. let signature = signatureWidgetAnnotation.signature()
  4280. if ((signature) != nil) {
  4281. popUpSignatureWidgetState(signature!, listView)
  4282. } else {
  4283. let widget = CPDFSignatureWidgetAnnotation.init(PDFListViewNoteWith: listView.document)
  4284. widget.bounds = NSMakeRect(-1000, -1000, 545, 178);
  4285. anotation.page.addAnnotation(widget)
  4286. let configWindowVC = DSignatureConfigWindowController.init(windowNibName: "DSignatureConfigWindowController")
  4287. configWindowVC.viewType = .fileList;
  4288. configWindowVC.appearanceWidget = widget;
  4289. configWindowVC.isCreatDS = false
  4290. configWindowVC.complentionHandle = {[weak self] isSign, dic, config, isLock in
  4291. widget.page.removeAnnotation(widget)
  4292. if isSign {
  4293. if (dic.object(forKey: SAVEFILEPATH_KEY) != nil) {
  4294. let p12Path = dic.object(forKey: SAVEFILEPATH_KEY) as! String
  4295. let password = dic.object(forKey: PASSWORD_KEY)
  4296. if p12Path.count > 0 {
  4297. self?.writeSignatureToWidget(signatureWidgetAnnotation, p12Path, password as! String, config, isLock)
  4298. }
  4299. }
  4300. } else {
  4301. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  4302. self?.listView.remove(anotation)
  4303. }
  4304. }
  4305. }
  4306. configWindowVC.actionBlock = {[weak self] controller, type in
  4307. if (type == .cancel) {
  4308. NSApplication.shared.stopModal()
  4309. controller.window?.orderOut(nil)
  4310. controller.window?.close()
  4311. widget.page.removeAnnotation(widget)
  4312. if signatureWidgetAnnotation.isSignSignatureAdd() == true {
  4313. self?.listView.remove(anotation)
  4314. } else {
  4315. self?.listView.setNeedsDisplayAnnotationViewFor(anotation.page)
  4316. }
  4317. } else if (type == .confirm) {
  4318. NSApplication.shared.stopModal()
  4319. controller.window?.orderOut(nil)
  4320. controller.window?.close()
  4321. }
  4322. }
  4323. configWindowVC.window?.center()
  4324. NSApplication.shared.runModal(for: configWindowVC.window!)
  4325. }
  4326. }
  4327. } else if anotation.isKind(of: CPDFRedactAnnotation.self) {
  4328. if let redactAnnotation = anotation as? CPDFRedactAnnotation {
  4329. let properties = KMRedactPropertiesWindowController()
  4330. properties.readactAnnotation = redactAnnotation
  4331. self.km_beginSheet(windowC: properties)
  4332. properties.callback = { [weak self] annotation in
  4333. if let page = annotation?.page {
  4334. self?.listView.setNeedsDisplayAnnotationViewFor(page)
  4335. }
  4336. }
  4337. }
  4338. }
  4339. }
  4340. //MARK: -Crop
  4341. func pdfListViewChangedSelectionOrMagnification(_ pdfListView: CPDFListView!) {
  4342. reloadPopUIWindow()
  4343. }
  4344. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  4345. if (!self.listView.isEqual(to: pdfListView)) {
  4346. return
  4347. }
  4348. if (self.listView.toolMode != .CSelectToolMode) {
  4349. return
  4350. }
  4351. reloadPopUIWindow()
  4352. }
  4353. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  4354. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  4355. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  4356. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  4357. } else {
  4358. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  4359. }
  4360. } else {
  4361. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  4362. }
  4363. }
  4364. func pdfListViewHaveDocumentAttribute() -> Bool {
  4365. if(!self.listView.document.allowsCopying) {
  4366. self.removeOwnerPassword()
  4367. return false
  4368. }
  4369. return true
  4370. }
  4371. func pdfListViewAnnotationMeasureInfoChange(_ pdfListView: CPDFListView!, with annotation: CPDFAnnotation!) {
  4372. guard let data = annotation else {
  4373. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  4374. distanceMeasureInfoWindowController?.clearData()
  4375. }
  4376. return
  4377. }
  4378. if let lineAnnotation = annotation as? CPDFLineAnnotation {
  4379. handleLineAnnotation(lineAnnotation)
  4380. } else if let polylineAnnotation = annotation as? CPDFPolylineAnnotation {
  4381. handlePolylineAnnotation(polylineAnnotation)
  4382. } else if let polygonAnnotation = annotation as? CPDFPolygonAnnotation {
  4383. handlePolygonAnnotation(polygonAnnotation)
  4384. }
  4385. }
  4386. func pdfListViewMeasureCancel(_ pdfListView: CPDFListView!) {
  4387. cancelMeasureType()
  4388. }
  4389. private func handleLineAnnotation(_ annotation: CPDFLineAnnotation) {
  4390. if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  4391. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4392. distanceMeasureInfoWindowController?.showWindow(self)
  4393. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  4394. areaMeasureInfoWindowController?.hideFloatingWindow()
  4395. distanceMeasureInfoWindowController?.showWindow(self)
  4396. } else if distanceMeasureInfoWindowController?.window?.isVisible == false {
  4397. distanceMeasureInfoWindowController?.showWindow(self)
  4398. }
  4399. let measureInfo = annotation.measureInfo
  4400. let startPoint = annotation.startPoint
  4401. let endPoint = annotation.endPoint
  4402. let angle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) * (180.0 / .pi)
  4403. distanceMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  4404. distanceMeasureInfoWindowController?.xLabel.stringValue = String(format: "%.0f", abs(endPoint.x - startPoint.x))
  4405. distanceMeasureInfoWindowController?.yLabel.stringValue = String(format: "%.0f", abs(endPoint.y - startPoint.y))
  4406. distanceMeasureInfoWindowController?.reloadData(with: measureInfo!)
  4407. }
  4408. private func handlePolylineAnnotation(_ annotation: CPDFPolylineAnnotation) {
  4409. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  4410. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4411. perimeterMeasureInfoWindowController?.showWindow(self)
  4412. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  4413. areaMeasureInfoWindowController?.hideFloatingWindow()
  4414. perimeterMeasureInfoWindowController?.showWindow(self)
  4415. } else if perimeterMeasureInfoWindowController?.window?.isVisible == false {
  4416. perimeterMeasureInfoWindowController?.showWindow(self)
  4417. }
  4418. let measureInfo = annotation.measureInfo
  4419. let savePoints = annotation.savePoints()
  4420. var angle: CGFloat = 0
  4421. if savePoints.count >= 3 {
  4422. let count = savePoints.count
  4423. let startPoint = savePoints[count - 3].pointValue
  4424. let midPoint = savePoints[count - 2].pointValue
  4425. let endPoint = savePoints.last!.pointValue
  4426. angle = angleBetweenPoints(startPoint, midPoint, endPoint)
  4427. }
  4428. angle = 180 - angle
  4429. perimeterMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  4430. perimeterMeasureInfoWindowController?.reloadData(with: measureInfo!)
  4431. }
  4432. private func handlePolygonAnnotation(_ annotation: CPDFPolygonAnnotation) {
  4433. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  4434. distanceMeasureInfoWindowController?.hideFloatingWindow()
  4435. areaMeasureInfoWindowController?.showWindow(self)
  4436. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  4437. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  4438. areaMeasureInfoWindowController?.showWindow(self)
  4439. } else if areaMeasureInfoWindowController?.window?.isVisible == false {
  4440. areaMeasureInfoWindowController?.showWindow(self)
  4441. }
  4442. let measureInfo = annotation.measureInfo
  4443. let savePoints = annotation.savePoints
  4444. var angle: CGFloat = 0
  4445. if savePoints.count >= 3 {
  4446. let count = savePoints.count
  4447. let startPoint = (savePoints[count - 3] as AnyObject).pointValue
  4448. let midPoint = (savePoints[count - 2] as AnyObject).pointValue
  4449. let endPoint = (savePoints.lastObject as AnyObject).pointValue
  4450. angle = angleBetweenPoints(startPoint!, midPoint!, endPoint!)
  4451. }
  4452. angle = 180 - angle
  4453. areaMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  4454. areaMeasureInfoWindowController?.reloadData(measureInfo!)
  4455. }
  4456. private func angleBetweenPoints(_ startPoint: CGPoint, _ midPoint: CGPoint, _ endPoint: CGPoint) -> CGFloat {
  4457. let vector1 = CGPoint(x: midPoint.x - startPoint.x, y: midPoint.y - startPoint.y)
  4458. let vector2 = CGPoint(x: endPoint.x - midPoint.x, y: endPoint.y - midPoint.y)
  4459. let dotProduct = vector1.x * vector2.x + vector1.y * vector2.y
  4460. let magnitude1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
  4461. let magnitude2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
  4462. return acos(dotProduct / (magnitude1 * magnitude2)) * (180.0 / .pi)
  4463. }
  4464. @objc func pdfUpdatedFinish() {
  4465. splitPDFController?.inPDFFirst = false
  4466. splitPDFController?.outPDFFirst = false
  4467. }
  4468. //MARK: - Notification
  4469. @objc private func pdfViewScrollViewDidScroll(_ noti: Notification) {
  4470. reloadPopUIWindow()
  4471. }
  4472. func pageCountChangedNotification(_ sender: Notification) {
  4473. guard let document = sender.object as? CPDFDocument else {
  4474. return
  4475. }
  4476. botaViewController?.pageCountChangedAction(document: document)
  4477. }
  4478. func annotationsAttributeHasChange(_ sender: Notification) {
  4479. guard let dict = sender.object as? [String : Any] else {
  4480. return
  4481. }
  4482. if let anno = dict["object"] as? CPDFAnnotation {
  4483. let value = dict["keyPath"] as? String ?? ""
  4484. let didEnd = dict["didEnd"] as? Bool ?? false
  4485. if didEnd {
  4486. if value == CPDFAnnotationBoundsKey {
  4487. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  4488. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  4489. }
  4490. }
  4491. if anno.km_isMeasure() && anno.contents == nil {
  4492. anno.contents = anno.string() ?? ""
  4493. }
  4494. var pageIndexes = IndexSet()
  4495. pageIndexes.insert(Int(anno.page.pageIndex()))
  4496. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  4497. reloadPopUIWindow()
  4498. } else {
  4499. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  4500. var pageIndexes = IndexSet()
  4501. pageIndexes.insert(Int(anno.page.pageIndex()))
  4502. botaViewController?.thumnailViewController?.reloadDataWithIndexs(pageIndexs: pageIndexes)
  4503. reloadPopUIWindow()
  4504. }
  4505. }
  4506. }
  4507. }
  4508. @objc fileprivate func signatureStateChangeNoti(_ sender: Notification) {
  4509. guard let objecListView = sender.object as? CPDFListView else {
  4510. return
  4511. }
  4512. if listView == objecListView {
  4513. reloadDigitalSigns()
  4514. alertTipViewController.reloadDigitalAlertUI()
  4515. alertTipViewController.reloadAlertUIFrame()
  4516. let signatureWidget = listView.editAnnotation
  4517. if let signatureWidgetAnnotation = signatureWidget as? CPDFSignatureWidgetAnnotation {
  4518. let signature = signatureWidgetAnnotation.signature()
  4519. if signature == nil {
  4520. return
  4521. }
  4522. signaturestateVC.signature = signature
  4523. signaturestateVC.reloadData()
  4524. }
  4525. }
  4526. }
  4527. //MARK: - Mouse Event
  4528. override func mouseMoved(with event: NSEvent) {
  4529. self.view.window?.mouseMoved(with: event)
  4530. }
  4531. }
  4532. //MARK: - KMNThumbnailBaseViewDelegate
  4533. extension KMMainViewController: KMNThumbnailBaseViewDelegate {
  4534. func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int) {
  4535. exitPageEditMode()
  4536. if listView.currentPageIndex != currentIndex {
  4537. listView.go(toPageIndex: currentIndex, animated: true)
  4538. }
  4539. viewManager.isPageEditMode = false
  4540. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_PageEdit_Identifier)
  4541. }
  4542. func insertPDFThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, pdfDocment: CPDFDocument?) {
  4543. if(pdfDocment != nil) {
  4544. insertDocuments.insert(pdfDocment!)
  4545. }
  4546. }
  4547. func changeIndexPathsThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, selectionIndexPaths: Set<IndexPath>, selectionStrings: String) {
  4548. toolbarManager.page_pageInfo_Property.text = selectionStrings
  4549. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  4550. toolbarManager.page_pageInfo_Property.creatable = true
  4551. }
  4552. pdfToolbarController?.refreshSecondToolbarItemsState()
  4553. }
  4554. }
  4555. //MARK: - KMNLeftSideViewControllerDelegate
  4556. extension KMMainViewController: KMNLeftSideViewControllerDelegate {
  4557. func enterPageEditLeftSideViewController(leftSideViewController: KMNLeftSideViewController) {
  4558. if viewManager.isPageEditMode == false {
  4559. viewManager.isPageEditMode = true
  4560. if(pdfToolbarController != nil) {
  4561. kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_PageEdit_Identifier)
  4562. pdfToolbarController?.reloadSecondToolbar()
  4563. }
  4564. }
  4565. }
  4566. func changeSelectePageLeftSideViewController(leftSideViewController: KMNLeftSideViewController, pageIndex: Int) {
  4567. if(listView.currentPageIndex != pageIndex) {
  4568. listView.go(toPageIndex: pageIndex, animated: true)
  4569. }
  4570. }
  4571. func addBookmarkForLeftC(controller: KMNLeftSideViewController, bookmark: CPDFBookmark?, info: [String : Any]?) {
  4572. if let result = info?["result"] as? Bool {
  4573. if result == false {
  4574. if let targetV = listView.superview {
  4575. _ = 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))
  4576. }
  4577. }
  4578. }
  4579. }
  4580. func switchSearchPopWindow(controller: KMNLeftSideViewController) {
  4581. if(viewManager.pdfSideBarType == .search) {
  4582. closeLeftPane()
  4583. }
  4584. let handdler = controller.searchViewC.handdler
  4585. showSearchPopWindow(type: handdler.type, keyborad: handdler.searchKey, replaceText: handdler.replaceKey, results: handdler.searchResults)
  4586. }
  4587. func searchTypeDidChange(controller: KMNLeftSideViewController) {
  4588. let handdler = controller.searchViewC.handdler
  4589. if handdler.type == .replace {
  4590. viewManager.toolMode = .Edit
  4591. updatePDFViewAnnotationMode()
  4592. }
  4593. }
  4594. }
  4595. //MARK: - ComponentGroupDelegate
  4596. extension KMMainViewController: ComponentGroupDelegate {
  4597. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  4598. if menuItemProperty?.identifier == PDFViewMenuIdentifier_PageNext {
  4599. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4600. if objectListView.canGoToNextPage() {
  4601. objectListView.goToNextPage(nil)
  4602. }
  4603. }
  4604. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PagePrevious) {
  4605. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4606. if objectListView.canGoToPreviousPage() {
  4607. objectListView.goToPreviousPage(nil)
  4608. }
  4609. }
  4610. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageFirst) {
  4611. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4612. if objectListView.canGoToFirstPage() {
  4613. objectListView.goToFirstPage(nil)
  4614. }
  4615. }
  4616. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageLast) {
  4617. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4618. if objectListView.canGoToLastPage() {
  4619. objectListView.goToLastPage(nil)
  4620. }
  4621. }
  4622. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_LaserPoint) {
  4623. listView.exitPresentationDrawMode()
  4624. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Brush) {
  4625. listView.enterPresentationDrawMode()
  4626. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Exit) {
  4627. self.exitFullScreen()
  4628. } else if menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIRewrite {
  4629. viewManager.pdfSideBarType = .aiTools
  4630. sideBarController?.reloadData()
  4631. if let sideVC = sideBarController {
  4632. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  4633. }
  4634. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIProofread) {
  4635. viewManager.pdfSideBarType = .aiTools
  4636. sideBarController?.reloadData()
  4637. if let sideVC = sideBarController {
  4638. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  4639. }
  4640. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AITranslate) {
  4641. viewManager.pdfSideBarType = .aiTools
  4642. sideBarController?.reloadData()
  4643. if let sideVC = sideBarController {
  4644. kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
  4645. }
  4646. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Past) {
  4647. listView.copy(nil)
  4648. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllText) {
  4649. listView.selectAll(nil)
  4650. } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddBook) {
  4651. menuItemBookMarkClick_add(sender: nil)
  4652. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TextTool) {
  4653. listView.toolMode = .CTextToolMode
  4654. listView.annotationType = .unkown
  4655. viewManager.viewToolsType = .Select
  4656. pdfToolbarController?.reloadToolsView()
  4657. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MoveTool) {
  4658. listView.toolMode = .CMoveToolMode
  4659. listView.annotationType = .unkown
  4660. viewManager.viewToolsType = .Scroll
  4661. pdfToolbarController?.reloadToolsView()
  4662. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectTool) {
  4663. listView.toolMode = .CSelectToolMode
  4664. listView.annotationType = .unkown
  4665. viewManager.viewToolsType = .Content_Selection
  4666. pdfToolbarController?.reloadToolsView()
  4667. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MagnifyTool) {
  4668. listView.toolMode = .CMagnifyToolMode
  4669. listView.annotationType = .unkown
  4670. viewManager.viewToolsType = .Magnify
  4671. pdfToolbarController?.reloadToolsView()
  4672. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectZoomTool) {
  4673. listView.toolMode = .CSelectZoomToolMode
  4674. listView.annotationType = .unkown
  4675. viewManager.viewToolsType = .AreaZoom
  4676. pdfToolbarController?.reloadToolsView()
  4677. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Single) {
  4678. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4679. objectListView.menuItemClick_SinglePage(nil)
  4680. }
  4681. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SingleContinuous) {
  4682. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4683. objectListView.menuItemClick_SinglePagesContinuous(nil)
  4684. }
  4685. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPages) {
  4686. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4687. objectListView.menuItemClick_TwoPages(nil)
  4688. }
  4689. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPagesContinuous) {
  4690. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4691. objectListView.menuItemClick_TwoPagesContinuous(nil)
  4692. }
  4693. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BookMode) {
  4694. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4695. objectListView.menuItemClick_BookMode(nil)
  4696. }
  4697. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ReadMode) {
  4698. openPDFReadMode()
  4699. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleWidth) {
  4700. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4701. objectListView.autoScales = true
  4702. }
  4703. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScalePage) {
  4704. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4705. let pageHeight = objectListView.currentPage()!.size.height
  4706. let pdfviewHeight = objectListView.bounds.size.height
  4707. objectListView.scaleFactor = pdfviewHeight/pageHeight
  4708. objectListView.autoScales = false
  4709. }
  4710. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleOrg) {
  4711. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4712. if objectListView.scaleFactor != 1.0 {
  4713. objectListView.scaleFactor = 1.0
  4714. objectListView.autoScales = false
  4715. }
  4716. }
  4717. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomIn) {
  4718. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4719. var scale = objectListView.scaleFactor
  4720. switch scale {
  4721. case 0...0.25:
  4722. scale += 0.25
  4723. case 0.25...3:
  4724. scale += 0.25
  4725. case 3.1...10:
  4726. scale += 0.4
  4727. case 10.1...100:
  4728. scale += 1
  4729. default:
  4730. scale += 1
  4731. }
  4732. objectListView.scaleFactor = scale
  4733. }
  4734. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomOut) {
  4735. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4736. var scale = objectListView.scaleFactor
  4737. switch scale {
  4738. case 0...0.25:
  4739. scale = 0
  4740. case 0.25...3:
  4741. scale -= 0.25
  4742. case 3.1...10:
  4743. scale -= 0.4
  4744. case 10.1...100:
  4745. scale -= 1
  4746. default:
  4747. scale -= 1
  4748. }
  4749. objectListView.scaleFactor = scale
  4750. }
  4751. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateLeft) {
  4752. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  4753. let objectListView = dic["Object"] as? CPDFListView
  4754. let theEvent = dic["theEvent"] as? NSEvent
  4755. if(objectListView != nil && theEvent != nil) {
  4756. var pagePoint = CGPoint.zero
  4757. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  4758. rotateLeft(page: page, listView: objectListView)
  4759. }
  4760. }
  4761. }
  4762. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateRight) {
  4763. if let dic = menuItemProperty?.representedObject as? NSDictionary {
  4764. let objectListView = dic["Object"] as? CPDFListView
  4765. let theEvent = dic["theEvent"] as? NSEvent
  4766. if(objectListView != nil && theEvent != nil) {
  4767. var pagePoint = CGPoint.zero
  4768. if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
  4769. rotateRight(page: page, listView: objectListView)
  4770. }
  4771. }
  4772. }
  4773. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_EnterPageNum) {
  4774. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageBack) {
  4775. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4776. if(objectListView.canGoBack() == true) {
  4777. objectListView.goBack(nil)
  4778. }
  4779. }
  4780. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageForward) {
  4781. if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
  4782. if(objectListView.canGoForward() == true) {
  4783. objectListView.goForward(nil)
  4784. }
  4785. }
  4786. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AutoScroll) {
  4787. toggleAutoFlow(nil)
  4788. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightForm) {
  4789. highlightFormFiled(nil)
  4790. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightLink) {
  4791. highlightLinks(nil)
  4792. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RestForm) {
  4793. resetForm(nil)
  4794. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Search) {
  4795. if botaViewController != nil {
  4796. switchSearchPopWindow(controller: botaViewController!)
  4797. }
  4798. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Print) {
  4799. menuItemAction_print(nil)
  4800. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Properties) {
  4801. menuItemAction_property(nil)
  4802. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Copy) {
  4803. if(listView.isEditing() == true) {
  4804. listView.copyEditAreaAction()
  4805. } else {
  4806. listView.copy(nil)
  4807. }
  4808. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Hight) {
  4809. if let currentSelect = listView.currentSelection {
  4810. if(currentSelect.selectionType() == .text) {
  4811. listView.addAnnotation(with: .highlight, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  4812. listView.currentSelection = nil;
  4813. }
  4814. }
  4815. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Underline) {
  4816. if let currentSelect = listView.currentSelection {
  4817. if(currentSelect.selectionType() == .text) {
  4818. listView.addAnnotation(with: .underline, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  4819. listView.currentSelection = nil;
  4820. }
  4821. }
  4822. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Squiggly) {
  4823. if let currentSelect = listView.currentSelection {
  4824. if(currentSelect.selectionType() == .text) {
  4825. listView.addAnnotation(with: .squiggly, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  4826. listView.currentSelection = nil;
  4827. }
  4828. }
  4829. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_StrikeOut) {
  4830. if let currentSelect = listView.currentSelection {
  4831. if(currentSelect.selectionType() == .text) {
  4832. listView.addAnnotation(with: .strikeOut, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  4833. listView.currentSelection = nil;
  4834. }
  4835. }
  4836. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Square) {
  4837. if let currentSelect = listView.currentSelection {
  4838. listView.addAnnotation(with: .square, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
  4839. listView.currentSelection = nil;
  4840. }
  4841. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Circle) {
  4842. if let currentSelect = listView.currentSelection {
  4843. listView.addAnnotation(with: .circle, selection: currentSelect, page: currentSelect.page, bounds: listView.currentSelection.bounds)
  4844. listView.currentSelection = nil;
  4845. }
  4846. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddOutLine) {
  4847. addOutLineItemAction()
  4848. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TTS) {
  4849. startSpeaking(nil)
  4850. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SearchText) {
  4851. searchBaiduAction()
  4852. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllForm) {
  4853. selectAllFormAnnotation()
  4854. listView.setNeedsDisplayForVisiblePages()
  4855. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowFormName) {
  4856. listView.showFormFieldName = true
  4857. listView.setNeedsDisplayForVisiblePages()
  4858. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllAnnotation) {
  4859. selectAllNomerAnnotation()
  4860. listView.setNeedsDisplayForVisiblePages()
  4861. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowAnnotation) {
  4862. let isHiden = listView.hideNotes
  4863. listView.hideNotes = !isHiden
  4864. listView.setNeedsDisplayForVisiblePages()
  4865. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_CopyText) {
  4866. var copyText:String = ""
  4867. let annotations = listView.activeAnnotations
  4868. for i in 0 ..< (annotations?.count ?? 0){
  4869. if let an = annotations?[i] as? CPDFMarkupAnnotation {
  4870. let markupContent = an.markupContent()
  4871. if markupContent.isEmpty == false {
  4872. if copyText.isEmpty == true {
  4873. copyText = markupContent
  4874. } else {
  4875. copyText = "\n" + markupContent
  4876. }
  4877. }
  4878. }
  4879. }
  4880. let pboard = NSPasteboard.general
  4881. if copyText.isEmpty == false {
  4882. pboard.clearContents()
  4883. pboard.writeObjects([copyText as NSPasteboardWriting])
  4884. }
  4885. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Cut) {
  4886. if(listView.isEditing() == true) {
  4887. listView.cutEditAreaAction()
  4888. } else {
  4889. listView.cut(nil)
  4890. }
  4891. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Delete) {
  4892. if(listView.isEditing() == true) {
  4893. listView.remove(with: listView.km_EditingAreas())
  4894. } else {
  4895. listView.delete(nil)
  4896. }
  4897. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowPopUI) {
  4898. reloadPopUIWindow()
  4899. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_LinkReade) {
  4900. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortFirstAnnotation) {
  4901. listView.menuItemClick_BringFront(nil)
  4902. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortTopAnnotation) {
  4903. listView.menuItemClick_BringForward(nil)
  4904. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortBottomAnnotation) {
  4905. listView.menuItemClick_SendBackward(nil)
  4906. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortLastAnnotation) {
  4907. listView.menuItemClick_SendBack(nil)
  4908. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Content) {
  4909. if let activeAnnotation = listView.activeAnnotation {
  4910. listView.edit(activeAnnotation)
  4911. }
  4912. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Apply) {
  4913. redactApplyAction()
  4914. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Multipage) {
  4915. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
  4916. redactMultipageAction(redactAnnotation: redactAnnotation)
  4917. }
  4918. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Default) {
  4919. if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
  4920. setPropertiesDefault(annotation: redactAnnotation)
  4921. }
  4922. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewSingleMode) {
  4923. listView.viewSplitMode = .disable
  4924. reloadPDFSplitInfo()
  4925. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewVerticalMode) {
  4926. listView.viewSplitMode = .vertical
  4927. reloadPDFSplitInfo()
  4928. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewHorizontalMode) {
  4929. listView.viewSplitMode = .horizontal
  4930. reloadPDFSplitInfo()
  4931. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_Sync) {
  4932. viewManager.splitSyncScroll = !viewManager.splitSyncScroll
  4933. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ShowBar) {
  4934. viewManager.splitShowBottomBar = !viewManager.splitShowBottomBar
  4935. splitPDFController?.refreshToolbarState()
  4936. reloadPDFPageNumberToolbar()
  4937. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_LeftAlight) {
  4938. if(listView.isEditing()) {
  4939. listView.changeEditingAreas(.left)
  4940. } else {
  4941. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
  4942. }
  4943. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_VerticallyAlight) {
  4944. if(listView.isEditing()) {
  4945. listView.changeEditingAreas(.vertical)
  4946. } else {
  4947. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
  4948. }
  4949. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RightAlight) {
  4950. if(listView.isEditing()) {
  4951. listView.changeEditingAreas(.right)
  4952. } else {
  4953. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
  4954. }
  4955. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TopAlight) {
  4956. if(listView.isEditing()) {
  4957. listView.changeEditingAreas(.top)
  4958. } else {
  4959. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
  4960. }
  4961. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HorizontallyAlight) {
  4962. if(listView.isEditing()) {
  4963. listView.changeEditingAreas(.horizontally)
  4964. } else {
  4965. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
  4966. }
  4967. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BottomAlight) {
  4968. if(listView.isEditing()) {
  4969. listView.changeEditingAreas(.bottom)
  4970. } else {
  4971. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
  4972. }
  4973. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeHorizontally) {
  4974. if(listView.isEditing()) {
  4975. listView.changeEditingAreas(.disHorizontally)
  4976. } else {
  4977. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
  4978. }
  4979. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeVertically) {
  4980. if(listView.isEditing()) {
  4981. listView.changeEditingAreas(.disVertical)
  4982. } else {
  4983. listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
  4984. }
  4985. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportJPG) {
  4986. if(listView.isEditing() == true) {
  4987. listView.exportEditingImageAreasAction(format: "jpg")
  4988. } else {
  4989. if let currentSelection = listView.currentSelection {
  4990. if(currentSelection.selectionType() == .image) {
  4991. listView.exprotSelection(currentSelection, type: 1)
  4992. }
  4993. }
  4994. }
  4995. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPNG) {
  4996. if(listView.isEditing() == true) {
  4997. listView.exportEditingImageAreasAction(format: "png")
  4998. } else {
  4999. if let currentSelection = listView.currentSelection {
  5000. if(currentSelection.selectionType() == .image) {
  5001. listView.exprotSelection(currentSelection, type: 0)
  5002. }
  5003. }
  5004. }
  5005. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPDF) {
  5006. if(listView.isEditing() == true) {
  5007. listView.exportEditingImageAreasAction(format: "pdf")
  5008. } else {
  5009. if let currentSelection = listView.currentSelection {
  5010. if(currentSelection.selectionType() == .image) {
  5011. listView.exprotSelection(currentSelection, type: 2)
  5012. }
  5013. }
  5014. }
  5015. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Paste) {
  5016. listView.pasteEditAreaMatchStyleAction()
  5017. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_NoStylePaste) {
  5018. listView.pasteEditAreaAction()
  5019. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_SelectAll) {
  5020. listView.selectAllAction(with: listView.km_EditingAreas().first)
  5021. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddLink) {
  5022. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_link_Identifier)
  5023. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddText) {
  5024. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_text_Identifier)
  5025. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddImage) {
  5026. pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_image_Identifier)
  5027. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontBold) {
  5028. listView.setEditingTextarea_Bold()
  5029. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontItalic) {
  5030. listView.setEditingTextarea_Italic()
  5031. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontUnderline) {
  5032. listView.setEditingTextarea_Under()
  5033. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontStrikeout) {
  5034. listView.setEditingTextarea_Strikeout()
  5035. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomIn) {
  5036. listView.zoomInEditTextFontSize()
  5037. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomOut) {
  5038. listView.zoomInEditTextFontSize()
  5039. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontColor) {
  5040. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH1Name) {
  5041. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH2Name) {
  5042. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH3Name) {
  5043. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB1Name) {
  5044. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB2Name) {
  5045. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB3Name) {
  5046. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontLeftAlight) {
  5047. listView.setEditingTextarea_Alignment(align:.left)
  5048. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontCenterAlight) {
  5049. listView.setEditingTextarea_Alignment(align:.center)
  5050. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontRightAlight) {
  5051. listView.setEditingTextarea_Alignment(align:.right)
  5052. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontJustAlight) {
  5053. listView.setEditingTextarea_Alignment(align:.justified)
  5054. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateLeft) {
  5055. listView.rotateEditingAreas(90)
  5056. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateRight) {
  5057. listView.rotateEditingAreas(-90)
  5058. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_HorizontalMirror) {
  5059. listView.reverseXAction()
  5060. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_VerticalMirror) {
  5061. listView.reverseYAction()
  5062. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Crop) {
  5063. listView.cropAction()
  5064. } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Replace) {
  5065. listView.replaceImageEdit()
  5066. }
  5067. }
  5068. func componentGroupDidDismiss(group: ComponentGroup?) {
  5069. }
  5070. }
  5071. //MARK: -
  5072. //MARK: -
  5073. //MARK: -
  5074. //MARK: - 旧代码,需要用到的内容需要拖出来,写好注释
  5075. extension KMMainViewController {
  5076. internal func removeNotifications() {
  5077. NotificationCenter.default.removeObserver(self)
  5078. }
  5079. func removeAllAnnotations() {
  5080. let alert = NSAlert()
  5081. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  5082. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  5083. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  5084. if (alert.runModal() != .alertFirstButtonReturn) {
  5085. return
  5086. }
  5087. DispatchQueue.main.async {
  5088. self.removeAllAnnotationsStore.store(t: self.listView)
  5089. }
  5090. }
  5091. //MARK: - AI
  5092. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  5093. if (self.document != nil) {
  5094. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  5095. } else {
  5096. AIChatInfoManager.defaultManager.currentFilePath = ""
  5097. }
  5098. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  5099. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  5100. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  5101. let documentArray = NSDocumentController.shared.documents
  5102. var didFileEdit: Bool = false
  5103. var curDoc: KMMainDocument!
  5104. for document in documentArray {
  5105. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  5106. didFileEdit = document.isDocumentEdited
  5107. curDoc = document as! KMMainDocument
  5108. break
  5109. }
  5110. }
  5111. if didFileEdit {
  5112. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  5113. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  5114. do {
  5115. try FileManager.default.removeItem(at: tempFileURL)
  5116. } catch {
  5117. }
  5118. }
  5119. if curDoc != nil {
  5120. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  5121. }
  5122. }
  5123. windowVC.window?.becomeMain()
  5124. }
  5125. }
  5126. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  5127. } else {
  5128. var windowRect = windowVC.window?.frame
  5129. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  5130. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  5131. windowVC.window?.setFrame(windowRect!, display: true)
  5132. windowVC.didSetOriginFrame = true
  5133. }
  5134. windowVC.eventLabel = "AITools_Tbr"
  5135. windowVC.showWindow(nil)
  5136. if (aiConfigType != .none) {
  5137. windowVC.eventLabel = "AITools_Start"
  5138. if self.listView.currentSelection?.string()?.isEmpty == false {
  5139. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  5140. }
  5141. windowVC.chooseAIFunctionWithType(aiConfigType)
  5142. }
  5143. }
  5144. @objc func aiTipIconViewShowStateChangeNoti() {
  5145. }
  5146. //MARK: - 引导
  5147. func loadFunctionGuide() -> Void {
  5148. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  5149. if self.view.window != nil {
  5150. self.loadOpenFileFunctionGuide(.openFileNormal)
  5151. }
  5152. }
  5153. }
  5154. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  5155. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  5156. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5157. guard let guideWC = self.guideInfoWindowController else { return }
  5158. guideWC.type = .openFileNormal
  5159. // guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  5160. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5161. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  5162. }
  5163. guideWC.finishHandle = { [weak self] windowVC, type in
  5164. if type == .windowNewFinish ||
  5165. type == . windowDigitalFinish {
  5166. self?.checkFirstTrialController()
  5167. }
  5168. }
  5169. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  5170. self?.checkFirstTrialController()
  5171. }
  5172. var rect = self.view.window!.frame
  5173. rect.size.height -= 20
  5174. guideWC.window?.setFrame(rect, display: false)
  5175. guideWC.window?.minSize = rect.size
  5176. guideWC.window?.maxSize = rect.size
  5177. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  5178. guideWC.show()
  5179. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  5180. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5181. guard let guideWC = self.guideInfoWindowController else { return }
  5182. guideWC.type = .digitalSignGuide
  5183. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5184. guideWC.finishHandle = { [weak self] windowVC, type in
  5185. self?.checkFirstTrialController()
  5186. }
  5187. var rect = self.view.window!.frame
  5188. rect.size.height -= 20
  5189. guideWC.window?.setFrame(rect, display: false)
  5190. guideWC.window?.minSize = rect.size
  5191. guideWC.window?.maxSize = rect.size
  5192. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  5193. guideWC.show()
  5194. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  5195. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  5196. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5197. guard let guideWC = self.guideInfoWindowController else { return }
  5198. guideWC.type = .pdfCompareGuide
  5199. guard let win = self.view.window else {
  5200. return
  5201. }
  5202. guideWC.finishHandle = { [weak self] winC, type in
  5203. if type == .windowNewFinish {
  5204. DispatchQueue.main.async {
  5205. self?.loadOpenFileFunctionGuide(.measureGuide)
  5206. }
  5207. return
  5208. }
  5209. }
  5210. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5211. var rect = self.view.window!.frame
  5212. rect.size.height -= 20
  5213. guideWC.window?.setFrame(rect, display: false)
  5214. guideWC.window?.minSize = rect.size
  5215. guideWC.window?.maxSize = rect.size
  5216. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  5217. guideWC.show()
  5218. }
  5219. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  5220. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  5221. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5222. guard let guideWC = self.guideInfoWindowController else { return }
  5223. guard let _ = self.view.window else {
  5224. return
  5225. }
  5226. guideWC.type = .measureGuide
  5227. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5228. var rect = self.view.window?.frame ?? .zero
  5229. rect.size.height -= 20
  5230. guideWC.window?.setFrame(rect, display: false)
  5231. guideWC.window?.minSize = rect.size
  5232. guideWC.window?.maxSize = rect.size
  5233. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  5234. guideWC.show()
  5235. }
  5236. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  5237. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  5238. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  5239. guard let guideWC = self.guideInfoWindowController else { return }
  5240. guideWC.type = .convertGuide
  5241. guard let win = self.view.window else {
  5242. return
  5243. }
  5244. guideWC.purchaseHandle = { [weak self] windowVC in
  5245. #if VERSION_DMG
  5246. if IAPProductsManager.default().isAvailableAllFunction() {
  5247. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  5248. //Convert:
  5249. self?.showAllConvertWindow(convertT: .Word)
  5250. } else {
  5251. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  5252. limitWC.continueBlock = { windowController in
  5253. }
  5254. limitWC.window?.center()
  5255. limitWC.showWindow(nil)
  5256. }
  5257. } else {
  5258. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  5259. }
  5260. #else
  5261. if IAPProductsManager.default().isAvailableAllFunction() {
  5262. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  5263. //Convert:
  5264. } else {
  5265. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  5266. vc.showWindow(nil)
  5267. }
  5268. } else {
  5269. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  5270. }
  5271. #endif
  5272. }
  5273. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  5274. var rect = self.view.window?.frame ?? .zero
  5275. rect.size.height -= 20
  5276. guideWC.window?.setFrame(rect, display: false)
  5277. guideWC.window?.minSize = rect.size
  5278. guideWC.window?.maxSize = rect.size
  5279. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  5280. guideWC.show()
  5281. }
  5282. } else {
  5283. }
  5284. }
  5285. func checkFirstTrialController() -> Void {
  5286. #if VERSION_DMG
  5287. //打开文档后引导相关
  5288. if VerificationManager.default().status == .none {
  5289. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  5290. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  5291. if lastVersion.isEmpty || lastVersion != appVersion {
  5292. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  5293. UserDefaults.standard.synchronize()
  5294. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  5295. }
  5296. }
  5297. #endif
  5298. }
  5299. // MARK: - Private Methods
  5300. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  5301. let url = URL(fileURLWithPath: filePath)
  5302. guard let document = PDFDocument(url: url) else {
  5303. return false
  5304. }
  5305. let pageCount = document.pageCount
  5306. return pageCount > 30
  5307. }
  5308. // MARK: - Redact 【标记密文】
  5309. func redactApplyAction() {
  5310. let returnCode = KMAlertTool.runModelForMainThread_r(message: "", informative: KMLocalizedString("This will permanently remove the redacted information from this document. Once you save this document, you won’t be able to retrieve the redacted information."), buttons: [KMLocalizedString("Apply"), KMLocalizedString("Cancel")])
  5311. if returnCode == .alertFirstButtonReturn {
  5312. DispatchQueue.main.async {
  5313. self.saveAsPath()
  5314. }
  5315. }
  5316. }
  5317. func redactMultipageAction(redactAnnotation:CPDFRedactAnnotation) {
  5318. let pagesWindowController = KMRedactSelectPagesWindowController(document: listView.document)
  5319. self.km_beginSheet(windowC: pagesWindowController)
  5320. pagesWindowController.callback = { [weak self] pages in
  5321. if pages.count > 0 {
  5322. self?.listView.redactAddAnnotationPages(pages, redactAnnotation: redactAnnotation)
  5323. }
  5324. }
  5325. }
  5326. func setPropertiesDefault(annotation:CPDFRedactAnnotation) {
  5327. CPDFRedactAnnotation.update_defaultOutlineColor(annotation.borderColor())
  5328. CPDFRedactAnnotation.update_defaultFillColor(annotation.interiorColor())
  5329. CPDFRedactAnnotation.update_defaultTextColor(annotation.fontColor())
  5330. CPDFRedactAnnotation.update_defaultFontSize(annotation.fontSize)
  5331. CPDFRedactAnnotation.update_defaultFontAlignment(annotation.alignment())
  5332. CPDFRedactAnnotation.update_defaultOverlayText(annotation.overlayText())
  5333. }
  5334. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  5335. let windowController = KMRedactConfirmWindowController(type)
  5336. self.currentWindowController = windowController
  5337. self.view.window?.beginSheet(windowController.window!)
  5338. windowController.itemClick = { [weak self] index in
  5339. if (index == 2) { /// 取消
  5340. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  5341. self?.currentWindowController = nil
  5342. callback()
  5343. return
  5344. }
  5345. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  5346. self?.currentWindowController = nil
  5347. let panel = NSSavePanel()
  5348. panel.nameFieldStringValue = "[新文件]"+((self?.listView.document?.documentURL.lastPathComponent) ?? "")
  5349. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  5350. button.state = .on
  5351. panel.accessoryView = button
  5352. panel.isExtensionHidden = true
  5353. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  5354. if response != .OK {
  5355. callback()
  5356. return
  5357. }
  5358. if (type == .redactOne) {
  5359. let anno = self!.listView.activeAnnotation
  5360. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  5361. callback()
  5362. return
  5363. }
  5364. (anno as! CPDFRedactAnnotation).applyRedaction()
  5365. } else if (type == .redactAll) {
  5366. self?.listView.document?.applyRedactions()
  5367. } else if (type == .eraserOne) {
  5368. let anno = self!.listView.activeAnnotation
  5369. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  5370. callback()
  5371. return
  5372. }
  5373. anno?.page.erasureRedact(from: anno!.bounds)
  5374. } else if (type == .eraserAll) {
  5375. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  5376. if (result == false) {
  5377. callback()
  5378. return
  5379. }
  5380. }
  5381. }
  5382. self!.listView.document?.write(to: panel.url)
  5383. if (button.state == .on) {
  5384. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  5385. }
  5386. } else {
  5387. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  5388. }
  5389. callback()
  5390. }
  5391. }
  5392. }
  5393. // MARK: - 保存文档
  5394. internal func needSaveDocument() -> Bool {
  5395. if (self.isPDFDocumentEdited) {
  5396. return self.isPDFDocumentEdited
  5397. }
  5398. if (self.needSave) {
  5399. return self.needSave
  5400. }
  5401. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  5402. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  5403. return false
  5404. }
  5405. return true
  5406. }
  5407. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  5408. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  5409. if (overlook) {
  5410. document?.save(nil)
  5411. return
  5412. }
  5413. if (self.isPDFDocumentEdited) {
  5414. self.clearIsPDFDocumentEdited()
  5415. self.needSave = false
  5416. document?.save(nil)
  5417. return
  5418. }
  5419. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  5420. return
  5421. }
  5422. document?.save(nil)
  5423. }
  5424. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  5425. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  5426. if (overlook) {
  5427. DispatchQueue.main.async {
  5428. document?.save(nil)
  5429. callback()
  5430. }
  5431. return
  5432. }
  5433. if (self.isPDFDocumentEdited) {
  5434. self.clearIsPDFDocumentEdited()
  5435. self.needSave = false
  5436. DispatchQueue.main.async {
  5437. document?.save(nil)
  5438. callback()
  5439. }
  5440. return
  5441. }
  5442. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  5443. callback()
  5444. return
  5445. }
  5446. DispatchQueue.main.async {
  5447. document?.save(nil)
  5448. callback()
  5449. }
  5450. }
  5451. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  5452. // 显示进度
  5453. AutoSaveManager.manager.isSaving = true
  5454. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  5455. self.progressC?.maxValue = 3.0
  5456. self.progressC?.increment(by: 1.0)
  5457. // 保存文档
  5458. self.asyncSaveDocument { [weak self] params in
  5459. // 执行进度 [假进度]
  5460. self?.progressC?.increment(by: 1.0)
  5461. self?.progressC?.increment(by: 1.0)
  5462. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  5463. // 隐藏进度
  5464. self?.hiddenProgressWindow()
  5465. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  5466. AutoSaveManager.manager.isSaving = false
  5467. }
  5468. // 回调
  5469. callback()
  5470. }
  5471. }
  5472. }
  5473. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  5474. self.document?.write(toFile: tempPath)
  5475. }
  5476. // MARK: - 定时保存
  5477. func addAutoSaveEvent() {
  5478. if (self.autoSaveTimer != nil) {
  5479. self.autoSaveTimer?.invalidate()
  5480. self.autoSaveTimer = nil
  5481. }
  5482. if self.document != nil {
  5483. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  5484. self?.autoSaveTimerAction(timer)
  5485. })
  5486. }
  5487. self.checkAutoSaveInfo()
  5488. }
  5489. func checkAutoSaveInfo() {
  5490. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  5491. return
  5492. }
  5493. if AutoSaveManager.manager.autoSaveAlertShow {
  5494. return
  5495. }
  5496. AutoSaveManager.manager.autoSaveDidEndAction = false
  5497. AutoSaveManager.manager.autoSaveAlertShow = true
  5498. let blockSaveWindow = AutoSavePopController()
  5499. blockSaveWindow.cancelHandle = { [weak self] windowController in
  5500. AutoSaveManager.manager.autoSaveDidEndAction = true
  5501. AutoSaveManager.manager.clearCache()
  5502. self?.km_quick_endSheet()
  5503. }
  5504. blockSaveWindow.confirmHandle = { [weak self] windowController in
  5505. self?.km_quick_endSheet()
  5506. self?.saveAutoSaveInfo()
  5507. }
  5508. self.km_beginSheet(windowC: blockSaveWindow)
  5509. }
  5510. func saveAutoSaveInfo() {
  5511. let openPanel = NSOpenPanel()
  5512. openPanel.canChooseDirectories = true
  5513. openPanel.canChooseFiles = false
  5514. openPanel.allowsMultipleSelection = false
  5515. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  5516. openPanel.beginSheetModal(for: win!) { result in
  5517. if (result == .OK) {
  5518. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  5519. for path in AutoSaveManager.manager.opendPaths ?? [] {
  5520. let _path = path as? String
  5521. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  5522. newPath = self.getValidFilePath(newPath)
  5523. do {
  5524. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  5525. } catch {
  5526. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  5527. }
  5528. }
  5529. AutoSaveManager.manager.clearCache()
  5530. }
  5531. AutoSaveManager.manager.autoSaveDidEndAction = true
  5532. }
  5533. }
  5534. func autoSaveTimerAction(_ timer: Timer) {
  5535. if (self.document == nil || self.listView.document?.documentURL.path == nil) {
  5536. return
  5537. }
  5538. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  5539. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  5540. return
  5541. }
  5542. if let data = self.document?.isLocked, data {
  5543. return
  5544. }
  5545. if AutoSaveManager.manager.autoSaveEnabled == false {
  5546. return
  5547. }
  5548. let documentArray = NSDocumentController.shared.documents
  5549. var didFileEdit = false
  5550. for doc in documentArray {
  5551. if doc.fileURL?.path == self.document?.documentURL.path {
  5552. didFileEdit = doc.isDocumentEdited
  5553. break
  5554. }
  5555. }
  5556. if (didFileEdit == false) {
  5557. return
  5558. }
  5559. AutoSaveManager.manager.isSaving = true
  5560. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView.document?.documentURL.path ?? "")
  5561. if (!self.document!.isLocked) {
  5562. self.document?.write(to: URL(fileURLWithPath: savePath))
  5563. }
  5564. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  5565. AutoSaveManager.manager.isSaving = false
  5566. }
  5567. }
  5568. func removeAutoSaveInfo() {
  5569. if self.autoSaveTimer != nil {
  5570. self.autoSaveTimer?.invalidate()
  5571. self.autoSaveTimer = nil
  5572. }
  5573. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  5574. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  5575. return
  5576. }
  5577. if AutoSaveManager.manager.autoSaveEnabled == false {
  5578. return
  5579. }
  5580. if self.document == nil || self.listView.document?.documentURL.path == nil {
  5581. return
  5582. }
  5583. AutoSaveManager.manager.removeAutoSavePath(self.listView.document?.documentURL.path ?? "")
  5584. }
  5585. // MARK: - 选择缩放模式
  5586. @objc public func selectZoom(_ type: KMPDFZoomType) {
  5587. switch type {
  5588. case .width:
  5589. self.listView.autoScales = true
  5590. break
  5591. case .fit:
  5592. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  5593. let pdfviewHeight = self.listView.bounds.size.height
  5594. self.listView.scaleFactor = pdfviewHeight/pageHeight
  5595. self.listView.autoScales = false
  5596. }
  5597. break
  5598. case .actualSize:
  5599. if self.listView.scaleFactor != 1.0 {
  5600. self.listView.scaleFactor = 1.0
  5601. self.listView.autoScales = false
  5602. }
  5603. break
  5604. }
  5605. }
  5606. // MARK: - Event 监听
  5607. private func addEventMonitor() {
  5608. if (self.eventMonitor != nil) {
  5609. self.removeEventMonitor()
  5610. }
  5611. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown, .leftMouseUp]) { [weak self] event in
  5612. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  5613. self?.listView.magnifyWheel(event)
  5614. return nil
  5615. } else if event.type == .leftMouseDown {
  5616. let point = event.locationInView(self?.listView ?? NSView())
  5617. let presentationDrawView = self?.listView.presentationDrawView
  5618. if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true { // 幻灯片模式下
  5619. if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
  5620. let can = self?.listView.canGoToNextPage() ?? false
  5621. if can {
  5622. self?.listView.goToNextPage(nil)
  5623. }
  5624. } else {
  5625. let can = self?.listView.canGoToPreviousPage() ?? false
  5626. if can {
  5627. self?.listView.goToPreviousPage(nil)
  5628. }
  5629. }
  5630. return nil
  5631. }
  5632. }
  5633. return event
  5634. }
  5635. }
  5636. func addKeyEventMonitor() {
  5637. if (self.keyEventMonitor != nil) {
  5638. self.removeKeyEventMonitor()
  5639. }
  5640. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  5641. if event.keyCode == 53 {
  5642. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  5643. self?.exitFullScreen()
  5644. return event
  5645. }
  5646. if self?.listView.toolMode == .CEditPDFToolMode {
  5647. if self != nil {
  5648. //使用editingSelectionString获取内容文字
  5649. if self!.listView.editingAreas() != nil {
  5650. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  5651. self!.listView.clearEditingSelectCharItem()
  5652. } else if self!.listView.editingAreas().count > 0 {
  5653. if self?.listView.shouAddEditAreaType() == .image ||
  5654. self?.listView.shouAddEditAreaType() == .text {
  5655. }
  5656. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  5657. self?.listView.updateEditing([])
  5658. self?.listView.isEditImage = false
  5659. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  5660. if self?.listView.shouAddEditAreaType() == .image {
  5661. self?.listView.change([.text, .image])
  5662. }
  5663. self?.toggleCloseRightSide()
  5664. } else if(self?.listView.shouAddEditAreaType() == .image || self!.listView.shouAddEditAreaType() == .text) {
  5665. if self?.listView.shouAddEditAreaType() == .image ||
  5666. self?.listView.shouAddEditAreaType() == .text {
  5667. }
  5668. self?.listView.setShouAddEdit([])
  5669. self?.listView.change([.text, .image])
  5670. self?.toggleCloseRightSide()
  5671. }
  5672. } else {
  5673. if self?.listView.shouAddEditAreaType() == .image ||
  5674. self?.listView.shouAddEditAreaType() == .text {
  5675. }
  5676. }
  5677. }
  5678. }
  5679. } else {
  5680. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  5681. self?.listView.keyDown(with: event)
  5682. return event
  5683. } else {
  5684. let cmd = event.modifierFlags.contains(.command)
  5685. let shift = event.modifierFlags.contains(.shift)
  5686. if event.keyCode == 6 { // z
  5687. let editPDFIng = self?.listView.isEditing() ?? false
  5688. if cmd && shift { // 恢复
  5689. let can = self?.listView.canEditTextRedo() ?? false
  5690. if can == false {
  5691. return event
  5692. }
  5693. if editPDFIng {
  5694. _ = CustomAlertView.alertView(message: NSLocalizedString("Redo", comment: ""), fromView: self!.view, withStyle: .black)
  5695. }
  5696. } else if cmd { // 撤回
  5697. let can = self?.listView.canEditTextUndo() ?? false
  5698. if can == false {
  5699. return event
  5700. }
  5701. if editPDFIng {
  5702. _ = CustomAlertView.alertView(message: NSLocalizedString("Undo", comment: ""), fromView: self!.view, withStyle: .black)
  5703. }
  5704. }
  5705. }
  5706. }
  5707. }
  5708. return event
  5709. }
  5710. }
  5711. func removeKeyEventMonitor() {
  5712. if (self.keyEventMonitor != nil) {
  5713. KMPrint("removeKeyEventMonitor 已移除事件监听")
  5714. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  5715. self.keyEventMonitor = nil
  5716. }
  5717. }
  5718. private func removeEventMonitor() {
  5719. if (self.eventMonitor != nil) {
  5720. KMPrint("已移除事件监听")
  5721. NSEvent.removeMonitor(self.eventMonitor as Any)
  5722. self.eventMonitor = nil
  5723. }
  5724. }
  5725. // MARK: - Tools
  5726. func pdfViewCanHorizontalScroll() -> Bool {
  5727. let scroll = self.listView.scroll()
  5728. if (scroll == nil) {
  5729. return false
  5730. }
  5731. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  5732. }
  5733. func pdfViewCanVerticalScroll() -> Bool {
  5734. let scroll = self.listView.scroll()
  5735. if (scroll == nil) {
  5736. return false
  5737. }
  5738. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  5739. }
  5740. // MARK: - Public Methods
  5741. // 清理数据 [eg. 通知]
  5742. public func clearData() {
  5743. KMThumbnailCache.shared.clearCache()
  5744. self.removeNotifications()
  5745. if (self.listView.spellingTag() > 0) {
  5746. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  5747. }
  5748. self.removeAutoSaveInfo()
  5749. self.myDocument = nil
  5750. }
  5751. public func clearSecureOptions() {
  5752. self._secureOptions = nil
  5753. self.documentAttribute = nil
  5754. }
  5755. public func clearRemoveSecureFlag() {
  5756. self._removeSecureFlag = false
  5757. }
  5758. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  5759. km_synchronized(self) {
  5760. self.model.isPDFDocumentEdited = true
  5761. if type == .editText || type == .editImage {
  5762. }
  5763. if let _document = self.myDocument {
  5764. KMTools.setDocumentEditedState(document: _document)
  5765. }
  5766. }
  5767. }
  5768. public func clearIsPDFDocumentEdited() {
  5769. km_synchronized(self) {
  5770. self.model.isPDFDocumentEdited = false
  5771. }
  5772. }
  5773. func showSnapshots(setups: NSArray?) {
  5774. if self.listView.document != nil {
  5775. for setup in setups ?? [] {
  5776. let swc = KMSnapshotWindowController()
  5777. swc.delegate = self
  5778. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  5779. swc.setForceOnTop(self.interactionMode != .normal)
  5780. self.myDocument?.addWindowController(swc)
  5781. }
  5782. }
  5783. }
  5784. // MARK: - Noti Actions
  5785. internal func documentDidUnlockNotification(_ sender: Notification) {
  5786. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  5787. if (self.myDocument == nil) {
  5788. return
  5789. }
  5790. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  5791. self.hiddenSecureLimitTip()
  5792. }
  5793. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  5794. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  5795. return
  5796. }
  5797. let type = KMPreferenceManager.shared.savePasswordType
  5798. if (type == .never) {
  5799. return
  5800. }
  5801. if (type == .always) {
  5802. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  5803. return
  5804. }
  5805. // 保存到钥匙串
  5806. let alert = NSAlert()
  5807. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  5808. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  5809. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  5810. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  5811. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  5812. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  5813. return
  5814. }
  5815. }
  5816. }
  5817. internal func applicationWillTerminateNotification(_ sender: Notification) {
  5818. self.savePageNumberIfNeed()
  5819. self.saveDocument()
  5820. }
  5821. }