KMMainViewController.swift 330 KB

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