KMMainViewController.swift 328 KB

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