KMMainViewController.swift 373 KB

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