KMMainViewController.swift 324 KB

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