KMMainViewController.swift 327 KB

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