1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593 |
- import Cocoa
- import KMComponentLibrary
- let MIN_SIDE_PANE_WIDTH: NSNumber = 264
- let CPDFViewIsReadModeKey = "kKMPDFViewIsReadMode"
- let CPDFViewLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
- struct KMNMWCFlags {
- var settingUpWindow: Bool = true
- }
- @objcMembers class KMMainViewController: KMNBaseViewController, NSTextFieldDelegate {
-
- @IBOutlet var contendBox: NSBox!
-
- @IBOutlet var toolbarBox: NSBox!
-
- @IBOutlet var bottomContendBox: NSBox!
-
- @IBOutlet var sidebarBox: NSBox!
-
- @IBOutlet var infoContendSplitView: NSSplitView!
- @IBOutlet var infoSplitLeftView: NSView!
- @IBOutlet var infoSplitRightView: NSView!
- @IBOutlet var infoSplitCenterView: NSView!
- @IBOutlet var infoSplitCenterSubView: NSBox!
- @IBOutlet var pdfSplitView: NSSplitView!
- @IBOutlet var pdfSplitTopView: NSView!
- @IBOutlet var pdfSplitBottomView: NSView!
-
- @IBOutlet var toolbarBoxHeightConst: NSLayoutConstraint!
- @IBOutlet var infoSplitViewLeftConst: NSLayoutConstraint!
- @IBOutlet var infoSplitViewRightConst: NSLayoutConstraint!
- @IBOutlet var infoSplitViewTopConst: NSLayoutConstraint!
-
- var viewManager: KMPDFViewManager = KMPDFViewManager.init()
- var toolbarManager: KMPDFToolbarManager = KMPDFToolbarManager.init()
-
- var listView: CPDFListView = CPDFListView.init()
- var document: CPDFDocument?
- var myDocument: NSDocument?
-
- var isFirstOpen: Bool = true
-
- var insertDocuments: Set<CPDFDocument> = []
-
-
- private var pdfToolbarController: KMPDFToolbarController?
-
-
- private var sideBarController: KMPDFSideBarController?
-
-
- private var pageEditViewController: KMNPageEditViewController?
-
-
- private var displaySettingController: KMNDisplayViewController?
-
-
- private var splitPDFController: KMSplitPDFViewController?
-
- private var pageNumberToolbar: KMPageNumberPromptView?
-
-
- var presentationTopViewController: KMPresentationTopViewController?
-
-
- var editToolbarView: KMEditToolbarView?
-
- var watermarkViewController: KMWatermarkController?
-
- var backgroundViewController: KMBackgroundController?
-
- var headerFooterViewController: KMHeaderFooterController?
-
- var batesViewController: KMBatesController?
-
- var cropController: KMCropController?
-
-
- var botaViewController: KMNLeftSideViewController?
-
-
- var rightSideController: KMRightSideController?
-
- let alertTipViewController: KMNAlertTipViewController = KMNAlertTipViewController(nibName: "KMNAlertTipViewController", bundle: nil)
-
-
- var mergeWindowController: KMMergeWindowController?
-
-
- var recommondPopWindowVC: KMRecommondPopWindow?
-
-
- var signaturestateVC: CDSignatureCertificateStateViewController = CDSignatureCertificateStateViewController.init()
-
-
- private var groupListMenuGroup: ComponentGroup? = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
-
- var textFieldSheet: KMTextFieldSheetController = KMTextFieldSheetController.init(windowNibName: "KMTextFieldSheetController")
-
- @IBOutlet weak var leftView: NSView!
-
- var model = KMMainModel()
-
-
- var searchIndex: Int = 0
-
-
- var isCompareModel: Bool = false
-
-
- var passwordWindow: KMPasswordInputWindow?
- var securityWindowController: KMSecurityWindowController?
-
-
- var compressWindowController: KMCompressWindowController?
-
-
- var guideInfoWindowController: KMGuideInfoWindowController?
-
-
- var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
- var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
- var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
-
-
- var bookletWindowController: KMPDFBookletWindowController?
- var multiplePrintWindowController: KMPDFMultiplePrintWindowController?
- var posterPrintWindowController: KMPDFPosterPrintWindowController?
-
- var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
-
- var componentMessageView: ComponentMessage = ComponentMessage()
-
- var blockSaveWindow = AutoSavePopController()
-
- private var _needSave = false
- var needSave: Bool {
- set {
- _needSave = newValue
-
- if (_needSave == false) {
- self.clearIsPDFDocumentEdited()
- }
- }
- get {
- return _needSave
- }
- }
-
- var isPDFDocumentEdited: Bool {
- get {
- return self.model.isPDFDocumentEdited
- }
- }
- var newMwcFlags = KMNMWCFlags(settingUpWindow: true)
-
- var searchResults: [KMSearchMode] = []
- var mwcFlags: MwcFlags = MwcFlags()
-
- weak var browserWindowController: KMBrowserWindowController?
-
- var currentWindowController: NSWindowController!
- var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
-
- let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
- let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
-
- var extract: KMExtractImageWindowController?
-
- var pageNumber: UInt?
-
- var autoSaveTimer: Timer?
- private var _documentFirstLoad: Bool = true
-
- var eventMonitor: Any?
- var keyEventMonitor: Any?
- var mouseRightMenuEvent: NSEvent?
-
- lazy private var homeVC: KMNHomeViewController? = {
- let vc = KMNHomeViewController()
- return vc
- }()
-
- fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
- var secureOptions: [CPDFDocumentWriteOption : Any]? {
- get {
- return self._secureOptions
- }
- }
- var documentAttribute: [CPDFDocumentAttribute : Any]?
-
- fileprivate var _removeSecureFlag = false
- var removeSecureFlag: Bool {
- get {
- return self._removeSecureFlag
- }
- }
-
- fileprivate var _saveWatermarkFlag = false
- var saveWatermarkFlag: Bool {
- get {
- return self._saveWatermarkFlag
- }
- }
-
- private var mainWindow_: NSWindow?
- var mainWindow: NSWindow? {
- get {
- return self.mainWindow_
- }
- set {
- self.mainWindow_ = newValue
- }
- }
-
- var setDocument: CPDFDocument? {
- get {
- return document
- }
- set {
- if document != newValue {
- document = newValue
- }
- listView.document = document
- botaViewController?.changeDocument(document: document)
- }
- }
-
- var setPageNumber: UInt {
- get {
- return pageNumber!
- }
- set {
- let pageCount = listView.document?.pageCount ?? 0
- var value = newValue
- if value > pageCount {
- value = pageCount
- }
- if value > 0 && listView.currentPage().pageIndex() != value-1 {
- listView.go(to: listView.document?.page(at: value-1))
- }
- if pageNumber != value {
- pageNumber = value
- }
- }
- }
-
-
-
-
- deinit {
- NotificationCenter.default.removeObserver(self)
-
- self.listView.delegate = nil
- self.listView.document?.delegate = nil
-
- self.removeEventMonitor()
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
-
- setupData()
-
- setupUI()
-
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- reloadPopUIWindow()
-
- addEventMonitor()
-
- addKeyEventMonitor()
-
- }
-
- override func viewDidDisappear() {
- super.viewDidDisappear()
-
- toggleClosePopUIWindow()
- }
-
- override func initContentView() {
- super.initContentView()
- }
-
- override func updateUIThemeColor() {
- super.updateUIThemeColor()
- }
-
- override func updateUILanguage() {
- super.updateUILanguage()
- }
-
-
- func setupUI() {
-
- initPDFView()
-
- initToolbar()
-
- initSideBar()
-
- setUpSplitView()
- }
-
- func setupData() {
- toolbarManager.pdfViewManager = viewManager
-
- if (UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) != nil) {
- UserDefaults.standard.set(MIN_SIDE_PANE_WIDTH, forKey: CPDFViewLeftSidePaneWidthKey)
- UserDefaults.standard.synchronize()
- }
-
- newMwcFlags.settingUpWindow = true
-
- Task {
- self.addAutoSaveEvent()
- }
-
- updateUndoRedoState()
- }
-
- @objc func editFontColorItemPanelAction(_ sender: Any) {
- if let color = (sender as? NSColorPanel)?.color {
- listView.changeEditingTextarea_Color(color: color)
- }
- }
-
-
- private func documentLoadComplete() {
-
- initLeftSideController()
-
- addNotificationCenter()
-
- activityLoadMethod()
-
- let readModel = UserDefaults.standard.bool(forKey: CPDFViewIsReadModeKey)
- if readModel == true {
- self.openPDFReadMode()
- }
-
- reloadDigitalSigns()
-
- alertTipViewController.showInView(listView: listView, subView: infoSplitCenterView)
- alertTipViewController.formFieldHighlightCallback = { [weak self] in
- let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
- CPDFAnnotation.updateHighlightFormFiled(self?.listView, highlightFormFiled: !value)
-
- self?.toolbarManager.refreshDefaultConfigItem()
- }
-
- alertTipViewController.enterPasswordCallback = { [weak self] in
- self?.removeOwnerPassword()
- }
-
- alertTipViewController.digitalDetailsCallback = { [weak self] in
- }
-
- alertTipViewController.redactApplyCallback = { [weak self] in
- self?.redactApplyAction()
- }
-
- alertTipViewController.heightCallback = { [weak self] height in
- self?.infoSplitViewTopConst.constant = height
- }
- newMwcFlags.settingUpWindow = false
-
- loadUserDefaultsData()
-
- }
-
- private func reloadDigitalSigns() {
- let signatures = listView.document.signatures()
-
- for i in 0 ..< (signatures?.count ?? 0) {
- let signature:CPDFSignature = signatures?[i] ?? CPDFSignature()
- if signature.signers.count > 0 {
- signature.verifySignature(with: listView.document)
- }
- }
-
- listView.signatures = signatures
- }
-
-
- private func activityLoadMethod() {
-
- }
-
- private func addNotificationCenter() {
- NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
- NotificationCenter.default.addObserver(self, selector: #selector(signatureStateChangeNoti), name: NSNotification.Name(rawValue: "CSignatureTrustCerDidChangeNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(pdfViewScrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: listView.documentView())
- NotificationCenter.default.addObserver(self, selector: #selector(pageCountChangedNotification), name: NSNotification.Name.CPDFDocumentPageCountChanged, object: listView.document)
- NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
-
- NotificationCenter.default.addObserver(self, selector: #selector(pdfViewHighlightFormFiledUpdateNoti), name: kPDFViewHighlightFormFiledUpdateNotiName, object: nil)
-
- NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
- }
-
- internal func removeNotifications() {
- NotificationCenter.default.removeObserver(self)
-
- }
-
-
- private func loadUserDefaultsData() {
- applyLeftSideWidth(0, rightSideWidth: 0)
-
-
- if SettingsManager.sharedInstance.leftPanelType == .defaultOpen {
- if SettingsManager.sharedInstance.defaultOpen == .thumbnail {
- viewManager.pdfSideBarType = .thumbnail
- } else if SettingsManager.sharedInstance.defaultOpen == .outline {
- viewManager.pdfSideBarType = .outline
- } else if SettingsManager.sharedInstance.defaultOpen == .bookmark {
- viewManager.pdfSideBarType = .bookmark
- } else if SettingsManager.sharedInstance.defaultOpen == .annotation {
- viewManager.pdfSideBarType = .annotation
- }
- } else if SettingsManager.sharedInstance.leftPanelType == .sameAsLastOpen {
- if let value = UserDefaults.standard.value(forKey: "KMPDFSidebarTypeKey"), let data = value as? Int {
- let pdfSideBarType: KMPDFSidebarType = KMPDFSidebarType(rawValue: data) ?? .none
- viewManager.pdfSideBarType = pdfSideBarType
- }
- } else if SettingsManager.sharedInstance.leftPanelType == .hideLeftSide {
- viewManager.pdfSideBarType = .none
- } else if SettingsManager.sharedInstance.leftPanelType == .prioritizeOutline {
- if let rootOutline = self.listView.document.outlineRoot(), rootOutline.numberOfChildren > 0 {
- viewManager.pdfSideBarType = .outline
- }
- }
- if viewManager.pdfSideBarType == .none {
- toggleCloseLeftSide()
- } else {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
- self.toggleCloseLeftSide()
- self.toggleOpenLeftSide(pdfSideBarType: self.viewManager.pdfSideBarType)
- }
- }
-
-
- let layoutType = SettingsManager.sharedInstance.layoutType
- if layoutType == .singlePage {
- self.updatePDFViewDisplayMode(viewMode: .singlePage)
- } else if layoutType == .singlePageContinue {
- self.updatePDFViewDisplayMode(viewMode: .singlePageContinuous)
- } else if layoutType == .twoPage {
- self.updatePDFViewDisplayMode(viewMode: .twoUp)
- } else if layoutType == .twoPageContinue {
- self.updatePDFViewDisplayMode(viewMode: .twoUpContinuous)
- } else if layoutType == .bookMode {
- self.updatePDFViewDisplayMode(isbookMode: true, direction: .horizontal)
- } else if layoutType == .bookModeContinue {
- self.updatePDFViewDisplayMode(isbookMode: true, direction: .vertical)
- }
-
- if self.listView.document != nil {
- if let pageIndex = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
- self.listView.go(toPageIndex: pageIndex, animated: false)
- }
- }
- if let scale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path) {
- self.listView.scaleFactor = CGFloat(scale)
- } else {
- let zoomType = SettingsManager.sharedInstance.zoomType
- self.refreshPDFViewZoomInfo(zoomType)
- }
- }
- }
-
- func refreshPDFViewZoomInfo(_ zoomType: zoomInfoType) {
- if zoomType == .adaptationWidth {
- listView.autoScales = true
- } else if zoomType == .adapPage {
- let pageHeight = listView.currentPage().size.height
- let pdfviewHeight = listView.bounds.size.height
- listView.scaleFactor = pdfviewHeight/pageHeight
- listView.autoScales = false
- } else if zoomType == .actualSize {
- if listView.scaleFactor != 1.0 {
- listView.scaleFactor = 1.0
- listView.autoScales = false
- }
- } else if zoomType == .percent_10 {
- listView.scaleFactor = 0.1
- } else if zoomType == .percent_25 {
- listView.scaleFactor = 0.25
- } else if zoomType == .percent_50 {
- listView.scaleFactor = 0.5
- } else if zoomType == .percent_75 {
- listView.scaleFactor = 0.75
- } else if zoomType == .percent_100 {
- listView.scaleFactor = 1.0
- } else if zoomType == .percent_150 {
- listView.scaleFactor = 1.5
- } else if zoomType == .percent_200 {
- listView.scaleFactor = 2.0
- } else if zoomType == .percent_400 {
- listView.scaleFactor = 4.0
- } else if zoomType == .percent_800 {
- listView.scaleFactor = 8.0
- }
- }
-
- func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
- infoContendSplitView.setPosition(infoContendSplitView.maxPossiblePositionOfDivider(at: 1) - infoContendSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
- infoContendSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
- }
-
-
- func initPDFView() {
- listView.autoresizingMask = [.width, .height]
- listView.autoScales = true
- listView.delegate = self
- listView.pdfListViewDelegate = self
- listView.document = self.document
- listView.pageBreakMargins = NSEdgeInsetsMake(10, 0, 10, 10)
- listView.hideNotes = false
-
- if let _ = UserDefaults.standard.value(forKey: "kPDFViewShowFormFieldNameKey") {
- listView.showFormFieldName = UserDefaults.getDefaultBoolValue(forKey: "kPDFViewShowFormFieldNameKey")
- } else {
- listView.showFormFieldName = true
- }
-
- reloadPDFSplitInfo()
-
- }
-
- func updatePDFViewAnnotationMode() {
- let toolbarMode = viewManager.toolMode
- let subToolMode = viewManager.subToolMode
-
- listView.isHidden = false
-
- if toolbarMode == .None {
- listView.toolMode = .CTextToolMode
- listView.annotationType = .unkown
-
- } else if toolbarMode == .Markup {
- if subToolMode == .None {
- listView.toolMode = .CTextToolMode
- } else {
- listView.toolMode = .CNoteToolMode
- }
-
-
- if subToolMode == .None {
- listView.annotationType = .unkown
- } else if subToolMode == .Highlight {
- listView.annotationType = .highlight
- } else if subToolMode == .Underline {
- listView.annotationType = .underline
- } else if subToolMode == .Waveline {
- listView.annotationType = .squiggly
- } else if subToolMode == .Strikethrough {
- listView.annotationType = .strikeOut
- } else if subToolMode == .Text {
- listView.annotationType = .freeText
- } else if subToolMode == .Note {
- listView.annotationType = .anchored
- } else if subToolMode == .Pen {
- listView.annotationType = .ink
- } else if subToolMode == .Eraser {
- listView.annotationType = .eraser
- } else if subToolMode == .Rectangle {
- listView.annotationType = .square
- } else if subToolMode == .Circle {
- listView.annotationType = .circle
- } else if subToolMode == .Arrow {
- listView.annotationType = .arrow
- } else if subToolMode == .Line {
- listView.annotationType = .line
- } else if subToolMode == .Measure {
- listView.annotationType = CPDFMeasureDefaultInfo.default_measureType()
-
- refreshMeasureInfo()
- } else if subToolMode == .Stamp {
- listView.annotationType = .stamp
- } else if subToolMode == .Sign {
- listView.annotationType = .signSignature
- }
- } else if toolbarMode == .Edit {
-
- if subToolMode == .None {
- if listView.toolMode != .CEditPDFToolMode {
- listView.toolMode = .CEditPDFToolMode
- listView.configPDFEditingInfo()
- }
- let editingPDFLoadType: CEditingLoadType = listView.editingPDFLoadType()
- listView.setShouAddEdit([])
- listView.change([.text, .image])
- } else if subToolMode == .Edit_text {
- if listView.toolMode != .CEditPDFToolMode {
- listView.toolMode = .CEditPDFToolMode
- listView.configPDFEditingInfo()
- }
- listView.setShouAddEdit([.text])
- listView.change(.text)
-
- } else if subToolMode == .Edit_Image {
- if listView.toolMode != .CEditPDFToolMode {
- listView.toolMode = .CEditPDFToolMode
- listView.configPDFEditingInfo()
- }
- listView.setShouAddEdit([.image])
- listView.change(.image)
-
- } else if subToolMode == .Edit_Link {
- listView.toolMode = .CEditLinkToolMode
-
- listView.annotationType = .link
-
- } else if subToolMode == .Edit_Crop {
- listView.isHidden = true
- listView.toolMode = .CCropToolMode
- }
-
- if viewManager.editType == .watermark ||
- viewManager.editType == .background ||
- viewManager.editType == .header_Footer ||
- viewManager.editType == .bates {
- listView.isHidden = true
- listView.toolMode = .CTextToolMode
-
- }
-
- if subToolMode != .Edit_Crop {
- removeCropController()
- }
-
- self.showOCREditAlert()
-
- } else if toolbarMode == .Form {
-
- listView.toolMode = .CFormToolMode
- if subToolMode == .None {
- listView.annotationType = .unkown
- } else if subToolMode == .Form_text {
- listView.annotationType = .textField
- } else if subToolMode == .Form_checkbox {
- listView.annotationType = .checkBox
- } else if subToolMode == .Form_radio {
- listView.annotationType = .radioButton
- } else if subToolMode == .Form_list {
- listView.annotationType = .listMenu
- } else if subToolMode == .Form_dropdown {
- listView.annotationType = .comboBox
- } else if subToolMode == .Form_OK {
- listView.annotationType = .actionButton
- } else if subToolMode == .Form_digitalSign {
- listView.annotationType = .signature
- }
-
- } else if toolbarMode == .Fill {
-
- if subToolMode == .None {
- listView.toolMode = .CTextToolMode
- } else {
- listView.toolMode = .CNoteToolMode
- }
- if subToolMode == .None {
-
- } else if subToolMode == .Fill_tick {
- listView.annotationType = .signTure
-
- } else if subToolMode == .fill_fork {
- listView.annotationType = .signFalse
-
- } else if subToolMode == .fill_rectangle {
- listView.annotationType = .signCircle
-
- } else if subToolMode == .fill_line {
- listView.annotationType = .signLine
-
- } else if subToolMode == .fill_dot {
- listView.annotationType = .signDot
-
- } else if subToolMode == .fill_date {
- listView.annotationType = .signDate
-
- } else if subToolMode == .fill_sign {
- listView.annotationType = .signSignature
- }
-
- } else if toolbarMode == .Convert {
-
- listView.toolMode = .CTextToolMode
-
- } else if toolbarMode == .Protect {
-
- listView.toolMode = .CTextToolMode
-
- if subToolMode == .Redact {
-
- listView.annotationType = .redact
- listView.toolMode = .CRedactToolMode
-
- } else if subToolMode == .Digital_Sign {
-
- listView.annotationType = .digitalSign
- listView.toolMode = .CDigitalSignToolMode
-
- self.enterDigitalSignature()
- }
-
-
-
- } else if toolbarMode == .Tools {
-
-
-
-
-
-
- }
-
- if (toolbarMode != .Edit) {
- self.closeOCREditAlert()
- }
- }
-
- func showOrHideNotes() {
- self.listView.hideNotes = !self.listView.hideNotes
-
- let items = [toolbarManager.highlightProperty, toolbarManager.UnderlineProperty,
- toolbarManager.wavelineProperty, toolbarManager.strikethroughProperty,
- toolbarManager.textProperty, toolbarManager.noteProperty,
- toolbarManager.penProperty, toolbarManager.eraserProperty,
- toolbarManager.rectangleProperty, toolbarManager.circleProperty,
- toolbarManager.arrowProperty, toolbarManager.lineProperty,
- toolbarManager.measureProperty, toolbarManager.stampProperty,
- toolbarManager.signProperty]
- for item in items {
- item.isDisabled = listView.hideNotes
- }
- pdfToolbarController?.resetSecondToolbar(forceRefresh: true)
-
- }
-
-
- func setUpSplitView() {
- infoContendSplitView.wantsLayer = true
- infoContendSplitView.layer?.backgroundColor = NSColor.clear.cgColor
- infoContendSplitView.delegate = self
- infoContendSplitView.layer?.masksToBounds = true
- }
-
- func setupSplitPDFController() {
- if splitPDFController == nil {
- splitPDFController = KMSplitPDFViewController.init()
- }
- splitPDFController?.view.frame = pdfSplitBottomView.bounds
- splitPDFController?.view.autoresizingMask = [.height, .width]
- splitPDFController?.viewManager = self.viewManager
- splitPDFController?.delegate = self
- splitPDFController?.pdfView?.pdfListViewDelegate = self
- splitPDFController?.reloadData()
-
- pdfSplitBottomView.addSubview(splitPDFController!.view)
- }
-
-
- func initToolbar() {
- toolbarBox.borderWidth = 0
-
- if pdfToolbarController == nil {
- pdfToolbarController = KMPDFToolbarController.init()
- }
- pdfToolbarController?.view.frame = toolbarBox.bounds
- pdfToolbarController?.view.autoresizingMask = [.width, .height]
- pdfToolbarController?.delegate = self
- toolbarBox.contentView = pdfToolbarController?.view
-
- pdfToolbarController?.viewManager = viewManager
- pdfToolbarController?.toolbarManager = toolbarManager
- pdfToolbarController?.pdfView = listView
- pdfToolbarController?.setUpData()
-
- refreshToolbarViewHeightInfo()
-
- if listView.showFormFieldName {
- toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
- } else {
- toolbarManager.form_ShowName_Property.righticon = nil
- }
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
- self.pdfToolbarController?.clickWithIdentify(KMPDFToolbar_Markup_Identifier)
- }
-
- }
-
- func refreshToolbarViewHeightInfo() {
- let _viewManager = viewManager
-
- if viewManager.isPageEditMode {
- toolbarBoxHeightConst.constant = 80
-
- } else if viewManager.editType == .watermark ||
- viewManager.editType == .background ||
- viewManager.editType == .header_Footer ||
- viewManager.editType == .bates {
-
- toolbarBoxHeightConst.constant = 40
- } else if _viewManager.toolMode == .Markup ||
- _viewManager.toolMode == .Edit ||
- _viewManager.toolMode == .Form ||
- _viewManager.toolMode == .Fill ||
- _viewManager.toolMode == .Convert ||
- _viewManager.toolMode == .Protect ||
- _viewManager.toolMode == .Tools {
-
- toolbarBoxHeightConst.constant = 80
- if _viewManager.subToolMode == .Redact {
- toolbarBoxHeightConst.constant = 40
- }
- } else {
- toolbarBoxHeightConst.constant = 40
- }
-
- }
-
- func toolbarViewModeChanged() {
- updatePDFViewAnnotationMode()
-
- refreshToolbarRightViewInfo()
-
- if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
- removeCropController()
- }
- }
-
- func updatePDFViewToolsType(_ viewToolsType: KMPDFViewToolsType) {
- viewManager.viewToolsType = viewToolsType
-
- pdfToolbarController?.reloadToolsView()
-
- if let toolbarVC = pdfToolbarController {
- kmPDFToolbarControllerDidViewToolsChanged(toolbarVC)
- }
- }
-
-
- func refreshToolbarRightViewInfo() {
-
- if viewManager.showRightSide == true {
- toolbarManager.rightViewProperty.state = .pressed
- toggleOpenRightSide()
-
- rightSideController?.reloadDataWithPDFView(pdfView: listView)
- } else {
- toggleCloseRightSide()
- }
-
- if viewManager.showRightSide == true {
- toolbarManager.rightViewProperty.state = .pressed
- } else {
- toolbarManager.rightViewProperty.state = .normal
- }
- pdfToolbarController?.reloadRightToolsView()
-
- }
-
-
- func initSideBar() {
- sidebarBox.borderWidth = 0
-
- if sideBarController == nil {
- sideBarController = KMPDFSideBarController.init()
- }
- sideBarController?.view.frame = sidebarBox.bounds
- sideBarController?.view.autoresizingMask = [.width, .height]
- sidebarBox.contentView = sideBarController?.view
-
- sideBarController?.pdfView = listView
- sideBarController?.delegate = self
- sideBarController?.pdfViewManager = viewManager
-
- sideBarController?.reloadData()
- }
-
- func reloadSideBar() {
- sideBarController?.reloadData()
-
- if viewManager.editType == .none {
- sideBarController?.searchItem.isHidden = false
- sideBarController?.thumbnailItem.isHidden = false
- sideBarController?.outlineItem.isHidden = false
- sideBarController?.bookmarkItem.isHidden = false
- sideBarController?.annotationItem.isHidden = false
- sideBarController?.aiToolItem.isHidden = false
- } else {
- sideBarController?.searchItem.isHidden = true
- sideBarController?.thumbnailItem.isHidden = true
- sideBarController?.outlineItem.isHidden = true
- sideBarController?.bookmarkItem.isHidden = true
- sideBarController?.annotationItem.isHidden = true
- sideBarController?.aiToolItem.isHidden = true
- }
- }
-
-
- func initLeftSideController() {
- if botaViewController == nil {
- botaViewController = KMNLeftSideViewController(listView.document)
- }
- botaViewController?.leftSideViewDelegate = self
- botaViewController?.view.frame = infoSplitLeftView.bounds
- botaViewController?.view.autoresizingMask = [.width, .height]
- if botaViewController != nil {
- infoSplitLeftView?.addSubview(botaViewController!.view)
- }
- }
-
- private func leftSidePaneIsOpen() -> Bool {
- return !infoContendSplitView.isSubviewCollapsed(infoSplitLeftView)
- }
-
- func toggleOpenLeftSide(pdfSideBarType: KMPDFSidebarType) {
- if(leftSidePaneIsOpen() == false) {
- let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) as? NSNumber ?? MIN_SIDE_PANE_WIDTH
- infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0)
- }
- if pdfSideBarType == .search {
- viewManager.pdfSideBarType = .search
- botaViewController?.searchViewC.handdler.pdfView = listView
- botaViewController?.leftsideType = .search
- } else if pdfSideBarType == .thumbnail {
- botaViewController?.leftsideType = pdfSideBarType
- } else if pdfSideBarType == .outline {
- botaViewController?.outlineViewC.handdler.pdfView = listView
- botaViewController?.leftsideType = pdfSideBarType
- } else if pdfSideBarType == .bookmark {
- botaViewController?.bookmarkViewC.handdler.pdfView = listView
- botaViewController?.leftsideType = pdfSideBarType
- } else if pdfSideBarType == .annotation {
- botaViewController?.annoController.listView = listView
- botaViewController?.leftsideType = .annotation
- } else if pdfSideBarType == .aiTools {
- botaViewController?.leftsideType = .aiTools
- }
- }
-
- func toggleCloseLeftSide() {
- if(leftSidePaneIsOpen() == true) {
- infoContendSplitView.setPosition(0, ofDividerAt: 0)
- }
- }
-
-
- func initRightSideController() {
- if rightSideController == nil {
- rightSideController = KMRightSideController.init()
- rightSideController?.delegate = self
- }
- rightSideController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, 680)
- rightSideController?.view.autoresizingMask = [.height, .maxXMargin]
- }
-
- func removeRightSideController() {
- rightSideController?.view.removeFromSuperview()
- rightSideController = nil
- }
-
- @objc func toggleOpenRightSide() -> Void {
- if rightSideController != nil {
- return
- }
- initRightSideController()
-
- rightSideController?.view.frame = infoSplitRightView.bounds
- rightSideController?.view.autoresizingMask = [.width, .height]
- infoSplitRightView.addSubview(rightSideController!.view)
- infoContendSplitView.setPosition(CGRectGetWidth(view.frame)-MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 1)
-
- rightSideController?.viewManager = self.viewManager
-
- rightSideController?.reloadDataWithPDFView(pdfView: listView)
-
-
-
- }
-
- @objc func toggleCloseRightSide() -> Void {
- removeRightSideController()
-
- infoContendSplitView.setPosition(CGRectGetWidth(view.frame), ofDividerAt: 1)
-
- viewManager.showRightSide = false
- pdfToolbarController?.reloadRightToolsView()
-
- }
-
- func refreshRightSide() -> Void {
- if let rightVC = rightSideController, let _ = rightSideController?.view.superview {
- rightVC.reloadDataWithPDFView(pdfView: listView)
- }
- }
-
-
- func updatePDFDisplaySettingView() {
- if viewManager.showDisplayView {
- infoSplitViewLeftConst.constant = 0
-
- infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0)
- } else {
- if viewManager.isPDFReadMode == false {
- infoSplitViewLeftConst.constant = 44
-
- if viewManager.pdfSideBarType == .none {
- toggleCloseLeftSide()
- } else {
- toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
- }
- } else {
- toggleCloseLeftSide()
- }
- }
-
- if viewManager.showDisplayView {
- if displaySettingController == nil {
- displaySettingController = KMNDisplayViewController.init()
- }
- displaySettingController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, CGRectGetHeight(bottomContendBox.frame))
- displaySettingController?.view.autoresizingMask = [.height, .width]
- infoSplitLeftView.addSubview(displaySettingController!.view)
- displaySettingController?.pdfView = self.listView
- displaySettingController?.viewManager = self.viewManager
- displaySettingController?.delegate = self
-
- displaySettingController?.reloadData()
-
- } else {
- displaySettingController?.view.removeFromSuperview()
- displaySettingController = nil
- }
- }
-
-
- func enterPageEditMode() {
- if(pageEditViewController == nil) {
- pageEditViewController = KMNPageEditViewController(self.document)
- }
- pageEditViewController?.view.frame = bottomContendBox.bounds
- pageEditViewController?.thumbnailBaseViewDelegate = self
- pageEditViewController?.selectionIndexPaths = [IndexPath(item: listView.currentPageIndex, section: 0)]
- pageEditViewController?.view.autoresizingMask = [.width,.height]
- pageEditViewController?.currentUndoManager = listView.undoManager
- bottomContendBox.addSubview(pageEditViewController!.view)
- toolbarManager.page_pageInfo_Property.text = String(listView.currentPageIndex + 1)
- pdfToolbarController?.refreshSecondToolbarItemsState()
-
- listView.isHidden = true
- listView.updateActiveAnnotations([])
- listView.updateEditing([])
- }
-
- func exitPageEditMode() {
- if pageEditViewController != nil {
- pageEditViewController?.view.removeFromSuperview()
- }
-
- listView.isHidden = false
-
- if listView.document?.isModified() == true {
- listView.layoutDocumentView()
-
- botaViewController?.reloadData()
- }
- botaViewController?.currentPageDidChangedAction(listView: listView)
- }
-
-
- func openPDFReadMode() {
- if viewManager.showDisplayView {
- UserDefaults.setDefaultBoolValue(true, toKey: "ShowDisplayViewWhenExitPDFReadMode")
- viewManager.showDisplayView = false
- pdfToolbarController?.reloadLeftIconView()
-
- updatePDFDisplaySettingView()
- }
-
- UserDefaults.setDefaultBoolValue(true, toKey: CPDFViewIsReadModeKey)
- if infoSplitViewLeftConst.constant != 0 {
- infoSplitViewLeftConst.constant = 0
-
- updatePDFDisplaySettingView()
- }
- if viewManager.pdfSideBarType != .none {
- UserDefaults.setDefaultIntValue(viewManager.pdfSideBarType.rawValue, toKey: "viewManagerPdfSideBarTypeRawValue")
-
- viewManager.pdfSideBarType = .none
- }
-
- if listView.toolMode != .CNoteToolMode {
- listView.toolMode = .CNoteToolMode
-
- viewManager.viewToolsType = .Select
- pdfToolbarController?.reloadToolsView()
- }
-
- toolbarBoxHeightConst.constant = 0
-
- view.window?.makeFirstResponder(listView)
-
- self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode On"))
- self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
- CGRectGetHeight(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
- self.componentMessageView.properties.propertyInfo.viewWidth,
- self.componentMessageView.properties.propertyInfo.viewHeight)
- self.componentMessageView.reloadData()
- self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
-
- setUpPDFPageNumberToolbar()
-
- if viewManager.toolMode != .Edit && viewManager.subToolMode != .Edit_Crop {
- removeCropController()
- }
- }
-
- func exitPDFReadMode() {
- viewManager.isPDFReadMode = false
-
- if UserDefaults.getDefaultBoolValue(forKey: "ShowDisplayViewWhenExitPDFReadMode") == true {
- if viewManager.showDisplayView == false {
- viewManager.showDisplayView = true
- pdfToolbarController?.reloadLeftIconView()
- }
- UserDefaults.setDefaultBoolValue(false, toKey: "ShowDisplayViewWhenExitPDFReadMode")
- }
-
- UserDefaults.setDefaultBoolValue(false, toKey: CPDFViewIsReadModeKey)
-
- if let index = UserDefaults.getDefaultIntValue(forKey: "viewManagerPdfSideBarTypeRawValue") {
- let type = KMPDFSidebarType(rawValue: index) ?? .none
- viewManager.pdfSideBarType = type
-
- UserDefaults.standard.removeObject(forKey: "viewManagerPdfSideBarTypeRawValue")
- UserDefaults.standard.synchronize()
- }
-
- updatePDFDisplaySettingView()
-
- refreshToolbarViewHeightInfo()
-
- reloadPDFPageNumberToolbar()
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
- self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode Off"))
- self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.infoSplitCenterView.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
- CGRectGetHeight(self.infoSplitCenterView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
- self.componentMessageView.properties.propertyInfo.viewWidth,
- self.componentMessageView.properties.propertyInfo.viewHeight)
- self.componentMessageView.reloadData()
- self.componentMessageView.showSelf(inView: self.infoSplitCenterView, autoHideSeconde: 2)
- }
- }
-
-
- func togglePresentation(_ sender: Any?) {
- if self.canExitPresentation() {
- exitFullScreen()
- } else if self.canEnterPresentation() {
- NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
-
- view.window?.enterPresentation(provider: self)
-
- if listView.toolMode != .CNoteToolMode {
- listView.toolMode = .CNoteToolMode
-
- viewManager.viewToolsType = .Select
- pdfToolbarController?.reloadToolsView()
- }
- }
- }
-
- func enterPresentationMode() {
- let scrollView = listView.documentView().enclosingScrollView
- savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
- savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
- savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
-
- listView.backgroundColor = NSColor.clear
- listView.setDisplay(.singlePage)
- listView.autoScales = true
- listView.displayBox = .cropBox
- listView.displaysPageBreaks = false
- scrollView?.autohidesScrollers = true
- scrollView?.hasHorizontalScroller = false
- scrollView?.hasVerticalScroller = false
-
- listView.setCurrentSelection(nil, animate: true)
- }
-
- func exitPresentationMode() {
-
- NotificationCenter.default.removeObserver(self, name: NSWindow.willEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.removeObserver(self, name: NSWindow.didEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
- NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
-
- }
-
- func exitFullScreen() {
- if self.canExitPresentation() == true {
- let mainDocument = self.myDocument as? KMMainDocument
- let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
- browserWindowController?.exitFullscreen()
-
- }
- }
-
- func exitFullscreenMode() {
- if self.interactionMode == .presentation {
- self.exitPresentationMode()
- }
-
- self.applyPDFSettings(self.savedNormalSetup)
- self.savedNormalSetup.removeAllObjects()
-
- listView.layoutDocumentView()
- listView.requiresDisplay()
-
- if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
- listView.backgroundColor = backgroundColor
- }
- reloadPDFSplitInfo()
- }
-
- func applyPDFSettings(_ setup: NSDictionary) {
- if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
- self.listView.autoScales = data.boolValue
- }
- if self.listView.autoScales == false {
- if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
- self.listView.scaleFactor = data.floatValue.cgFloat
- }
- }
-
- if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
- self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
- }
-
- if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
- self.listView.displaysAsBook = data.boolValue
- }
-
- if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
- self.listView.displaysPageBreaks = data.boolValue
- }
-
- if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
-
- }
-
- self.listView.layoutDocumentView()
- }
-
- func currentPDFSettings() -> NSDictionary {
- let setup = NSMutableDictionary()
- setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
- setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
- setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
- setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
- setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
- setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
-
- return setup
- }
-
- func canEnterFullscreen() -> Bool {
- if (mwcFlags.isSwitchingFullScreen != 0) {
- return false
- }
- if useNativeFullScreen() {
- return interactionMode == .normal || interactionMode == .presentation
- } else {
- return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
- }
- }
-
- override func canEnterPresentation() -> Bool {
- let can = super.canEnterPresentation()
- if can == false {
- return false
- }
- guard let doc = self.listView.document, doc.isLocked == false else {
- return false
- }
- return can
- }
-
- func fadeOutFullScreenWindow() {
- guard let fullScreenWindow = self.view.window as? KMFullScreenWindow else {
- NSSound.beep()
- return
- }
-
- let mainWindow = fullScreenWindow.interactionParent
- let collectionBehavior = mainWindow?.collectionBehavior
-
- mainWindow?.alphaValue = 0
- if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
- mainWindow?.animationBehavior = .none
- }
-
- fullScreenWindow.addChildWindow(mainWindow!, ordered: .below)
- fullScreenWindow.removeChildWindow(mainWindow!)
- fullScreenWindow.level = .popUpMenu
-
- mainWindow?.level = .normal
- mainWindow?.alphaValue = 1.0
- mainWindow?.collectionBehavior = collectionBehavior!
- mainWindow?.display()
- mainWindow?.makeFirstResponder(self.listView)
- mainWindow?.recalculateKeyViewLoop()
-
- mainWindow?.makeKey()
-
- if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
- mainWindow?.animationBehavior = .default
- }
- NSApp.removeWindowsItem(fullScreenWindow)
- fullScreenWindow.fadeOut()
- }
-
-
- func reloadPDFSplitInfo() {
- if listView.viewSplitMode == .disable {
- pdfSplitView.isHidden = true
- listView.frame = infoSplitCenterSubView.bounds
- infoSplitCenterSubView.addSubview(listView)
-
- if splitPDFController != nil {
- splitPDFController = nil
- }
- } else {
- pdfSplitView.isHidden = false
- listView.frame = pdfSplitTopView.bounds
- pdfSplitTopView.addSubview(listView)
-
- setUpPDFPageNumberToolbar()
-
- setupSplitPDFController()
-
- if listView.viewSplitMode == .horizontal {
- pdfSplitView.isVertical = false
- } else if listView.viewSplitMode == .vertical {
- pdfSplitView.isVertical = true
- }
- }
- }
-
- func setUpPDFPageNumberToolbar() {
- if pageNumberToolbar != nil {
- pageNumberToolbar?.removeFromSuperview()
- pageNumberToolbar = nil
- }
- if pageNumberToolbar == nil {
- pageNumberToolbar = KMPageNumberPromptView.init()
- }
- if viewManager.isPDFReadMode {
- pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-366/2, 20, 366, 40)
- pageNumberToolbar?.hideBackForwordButton(false)
- } else {
- pageNumberToolbar?.frame = CGRectMake(CGRectGetWidth(listView.frame)/2-288/2, 20, 288, 40)
- pageNumberToolbar?.hideBackForwordButton(true)
- }
- pageNumberToolbar?.autoresizingMask = [.minXMargin, .maxXMargin, .maxYMargin]
- pageNumberToolbar?.pdfView = self.listView
- pageNumberToolbar?.reloadData()
- pageNumberToolbar?.isHidden = true
-
- listView.addSubview(pageNumberToolbar!)
-
- reloadPDFPageNumberToolbar()
- }
-
- func reloadPDFPageNumberToolbar() {
- if viewManager.isPDFReadMode == true ||
- (viewManager.splitShowBottomBar && listView.viewSplitMode != .disable) {
-
- pageNumberToolbar?.isHidden = false
- pageNumberToolbar?.reloadData()
- } else {
- pageNumberToolbar?.isHidden = true
-
- }
- }
-
- func showEditToolbarView() {
- if editToolbarView == nil {
- editToolbarView = KMEditToolbarView()
- }
- editToolbarView?.frame = toolbarBox.bounds
- editToolbarView?.delegate = self
- editToolbarView?.autoresizingMask = [.width, .height]
- toolbarBox.contentView = editToolbarView
-
- reloadSideBar()
- }
-
- func exitEditToolbarView() {
- viewManager.editType = .none
- viewManager.subToolMode = .None
-
- editToolbarView?.removeFromSuperview()
- editToolbarView = nil
-
- watermarkViewController?.view.removeFromSuperview()
- watermarkViewController = nil
-
- backgroundViewController?.view.removeFromSuperview()
- backgroundViewController = nil
-
- headerFooterViewController?.view.removeFromSuperview()
- headerFooterViewController = nil
-
- batesViewController?.view.removeFromSuperview()
- batesViewController = nil
-
- refreshToolbarViewHeightInfo()
- toolbarBox.contentView = pdfToolbarController?.view
-
- updatePDFViewAnnotationMode()
-
- reloadSideBar()
-
- KMWatermarkManager.defaultManager.defaultWatermarkData = KMWatermarkModel.defaultWDData()
-
- }
-
- func updateEditModeDocumentWhenPageChanged() {
- if viewManager.editType == .watermark {
- updateWatermarkDocument()
- } else if viewManager.editType == .background {
- updateBackgroundDocument()
- } else if viewManager.editType == .header_Footer {
- updateHeaderFooterDocument()
- } else if viewManager.editType == .bates {
- updateBatesDocument()
- } else if viewManager.subToolMode == .Edit_Crop {
- updateCropDocument()
- }
- }
-
- func menuItemAction_FontPanel() {
- NSFontManager.shared.target = self
- NSFontManager.shared.action = #selector(changeFont(_:))
- NSFontManager.shared.orderFrontFontPanel(nil)
- }
-
- func menuItemAction_FontAction(_ index: Int) {
- if index == 0 {
- self.listView.setEditingTextarea(isBold: true)
- } else if index == 1 {
- self.listView.setEditingTextarea(isItalic: true)
- } else if index == 2 {
- self.listView.fontAddAction()
- } else if index == 3 {
- self.listView.fontReduceAction()
- } else if index == 4 {
- let colorPanel = NSColorPanel.shared
- colorPanel.setTarget(self)
- colorPanel.showsAlpha = false
- colorPanel.setAction(#selector(self.menuItemAction_FontColor(_:)))
- colorPanel.orderFront(nil)
- }
- }
-
- func menuItemAction_FontAlign(_ index: Int) {
- if index == 0 {
- self.listView.setEditingTextarea_Alignment(align: .left)
- } else if index == 1 {
- self.listView.setEditingTextarea_Alignment(align: .center)
- } else if index == 2 {
- self.listView.setEditingTextarea_Alignment(align: .right)
- }
- }
- func menuItemAction_CustomFont(_ index: Int) {
- if index == 0 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h1)
- self.updateEditPDFTextFontModel(model)
- } else if index == 1 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h2)
- self.updateEditPDFTextFontModel(model)
- } else if index == 2 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h3)
- self.updateEditPDFTextFontModel(model)
- } else if index == 3 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b1)
- self.updateEditPDFTextFontModel(model)
- } else if index == 4 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b2)
- self.updateEditPDFTextFontModel(model)
- } else if index == 5 {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b3)
- self.updateEditPDFTextFontModel(model)
- }
- }
-
- @objc func menuItemAction_FontColor(_ sender: Any) {
- if let color = (sender as? NSColorPanel)?.color {
- listView.changeEditingTextarea_Color(color: color)
- }
- }
-
- @objc func changeFont(_ sender: NSFontManager) {
- let newFont = sender.convert(NSFont.systemFont(ofSize: 14))
- let value = CPDFFont(familyName: newFont.fontName, fontStyle: newFont.style ?? "Regular")
- listView.setEditingTextarea_font(font: value)
-
- listView.setEditingTextarea_FontSize(size: newFont.pointSize)
-
- rightSideController?.reloadData()
- }
-
-
- func writeSignatureToWidget(_ widget: CPDFSignatureWidgetAnnotation, _ path: String, _ password: String, _ config: CPDFSignatureConfig, _ isLock: Bool) ->() {
-
- let fileName = listView.document.documentURL?.lastPathComponent
- let fileNameWithoutExtension = URL(fileURLWithPath: fileName!).deletingPathExtension().lastPathComponent
-
- let outputSavePanel = NSSavePanel()
- outputSavePanel.directoryURL = listView.document.documentURL.deletingLastPathComponent()
- outputSavePanel.title = KMLocalizedString("", comment: "Save as PDF")
- outputSavePanel.allowedFileTypes = ["pdf"]
- outputSavePanel.nameFieldStringValue = fileNameWithoutExtension + "_" + KMLocalizedString("Signed", comment: "")
- let result = outputSavePanel.runModal()
- if result == .OK {
- let contentArr = NSMutableArray()
- var locationStr = ""
- var reasonStr = KMLocalizedString("none", comment: "")
- for item in config.contents {
- if item.key == KMLocalizedString("Reason", comment: "") {
- if item.value == KMLocalizedString("<your signing reason here>", comment: "") {
- item.value = " " + KMLocalizedString("none", comment: "")
- }
- reasonStr = item.value
- } else if item.key == KMLocalizedString("Location", comment: "") {
- if item.value == KMLocalizedString("<your signing location here>", comment: "") {
- item.value = " "
- }
- locationStr = item.value
- }
- contentArr.add(item)
- }
- config.contents = contentArr as? [CPDFSignatureConfigItem]
- widget.setFieldName(widget.getValidName(inPage: widget.page))
-
- widget.signAppearanceConfig(config)
-
- let success = listView.document.writeSignature(to: outputSavePanel.url, withWidget: widget, pkcs12Cert: path, password: password, location: locationStr, reason: reasonStr, permissions: .forbidChange)
- widget.removeSignature()
- if success {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
- NSDocumentController.shared.openDocument(withContentsOf: outputSavePanel.url!, display: true) { document, documentWasAlreadyOpen, error in
- if error != nil {
- NSApp.presentError(error!)
- return
- }
- }
- }
- } else {
- let alert = NSAlert.init()
- alert.messageText = KMLocalizedString("Save failed!", comment: "")
- alert.addButton(withTitle: KMLocalizedString("OK", comment: ""))
- alert.runModal()
- }
- widget.page.removeAnnotation(widget)
- listView.setNeedsDisplayAnnotationViewFor(widget.page)
- } else {
- widget.page.removeAnnotation(widget)
- listView.setNeedsDisplayAnnotationViewFor(widget.page)
- }
- }
-
- func popUpSignatureWidgetState(_ signature: CPDFSignature, _ pdfListView: CPDFListView) ->(){
- signaturestateVC.signature = signature
- signaturestateVC.pdfListView = pdfListView
- signaturestateVC.actionBlock = { [weak self, weak signaturestateVC] stateVCSelf, actionType in
- guard let weakSelf = self, let stateVC = signaturestateVC else { return }
- if actionType == .cancel {
- stateVC.dismiss(stateVCSelf)
- } else if actionType == .confirm {
- if let signer = signature.signers.first, let data = signer.certificates {
- let signatureDetail = DSignatureDetailsViewController.init()
- signatureDetail.certificates = data
- signatureDetail.signature = signature
- signatureDetail.pdfListView = pdfListView
- stateVCSelf.presentAsSheet(signatureDetail)
- } else {
- NSSound.beep()
- }
- }
- }
- self.presentAsSheet(signaturestateVC)
- signaturestateVC.reloadData()
- }
-
- func enterDigitalSignature() {
- if UserDefaults.standard.object(forKey: "kDigitalSignature") != nil {
- return
- }
- let alert = NSAlert()
- alert.alertStyle = .informational
- 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. ")
- alert.addButton(withTitle: KMLocalizedString("OK"))
- alert.showsSuppressionButton = true
- let response = alert.runModal()
- if response.rawValue == 1000 {
- if alert.suppressionButton?.state == .on {
- UserDefaults.standard.set("YES", forKey: "kDigitalSignature")
- UserDefaults.standard.synchronize()
- }
- }
- }
-
-
-
- public func showMergeWindow(url: URL? = nil) {
- DispatchQueue.main.async {
-
- self.mergeWindowController = KMMergeWindowController(windowNibName: "KMMergeWindowController")
-
- self.mergeWindowController!.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet(mergeWindowController!.window!)
- }
-
- self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
- self.view.window?.endSheet(mergeWindowController!.window!)
- }
-
- self.view.window?.beginSheet(self.mergeWindowController!.window!)
- }
- }
-
-
- func showCropController() {
- if cropController == nil {
- cropController = KMCropController.init()
- cropController?.view.frame = infoSplitCenterView.bounds
- cropController?.view.autoresizingMask = [.width, .height]
- cropController?.delegate = self
- infoSplitCenterView.addSubview(cropController!.view)
-
- if viewManager.showRightSide == false {
- viewManager.showRightSide = true
-
- refreshToolbarRightViewInfo()
- }
- updateCropDocument()
- }
- }
-
- func updateCropDocument() {
- guard let controller = cropController else { return }
- controller.pdfDocument = nil
-
- let page = listView.document.page(at: UInt(listView.currentPageIndex))
- let editDocument = CPDFDocument.init()
- editDocument?.insertPageObject(page, at: 0)
- if let editPage = editDocument?.page(at: 0) {
- let mediaRect = editPage.bounds(for: .mediaBox)
- editPage.setBounds(mediaRect, for: .cropBox)
-
- if let rect = KMCropManager.defaultManager.cropRect {
- controller.selectionRect = rect
- } else {
- if KMCropManager.defaultManager.cropSeparateOn {
- let rect = KMCropTools.getPageForegroundBox(editPage)
- controller.selectionRect = rect
- } else if KMCropManager.defaultManager.cropAutoOn {
- let rect = KMCropTools.getPageForegroundBox(editPage)
- controller.selectionRect = rect
- } else {
- controller.selectionRect = page?.bounds(for: .cropBox) ?? .zero
- }
- }
-
- if let cropVC = rightSideController?.edit_cropController {
- cropVC.pageCropBounds = page?.bounds(for: .cropBox) ?? .zero
- cropVC.reloadData()
- }
- }
- controller.pdfDocument = editDocument
- controller.reloadData()
- }
-
- func removeCropController() {
- if cropController != nil {
- cropController?.view.removeFromSuperview()
- cropController = nil
-
- KMCropManager.defaultManager.clear()
-
- toolbarManager.edit_crop_Property.state = .normal
- }
- }
-
-
- public func hiddenSecureLimitTip() {
-
- }
-
- func savePageNumberIfNeed() {
-
- let scaleFactor = self.listView.scaleFactor
- if scaleFactor <= 0 {
- return
- }
- if self.listView.document != nil {
- KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
- KMPreferenceManager.shared.setPageScale(Float(scaleFactor), forKey: self.listView.document.documentURL.path)
- }
- }
-
-
- public func showSecureWindow() {
- guard let url = self.listView.document?.documentURL else {
- return
- }
- self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
- guard let securityWindowController = securityWindowController else { return }
-
- securityWindowController.documentURL = self.listView.document?.documentURL
- securityWindowController.batchAction = { [unowned self] controller, files in
- self.view.window?.endSheet((securityWindowController.window)!)
- self.showBatchWindow(type: .security, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
- securityWindowController.doneAction = { [unowned self] controller, options, attribute in
- let openPanel = NSOpenPanel()
- openPanel.canChooseFiles = false
- openPanel.canChooseDirectories = true
- openPanel.canCreateDirectories = true
- openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
- if result == NSApplication.ModalResponse.OK {
- for fileURL in openPanel.urls {
- let document = CPDFDocument(url: self.document?.documentURL)
- if document != nil {
- document!.setDocumentAttributes(attribute)
-
- let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
- let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
- if success {
- self.view.window?.endSheet((securityWindowController.window)!)
-
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
- }
- }
- }
- }
- }
- }
-
- securityWindowController.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((securityWindowController.window)!)
- }
- NSWindow.currentWindow().beginSheet(securityWindowController.window!)
- }
-
-
- public func showRemoveSecureWindow() {
- var isDocumentLocked: Bool = false
- if self.document?.allowsCopying == false || self.document?.allowsPrinting == false {
- isDocumentLocked = true
- } else if (self.document?.password ?? "").count > 0 {
- isDocumentLocked = true
- }
- if isDocumentLocked == false {
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = KMLocalizedString("This document doesn’t contain any security settings and doesn‘t need to be removed.")
- alert.addButton(withTitle: KMLocalizedString("OK"))
- alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
-
- }
- } else {
- let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
- controller.pdfDocument = self.document
- self.currentWindowController = controller
-
- controller.batchAction = { [unowned self] controller, files in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
- var array: [URL] = []
- for item in files {
- array.append(NSURL(fileURLWithPath: item.filePath) as URL)
- }
- self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.security.rawValue, files: array)
- }
-
- controller.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
- }
-
- controller.doneAction = { [unowned self] controller in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
- NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
- if success {
-
- let savePanel = NSSavePanel()
- savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
- savePanel.allowedFileTypes = ["pdf"]
-
- savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
- guard result == .OK else { return }
-
-
- if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
- self.model.isSaveKeyChain = false
- self.listView.document.unlock(withPassword: resultPassword)
- }
-
- let document = CPDFDocument.init(url: self.listView.document.documentURL)
- guard let document = document else { return }
-
- document.unlock(withPassword: resultPassword)
- let success = document.writeDecrypt(to: savePanel.url)
- if success {
- self.hiddenSecureLimitTip()
-
- NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
- } else {
- self.hiddenSecureLimitTip()
-
- }
- }
- }
- }
- }
- NSWindow.currentWindow().beginSheet(controller.window!)
-
- }
- }
-
-
- func unlockPDFDocument() {
- NSWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
- self.listView.document.unlock(withPassword: resultPassword)
- }
- }
-
-
- func reloadPopUIWindow() {
- if listView.toolMode == .CSelectToolMode {
- let pageRect = listView.currentSelectionRect()
- let page:CPDFPage? = listView.currentSelectionPage()
-
- if listView.selectionRect != CGRectZero && page != nil {
- let positioningRect = listView.convert(pageRect, from: page)
- if (CGRectIntersectsRect(positioningRect, listView.frame)) {
- reloadPopUIOperation()
- return
- }
- }
- toggleClosePopUIWindow()
- } else if listView.toolMode == .COCRToolMode {
- let pageRect = listView.currentSelectionRect()
- let page:CPDFPage? = listView.currentSelectionPage()
-
- if listView.selectionRect != CGRectZero && page != nil {
- let positioningRect = listView.convert(pageRect, from: page)
- if (CGRectIntersectsRect(positioningRect, listView.frame)) {
- reloadPopUIOperation()
- return
- }
- }
- toggleClosePopUIWindow()
- } else if(listView.isEditing() == false) {
- let activeAnnotations:[CPDFAnnotation] = listView.activeAnnotations as! [CPDFAnnotation]
- if(activeAnnotations.count > 0) {
- if let page = activeAnnotations.first?.page {
- let pageRect = listView.selectionMultipleBounds(with: activeAnnotations)
- let positioningRect = listView.convert(pageRect, from: page)
- if (CGRectIntersectsRect(positioningRect, listView.frame)) {
- reloadPopUIActiveAnnotations(activeAnnotations: activeAnnotations)
- } else {
- toggleClosePopUIWindow()
- }
- } else {
- toggleClosePopUIWindow()
- }
- } else {
- toggleClosePopUIWindow()
- }
-
- if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) {
- toggleClosePopUIWindow()
- }
- } else {
- let editAreas:[CPDFEditArea] = listView.km_EditingAreas()
- if(editAreas.count > 0) {
- if let page = editAreas.first?.page {
- let pageRect = listView.selectionMultipleBounds(withEditArea: editAreas)
- let positioningRect = listView.convert(pageRect, from: page)
- if (CGRectIntersectsRect(positioningRect, listView.frame)) {
- reloadPopUIContentEdits(editAreas: editAreas)
- } else {
- toggleClosePopUIWindow()
- }
- } else {
- toggleClosePopUIWindow()
- }
- } else {
- toggleClosePopUIWindow()
- }
-
- if(listView.popOver?.isShown == true || (groupListMenuGroup?.superview) != nil) {
- toggleClosePopUIWindow()
- }
- }
- }
-
- func toggleClosePopUIWindow() {
- let popWindow = KMNAnnotationPopToolbarWindow.shared
- if popWindow.isVisible == true {
- closeAnnotationPopWindow()
- }
- let editPopWindow = KMNContentEditPopToolbarWindow.shared
- if editPopWindow.isVisible == true {
- closePopContentEditWindow()
- }
-
- let operationWindow = KMNOperationPopToolbarWindow.shared
- if operationWindow.isVisible == true {
- closePopOperationWindow()
- }
- }
-
- func closeAnnotationPopWindow() {
- KMNAnnotationPopToolbarWindow.shared.closeWindow(listView: listView)
- }
-
- func closePopContentEditWindow() {
- KMNContentEditPopToolbarWindow.shared.closeWindow(listView: listView)
- }
-
- func closePopOperationWindow() {
- KMNOperationPopToolbarWindow.shared.closeWindow(listView: listView)
- }
-
- func reloadPopUIOperation() {
- if listView.selectionRect != CGRectZero {
- let popWindow = KMNOperationPopToolbarWindow.shared
- popWindow.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
- self.listView.window?.addChildWindow(popWindow, ordered: .above)
- let operationViewController = KMNPopOperationViewController.shared
- operationViewController.listView = listView
- if listView.toolMode == .CSelectToolMode {
- operationViewController.popType = .crop
- operationViewController.cropCurrentCallback = {[weak self] in
- let rect = self?.listView.currentSelectionRect() ?? CGRect.zero
- let orgPage : CPDFPage = self?.listView.currentSelectionPage() ?? CPDFPage()
- self?.cropPages(atIndexs: [orgPage.pageIndex()], to: [rect])
- self?.closePopOperationWindow()
- }
- } else if listView.toolMode == .COCRToolMode {
- operationViewController.popType = .ocr
- operationViewController.OCRAction = { [weak self] in
- self?.convertSelectionRectOCR(rect: self?.listView.currentSelectionRect() ?? CGRectZero)
- }
- }
- operationViewController.updatePDFViewCallback = {[weak self] in
- self?.closePopOperationWindow()
- self?.listView.setNeedsDisplayForVisiblePages()
- }
- updatePopOperationPopWinodwFrame()
-
- } else {
- closePopOperationWindow()
- }
- }
-
- func reloadPopUIActiveAnnotations(activeAnnotations:[CPDFAnnotation]) {
- let annotationMode = KMNAnnotationPopMode(pdfAnnotations: activeAnnotations )
- let popVC = KMNPopAnnotationViewController.shared
- if annotationMode.popType == .popTypeNone || !SettingsManager.sharedInstance.showQuickActionBar {
- closeAnnotationPopWindow()
- } else {
- let win = KMNAnnotationPopToolbarWindow.shared
- win.annotationPopMode = annotationMode
- win.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
- self.listView.window?.addChildWindow(win, ordered: .above)
-
- popVC.listView = listView
- popVC.annotationPopMode = annotationMode
- popVC.isOpenPane = viewManager.showRightSide
- updateAnnotationsPopWinodwFrame()
-
- popVC.updatePDFViewCallback = {[weak self] in
- self?.rightSideController?.reloadDataWithPDFView(pdfView: self?.listView ?? CPDFListView())
- self?.listView.setNeedsDisplayMultiAnnotations(annotationMode.annotations)
- NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
- }
-
- popVC.paneCallback = {[weak self] isOpen in
- if isOpen == true {
- self?.viewManager.showRightSide = true
- } else {
- self?.viewManager.showRightSide = false
- }
- self?.refreshToolbarRightViewInfo()
- }
- }
- }
-
- func reloadPopUIContentEdits(editAreas:[CPDFEditArea]) {
- let editingAreas = listView.km_EditingAreas()
- let editMode = KMNEditContentPopMode(currentEditAreas: editingAreas)
- let popVC = KMNPopContentEditViewController.shared
- if editMode.popType == .editNone || !SettingsManager.sharedInstance.showQuickActionBar {
- closePopContentEditWindow()
- } else {
- let win = KMNContentEditPopToolbarWindow.shared
- win.editContentPopMode = editMode
- win.show(relativeTo: CGRectZero, of: self.listView, preferredEdge: .maxY)
- self.listView.window?.addChildWindow(win, ordered: .above)
-
- popVC.listView = listView
- popVC.editContentPopMode = editMode
- popVC.isOpenPane = viewManager.showRightSide
- popVC.editContentPopMode = editMode
- updateContentEditPopWinodwFrame()
-
- popVC.paneCallback = {[weak self] isOpen in
- if isOpen == true {
- self?.viewManager.showRightSide = false
- } else {
- self?.viewManager.showRightSide = true
- }
- self?.refreshToolbarRightViewInfo()
- }
- popVC.updatePDFViewCallback = { [weak self] in
- self?.rightSideController?.reloadEditingAreas()
- }
- }
- }
-
- func updateAnnotationsPopWinodwFrame() {
- let popWindow = KMNAnnotationPopToolbarWindow.shared
- popWindow.updateFrame(listView: listView)
- }
-
- func updateContentEditPopWinodwFrame() {
- let popWindow = KMNContentEditPopToolbarWindow.shared
- popWindow.updateFrame(listView: listView)
- }
-
- func updatePopOperationPopWinodwFrame() {
- let popWindow = KMNOperationPopToolbarWindow.shared
- popWindow.updateFrame(listView: listView,page: listView.currentSelectionPage())
- }
-
-
- func removeOwnerPassword() {
- guard let doc = listView.document else {
- NSSound.beep()
- return
- }
- if doc.permissionsStatus != .user {
- NSSound.beep()
- return
- }
- _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
- if result == .cancel {
- return
- }
- self?.listView.document?.unlock(withPassword: password)
-
- if doc.permissionsStatus == .owner {
- self?.alertTipViewController.reloadSecureAlertUI()
- self?.alertTipViewController.reloadAlertUIFrame()
- }
- }
- }
-
-
- func showWatermarkController() {
- viewManager.editType = .watermark
-
- showEditToolbarView()
- editToolbarView?.editType = .watermark
- if KMWatermarkManager.defaultManager.watermarks.count == 0 {
- editToolbarView?.editSubType = .add
- } else {
- editToolbarView?.editSubType = .template
- }
- editToolbarView?.reloadData()
-
- if watermarkViewController == nil {
- watermarkViewController = KMWatermarkController.init()
- }
- watermarkViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
- watermarkViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
- watermarkViewController?.delegate = self
- bottomContendBox.contentView?.addSubview(watermarkViewController!.view)
- watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
- watermarkViewController?.reloadData()
-
- updateWatermarkDocument()
-
- watermarkViewController?.loadData()
- }
-
- func updateWatermarkDocument() {
- guard let controller = watermarkViewController else { return }
-
- var editDocument = CPDFDocument.init()
- if let vcDoc = controller.pdfDocument {
- editDocument = vcDoc
- }
-
- let page = listView.document.page(at: UInt(listView.currentPageIndex))
- editDocument?.insertPageObject(page, at: 0)
- if editDocument?.pageCount == 2 {
- let theIndex = IndexSet(integer: 1)
- editDocument?.removePage(at: theIndex)
- }
- if watermarkViewController?.pdfDocument == nil {
- watermarkViewController?.pdfDocument = editDocument
- }
- watermarkViewController?.resetUI()
- watermarkViewController?.reloadData()
- watermarkViewController?.loadData()
-
- }
-
-
- func removePDFWatermark() {
- let watermarks = self.listView.document.watermarks()
- if (watermarks == nil || watermarks!.count <= 0) {
- let alert = NSAlert()
- alert.alertStyle = .warning
- 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: "")
- alert.addButton(withTitle: KMLocalizedString("Confirm", comment: ""))
- alert.runModal()
- return
- }
-
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = KMLocalizedString("Are you sure you want to remove the watermark?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
- for watermark in watermarks! {
- listView.document.removeWatermark(watermark)
- }
- listView.layoutDocumentView()
-
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Watermark removed"),
- type: .success,
- fromView: bottomContendBox,
- point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
-
- }
- }
-
- func batchAddWatermark() {
- self.showBatchWindow(type: .watermark, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
- func batchRemoveWatermark() {
- self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.watermark.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
-
- func showBackgroundController() {
-
- viewManager.editType = .background
-
- showEditToolbarView()
- editToolbarView?.editType = .background
- if KMBackgroundManager.defaultManager.datas.count == 0 {
- editToolbarView?.editSubType = .add
- } else {
- editToolbarView?.editSubType = .template
- }
- editToolbarView?.reloadData()
-
- if backgroundViewController == nil {
- backgroundViewController = KMBackgroundController.init()
- }
- backgroundViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
- backgroundViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
- backgroundViewController?.delegate = self
- bottomContendBox.contentView?.addSubview(backgroundViewController!.view)
- backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
- backgroundViewController?.resetUI()
-
- updateBackgroundDocument()
- }
-
- func updateBackgroundDocument() {
- guard let controller = backgroundViewController else { return }
-
- controller.pdfDocument = nil
-
- let editDocument = CPDFDocument.init()
-
- let page = listView.document.page(at: UInt(listView.currentPageIndex))
- editDocument?.insertPageObject(page, at: 0)
-
- backgroundViewController?.pdfDocument = editDocument
- backgroundViewController?.reloadData()
-
- }
-
- func removePDFBackground() {
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = KMLocalizedString("Are you sure you want to remove the background?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
- let background = listView.document.background()
- background?.clear()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
-
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Background removed"),
- type: .success,
- fromView: bottomContendBox,
- point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
-
- }
- }
-
- func batchAddBackground() {
- self.showBatchWindow(type: .background, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
- func batchRemoveBackground() {
- self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.background.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
-
- func showHeaderFooterController() {
-
- viewManager.editType = .header_Footer
-
- showEditToolbarView()
- editToolbarView?.editType = .header_Footer
- if KMHeaderFooterManager.defaultManager.headFooterObjects.count == 0 {
- editToolbarView?.editSubType = .add
- } else {
- editToolbarView?.editSubType = .template
- }
- editToolbarView?.reloadData()
-
- if headerFooterViewController == nil {
- headerFooterViewController = KMHeaderFooterController.init()
- }
- headerFooterViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
- headerFooterViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
- headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
- headerFooterViewController?.delegate = self
- bottomContendBox.contentView?.addSubview(headerFooterViewController!.view)
- headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
-
- updateHeaderFooterDocument()
- }
-
- func updateHeaderFooterDocument() {
- guard let controller = headerFooterViewController else { return }
- controller.pdfDocument = nil
-
- let editDocument = CPDFDocument.init()
- let page = listView.document.page(at: UInt(listView.currentPageIndex))
- editDocument?.insertPageObject(page, at: 0)
-
- headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
- headerFooterViewController?.pdfDocument = editDocument
- headerFooterViewController?.resetUI()
- headerFooterViewController?.reloadData()
-
- }
-
- func removeHeaderFooter() {
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = KMLocalizedString("Are you sure you want to remove the Header & Footer?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
- let headerFooter = listView.document.headerFooter()
- headerFooter?.clear()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
-
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Header & Footer removed"),
- type: .success,
- fromView: bottomContendBox,
- point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
-
- }
-
- }
-
- func batchAddHeaderFooter() {
- self.showBatchWindow(type: .headerAndFooter, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
- func batchRemoveHeaderFooter() {
- self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.headerAndFooter.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
-
- func showBatesController() {
- viewManager.editType = .bates
-
- showEditToolbarView()
- editToolbarView?.editType = viewManager.editType
- if KMBatesManager.defaultManager.datas.count == 0 {
- editToolbarView?.editSubType = .add
- } else {
- editToolbarView?.editSubType = .template
- }
- editToolbarView?.reloadData()
-
- if batesViewController == nil {
- batesViewController = KMBatesController.init()
- }
- batesViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
- batesViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
- batesViewController?.delegate = self
- batesViewController?.totalPDFCount = Int(listView.document.pageCount)
- bottomContendBox.contentView?.addSubview(batesViewController!.view)
- batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
-
- updateBatesDocument()
-
- batesViewController?.resetUI()
- }
-
- func updateBatesDocument() {
- guard let controller = batesViewController else { return }
-
- controller.pdfDocument = nil
-
- let editDocument = CPDFDocument.init()
- let page = listView.document.page(at: UInt(listView.currentPageIndex))
- editDocument?.insertPageObject(page, at: 0)
-
- batesViewController?.pdfDocument = editDocument
- batesViewController?.reloadData()
-
- }
-
- func removePDFBates() {
- let alert = NSAlert()
- alert.alertStyle = .warning
- alert.messageText = KMLocalizedString("Are you sure you want to remove the Bates?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Delete", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
- let bates = listView.document.bates()
- bates?.clear()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
-
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Bates removed"),
- type: .success,
- fromView: bottomContendBox,
- point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
-
- }
-
- }
-
- func batchAddBates() {
- self.showBatchWindow(type: .batesNumber, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
- func batchRemoveBates() {
- self.showBatchWindow(type: .batchRemove, subType: KMBatchRemoveOptions.batesNumber.rawValue, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
-
-
-
-
- @objc func auto_cropPagesWhiteMargin(_ pageIndexs: [UInt]) {
- var size = NSZeroSize
- for i in pageIndexs {
- let page = self.listView.document.page(at: i)
- let rect = KMCropTools.getPageForegroundBox(page!)
- size.width = fmax(size.width, NSWidth(rect))
- size.height = fmax(size.height, NSHeight(rect))
- }
-
- var rectArray: Array<NSRect> = []
- for i in pageIndexs {
- progressC?.increment(by: Double(i))
- progressC?.doubleValue = Double(i)
- let page = self.listView.document.page(at: i)
- var rect = KMCropTools.getPageForegroundBox(page!)
- let bounds: NSRect = (page?.bounds(for: .mediaBox))!
- if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
- rect.origin.x = rect.maxX-size.width
- }
-
- rect.origin.y = rect.maxY-size.height
- rect.size = size
-
- if (NSWidth(rect) > NSWidth(bounds)) {
- rect.size.width = NSWidth(bounds)
- }
- if (NSHeight(rect) > NSHeight(bounds)) {
- rect.size.height = NSHeight(bounds)
- }
-
- if (NSMinX(rect) < NSMinX(bounds)) {
- rect.origin.x = NSMinX(bounds)
- } else if (NSMaxX(rect) > NSMaxX(bounds)) {
- rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
- }
-
- if (NSMinY(rect) < NSMinY(bounds)) {
- rect.origin.y = NSMinY(bounds)
- } else if (NSMaxY(rect) > NSMaxY(bounds)) {
- rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
- }
-
- rectArray.append(rect)
- }
- self.cropPages(atIndexs: pageIndexs, to: rectArray)
-
- }
-
- func cropPages(atIndexs pageIndexs: [UInt], to rects: Array<NSRect>) {
- let currentPage = self.listView.currentPage()
- let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
-
- var oldRectArray: Array<NSRect> = []
- let rectCount = rects.count
- for i in pageIndexs {
- if let page = self.listView.document.page(at: i) {
- let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page.bounds(for: .mediaBox)))
- let oldRect = page.bounds(for: .cropBox)
- oldRectArray.append(oldRect)
-
- page.setBounds(rect, for: .cropBox)
- }
- }
-
- let undoManager = self.listView.undoManager
- (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(atIndexs: pageIndexs, to: oldRectArray)
-
-
- self.listView.layoutDocumentView()
-
- self.listView.displayBox = .cropBox
-
- self.listView.go(to: currentPage)
- self.listView.go(to: visibleRect, on: currentPage)
-
- }
-
-
- func beginCompareAction(_ index: Int) {
- guard let filePath = self.document?.documentURL.path else { return }
- if !FileManager.default.fileExists(atPath: filePath) {
- let alert = NSAlert.init()
- alert.alertStyle = .critical
- alert.messageText = "\(filePath.lastPathComponent) \(NSLocalizedString("File Not Exist", comment: ""))"
- alert.runModal()
- return
- }
-
- let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
- self.currentWindowController = controller
- controller.password = self.document?.password ?? ""
- controller.filePath = (self.document?.documentURL.path)!
-
- controller.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
- }
-
- controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
- self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
- }
-
- controller.coveringComplete = { [unowned self] controller, document in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
- self.openCoveringCompareVC(with: document)
- }
-
- if index == 1 {
- controller.fileType = .content
- } else {
- controller.fileType = .coverting
- }
- NSWindow.currentWindow().beginSheet(controller.window!)
-
- }
-
-
- func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
- self.isCompareModel = true
-
- let compareContentView = KMCompareContentView()
- compareContentView.oldDocument = oldDocument
- compareContentView.document = document
- compareContentView.compareResults = results
- compareContentView.saveHandle = { [unowned self] view in
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
- let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
- self.currentWindowController = saveController
- saveController.cancelHandle = { [unowned self] controller in
- self.view.window!.endSheet(controller.window!)
- self.currentWindowController = nil
- }
-
- saveController.saveHandle = { [unowned self] controller, saveType in
- let folderPath = controller.fileSaveFolderPath
- if folderPath != nil {
- if !FileManager.default.fileExists(atPath: folderPath) {
- try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
- }
- #if VERSION_DMG
- #else
- let url = URL(fileURLWithPath: folderPath)
- let fileAccess = AppSandboxFileAccess()
- fileAccess?.persistPermissionURL(url)
- if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
- fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
- let urlString = url.path
- let _url = URL(fileURLWithPath: urlString)
- fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
- }
- #endif
- var savePath: String
-
- switch saveType {
- case 0:
- let filePath = oldDocument.documentURL.path
- let fileName = filePath.deletingPathExtension.lastPathComponent
-
- savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
- savePath = self.getValidFilePath(savePath)
- oldDocument.write(to: URL(fileURLWithPath: savePath))
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
- case 1:
- let filePath = document.documentURL.path
- let fileName = filePath.deletingPathExtension.lastPathComponent
-
- savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
- savePath = self.getValidFilePath(savePath)
- document.write(to: URL(fileURLWithPath: savePath))
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
- case 2:
- let filePath = oldDocument.documentURL.path
- let fileName = filePath.deletingPathExtension.lastPathComponent
-
- savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
- savePath = self.getValidFilePath(savePath)
- pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
- default:
- break
- }
- }
-
- self.view.window!.endSheet(controller.window!)
- self.currentWindowController = nil
- }
-
- NSWindow.currentWindow().beginSheet(saveController.window!)
- }
- }
-
- compareContentView.closeHandle = { [unowned self] view in
- self.isCompareModel = false
- view.removeFromSuperview()
- }
-
- contendBox.addSubview(compareContentView)
- compareContentView.frame = contendBox.bounds
- compareContentView.autoresizingMask = [.width,.height]
- }
-
- func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
- self.isCompareModel = true
-
- let coveringView = KMCompareCoveringView()
- coveringView.pdfDocument = pdfDocument
- coveringView.closeHandle = { [unowned self] view in
- self.isCompareModel = false
- view.removeFromSuperview()
- }
-
- coveringView.saveHandle = { [unowned self] view in
- let savePanel = NSSavePanel()
- savePanel.nameFieldStringValue = "untitled"
- savePanel.allowedFileTypes = ["pdf"]
- savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
- if result == .OK {
- pdfDocument.write(to: savePanel.url!)
- NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
- }
- }
- }
-
- contendBox.addSubview(coveringView)
- coveringView.frame = contendBox.bounds
- coveringView.autoresizingMask = [.width,.height]
- }
-
- func getValidFilePath(_ oldPath: String) -> String {
- let fileManager = FileManager.default
-
- do {
- let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
- guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
- return oldPath
- }
-
- var i = 1
- var newPath = oldPath
-
- while fileManager.fileExists(atPath: newPath) {
- if fileType == FileAttributeType.typeDirectory.rawValue {
- newPath = oldPath + "(\(i))"
- } else {
- let fileExtension = (oldPath as NSString).pathExtension
- newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
- }
- i += 1
- }
-
- return newPath
- } catch {
- print("Error getting file attributes: \(error)")
- return oldPath
- }
- }
-
- @IBAction func startSpeaking(_ sender: Any?) {
- self.showTTSWindow()
- let ttsView = KMTTSWindowController.share
- }
-
- @IBAction func stopSpeaking(_ sender: Any) {
- let ttsWindowC = KMTTSWindowController.share
- if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
- if let data = ttsWindowC.window?.isVisible, data {
- ttsWindowC.stopSpeaking()
- ttsWindowC.close()
- }
- }
- }
-
- func showTTSWindow() {
- var lastPDFView: CPDFView?
- let ttsView = KMTTSWindowController.share
- if (ttsView.window?.isVisible ?? false) {
- lastPDFView = ttsView.pdfView
- if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
- lastPDFView = nil
- ttsView.window?.orderOut(nil)
- } else {
- ttsView.pdfView = self.listView
- ttsView.showWindow(nil)
- }
- } else {
- ttsView.pdfView = self.listView
- ttsView.showWindow(nil)
- }
- ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
- if isCloseWindow {
-
- }
- }
-
- if let currentSelection = self.listView.currentSelection {
- if let data = currentSelection.selectionsByLine, data.isEmpty == false {
- ttsView.startSpeakingPDFSelection(currentSelection)
- }
- }
- if let lastPDFView = lastPDFView {
- lastPDFView.setHighlightedSelections([])
- ttsView.stopSpeaking()
- }
- }
-
-
- func extractImageAction(num: Int) {
- guard let filePath = self.document?.documentURL.path else { return }
- if !FileManager.default.fileExists(atPath: filePath) {
- let alert = NSAlert.init()
- alert.alertStyle = .critical
- alert.messageText = "\(filePath.lastPathComponent) \(NSLocalizedString("File Not Exist", comment: ""))"
- alert.runModal()
- return
- }
-
- if !IAPProductsManager.default().isAvailableAllFunction(){
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.kEventName = "Reading_ExtractImage_BuyNow"
- winC?.showWindow(nil)
- return
- }
-
- if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
- alert.runModal()
- return
- }
-
- let document = self.listView.document
- var fileURL = document?.documentURL
-
- if num == 1 {
- let pageCount = document?.pageCount ?? 0
- let indeSet = NSMutableIndexSet()
-
- indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
- if indeSet.count == 0 {
- return
- }
- let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
- let tFileName = (String(format: "%@_Extract Images", lastPathName))
- let outputSavePanel = NSSavePanel()
- outputSavePanel.title = KMLocalizedString("Save as PDF", comment: "")
- outputSavePanel.allowsOtherFileTypes = true
- outputSavePanel.isExtensionHidden = true
- outputSavePanel.canCreateDirectories = true
- outputSavePanel.nameFieldStringValue = tFileName
- outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
- if result == NSApplication.ModalResponse.OK {
- DispatchQueue.main.async {
- self.beginProgressSheet(withMessage: KMLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
- let tDestFile = outputSavePanel.url!.path
- let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
- let pdfconverter = PDFConvertObject()
- pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
- self.dismissProgressSheet()
- let fileManager = FileManager.default
- if fileManager.fileExists(atPath: tDestFile) {
- let workspace = NSWorkspace.shared
- let url = URL(fileURLWithPath: tDestFile)
- workspace.activateFileViewerSelecting([url])
- }
- }
- }
- })
- return
- }
-
- if fileURL != nil {
- self.myDocument?.save(nil)
- } else {
- let myDocument = self.myDocument
- let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
- let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
- if writeSuccess {
- var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
- fileURL = document?.documentURL
- } else {
- NSSound.beep()
- return
- }
- }
- extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
- extract?.docPath = fileURL?.path ?? ""
- extract?.password = document?.password ?? ""
- extract?.currentPage = self.listView.currentPageIndex
- extract?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
-
- })
- extract?.selectCurrentPageBtn()
- }
-
- func beginProgressSheet(withMessage message: String, maxValue: UInt) {
-
- let progress = SKProgressController()
- progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
- progress.window?.contentView?.wantsLayer = true
- progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
- progress.progressField.textColor = NSColor.white
- progress.message = KMLocalizedString("Converting...", comment: "")
- progressC = progress
- progressC?.message = message
- if maxValue > 0 {
- progressC?.indeterminate = false
- progressC?.maxValue = Double(maxValue)
- progressC?.progressBar.doubleValue = 0.3
- } else {
- progressC?.indeterminate = true
- }
- progressC?.own_beginSheetModal(for: self.view.window, completionHandler: { result in
-
- })
- }
-
- func dismissProgressSheet() {
- progressC?.stopAnimation()
- progressC?.own_closeEndSheet()
- progressC = nil
- }
-
-
- internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
- self.saveDocument()
- if (self.listView.document != nil && !self.listView.document.allowsPrinting) {
- KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
- if (result == .cancel) {
- return
- }
-
- self?.listView.document.unlock(withPassword: password)
-
- self?.hiddenSecureLimitTip()
-
- KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
- }
- return
- }
- KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
- }
-
-
- func showPosterPrintWindow() {
- guard let document = self.document else { return }
- guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
-
- if self.posterPrintWindowController == nil {
- posterPrintWindowController = KMPDFPosterPrintWindowController.init(pdfDocument: pdfDocument)
- }
- if let window = posterPrintWindowController?.window {
- NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
-
- })
- }
- }
-
-
- func showMultiplePrintWindow() {
- guard let document = self.document else { return }
- guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
-
- if self.multiplePrintWindowController == nil {
- multiplePrintWindowController = KMPDFMultiplePrintWindowController.init(pdfDocument: pdfDocument)
- }
- if let window = multiplePrintWindowController?.window {
- NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
-
- })
- }
- }
-
- func showBookletPrintWindow() {
- guard let document = self.document else { return }
- guard let pdfDocument = PDFDocument(url: document.documentURL) else { return }
-
- if self.bookletWindowController == nil {
- bookletWindowController = KMPDFBookletWindowController.init(document: pdfDocument)
- }
- if let window = bookletWindowController?.window {
- NSApp.mainWindow?.beginSheet(window, completionHandler: { response in
-
- })
- }
- }
-
-
- func showFileInfo() {
- KMInfoWindowController.shared.showWindow(nil)
- }
-
-
- @objc private func shareDocument(sender: NSView) {
- let document = self.listView.document ?? CPDFDocument()
- if document?.documentURL == nil {
- return
- }
- var doucumentURL : URL = self.listView.document.documentURL
- if doucumentURL.path.count > 0 {
- let docDir = NSTemporaryDirectory()
- let documentName : String = doucumentURL.path.lastPathComponent
- let path = docDir.stringByAppendingPathComponent(documentName)
- let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
- if writeSuccess == false {
- __NSBeep()
- return;
- }
- doucumentURL = URL(fileURLWithPath: path)
- }
- let array = [doucumentURL]
- let picker = NSSharingServicePicker.init(items: array)
- if sender.window != nil {
- picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
- } else {
- 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)
- }
- }
-
- @objc private func shareFlatten(sender: NSView) {
- let document = self.listView.document ?? CPDFDocument()
- var path: String?
- if document?.documentURL != nil {
- path = document?.documentURL.path ?? ""
- }
- if path?.count ?? 0 > 0 {
- let docDir = NSTemporaryDirectory()
- let documentName : String = path?.lastPathComponent ?? ""
- path = docDir.stringByAppendingPathComponent(documentName)
- }
- let pathFolder = path?.fileURL.deletingLastPathComponent().path
- var tfileName = path?.deletingPathExtension.lastPathComponent
- let tStdFileSuffix = "_flatten"
- tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
- path = (pathFolder ?? "") + "/" + (tfileName ?? "")
- let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
- if success {
- let url = URL(fileURLWithPath: path ?? "")
- let picker = NSSharingServicePicker.init(items: [url])
- if sender.window != nil {
- picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
- } else {
- 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)
- }
- }
- }
-
- @objc private func shareOriginalPDF(sender: NSView) {
- guard let pdfDoc = self.listView.document else {
- NSSound.beep()
- return
- }
- if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
- alert.runModal()
- return
- }
-
- let document = self.listView.document ?? CPDFDocument()
- var path: String?
- if document?.documentURL != nil {
- path = document?.documentURL.path ?? ""
- }
- if path?.count ?? 0 > 0 {
- let docDir = NSTemporaryDirectory()
- let documentName : String = path?.lastPathComponent ?? ""
- path = docDir.stringByAppendingPathComponent(documentName)
- }
- var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
- if writeSuccess == false {
- __NSBeep()
- return;
- }
- let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
-
- let cnt = newDocument?.pageCount ?? 0
- for i in 0 ..< cnt {
- let page = newDocument!.page(at: i)
- var annotations : [CPDFAnnotation] = []
- for annotation in page!.annotations {
- annotations.append(annotation)
- }
- for annotation in annotations {
- annotation.page.removeAnnotation(annotation)
- }
- }
- writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
- if writeSuccess ?? false {
- let url = URL(fileURLWithPath: path ?? "")
- let picker = NSSharingServicePicker.init(items: [url])
- if sender.window != nil {
- picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
- } else {
- 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)
- }
- }
- }
-
- @objc func shareFromService(sender: NSMenuItem) {
- if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
- return
- }
-
- var string = ""
- if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
- string = freeTextAnnotation.contents ?? ""
- } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
- if let page = markupAnnotation.page {
- if let selection = page.selection(for: markupAnnotation.bounds) {
- string = selection.string() ?? ""
- }
- }
- } else {
- string = listView.currentSelection?.string() ?? ""
- }
-
- let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
- let model = windowControler.browser?.tabStripModel
- if let cnt = model?.count(), cnt <= 0 {
- return
- }
-
- if let data = model?.activeTabContents().isHome, data {
- return
- }
-
- let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
- if string.count > 0 {
- let represent : NSSharingService = sender.representedObject as! NSSharingService
- represent.perform(withItems: [string])
- return
- }
-
- let represent = sender.representedObject as? NSSharingService
- represent?.perform(withItems: [string])
- }
-
-
- func clickPresentationMenu(point:NSPoint)->KMNMenuStruct {
- var viewHeight: CGFloat = 8
- var menuItemArr: [ComponentMenuitemProperty] = []
-
- var items: [(String, String)] = []
- items.append(("Next Page", PDFViewMenuIdentifier_PageNext))
- items.append(("Previous Page", PDFViewMenuIdentifier_PagePrevious))
- items.append(("First", PDFViewMenuIdentifier_PageFirst))
- items.append(("Last", PDFViewMenuIdentifier_PageLast))
- items.append(("", ""))
- items.append(("Laser pointer", PDFViewMenuIdentifier_Presentation_LaserPoint))
- items.append(("Brush", PDFViewMenuIdentifier_Presentation_Brush))
- items.append(("", ""))
- items.append(("Exit Presentation", PDFViewMenuIdentifier_Presentation_Exit))
-
- for (i, value) in items {
- if value.count == 0 {
- let property: ComponentMenuitemProperty = ComponentMenuitemProperty.divider()
- menuItemArr.append(property)
- viewHeight += 8
- } else {
- let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
- itemSelected: false,
- isDisabled: false,
- keyEquivalent: nil,
- text: KMLocalizedString(i),
- identifier: value,representedObject: point)
-
- if value == PDFViewMenuIdentifier_PageNext {
- properties_Menuitem.keyEquivalent = "▶"
- } else if value == PDFViewMenuIdentifier_PagePrevious {
- properties_Menuitem.keyEquivalent = "◀"
- } else if value == PDFViewMenuIdentifier_PageFirst {
- properties_Menuitem.keyEquivalent = "⌘ ◀"
- } else if value == PDFViewMenuIdentifier_PageLast {
- properties_Menuitem.keyEquivalent = "⌘ ▶"
- } else if value == PDFViewMenuIdentifier_Presentation_Exit {
- properties_Menuitem.keyEquivalent = "ESC"
- }
-
- if(value == PDFViewMenuIdentifier_Presentation_LaserPoint) {
- if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
- } else {
- properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
- }
- } else if value == PDFViewMenuIdentifier_Presentation_Brush {
- if((listView.presentationDrawView != nil) && listView.presentationDrawView.isHidden == false) {
- properties_Menuitem.righticon = NSImage(named: "KMNImageNameMenuSelect")
- } else {
- }
- }
-
- menuItemArr.append(properties_Menuitem)
- viewHeight += 36
- }
- }
-
- let menuStruct = KMNMenuStruct(menuitems: menuItemArr, viewHeight: viewHeight)
-
- return menuStruct
- }
-
- func gotoPage(_ sender: Any?) {
- var pages : [String] = []
- for i in 0 ..< self.listView.document.pageCount {
- pages.append("\(i)")
- }
- self.textFieldSheet.callback = { [weak self] stringValue in
- guard let index = Int(stringValue) else {
- return
- }
- if (self?.listView == nil) {
- return
- }
- if (index > 0 && index <= self!.listView.document.pageCount) {
- self?.listView.go(toPageIndex: index-1, animated: true)
- }
- }
- self.textFieldSheet.showWindow(nil)
- self.textFieldSheet.pageBox.addItems(withObjectValues: pages)
- self.textFieldSheet.stringValue = "\(self.listView.currentPageIndex+1)"
- }
-
-
-
- @objc func menuItemBookMarkClick_add(sender:NSMenuItem?) {
- toggleOpenLeftSide(pdfSideBarType: .bookmark)
- viewManager.pdfSideBarType = .bookmark
- sideBarController?.reloadData()
-
- if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
- let index = self.listView.currentPageIndex
- self.listView.document?.addBookmark("\(KMLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
- self.listView.updateRender(true)
- } else {
- self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
- self.listView.updateRender(true)
- }
-
- botaViewController?.reloadData()
-
- self.listView.undoManager?.setActionName("")
- }
-
-
- func rotateLeft(page:CPDFPage,listView:CPDFListView?) {
- Task { @MainActor in
- let rotation = page.rotation
- page.leftRotate()
- listView?.layoutDocumentView()
-
- if(listView == self.listView) {
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(page.pageIndex()))
- KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
- botaViewController?.reloadData()
- }
-
- }
- }
-
- func rotateRight(page:CPDFPage,listView:CPDFListView?) {
- Task { @MainActor in
- let rotation = page.rotation
- page.rightRotate()
- listView?.layoutDocumentView()
-
- if(listView == self.listView) {
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(page.pageIndex()))
- KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
- botaViewController?.reloadData()
- }
-
- }
- }
-
-
- func isAutoFlowOn() -> Bool {
- return listView.isAutoFlow()
- }
-
- func toggleAutoFlow(_ sender: Any?) {
- if (listView.isAutoFlow()) {
- listView.stopAutoFlow()
- } else {
- listView.startAutoFlow()
- }
- }
-
-
- func highlightFormFiled(_ sender: Any?) {
- let enabled = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
- CPDFKitConfig.sharedInstance().setEnableFormFieldHighlight(!enabled)
-
- listView.setNeedsDisplayForVisiblePages()
- self.alertTipViewController.reloadFormAlertUI()
- }
-
-
- func highlightLinks(_ sender: Any?) {
- let enabled = CPDFKitConfig.sharedInstance().enableLinkFieldHighlight()
- CPDFAnnotation.updateLinkFieldHighlight(listView, linkFieldHighlight: !enabled)
- }
-
-
- func resetForm(_ sender: Any?) {
- listView.resetFormAnnotation()
- }
-
-
- @IBAction func menuItemAction_property(_ sender: Any?) {
- showFileInfo()
- }
-
-
- @IBAction func menuItemAction_print(_ sender: Any?) {
- self.showPrintWindow()
- }
-
-
- func updateUndoRedoState() {
- let undo: Bool = self.listView.undoManager?.canUndo ?? false
- let redo: Bool = self.listView.undoManager?.canRedo ?? false
-
- toolbarManager.undoProperty.isDisabled = undo ? false : true
- toolbarManager.redoProperty.isDisabled = redo ? false : true
-
- pdfToolbarController?.reloadUndoRedoButtonState()
- }
-
-
- func saveAsFlattenedPDFAction() {
- DispatchQueue.main.async {
- NSPanel.savePanel(self.view.window!, true) { panel in
- panel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_flatten" + ".pdf"
- } completion: { response, url, isOpen in
- if (response == .cancel) {
- return
- }
-
- var result = self.listView.document.writeFlatten(to: url!)
- if (!result) {
- return
- }
-
- if (isOpen) {
- NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
-
- }
- } else {
- NSWorkspace.shared.activateFileViewerSelecting([url!])
- }
- }
- }
- }
-
- func showInFinder() {
- NSWorkspace.shared.activateFileViewerSelecting([self.listView.document.documentURL])
- }
-
-
- func getPDFViewPageLayoutType() -> pageLayoutType {
- if listView.displayMode() == .singlePage {
- return .singlePage
- } else if listView.displayMode() == .singlePageContinuous {
- return .singlePageContinue
- } else if listView.displayMode() == .twoUp {
- if listView.displaysAsBook == true {
- return .bookMode
- }
- return .twoPage
- } else if listView.displayMode() == .twoUpContinuous {
- if listView.displaysAsBook == true {
- return .bookMode
- }
- return .twoPageContinue
- }
- return .singlePage
- }
-
- func updatePDFViewDisplayMode(viewMode mode: CPDFDisplayViewMode = .singlePage, isbookMode bookMode: Bool = false, direction directionValue: CPDFDisplayDirection? = nil) {
- if bookMode == true {
-
- listView.displaysAsBook = true
- listView.displayTwoUp = true
-
- if let value = directionValue {
- listView.displayDirection = value
- }
- } else {
- listView.setDisplay(mode)
- }
- listView.layoutDocumentView()
- }
-
-
- @objc func addOutLineItemAction() {
- toggleOpenLeftSide(pdfSideBarType: .outline)
-
- botaViewController?.outlineViewC.addOutline()
- }
-
-
- @objc func searchBaiduAction() {
- let label = self.listView.currentSelection?.string() ?? ""
- let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
- if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
- NSWorkspace.shared.open(url)
- }
- }
-
-
- func showConvertWindow(_ convertType: KMPDFConvertType) {
-
- var winC: KMConvertBaseWindowController = KMConvertBaseWindowController()
- let model = KMDocumentModel(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- if convertType == .word {
- winC = KMConvertWordWindowController()
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .ppt {
- winC = KMConvertPPTsWindowController()
- winC.subType = 1
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .rtf {
- winC = KMConvertPPTsWindowController()
- winC.subType = 2
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .text {
- winC = KMConvertPPTsWindowController()
- winC.subType = 4
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .csv {
- winC = KMConvertCSVWindowController()
- winC.subType = 5
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .excel {
- winC = KMConvertExcelWindowController()
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .html {
- winC = KMConvertHtmlWindowController()
- winC.documentModel = model
- winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- } else if convertType == .json {
- winC = KMConvertJsonWindowController()
- winC.documentModel = model
- winC.own_beginSheetModal(for: view.window, completionHandler: nil)
- } else if convertType == .jpeg ||
- convertType == .jpg ||
- convertType == .png ||
- convertType == .gif ||
- convertType == .tiff ||
- convertType == .tga ||
- convertType == .bmp ||
- convertType == .jp2{
- winC = KMConvertImageWindowController()
- winC.documentModel = model
- winC.own_beginSheetModal(for: view.window, completionHandler: nil)
- if let settingView = winC.settingView as? KMConvertImageSettingView {
- settingView.selectConvertType(convertType: convertType)
- }
- }
-
- winC.batchAction = { [unowned self] in
- let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- self.showBatchWindow(type: .convertPDF, subType: convertType.rawValue, files: [], fileModels: [model])
- }
- }
-
-
- @objc func selectAllFormAnnotation (currentPage:CPDFPage) {
- var formActiveAnnotations:[CPDFAnnotation] = []
- for i in 0 ..< listView.document.pageCount {
- let page = listView.document.page(at: i)
- if(page?.pageIndex() == currentPage.pageIndex()) {
- let annotations = page?.annotations
- for j in 0 ..< (annotations?.count ?? 0) {
- if let an = annotations?[j] as? CPDFAnnotation {
- if (an.isKind(of: CPDFWidgetAnnotation.self) == true) {
- formActiveAnnotations.append(an)
- }
- }
- }
- }
- }
- listView.updateActiveAnnotations(formActiveAnnotations)
- }
-
- @objc func selectAllNomerAnnotation (currentPage:CPDFPage) {
- var normalActiveAnnotations:[CPDFAnnotation] = []
- for i in 0 ..< listView.document.pageCount {
- let page = listView.document.page(at: i)
- if(page?.pageIndex() == currentPage.pageIndex()) {
- let annotations = page?.annotations
- for j in 0 ..< (annotations?.count ?? 0) {
- if let an = annotations?[j] as? CPDFAnnotation {
- if an.isKind(of: CPDFWidgetAnnotation.self) == true ||
- an.isKind(of: CPDFLinkAnnotation.self) == true ||
- an.isKind(of: CPDFRedactAnnotation.self) == true {
- } else {
- normalActiveAnnotations.append(an)
- }
- }
- }
- }
- }
- listView.updateActiveAnnotations(normalActiveAnnotations)
- }
-
- @objc func selectAllRedactAnnotation (currentPage:CPDFPage) {
- var selectAllRedactAnnotation: [CPDFAnnotation] = []
- for i in 0 ..< listView.document.pageCount {
- let page = listView.document.page(at: i)
- if(page?.pageIndex() == currentPage.pageIndex()) {
-
- let annotations = page?.annotations
- for j in 0 ..< (annotations?.count ?? 0) {
- if let an = annotations?[j] as? CPDFAnnotation {
- if an.isKind(of: CPDFRedactAnnotation.self) == true {
- selectAllRedactAnnotation.append(an)
- }
- }
- }
- }
- }
- listView.updateActiveAnnotations(selectAllRedactAnnotation)
- listView.setNeedsDisplayForVisiblePages()
- }
-
-
- func showSearchPopWindow(type: KMNBotaSearchType, keyborad: String?, replaceText: String?, results: [KMSearchMode]) {
- if (self.currentWindowController != nil) && ((self.currentWindowController as? KMSearchReplaceWindowController) != nil) {
- return
- }
-
- let toolMode = self.listView.toolMode
- let isEditing = self.listView.isEditing()
-
- var winH: CGFloat = 112
- if type == .replace {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.kEventName = "Reading_ReplaceText_BuyNow"
- winC?.showWindow(nil)
- return
- }
-
- if toolMode == .CEditPDFToolMode && isEditing {
-
- } else {
- viewManager.toolMode = .Edit
- updatePDFViewAnnotationMode()
- }
- winH = 208
- }
-
- self.view.window?.makeFirstResponder(nil)
- let winC = KMSearchReplaceWindowController(with: listView, type: type)
- self.currentWindowController = winC
-
- winC.replaceCallback = { [weak self] in
- let toolMode = self?.listView.toolMode ?? .none
- let isEditing = self?.listView.isEditing() ?? false
- if toolMode == .CEditPDFToolMode && isEditing {
-
- } else {
- self?.viewManager.toolMode = .Edit
- self?.updatePDFViewAnnotationMode()
- }
- }
- winC.itemClick = { [weak self] idx, params in
- if idx == 1 {
- self?.toggleOpenLeftSide(pdfSideBarType: .search)
-
- guard let handdler = params.first as? KMNSearchHanddler else {
- return
- }
- let viewC = self?.botaViewController?.searchViewC
- viewC?.update(keyborad: handdler.searchKey, replaceKey: handdler.replaceKey, results: handdler.searchSectionResults)
- }
- }
-
- winC.closeCallback = { [weak self] in
- if (self?.currentWindowController != nil) {
- self?.currentWindowController = nil
- }
- }
-
- let targetView = self.pdfToolbarController?.leftViewButton
- let point = targetView?.convert(targetView?.frame.origin ?? .zero, to: nil) ?? .zero
-
- let x = point.x + (self.view.window?.frame.origin.x ?? 0) - 32
- let y = point.y + (self.view.window?.frame.origin.y ?? 0) - winH - 32
-
- let winFramePoint = NSPoint(x: x, y: y)
- winC.window?.setFrameOrigin(winFramePoint)
-
- winC.update(keyborad: keyborad, replaceKey: replaceText, results: results)
- self.view.window?.addChildWindow(winC.window!, ordered: .above)
- }
-
- func searchPDF() {
-
- }
-
- func find_ReplacePDF() {
-
- }
-
- func fineNext() {
-
- }
-
- func findPrevious() {
-
- }
-
- func useSelectionForFind() {
-
- }
-
-
-
-
- func refreshMeasureInfo() {
- if distanceMeasureInfoWindowController == nil {
- distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
- }
-
- if perimeterMeasureInfoWindowController == nil {
- perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
- }
-
- if areaMeasureInfoWindowController == nil {
- areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
- }
-
- showMeasureFloatingWindowsIfNeed()
-
- }
-
- @objc func cancelMeasureType() {
- self.hideMeasureFloatingWindows()
-
- }
-
- func hideMeasureFloatingWindows() {
- if distanceMeasureInfoWindowController?.window?.isVisible == true {
- distanceMeasureInfoWindowController?.hideFloatingWindow()
- } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
- perimeterMeasureInfoWindowController?.hideFloatingWindow()
- } else if areaMeasureInfoWindowController?.window?.isVisible == true {
- areaMeasureInfoWindowController?.hideFloatingWindow()
- }
- }
-
- func showMeasureFloatingWindowsIfNeed() {
- cancelMeasureType()
-
- let toolMode = self.listView.toolMode
- if toolMode != .CNoteToolMode {
- return
- }
-
- if let data = self.listView.activeAnnotation as? CPDFPolylineAnnotation {
- } else if let data = self.listView.activeAnnotation as? CPDFPolygonAnnotation {
-
- } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
-
- } else {
- let type = self.listView.annotationType
- if type == .measureLine {
- distanceMeasureInfoWindowController?.measureInfo = listView.distanceMeasureInfo
- distanceMeasureInfoWindowController?.window?.orderFront(nil)
- } else if type == .measurePolyLine {
- perimeterMeasureInfoWindowController?.measureInfo = listView.perimeterMeasureInfo
- perimeterMeasureInfoWindowController?.window?.orderFront(nil)
- } else if type == .measurePolyGon {
- areaMeasureInfoWindowController?.measureInfo = listView.polygonAreaMeasureInfo
- areaMeasureInfoWindowController?.window?.orderFront(nil)
- } else if type == .measureSquare {
- areaMeasureInfoWindowController?.measureInfo = listView.squareAreaMeasureInfo
- areaMeasureInfoWindowController?.window?.orderFront(nil)
- } else {
- cancelMeasureType()
- }
- }
- }
-
- func showMeasureSettingWindow() {
- let distanceSettingWC = CDistanceSettingWindowController(measureInfo: self.listView.distanceMeasureInfo)
- self.distanceMeasureInfoWindowController?.hideFloatingWindow()
- distanceSettingWC.delegate = self
- distanceSettingWC.own_beginSheetModal(for: self.view.window) { string in
-
- }
- }
- }
- extension KMMainViewController {
-
- func showCompressController(model: KMBatchProcessingTableViewModel) {
- let filePath = model.filePath
- if !FileManager.default.fileExists(atPath: filePath) {
- let alert = NSAlert.init()
- alert.alertStyle = .critical
- alert.messageText = "\(filePath.lastPathComponent) \(NSLocalizedString("File Not Exist", comment: ""))"
- alert.runModal()
- return
- }
-
- let document = CPDFDocument(url: model.filePath.fileURL)
- document?.unlock(withPassword: model.password)
-
- if !document!.allowsPrinting && !document!.allowsCopying {
- KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: .owner, url: document!.documentURL) { [unowned self] result, password in
- if (result == .success) {
- model.password = password ?? ""
- model.isLock = false
- self.showCompress(model: model)
- }
- }
- } else {
- self.showCompress(model: model)
- }
- }
-
- func showCompress(model: KMBatchProcessingTableViewModel) {
- self.compressWindowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
- self.compressWindowController?.password = model.password
- self.compressWindowController?.documentURL = model.filePath.fileURL
-
- let controllerWindow = self.view.window
- controllerWindow?.beginSheet(self.compressWindowController!.window!)
-
- self.compressWindowController?.itemClick = { [unowned self] in
- controllerWindow?.endSheet((self.compressWindowController?.window)!)
-
- }
-
- self.compressWindowController?.batchAction = { [unowned self] view, filePaths in
- controllerWindow?.endSheet((self.compressWindowController?.window)!)
- self.showBatchWindow(type: .compress, files: filePaths)
- }
-
- self.compressWindowController?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
- controllerWindow?.endSheet((self.compressWindowController?.window)!)
- if (result) {
-
- if (openDocument) {
- NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
- } else {
- NSWorkspace.shared.activateFileViewerSelecting([fileURL])
- }
- } else {
- let alert = NSAlert()
- alert.messageText = KMLocalizedString("Compress Faild", comment: "")
- alert.runModal()
- }
- }
- }
- }
- extension KMMainViewController {
-
- func showOCRWindow() {
- if !IAPProductsManager.default().isAvailableAllFunction(){
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
- let window = KMOCRSettingWindowController(windowNibName: "KMOCRSettingWindowController")
- window.OCRAction = {[unowned self] controller, model in
- self.convertOCRScanFile(window: window, document: self.listView.document, model: model)
- }
-
- window.cancelAction = {[unowned self] controller in
- self.view.window?.endSheet(window.window ?? NSWindow())
- }
-
- self.view.window?.beginSheet(window.window ?? NSWindow())
-
- }
-
- func showOCREditAlert() {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
- alertTipViewController.showInView(listView: listView, subView: infoSplitCenterView)
- alertTipViewController.reloadOCRAlertUI()
- alertTipViewController.reloadAlertUIFrame()
-
- alertTipViewController.OCRApplyCallback = { [unowned self] in
- self.showOCRWindow()
- }
- }
- }
-
- func closeOCREditAlert() {
- guard let view = alertTipViewController.OCRComponentAlert else { return }
- alertTipViewController.reloadOCRAlertUI()
- alertTipViewController.reloadAlertUIFrame()
- }
-
- func showOCRToolAlert(_ string: String) {
- let alertView = ComponentMessage()
- alertView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString(string))
- alertView.frame = CGRectMake((CGRectGetWidth(self.listView.frame) - alertView.properties.propertyInfo.viewWidth) / 2,
- CGRectGetHeight(self.listView.frame) - alertView.properties.propertyInfo.viewHeight - 8,
- alertView.properties.propertyInfo.viewWidth,
- alertView.properties.propertyInfo.viewHeight)
- alertView.reloadData()
- self.listView.addSubview(alertView)
-
-
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
- self.removeOCRToolAlert(alertView)
- }
- }
-
- private func removeOCRToolAlert(_ alertView: NSView) {
-
- NSAnimationContext.runAnimationGroup({ context in
- context.duration = 0.3
- alertView.animator().alphaValue = 0
- }, completionHandler: {
- alertView.removeFromSuperview()
- })
- }
-
-
- func convertOCRScanFile(window: KMOCRSettingWindowController, document: CPDFDocument, model: KMOCRModel) {
- KMCompressManager.shared.showLoadingWindow(window: window.window)
- KMCompressManager.shared.cancelAction = {
- KMOCRManager.manager.cancelRecognition()
- }
-
- if model.pageRangeType == .current {
- model.pageRange = [self.listView.currentPageIndex]
- }
-
- KMOCRManager.manager.convertScanFile(document: document, model: model, progress: { progress in
- KMCompressManager.shared.updateLoadingProgress(value: progress)
- }) { [weak self] document, text, error in
- KMCompressManager.shared.dismissLoadiingWindow(window: window.window)
- window.endLoading()
- window.km_quick_endSheet()
- if !model.saveAsPDF {
- self?.listView.layoutDocumentView()
- self?.needSave = true
- }
- }
- }
-
- func convertOCR(document: CPDFDocument, model: KMOCRModel) {
-
-
- if model.pageRangeType == .current {
- model.pageRange = [self.listView.currentPageIndex]
- }
-
- KMOCRManager.manager.clearOCRTextData()
- KMOCRManager.manager.convertOCR(document: document, model: model, beginProgress: { [weak self] progress in
- KMCompressManager.shared.showLoadingWindow(window: self?.view.window)
- }, progress: { [weak self] progress in
- KMCompressManager.shared.updateLoadingProgress(value: progress)
- }) { [weak self] document, text, error in
- if !model.saveAsPDF {
- self?.listView.layoutDocumentView()
-
- self?.needSave = true
- }
- KMCompressManager.shared.dismissLoadiingWindow(window: self?.view.window)
- }
-
- KMCompressManager.shared.cancelAction = {
- KMOCRManager.manager.cancelRecognition()
- }
- }
-
- func convertOCRSaveAsTXT(text: String) {
- NSPanel.savePanel(NSWindow.currentWindow()) { panel in
- let url: URL = self.listView.document.documentURL
- panel.nameFieldStringValue = ""+url.deletingPathExtension().lastPathComponent+"_OCR"
- panel.allowedFileTypes = ["txt"]
- } completion: { [unowned self] response, url in
- if (response == .cancel) {
- return
- }
- let saveAsPDFFilePath = url?.path ?? ""
- let outputURL = URL(fileURLWithPath: saveAsPDFFilePath)
- try? text.write(to: outputURL, atomically: true, encoding: .utf8)
- }
- }
-
- func convertSelectionRectOCR(rect: NSRect) {
- let rect = NSIntegralRect(rect)
- let orgPage : CPDFPage = listView.currentSelectionPage() ?? CPDFPage()
-
- if let page : CPDFPage = orgPage.copy() as? CPDFPage {
- KMCompressManager.shared.showLoadingWindow(window: self.view.window)
- KMCompressManager.shared.cancelAction = {
- KMOCRManager.manager.cancelRecognition()
- }
-
- page.setBounds(rect, for: .cropBox)
- let image = page.thumbnail(of: rect.size) ?? NSImage()
- guard let model = self.rightSideController?.tool_OCRController?.model else { return }
- model.pageRange = [Int(orgPage.pageIndex())]
- KMOCRManager.manager.clearOCRTextData()
- KMOCRManager.manager.convertOCR(images: [image], model: model, progress: { progress in
- KMCompressManager.shared.updateLoadingProgress(value: progress)
- }) { [weak self] document, text, error in
- KMCompressManager.shared.dismissLoadiingWindow(window: self?.view.window)
- self?.rightSideController?.tool_OCRController?.model.text = text ?? ""
- self?.rightSideController?.tool_OCRController?.reloadData()
-
- }
- }
- }
- }
- extension KMMainViewController {
- func showBatchWindow(type: KMBatchCollectionViewType, fileModels: [KMBatchProcessingTableViewModel]?) {
- self.showBatchWindow(type: type, subType: 0, files: [], fileModels: fileModels ?? [])
- }
-
- func showBatchWindow(type: KMBatchCollectionViewType, files: [URL]?) {
- self.showBatchWindow(type: type, subType: 0, files: files ?? [], fileModels: [])
- }
-
- func showBatchWindow(type: KMBatchCollectionViewType, subType: Int = 0, files: [URL] = [], fileModels: [KMBatchProcessingTableViewModel] = []) {
- let batchWindowController = KMBatchWindowController.manager
- batchWindowController.window?.makeKeyAndOrderFront("")
-
- if files.count != 0 {
- batchWindowController.inputData = files
- }
- if fileModels.count != 0 {
- batchWindowController.inputDataModel = fileModels
- }
- batchWindowController.type = type
- batchWindowController.inputSubType = subType
- }
- }
- extension KMMainViewController: NSSplitViewDelegate {
-
- func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
- if splitView == infoContendSplitView {
- return subview.isEqual(to: infoSplitCenterView) == false
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
- if splitView == infoContendSplitView {
- if(subview.isEqual(to: infoSplitLeftView)) {
-
- } else if(subview.isEqual(to: infoSplitRightView)) {
-
- }
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
- if splitView == infoContendSplitView {
- return splitView == infoContendSplitView
- } else if splitView == pdfSplitView {
- return splitView == pdfSplitView
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
- if splitView == infoContendSplitView {
- if dividerIndex == 0 {
- if viewManager.showDisplayView {
- return MIN_SIDE_PANE_WIDTH.doubleValue
- }
- return infoContendSplitView.bounds.width/2
- } else if (dividerIndex == 1) {
- return proposedMaximumPosition - MIN_SIDE_PANE_WIDTH.doubleValue
- }
- }
- return proposedMaximumPosition
- }
-
- func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
- if(splitView == infoContendSplitView && dividerIndex == 0) {
- return proposedMinimumPosition + MIN_SIDE_PANE_WIDTH.doubleValue
- }
- return proposedMinimumPosition
- }
-
- func splitView(_ splitView: NSSplitView, shouldAdjustSizeOfSubview view: NSView) -> Bool {
- if splitView == infoContendSplitView {
- if view == splitView.subviews[0] || view == splitView.subviews[2] {
- return false
- }
- }
- return true
- }
-
- func splitViewDidResizeSubviews(_ notification: Notification) {
- let splitView = notification.object as? NSSplitView
- if(splitView == infoContendSplitView) {
- leftSplitViewResizeFinish()
-
- if(newMwcFlags.settingUpWindow == false && self.view.window?.frameAutosaveName != nil) {
- let leftWidth = infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) ? 0.0 : infoSplitLeftView.frame.width
- UserDefaults.standard.set(leftWidth, forKey: CPDFViewLeftSidePaneWidthKey)
- UserDefaults.standard.synchronize()
- }
- if listView.isEditing() == false {
- updateAnnotationsPopWinodwFrame()
- } else {
- updateContentEditPopWinodwFrame()
- }
- }
-
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(splitViewResizeFinish), object: nil)
- self.perform(#selector(splitViewResizeFinish), with: nil, afterDelay: 0.15)
- }
-
- @objc func leftSplitViewResizeFinish() {
- botaViewController?.changeLeftSideBounds()
- }
-
- @objc func splitViewResizeFinish() {
- if infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) {
- if viewManager.pdfSideBarType != .none {
- sideBarController?.reloadBOTAData()
- }
- }
- }
-
- }
- extension KMMainViewController: KMPDFSideBarControllerDelegate {
- func kmPDFSideBarControllerDidSidebarTypeUpdated(_ view: KMPDFSideBarController) {
- if viewManager.pdfSideBarType == .none {
- toggleCloseLeftSide()
- } else {
- toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
- }
- }
-
- func kmPDFSideBarControllerDidGotoPage(_ view: KMPDFSideBarController, _ pageIndex: Int) {
- listView.go(toPageIndex: pageIndex, animated: true)
-
- }
-
- }
- extension KMMainViewController: KMPDFToolbarControllerDelegate {
-
-
- func kmPDFToolbarControllerDidViewToolsChanged(_ controller: KMPDFToolbarController) {
- let viewToolsType = viewManager.viewToolsType
-
- if viewToolsType == .Select {
- listView.toolMode = .CNoteToolMode
- } else if viewToolsType == .Scroll {
- listView.toolMode = .CMoveToolMode
- } else if viewToolsType == .Content_Selection {
- listView.toolMode = .CSelectToolMode
- } else if viewToolsType == .Magnify {
- listView.toolMode = .CMagnifyToolMode
- } else if viewToolsType == .AreaZoom {
- listView.toolMode = .CSelectZoomToolMode
- }
-
- refreshToolbarViewHeightInfo()
- }
-
-
- func kmPDFToolbarControllerDidToolModeChanged(_ controller: KMPDFToolbarController) {
- refreshToolbarViewHeightInfo()
-
- toolbarViewModeChanged()
- }
-
-
- func kmPDFToolbarControllerDidToolbarItemClickedEnable(_ controller: KMPDFToolbarController, _ itemIdentifier: String) -> Bool {
- if viewManager.subToolMode == .Edit_Crop && itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
- if rightSideController?.edit_cropController?.cropEnable() == true {
-
- let alert = NSAlert()
- alert.messageText = KMLocalizedString("There are unapplied settings, do you want to apply them?", comment: "")
- alert.informativeText = KMLocalizedString("If not, the changes will be lost.", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Apply", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
-
- if let button = self.rightSideController?.edit_cropController?.cropButton {
- self.rightSideController?.edit_cropController?.cropButtonClicked(button)
- }
- } else if (result == .alertSecondButtonReturn) {
-
- return true
- }
- return false
- }
- }
- return true
- }
-
- func kmPDFToolbarControllerDidToolbarItemClicked(_ controller: KMPDFToolbarController, _ itemIdentifier: String) {
-
- print("toolbar点击", itemIdentifier)
-
- if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_PageEdit_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_PageEdit_InsertFile_Identifier {
- pageEditViewController?.insertFromPDFAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertBlank_Identifier {
- pageEditViewController?.insertFromBlankAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertClip_Identifier {
- pageEditViewController?.insertFromClipboardAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertScanner_Identifier {
- pageEditViewController?.insertFromScannerAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Extract_Identifier {
- pageEditViewController?.extractPDFAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Replace_Identifier {
- pageEditViewController?.replacePDFAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Split_Identifier {
- pageEditViewController?.splitPDFAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Reverse_Identifier {
- pageEditViewController?.reversePDFAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_LeftRotate_Identifier {
- pageEditViewController?.rotatePageLeftAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_RightRotate_Identifier{
- pageEditViewController?.rotatePageRightAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Delete_Identifier {
- pageEditViewController?.deletePageAction()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Reduce_Identifier {
- pageEditViewController?.zoomOutPageAction()
- if(pageEditViewController?.canZoomInPageSize() == false) {
- toolbarManager.page_Increase_Property.isDisabled = true
- } else {
- toolbarManager.page_Increase_Property.isDisabled = false
- }
- if(pageEditViewController?.canZoomOutPageSize() == false) {
- toolbarManager.page_Reduce_Property.isDisabled = true
- } else {
- toolbarManager.page_Reduce_Property.isDisabled = false
- }
- controller.refreshSecondToolbarItemsState()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Increase_Identifier {
- pageEditViewController?.zoomInPageAction()
-
- if(pageEditViewController?.canZoomInPageSize() == false) {
- toolbarManager.page_Increase_Property.isDisabled = true
- } else {
- toolbarManager.page_Increase_Property.isDisabled = false
- }
- if(pageEditViewController?.canZoomOutPageSize() == false) {
- toolbarManager.page_Reduce_Property.isDisabled = true
- } else {
- toolbarManager.page_Reduce_Property.isDisabled = false
- }
- controller.refreshSecondToolbarItemsState()
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_oddPage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .odd
- if(toolbarManager.page_pageInfo_Property.creatable == true) {
- toolbarManager.page_pageInfo_Property.creatable = false
- controller.refreshSecondToolbarItemsState()
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_EvenPage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .even
- if(toolbarManager.page_pageInfo_Property.creatable == true) {
- toolbarManager.page_pageInfo_Property.creatable = false
- controller.refreshSecondToolbarItemsState()
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_PortraitPage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .horizontal
- if(toolbarManager.page_pageInfo_Property.creatable == true) {
- toolbarManager.page_pageInfo_Property.creatable = false
- controller.refreshSecondToolbarItemsState()
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_LandscapePage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .vertical
- if(toolbarManager.page_pageInfo_Property.creatable == true) {
- toolbarManager.page_pageInfo_Property.creatable = false
- controller.refreshSecondToolbarItemsState()
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_AllPage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .allPage
- if(toolbarManager.page_pageInfo_Property.creatable == true) {
- toolbarManager.page_pageInfo_Property.creatable = false
- controller.refreshSecondToolbarItemsState()
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_page_CustomPage_Identifier {
- pageEditViewController?.thumbnailChoosePageStyle = .custom
- toolbarManager.page_pageInfo_Property.text = nil
- if(toolbarManager.page_pageInfo_Property.creatable == false) {
- toolbarManager.page_pageInfo_Property.creatable = true
- }
- controller.refreshSecondToolbarItemsState()
- }
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Markup_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_eye_Identifier {
- self.showOrHideNotes()
- }
-
- if viewManager.subToolMode == .None {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- } else if viewManager.subToolMode == .Stamp || viewManager.subToolMode == .Sign {
- viewManager.showRightSide = true
- }
- self.refreshToolbarRightViewInfo()
-
- if let currentSelect = listView.currentSelection {
- if(currentSelect.selectionType() == .text) {
- let annotationType: CAnnotationType = KMPDFViewManager.getValidPDFAnnotationType(viewManager.subToolMode)
- if annotationType != .unkown {
- listView.addAnnotation(with: annotationType, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- }
- }
- }
-
- toolbarViewModeChanged()
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Edit_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_edit_addWatermark_Identifier {
- showWatermarkController()
- } else if itemIdentifier == KMPDFToolbar_edit_removeWatermark_Identifier {
- removePDFWatermark()
- } else if itemIdentifier == KMPDFToolbar_edit_batch_AddWatermark_Identifier {
- batchAddWatermark()
- } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveWatermark_Identifier {
- batchRemoveWatermark()
- } else if itemIdentifier == KMPDFToolbar_edit_addBG_Identifier {
- showBackgroundController()
- } else if itemIdentifier == KMPDFToolbar_edit_removeBG_Identifier {
- removePDFBackground()
- } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBG_Identifier {
- batchAddBackground()
- } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBG_Identifier {
- batchRemoveBackground()
- } else if itemIdentifier == KMPDFToolbar_edit_addHF_Identifier {
- showHeaderFooterController()
- } else if itemIdentifier == KMPDFToolbar_edit_removeHF_Identifier {
- removeHeaderFooter()
- } else if itemIdentifier == KMPDFToolbar_edit_batch_AddHF_Identifier {
- batchAddHeaderFooter()
- } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveHF_Identifier {
- batchRemoveHeaderFooter()
- } else if itemIdentifier == KMPDFToolbar_edit_addBates_Identifier {
- showBatesController()
- } else if itemIdentifier == KMPDFToolbar_edit_removeBates_Identifier {
- removePDFBates()
- } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBates_Identifier {
- batchAddBates()
- } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBates_Identifier {
- batchRemoveBates()
- } else if itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
- showCropController()
- }
-
- if viewManager.subToolMode == .None {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- }
- self.refreshToolbarRightViewInfo()
-
- toolbarViewModeChanged()
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Form_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier {
-
- let value = CPDFKitConfig.sharedInstance().enableFormFieldHighlight()
- CPDFAnnotation.updateHighlightFormFiled(listView, highlightFormFiled: !value)
-
- self.toolbarManager.refreshDefaultConfigItem()
- self.alertTipViewController.reloadFormAlertUI()
-
- } else if itemIdentifier == KMPDFToolbar_form_ShowName_Identifier {
- listView.showFormFieldName = !listView.showFormFieldName
- if listView.showFormFieldName {
- toolbarManager.form_ShowName_Property.righticon = NSImage(named: "tick_Green")
- } else {
- toolbarManager.form_ShowName_Property.righticon = nil
- }
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier {
- listView.resetFormAnnotation()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
- listView.setNeedsDisplayForVisiblePages()
- } else if itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
- listView.setNeedsDisplayForVisiblePages()
- }
-
- if itemIdentifier == KMPDFToolbar_form_HighlightFields_Identifier ||
- itemIdentifier == KMPDFToolbar_form_ShowName_Identifier ||
- itemIdentifier == KMPDFToolbar_form_ClearForm_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Left_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Hori_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Right_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Top_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Vert_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Align_Bottom_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Distribute_Vert_Identifier ||
- itemIdentifier == KMPDFToolbar_form_Distribute_Hori_Identifier {
- } else {
- toolbarViewModeChanged()
- }
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Fill_Identifier).contains(itemIdentifier) {
-
-
- if viewManager.subToolMode == .None {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- }
- self.refreshToolbarRightViewInfo()
-
- toolbarViewModeChanged()
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Convert_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_convert_word_Identifier {
- self.showConvertWindow(.word)
-
- } else if itemIdentifier == KMPDFToolbar_convert_ppt_Identifier {
- self.showConvertWindow(.ppt)
-
- } else if itemIdentifier == KMPDFToolbar_convert_RTF_Identifier {
- self.showConvertWindow(.rtf)
-
- } else if itemIdentifier == KMPDFToolbar_convert_Text_Identifier {
- self.showConvertWindow(.text)
-
- } else if itemIdentifier == KMPDFToolbar_convert_CSV_Identifier {
- self.showConvertWindow(.csv)
-
- } else if itemIdentifier == KMPDFToolbar_convert_excel_Identifier {
- self.showConvertWindow(.excel)
-
- } else if itemIdentifier == KMPDFToolbar_convert_HTML_Identifier {
- self.showConvertWindow(.html)
-
- } else if itemIdentifier == KMPDFToolbar_convert_Json_Identifier {
- self.showConvertWindow(.json)
-
- } else if itemIdentifier == KMPDFToolbar_convert_image_Identifier {
- self.showConvertWindow(.jpeg)
-
- } else if itemIdentifier == KMPDFToolbar_convert_imageToPDF_Identifier {
- self.showBatchWindow(type: .imageToPDF, files: [])
- }
- self.refreshToolbarRightViewInfo()
-
- toolbarViewModeChanged()
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Protect_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_protect_redact_Identifier {
- toolbarViewModeChanged()
-
- if viewManager.showRightSide == true {
- viewManager.showRightSide = false
- pdfToolbarController?.reloadRightToolsView()
-
- toggleCloseRightSide()
- }
-
- self.enterRedactAlert()
- } else if itemIdentifier == KMPDFToolbar_protect_redact_Property_Identifier {
- self.showRedactProperty(readactAnnotation: nil)
-
- toolbarViewModeChanged()
- } else if itemIdentifier == KMPDFToolbar_protect_redact_Apply_Identifier {
- toolbarViewModeChanged()
-
- self.redactApplyAction(needAlert: false)
-
- } else if itemIdentifier == KMPDFToolbar_protect_redact_Exit_Identifier {
- toolbarViewModeChanged()
-
- alertTipViewController.reloadRedactAlertUI()
- alertTipViewController.reloadAlertUIFrame()
- } else if itemIdentifier == KMPDFToolbar_protect_security_Identifier {
- self.showSecureWindow()
-
- } else if itemIdentifier == KMPDFToolbar_protect_removeSecurity_Identifier {
- self.showRemoveSecureWindow()
-
- } else if itemIdentifier == KMPDFToolbar_protect_digitalSign_Identifier {
- self.toolbarViewModeChanged()
- }
- alertTipViewController.reloadAlertUIFrame()
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Tools_Identifier).contains(itemIdentifier) {
-
- if itemIdentifier == KMPDFToolbar_tools_compress_Identifier {
- let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- self.showCompressController(model: model)
-
- } else if itemIdentifier == KMPDFToolbar_tools_batch_compress_Identifier {
- let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- self.showBatchWindow(type: .compress, files: [], fileModels: [model])
-
-
- } else if itemIdentifier == KMPDFToolbar_tools_OCR_Identifier {
- viewManager.showRightSide = !viewManager.showRightSide
- self.refreshToolbarRightViewInfo()
-
- } else if itemIdentifier == KMPDFToolbar_tools_merge_Identifier {
- self.showMergeWindow()
-
- } else if itemIdentifier == KMPDFToolbar_tools_TTS_Identifier {
- self.showTTSWindow()
-
- } else if itemIdentifier == KMPDFToolbar_tools_extractImage_Identifier {
- self.extractImageAction(num: 2)
-
- } else if itemIdentifier == KMPDFToolbar_tools_AITools_Identifier {
- self.viewManager.pdfSideBarType = .aiTools
- self.sideBarController?.reloadData()
- if let sideVC = self.sideBarController {
- self.kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
- }
- } else if itemIdentifier == KMPDFToolbar_tools_compare_side_Identifier {
- self.beginCompareAction(1)
- } else if itemIdentifier == KMPDFToolbar_tools_compare_Overlay_Identifier {
- self.beginCompareAction(2)
- } else if itemIdentifier == KMPDFToolbar_tools_batch_Identifier {
- let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
- }
-
- if viewManager.subToolMode == .None {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- } else if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- }
- self.refreshToolbarRightViewInfo()
-
- toolbarViewModeChanged()
- } else if itemIdentifier == KMPDFToolbar_ViewDisplay_Identifier {
-
- updatePDFDisplaySettingView()
-
- } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Right_Identifiers).contains(itemIdentifier) {
- if (itemIdentifier == KMPDFToolbar_undo_Identifier) {
-
- if(listView.isEditing()) {
- if(listView.canEditTextUndo()){
- listView.editTextUndo()
- }
- } else {
- listView.undoManager?.undo()
-
- self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Undo"))
- self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
- CGRectGetHeight(listView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
- self.componentMessageView.properties.propertyInfo.viewWidth,
- self.componentMessageView.properties.propertyInfo.viewHeight)
- self.componentMessageView.reloadData()
- self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
- }
- } else if(itemIdentifier == KMPDFToolbar_redo_Identifier) {
-
- if(listView.isEditing()) {
- if(listView.canEditTextRedo()) {
- listView.editTextRedo()
- }
- } else {
- listView.undoManager?.redo()
-
- self.componentMessageView.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Redo"))
- self.componentMessageView.frame = CGRectMake((CGRectGetWidth(self.view.frame) - self.componentMessageView.properties.propertyInfo.viewWidth)/2,
- CGRectGetHeight(listView.frame) - self.componentMessageView.properties.propertyInfo.viewHeight - 8,
- self.componentMessageView.properties.propertyInfo.viewWidth,
- self.componentMessageView.properties.propertyInfo.viewHeight)
- self.componentMessageView.reloadData()
- self.componentMessageView.showSelf(inView: self.view, autoHideSeconde: 2)
- }
- } else if(itemIdentifier == KMPDFToolbar_fileInfo_Identifier) {
- self.showFileInfo()
-
- } else if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier ||
- itemIdentifier == KMPDFToolbar_share_Flattened_Identifier ||
- itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
-
- if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier) {
- if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
- shareDocument(sender: view)
- }
- } else if(itemIdentifier == KMPDFToolbar_share_Flattened_Identifier) {
- if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
- shareFlatten(sender: view)
- }
- } else if(itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
- if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
- shareOriginalPDF(sender: view)
- }
- }
- } else if itemIdentifier == KMPDFToolbar_save_Identifier {
- myDocument?.save(nil)
-
- } else if itemIdentifier == KMPDFToolbar_print_Identifier {
- self.showPrintWindow()
-
- } else if itemIdentifier == KMPDFToolbar_tts_Identifier {
- self.showTTSWindow()
-
- } else if itemIdentifier == KMPDFToolbar_ppt_Identifier {
- self.togglePresentation(nil)
-
- } else if itemIdentifier == KMPDFToolbar_batch_Identifier {
- let model = KMBatchProcessingTableViewModel.initWithFilePath(url: listView.document.documentURL)
- model.password = listView.document.password ?? ""
-
- self.showBatchWindow(type: .convertPDF, files: [], fileModels: [model])
-
- }
- } else if itemIdentifier == KMPDFToolbar_PageEdit_Identifier {
-
- if viewManager.isPageEditMode == true {
- enterPageEditMode()
- } else {
- exitPageEditMode()
- }
- } else if itemIdentifier == KMPDFToolbar_rightView_Identifier {
-
- self.refreshToolbarRightViewInfo()
-
- } else {
- print("click else")
- }
-
- refreshToolbarViewHeightInfo()
-
-
- refreshRightSide()
-
- }
-
- func kmPDFToolbarControllerDidSelectTextDidBeginEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
-
- }
-
- func kmPDFToolbarControllerDidSelectTextDidChange(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
-
- }
-
- func kmPDFToolbarControllerDidSelectTextDidEndEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
- if view.properties == toolbarManager.page_pageInfo_Property {
- if viewManager.isPageEditMode == true {
- let fileAttribute = KMNFileAttribute()
- fileAttribute.password = listView.document?.password ?? ""
- fileAttribute.pdfDocument = listView.document
- fileAttribute.filePath = listView.document?.documentURL.path ?? ""
- fileAttribute.bAllPage = false
- fileAttribute.pagesType = .PagesString
- fileAttribute.pagesString = view.properties.text ?? ""
-
- let fetchSelectPages = fileAttribute.fetchSelectPages()
- if (fetchSelectPages.isEmpty) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
- alert.runModal()
- toolbarManager.page_pageInfo_Property.text = ""
- controller.refreshSecondToolbarItemsState()
- } else {
- var tIndexPaths: Set<IndexPath> = []
- for i in 0 ..< fetchSelectPages.count {
- tIndexPaths.insert(IndexPath(item: (fetchSelectPages[i] - 1), section: 0))
- }
- pageEditViewController?.selectionIndexPaths = tIndexPaths
-
- }
-
- }
- }
- }
-
- func kmPDFToolbarControllerDidExitPageEditMode(_ controller: KMPDFToolbarController) {
- exitPageEditMode()
- }
- }
- extension KMMainViewController: KMRightSideControllerDelegate {
- func kmRightSideControllerRotateLeft(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
- CPDFStampAnnotation.rotateLeft(annotations, withPDFView: pdfView)
- (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateRight(annotations, withPDFView: pdfView)
- }
-
- func kmRightSideControllerRotateRight(_ annotations: [CPDFStampAnnotation], withPDFView pdfView: CPDFListView?) {
- CPDFStampAnnotation.rotateRight(annotations, withPDFView: pdfView)
- (undoManager?.prepare(withInvocationTarget: self) as AnyObject).kmRightSideControllerRotateLeft(annotations, withPDFView: pdfView)
- }
-
- func kmRightSideControllerDidContendVCUpdated(_ controller: KMRightSideController) {
-
- if (controller.contentViewController is KMCropPropertyController) {
- if let cropVC = rightSideController?.edit_cropController {
- cropVC.pdfView = controller.pdfView
- if cropVC.delegate == nil {
- cropVC.delegate = cropController
- }
- cropVC.reloadData()
- }
- }
-
- reloadPopUIWindow()
- }
-
- func kmRightSideControllerOCRShowTypeChange(_ controller: KMRightSideController, _ type: KMOCRShowType) {
- if type == .area {
- self.listView.toolMode = .COCRToolMode
- self.showOCRToolAlert(KMLocalizedString("Please select the area that needs OCR and click the “OCR” button to start"))
-
- } else {
- self.listView.toolMode = .CTextToolMode
- }
- }
-
- func kmRightSideControllerOCRDoneAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
- if model.showType == .area {
- self.convertOCRSaveAsTXT(text: model.text)
- } else {
- if model.saveAsPDF {
- if model.saveType == .PDF {
-
- } else {
-
- }
- } else {
-
- }
- self.convertOCR(document: self.listView.document, model: model)
- }
- }
-
- func kmRightSideControllerOCRLanguageChangeAction(_ controller: KMRightSideController, _ model: KMOCRModel) {
- self.convertSelectionRectOCR(rect: self.listView.currentSelectionRect())
- }
-
-
- func kmRightSideControllerShowMeasureSetting(_ controller: KMRightSideController) {
- showMeasureSettingWindow()
- }
-
-
- func kmRightSideControllerDidRevertCropInfo(_ controller: KMRightSideController) {
- if let cropVC = cropController {
- cropVC.selectionRect = rightSideController?.edit_cropController?.pageBounds ?? CGRectZero
- cropVC.reloadSelectionRect()
-
- self.kmCropControllerDidChangedSelectionOrMagnification(cropVC)
- }
- }
- }
- extension KMMainViewController: KMNDisplayViewControllerDelegate {
-
- func displayViewControllerDidDisplayModeChanged(_ controller: KMNDisplayViewController) {
- listView.layoutDocumentView()
-
- }
-
-
- func displayViewControllerDidReadModeUpdated(_ controller: KMNDisplayViewController) {
- if viewManager.isPDFReadMode {
- openPDFReadMode()
- } else {
- exitPDFReadMode()
- }
- }
-
-
- func displayViewControllerDidGotoSlideShow(_ controller: KMNDisplayViewController) {
- togglePresentation(nil)
- }
-
-
- func displayViewControllerDidSplitModeChanged(_ controller: KMNDisplayViewController) {
- reloadPDFSplitInfo()
-
- }
-
- func displayViewControllerDidSplitFileChanged(_ controller: KMNDisplayViewController) {
- splitPDFController?.reloadData()
-
- }
-
- func displayViewControllerDidToolbarStateChanged(_ controller: KMNDisplayViewController) {
- splitPDFController?.refreshToolbarState()
-
- reloadPDFPageNumberToolbar()
- }
- }
- extension KMMainViewController: KMInteractionProviderProtocol {
- func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
- if(interactionMode == .presentation) {
- if listView.presentationDrawView == nil {
- listView.createPresentationDraw()
- }
-
- presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
- presentationTopViewController?.pdfView = listView
- presentationTopViewController?.delegate = self
- presentationTopViewController?.isSelectionPre = true
- listView.isPresentationMode = true
- presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
- if((presentationTopViewController) != nil) {
- fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
- }
- } else {
- listView.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
- }
-
- fullScreenWindow.contentView?.addSubview(listView)
- if(interactionMode == .presentation) {
- let frame = fullScreenWindow.frame
- listView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-42)
- listView.autoresizingMask = [.width, .maxYMargin]
- }
- return view
- }
-
- @objc func willEnterInteractionModeNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
- if interactionMode == .presentation {
- let backgroundColor = NSColor.black
- let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
-
- let wasInteractionMode = self.interactionMode
- if wasInteractionMode == .normal {
- self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
- }
-
- if wasInteractionMode == .legacyFullScreen {
- self.enterPresentationMode()
-
- self.listView.frame = (self.view.window?.contentView?.bounds)!
- self.view.window?.contentView?.addSubview(listView)
-
-
- self.view.window?.level = level
- self.listView.layoutDocumentView()
- self.listView.requiresDisplay()
-
- }
- } else {
- KMPrint("2")
- }
- }
-
- @objc func didEnterInteractionModeNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
-
- self.listView.layoutDocumentView()
- self.listView.requiresDisplay()
- }
- }
-
- @objc func willShowFullScreenNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
- let view = self.view.window?.firstResponder as? NSView
- if let data = view?.isDescendant(of: self.pdfSplitView), data {
- self.view.window?.makeFirstResponder(nil)
- }
- }
- }
-
- @objc func didShowFullScreenNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
- self.enterPresentationMode()
- }
- }
- }
- extension KMMainViewController: KMPresentationTopViewControllerDelegate {
- func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
- self.exitFullScreen()
- }
-
- func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
- listView.presentationDrawView?.clear()
- }
-
- func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
- let presentationDrawView = listView.presentationDrawView
- if presentationDrawView?.canUndo() == true {
- presentationDrawView?.undo()
- }
- }
-
- func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
- listView.isPresentationMode = isSeletion
- if listView.isEnterPresentationDrawMode() == true {
- listView.exitPresentationDrawMode()
- }
- }
-
- func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
- if color == nil{
- listView.exitPresentationDrawMode()
- } else {
- if listView.isEnterPresentationDrawMode() == false {
- listView.enterPresentationDrawMode()
- }
- listView.changePresentationDrawModelColor(color)
- }
- }
- }
- extension KMMainViewController: KMSplitPDFViewControllerDelegate {
- func splitPDFViewControllerDidUpdateFilePath(_ controller: KMSplitPDFViewController) {
- displaySettingController?.reloadData()
-
- }
-
- func splitPDFViewControllerDidUpdatePDFScale(_ controller: KMSplitPDFViewController) {
- if let scaleFactor = controller.pdfView?.scaleFactor {
- listView.scaleFactor = scaleFactor
- }
- }
-
- func splitPDFViewControllerDidUpdatePDFPageIndex(_ controller: KMSplitPDFViewController) {
- if let pageIndex = controller.pdfView?.currentPageIndex {
- listView.go(toPageIndex: pageIndex, animated: false)
- }
-
- }
- }
- extension KMMainViewController: KMEditToolbarViewDelegate {
- func kmEditToolbarViewDidUpdateMode(_ view: KMEditToolbarView) {
- if view.editType == .watermark {
- watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
- watermarkViewController?.reloadData()
- watermarkViewController?.loadData()
-
- } else if view.editType == .background {
- backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
- backgroundViewController?.resetUI()
- backgroundViewController?.reloadData()
- } else if view.editType == .header_Footer {
- headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
- headerFooterViewController?.resetUI()
- headerFooterViewController?.reloadData()
- } else if view.editType == .bates {
- batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
- batesViewController?.resetUI()
- batesViewController?.reloadData()
- }
- }
-
- func kmEditToolbarViewDidChooseBatch(_ view: KMEditToolbarView) {
- if view.editType == .watermark {
- self.showBatchWindow(type: .watermark, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- } else if view.editType == .background {
- self.showBatchWindow(type: .background, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- } else if view.editType == .header_Footer {
- self.showBatchWindow(type: .headerAndFooter, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- } else if view.editType == .bates {
- self.showBatchWindow(type: .batesNumber, files: [URL(fileURLWithPath: self.document?.documentURL.path ?? "")])
- }
- }
-
- func kmEditToolbarViewDidChooseApply(_ view: KMEditToolbarView) {
- let pageInfo = view.pageRangeSelectView.getSelectedPageIndex(listView.document)
- let pageIndex = pageInfo.0
- let isCurrentPage = pageInfo.1
-
- if pageIndex.isEmpty {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
- alert.runModal()
- return
- }
- var pageString = view.pageRangeSelectView.getSelectedPageString(listView.document, pageIndex)
- if isCurrentPage {
- pageString = String(format: "%ld", listView.currentPageIndex)
- }
- if view.editType == .watermark {
- if view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert(completion: { response in
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.applyWatermarkInfo(pageString)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- })
- } else {
- self.applyWatermarkInfo(pageString)
- }
- } else if view.editType == .background {
- if view.editSubType == .edit, let propertyVC = backgroundViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert(completion: { response in
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.applyBackgroundInfo(pageString)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- })
- } else {
- self.applyBackgroundInfo(pageString)
- }
- } else if view.editType == .header_Footer {
- if view.editSubType == .edit, let propertyVC = headerFooterViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.applyHeaderFooterInfo(pageString)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- } else {
- self.applyHeaderFooterInfo(pageString)
- }
- } else if view.editType == .bates {
- if view.editSubType == .edit, let propertyVC = batesViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.applyBatesInfo(pageString)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- } else {
- self.applyBatesInfo(pageString)
- }
- }
-
- }
-
- func kmEditToolbarViewDidChooseExit(_ view: KMEditToolbarView) {
-
-
- if view.editType == .watermark, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- DispatchQueue.main.async {
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.kmEditToolbarViewDidChooseExit(view)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- }
- return
- } else if view.editType == .background, view.editSubType == .edit, let propertyVC = backgroundViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- DispatchQueue.main.async {
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.kmEditToolbarViewDidChooseExit(view)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- }
- return
- } else if view.editType == .header_Footer, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- DispatchQueue.main.async {
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.kmEditToolbarViewDidChooseExit(view)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- }
- return
- } else if view.editType == .bates, view.editSubType == .edit, let propertyVC = watermarkViewController?.propertyController, propertyVC.isOriginalDataDictChanged() == true {
- propertyVC.showSaveEditChangeAlert { response in
- DispatchQueue.main.async {
- if response == NSApplication.ModalResponse.alertFirstButtonReturn {
-
- propertyVC.saveDataEdit()
-
- self.kmEditToolbarViewDidChooseExit(view)
- } else {
-
- propertyVC.cancelDataEdit()
- }
- }
- }
- return
- }
-
- if view.applyEnable {
- let alert = NSAlert()
- if view.editType == .watermark {
- alert.messageText = KMLocalizedString("There are unapplied Watermark settings, do you want to apply them?", comment: "")
- } else if view.editType == .background {
- alert.messageText = KMLocalizedString("There are unapplied Background settings, do you want to apply them?", comment: "")
- } else if view.editType == .header_Footer {
- alert.messageText = KMLocalizedString("There are unapplied Header & Footer settings, do you want to apply them?", comment: "")
- } else if view.editType == .bates {
- alert.messageText = KMLocalizedString("There are unapplied Bates settings, do you want to apply them?", comment: "")
- }
- alert.informativeText = KMLocalizedString("If not, the changes will be lost.", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Apply", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Don't Apply", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("Cancel", comment: ""))
- let result = alert.runModal()
- if (result == .alertFirstButtonReturn) {
- self.kmEditToolbarViewDidChooseApply(view)
- } else if (result == .alertSecondButtonReturn) {
-
- exitEditToolbarView()
- } else if (result == .alertThirdButtonReturn) {
-
-
- }
- } else {
- exitEditToolbarView()
- }
- }
-
- func applyWatermarkInfo(_ pageString: String) {
- if let model = watermarkViewController?.currentWatermarkData {
- let watermark = KMWatermarkModel.returnWaterMarkWith(model, listView.document)
- watermark.pageString = pageString
- listView.document.addWatermark(watermark)
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
- }
- exitEditToolbarView()
- }
-
- func applyBackgroundInfo(_ pageString: String) {
- if let model = backgroundViewController?.backgroundModel {
- if let background = listView.document.background() {
- KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
- background.pageString = pageString
- background.update()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
- }
- }
- exitEditToolbarView()
- }
-
- func applyHeaderFooterInfo(_ pageString: String) {
- if let model = headerFooterViewController?.headerFooterModel {
- if let headerFooter = listView.document.headerFooter() {
- KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(listView.document.pageCount))
- headerFooter.pageString = pageString
- headerFooter.update()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
- }
-
- }
-
- exitEditToolbarView()
- }
-
- func applyBatesInfo(_ pageString: String) {
- if let model = batesViewController?.batesModel {
- if let bates = listView.document.bates() {
- KMBatesManager.defaultManager.updateCPDFBates(bates, withModel: model, Int(listView.document.pageCount))
- bates.pageString = pageString
- bates.update()
-
- listView.document?.refreshPageData()
- listView.layoutDocumentView()
-
- self.recordIsPDFDocumentEdited()
- }
- }
- exitEditToolbarView()
- }
-
- }
- extension KMMainViewController: KMCropControllerDelegate {
- func kmCropControllerDidCrop(_ controller: KMCropController, _ cropRect: CGRect, _ view: KMPageRangeSelectView) {
- let rangeSelectResult = view.getSelectedPageIndex(listView.document)
- let indexs = rangeSelectResult.0
- let isCurrentPage = rangeSelectResult.1
- var uIndexs: [UInt] = []
- for index in indexs {
- if index > 0 {
- uIndexs.append(UInt(index-1))
- }
- }
- if isCurrentPage {
- uIndexs = [UInt(listView.currentPageIndex)]
- }
- cropPages(atIndexs: uIndexs, to: [cropRect])
- removeCropController()
-
- viewManager.subToolMode = .None
- if let toolbarVC = self.pdfToolbarController {
- toolbarVC.refreshSecondToolbarItemsState()
- self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
- }
- }
-
- func kmCropControllerDidCropSeparate(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
- let rangeSelectResult = view.getSelectedPageIndex(listView.document)
- let indexs = rangeSelectResult.0
- let isCurrentPage = rangeSelectResult.1
- var rectArray: Array<NSRect> = []
- var uIndexs: [UInt] = []
- for index in indexs {
- if index > 0 {
- uIndexs.append(UInt(index-1))
-
- let page = self.listView.document.page(at: UInt(index-1))
- let rect = KMCropTools.getPageForegroundBox(page!)
- rectArray.append(rect)
- }
- }
- if isCurrentPage {
- uIndexs = [UInt(listView.currentPageIndex)]
- }
- cropPages(atIndexs: uIndexs, to: rectArray)
- removeCropController()
-
- viewManager.subToolMode = .None
- if let toolbarVC = self.pdfToolbarController {
- toolbarVC.refreshSecondToolbarItemsState()
- self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
- }
- }
-
- func kmCropControllerDidCropAuto(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
- let rangeSelectResult = view.getSelectedPageIndex(listView.document)
- let indexs = rangeSelectResult.0
- let isCurrentPage = rangeSelectResult.1
- var uIndexs: [UInt] = []
- for index in indexs {
- if index > 0 {
- uIndexs.append(UInt(index-1))
- }
- }
- if isCurrentPage {
- uIndexs = [UInt(listView.currentPageIndex)]
- }
- auto_cropPagesWhiteMargin(uIndexs)
- removeCropController()
-
- viewManager.subToolMode = .None
- if let toolbarVC = self.pdfToolbarController {
- toolbarVC.refreshSecondToolbarItemsState()
- self.kmPDFToolbarControllerDidToolbarItemClicked(toolbarVC, KMPDFToolbar_edit_crop_Identifier)
- }
- }
-
- func kmCropControllerDidChangedSelectionOrMagnification(_ controller: KMCropController) {
- if let cropVC = rightSideController?.edit_cropController {
- if cropVC.pdfView != controller.pdfView {
- cropVC.pdfView = controller.pdfView
- }
- cropVC.reloadData()
-
- rightSideController?.reloadRightButtonState()
- }
- }
-
- }
- extension KMMainViewController: KMWatermarkControllerDelegate {
- func kmWatermarkControllerDidUpdateMode(_ view: KMWatermarkController) {
- editToolbarView?.editSubType = view.editSubType
- editToolbarView?.reloadData()
-
- }
-
- func kmWatermarkControllerDidWatermarkUpdated(_ view: KMWatermarkController) {
- var applyEnable = true
- if let model = view.currentWatermarkData {
- if model.watermarkType == .text {
- if model.text == nil || model.text?.count == 0 {
- applyEnable = false
- }
- } else if model.watermarkType == .image {
- if model.imagePath == nil {
- applyEnable = false
- }
- }
- } else {
- applyEnable = false
- }
- editToolbarView?.applyEnable = applyEnable
-
- editToolbarView?.reloadData()
-
- }
- }
- extension KMMainViewController: KMBackgroundControllerDelegate {
- func kmBackgroundControllerDidUpdateMode(_ view: KMBackgroundController) {
- editToolbarView?.editSubType = view.editSubType
-
- }
-
- func kmBackgroundControllerDidBGDataUpdated(_ view: KMBackgroundController) {
- var applyEnable = true
- if let model = view.backgroundModel {
- if model.type == .image {
- if model.imagePath == nil {
- applyEnable = false
- }
- }
- } else {
- applyEnable = false
- }
- editToolbarView?.applyEnable = applyEnable
-
- editToolbarView?.reloadData()
- }
- }
- extension KMMainViewController: KMHeaderFooterControllerDelegate {
- func kmHeaderFooterControllerDidUpdateModeType(_ view: KMHeaderFooterController) {
- editToolbarView?.editSubType = view.editSubType
-
- }
-
- func kmHeaderFooterControllerDidModelDataUpdated(_ view: KMHeaderFooterController) {
- var applyEnable = true
- if let model = view.headerFooterModel {
- if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
- model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
- applyEnable = false
- }
- } else {
- applyEnable = false
- }
- editToolbarView?.applyEnable = applyEnable
-
- editToolbarView?.reloadData()
- }
- }
- extension KMMainViewController: KMBatesControllerDelegate {
- func kmBatesControllerDidUpdateMode(_ view: KMBatesController) {
- editToolbarView?.editSubType = view.editSubType
- editToolbarView?.reloadData()
-
- }
-
- func kmBatesControllerDidModelDataUpdated(_ view: KMBatesController) {
- var applyEnable = true
- if let model = view.batesModel {
- if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
- model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
- applyEnable = false
- }
- } else {
- applyEnable = false
- }
- editToolbarView?.applyEnable = applyEnable
-
- editToolbarView?.reloadData()
- }
-
- }
- extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
-
- func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
- sideBarController?.reloadPageTurnerData()
-
- documentLoadComplete()
- }
-
- func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
-
- sideBarController?.reloadPageTurnerData()
-
- botaViewController?.currentPageDidChangedAction(listView: listView)
-
-
- reloadPDFPageNumberToolbar()
-
- if viewManager.splitSyncScroll {
- if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
- splitPDFController?.outPDFFirst = true
-
- if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
- var index = pdfView.currentPageIndex
- if index > document.pageCount {
- index = Int(splitPDFView.document.pageCount - 1)
- }
- splitPDFView.go(toPageIndex: index, animated: false)
- }
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
- self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
- } else if splitPDFController?.outPDFFirst == true {
- if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
- var index = pdfView.currentPageIndex
- if index > document.pageCount {
- index = Int(splitPDFView.document.pageCount - 1)
- }
- splitPDFView.go(toPageIndex: index, animated: false)
- }
-
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
- self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
- }
- }
-
-
- updateEditModeDocumentWhenPageChanged()
-
-
- }
-
- func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
-
- pdfToolbarController?.reloadSelectZoomView()
-
- reloadPDFPageNumberToolbar()
-
- reloadPopUIWindow()
-
-
- if viewManager.splitSyncScroll {
- if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
- splitPDFController?.outPDFFirst = true
-
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
- self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
- } else if splitPDFController?.outPDFFirst == true {
- if let splitPDFView = splitPDFController?.pdfView {
- splitPDFView.scaleFactor = pdfView.scaleFactor
- }
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
- self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
- }
- }
- }
-
- func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
- if let urlString = url, urlString == Store_Link {
-
- return
- }
-
- if url.hasPrefix("smb://") {
- NSWorkspace.shared.openFile(url)
- } else {
- KMTools.openURL(urlString: url)
- }
- }
-
- func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
- KMPrint("pdfViewPerformURL")
- if content != nil {
- NSWorkspace.shared.open(URL(string: content)!)
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.informativeText = KMLocalizedString("The hyperlink is invalid.", comment: "")
- alert.messageText = ""
- alert.addButton(withTitle: KMLocalizedString("OK", comment: ""))
- alert.runModal()
- return
- }
- }
-
- func pdfViewPerformPrint(_ pdfView: CPDFView!) {
- KMPrint("pdfViewPerformPrint")
- self.showPrintWindow()
- }
-
- func pdfViewPerformGo(toPage pdfView: CPDFView!) {
- KMPrint("pdfViewPerformGo")
- }
-
- func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
- KMPrint("pdfViewOpenPDF")
- }
-
- func pdfViewPerformReset(_ pdfView: CPDFView!) {
- KMPrint("pdfViewPerformReset")
- pdfView.document?.resetForm()
- }
-
- func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
- KMPrint("pdfViewEditingBlockDidChanged")
- }
-
- func pdfViewAsBookBookmark() -> NSImage! {
- return NSImage(named: "KMImageNameBookmarkIcon")!
- }
-
-
- func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
-
- reloadPopUIWindow()
- }
-
- func pdfViewPDFSelectionAttributeDidChanged(_ pdfView: CPDFView!) {
- reloadPopUIWindow()
- }
-
- func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
-
- rightSideController?.reloadDataWithPDFView(pdfView: (pdfView as! CPDFListView))
-
- if pdfView is CPDFListView {
- (pdfView as! CPDFListView).isEditImage = false
- }
-
- if let areas = pdfView.editingAreas(), areas.count > 0 {
- if viewManager.showRightSide == false && SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- self.refreshToolbarRightViewInfo()
- }
- } else {
- if viewManager.subToolMode == .None {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- self.refreshToolbarRightViewInfo()
- }
- }
- reloadPopUIWindow()
- }
-
- func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
- if self.listView.cropAreas == nil && editArea != nil && (editArea is CPDFEditImageArea){
- self.listView.cropAreas = editArea as? CPDFEditImageArea
- }
- reloadPopUIWindow()
- }
-
-
- func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
- if (pdfView as! CPDFListView).isEditImage {
- return
- }
-
- if listView.editingAreas().count > 0 {
- pdfView.updateEditing([])
- return
- }
-
- let panel = NSOpenPanel()
- panel.allowsMultipleSelection = false
- panel.allowedFileTypes = ["png","jpg"]
- panel.beginSheetModal(for: NSApp.mainWindow!) { response in
- if response == .OK {
- var filePath = panel.url?.path
- let image = NSImage.init(contentsOf: panel.url!)
-
- if image != nil {
- var imageRect = rect
- let imageSize = image!.size
- var previewSize = rect.size
- var isChangeSize = false
- if previewSize.width == 0 && previewSize.height == 0 {
- previewSize = CGSize(width: 500, height: 500)
- isChangeSize = true
- }
-
- var scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
- if scale < 1 {
-
- } else {
- let wh = max(imageSize.width, imageSize.height)
- if wh >= 72 {
- scale = min(scale, 1)
- } else {
- scale = min(72 / imageSize.width, 72 / imageSize.height)
- }
- }
-
- let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
-
- if isChangeSize {
- imageRect.origin.x = imageRect.origin.x - newSize.width / 2
- imageRect.origin.y = imageRect.origin.y - newSize.height / 2
- } else {
- imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
- imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
- }
-
- imageRect.size = newSize
- let limitWidth = 1920.0
- if imageSize.width > limitWidth || imageSize.height > limitWidth {
- filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
- targetSize: CGSize(width: limitWidth, height: limitWidth),
- maxSizeInBytes: 1024 * 1024 * 5,
- targetCompression: 1.0)
- }
-
-
- let pageRect = self.listView.currentPage().bounds ?? .zero
- if imageRect.width > pageRect.width ||
- imageRect.height > pageRect.height {
- let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
- imageRect = CGRect(x: imageRect.origin.x,
- y: imageRect.origin.y,
- width: imageRect.width * pageScale,
- height: imageRect.height * pageScale)
- }
-
- if imageRect.origin.x < 0 {
- imageRect.origin.x = 5
- }
-
- if imageRect.origin.y < 0 {
- imageRect.origin.y = 5
- }
-
- if imageRect.origin.x + imageRect.width > pageRect.width ||
- imageRect.origin.y + imageRect.height > pageRect.height {
- let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
- let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
-
- imageRect.origin.x = imageRect.origin.x - offsetX - 5
- imageRect.origin.y = imageRect.origin.y - offsetY - 5
- }
- DispatchQueue.main.async {
- self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
- }
- }
- }
- }
- }
-
- func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
- let areas = self.listView.km_EditingAreas()
- if let area = areas.last {
- if let data = area as? CPDFEditTextArea {
- if let str = data.editTextAreaString(), str.isEmpty {
- self.listView.remove(with: [area])
- } else {
- self.listView.updateEditing([])
- return
- }
- }
- }
-
- var newRect = rect
- if rect.size.equalTo(.zero) {
- newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
- } else {
- newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
- }
-
- let fontSize = CPDFEditTextArea.defaultFontSize()
- let fontColor = CPDFEditTextArea.defaultColor()
- let fontAlign = CPDFEditTextArea.defaultFontAlignment()
- NSColorPanel.shared.color = fontColor
-
- let attri = CEditAttributes()
- attri.cFont = CPDFFont(familyName: CPDFEditTextArea.defaultFontName(), fontStyle: CPDFEditTextArea.defaultFontStyle())
- attri.fontColor = fontColor
- attri.alignment = fontAlign
- attri.fontSize = fontSize
- attri.isBold = CPDFEditTextArea.defaultIsBold()
- attri.isItalic = CPDFEditTextArea.defaultIsItality()
-
- self.listView.createStringBounds(newRect, with: attri, page: page)
-
- }
-
- func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
- rightSideController?.reloadEditingAreas()
-
- toggleClosePopUIWindow()
- }
-
- func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
- rightSideController?.reloadEditingAreas()
-
- toggleClosePopUIWindow()
- }
-
- func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
- rightSideController?.reloadEditingAreas()
-
- reloadPopUIWindow()
- }
-
- func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
- rightSideController?.reloadEditingAreas()
- reloadPopUIWindow()
- }
-
- func pdfViewEditingExitCropMode(_ pdfView: CPDFView!, forEditing editingArea: CPDFEditImageArea!) {
- rightSideController?.reloadEditingAreas()
-
- toggleClosePopUIWindow()
- }
-
- func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
- let areas = self.listView.km_editingImageAreas()
- self.recordIsPDFDocumentEdited()
- if areas.count == 1 {
- if let data = areas.first as? CPDFEditImageArea {
- let updating = self.listView.editAreaBoundUpdating
- if updating {
- self.listView.editAreaBoundUpdating = false
- }
- }
- }
-
- }
-
- func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
- if(editArea.isImageArea()) {
- listView.cropAction()
-
- rightSideController?.reloadEditingAreas()
- }
- }
-
-
- func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
- let command = theEvent.modifierFlags.contains(.command)
- let control = theEvent.modifierFlags.contains(.control)
- let shift = theEvent.modifierFlags.contains(.shift)
- let option = theEvent.modifierFlags.contains(.option)
-
- KMPrint(theEvent.keyCode)
- if self.listView.isEditing() == true {
- if control && theEvent.keyCode == 11 {
- self.listView.setEditingTextarea_Bold()
- rightSideController?.reloadEditingAreas()
-
- return false
- } else if control && theEvent.keyCode == 34 {
- self.listView.setEditingTextarea_Italic()
- rightSideController?.reloadEditingAreas()
-
- return false
- } else if theEvent.keyCode == 36 {
- if self.listView.isCropMode {
- self.listView.cropComfirmAction()
- rightSideController?.reloadEditingAreas()
-
- return false
- }
- } else if theEvent.keyCode == 53 {
- if self.listView.isCropMode {
- self.listView.cropCancelAction()
- rightSideController?.reloadEditingAreas()
-
- return false
- }
- }
- }
-
- if self.listView.toolMode == .COCRToolMode {
- if theEvent.keyCode == 53 {
- self.listView.selectionRect = NSZeroRect
- self.listView.selectionPageIndex = UInt(NSNotFound)
- self.closePopOperationWindow()
- self.listView.setNeedsDisplayForVisiblePages()
- return false
- } else if theEvent.keyCode == 36 {
- self.convertSelectionRectOCR(rect: self.listView.currentSelectionRect())
- return false
- }
- }
-
- if (theEvent.keyCode == 11 && command) {
- self.menuItemBookMarkClick_add(sender: NSMenuItem())
- return false
- } else if (command && control && theEvent.keyCode == 14) {
- return false
- } else if (theEvent.keyCode == 123) {
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
- self.listView.goToPreviousPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 126) {
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.listView.isContinousScroll()) {
- return true
- }
- if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
- self.listView.goToPreviousPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 124) {
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 125) {
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.listView.isContinousScroll()) {
- return true
- }
- if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 36) {
- if self.listView.shouAddEditAreaType() == .image || self.listView.shouAddEditAreaType() == .text {
- if self.listView.isEditImage {
- self.menuItemEditingClick_CropImage(sender: NSMenuItem())
- }
- }
-
- } else if option && theEvent.keyCode == 18 {
-
- updatePDFViewToolsType(.Select)
- } else if option && theEvent.keyCode == 19 {
-
- updatePDFViewToolsType(.Scroll)
- } else if option && theEvent.keyCode == 20 {
-
- updatePDFViewToolsType(.Content_Selection)
- } else if option && theEvent.keyCode == 21 {
-
- updatePDFViewToolsType(.Magnify)
- } else if option && theEvent.keyCode == 23 {
-
- updatePDFViewToolsType(.AreaZoom)
- } else if theEvent.keyCode == 53 {
-
- self.exitFullScreen()
- self.toggleClosePopUIWindow()
-
- if viewManager.isPDFReadMode {
- self.exitPDFReadMode()
- }
-
- self.leftSideViewCancelSelect()
-
-
-
- }
- return true
- }
-
- func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
- guard let action = menuItem.action else {
- isTakesEffect.pointee = false
- return false
- }
- isTakesEffect.pointee = false
- return false
- }
-
-
-
- func pdfListViewChangedToolMode(_ pdfListView: CPDFListView!, for toolMode: CToolMode) {
- reloadPopUIWindow()
- }
-
- func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
- if(annotationType == .unkown) {
-
- if viewManager.showRightSide == false {
- toggleCloseRightSide()
- }
-
- if viewManager.subToolMode != .None {
- viewManager.subToolMode = .None
- pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
- pdfToolbarController?.refreshSecondToolbarItemsState()
- }
-
- cancelMeasureType()
- } else if annotationType == .measureLine ||
- annotationType == .measurePolyLine ||
- annotationType == .measurePolyGon ||
- annotationType == .measureSquare {
- refreshMeasureInfo()
- } else {
- cancelMeasureType()
-
- }
- }
-
- func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
- self.view.window?.makeFirstResponder(self.listView)
-
- reloadPopUIWindow()
-
- if isRightMenu {
-
- } else if annotations.count > 0 {
- if self.viewManager.isPDFReadMode {
- toggleCloseRightSide()
- } else {
- let isMultiAnnotations = pdfListView.isMultiAnnotation(annotations)
- if isMultiAnnotations == true, SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- } else {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = true
- }
- }
- refreshToolbarRightViewInfo()
- }
-
- } else if (annotations.count == 0){
- if pdfListView.annotationType == .unkown {
- if SettingsManager.sharedInstance.autoExpandPropertyPanel == true {
- viewManager.showRightSide = false
- }
- } else {
- if self.viewManager.isPDFReadMode {
- viewManager.showRightSide = false
- } else {
-
- }
- }
- refreshToolbarRightViewInfo()
- }
-
- self.refreshMeasureInfo()
-
-
- pdfToolbarController?.pdfViewActiveAnnotationsChanged()
- }
-
- func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
- toggleClosePopUIWindow()
- self.view.window?.orderFront(nil)
-
- var pagePoint = CGPoint.zero
- let point = self.view.convert(theEvent.locationInWindow, from: nil)
-
- let isShowPopUI:Bool = true
- if let page = pdfListView.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
- if view.window?.interactionMode == .presentation {
- let menuStruct = clickPresentationMenu(point: pagePoint)
- groupListMenuGroup?.pagePoint = pagePoint
- groupListMenuGroup?.groupDelegate = self
- groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
- groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
-
- groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil)
- } else {
- var menuStringArr: [String] = []
- let activeAnnotations = pdfListView.activeAnnotations as? [CPDFAnnotation]
- if activeAnnotations?.count ?? 0 > 1 {
- var isSameAnnotation = true
- let firstAnnotation = activeAnnotations?.first
-
- var isContainMark = false
- if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
- isContainMark = true
- }
- for i in 1..<(activeAnnotations?.count ?? 1) {
-
- if firstAnnotation?.type != activeAnnotations?[i].type {
- isSameAnnotation = false
- }
- if activeAnnotations?[i].isKind(of: CPDFMarkupAnnotation.self) == true {
- isContainMark = true
- }
- }
-
- if isSameAnnotation {
- if firstAnnotation?.isKind(of: CPDFMarkupAnnotation.self) == true {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- }
- } else if firstAnnotation?.isKind(of: CPDFRedactAnnotation.self) == true {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
- menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
-
- if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true {
-
- } else {
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- }
- }
-
- if firstAnnotation?.isKind(of: CPDFRedactAnnotation.self) == true {
-
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
- }
-
- if firstAnnotation?.isKind(of: CPDFLinkAnnotation.self) == true || firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
- }
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- if isContainMark == false {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
- if firstAnnotation?.isKind(of: CPDFWidgetAnnotation.self) == true {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
- }
- }
- } else if activeAnnotations?.count == 1 {
- let activeAnnotation = pdfListView.activeAnnotation!
- if activeAnnotation.isKind(of: CPDFMarkupAnnotation.self) {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_CopyText)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
- } else if activeAnnotation.isKind(of: CPDFRedactAnnotation.self) {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Redact_Apply)
- menuStringArr.append(PDFViewMenuIdentifier_Redact_Multipage)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_RedactProperties)
- menuStringArr.append(PDFViewMenuIdentifier_Redact_Default)
- } else if activeAnnotation.isKind(of: CPDFLinkAnnotation.self) {
- let link = activeAnnotation as? CPDFLinkAnnotation
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- } else {
- if activeAnnotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
- let signatureWidgetAnnotation = activeAnnotation as? CPDFSignatureWidgetAnnotation
- if(signatureWidgetAnnotation?.isSigned() == true) {
- return
- }
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- if activeAnnotation.isKind(of: CPDFTextAnnotation.self) ||
- activeAnnotation.isKind(of: CPDFFreeTextAnnotation.self) ||
- activeAnnotation.isKind(of: CSelfSignAnnotation.self) ||
- activeAnnotation.isKind(of: CPDFWidgetAnnotation.self) {
-
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Content)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- }
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SortAnnotation)
- }
- } else {
- let currentSelection = pdfListView.currentSelection
- if currentSelection != nil {
- if currentSelection?.selectionType() == .text && pdfListView == self.listView {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- if pdfListView.canPaste() {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Hight)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Underline)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_StrikeOut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Squiggly)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AddOutLine)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_TTS)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SearchText)
- } else if currentSelection?.selectionType() == .image && pdfListView == self.listView {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- if pdfListView.canPaste() {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Square)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Circle)
- }
- } else {
- if(pdfListView == self.listView) {
- if pdfListView.toolMode == .CFormToolMode {
- if pdfListView.canPaste() {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllForm)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowFormName)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
- } else if pdfListView.toolMode == .CRedactToolMode {
-
- } else {
- if(listView.viewSplitMode != .disable) {
- menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
- menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
- menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AITool)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- if pdfListView == listView {
- if pdfListView.canPaste() {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Past)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllText)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_SelectAllAnnotation)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowAnnotation)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- }
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
-
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
- if(listView.viewSplitMode != .disable) {
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AutoScroll)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
- }
- }
- }
- }
- if(menuStringArr.count > 0) {
- let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
- groupListMenuGroup?.pagePoint = pagePoint
- groupListMenuGroup?.groupDelegate = self
- groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
- groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
-
- groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil, withWindow: self.view.window)
- }
- }
- } else {
- var menuStringArr: [String] = []
- if(listView.viewSplitMode != .disable) {
- menuStringArr.append(PDFViewMenuIdentifier_Split_ViewMode)
- menuStringArr.append(PDFViewMenuIdentifier_Split_Sync)
- menuStringArr.append(PDFViewMenuIdentifier_Split_ShowBar)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
-
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageView)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ReadMode)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightLink)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_HightForm)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_RestForm)
- }
- let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: theEvent, listView: pdfListView)
- groupListMenuGroup?.pagePoint = pagePoint
- groupListMenuGroup?.groupDelegate = self
- groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
- groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
-
- groupListMenuGroup?.showWithPoint(CGPoint(x: point.x, y: point.y - menuStruct.viewHeight), relativeTo: nil, withWindow: self.view.window)
- }
- }
-
- func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
- toggleClosePopUIWindow()
-
- var windowPoint = listView.convert(point, from: page)
- let view: NSView? = nil
- windowPoint = listView.convert(windowPoint, to: view)
- if self.view.window?.interactionMode == .presentation {
- let menuStruct = clickPresentationMenu(point: point)
- groupListMenuGroup?.pagePoint = point
- groupListMenuGroup?.groupDelegate = self
- groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
- groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
-
- groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: nil)
- } else {
- let isShowPopUI:Bool = true
- var menuStringArr: [String] = []
- let editingAreas = listView.km_EditingAreas()
- let firstEditingArea = editingAreas.first
- if editingAreas.count > 1 {
- var isSameEditingArea = true
- if(firstEditingArea?.isTextArea() == true) {
- for i in 1..<(editingAreas.count) {
- if !editingAreas[i].isTextArea() {
- isSameEditingArea = false
- break
- }
- }
- } else if (firstEditingArea?.isImageArea() == true) {
- for i in 1..<(editingAreas.count) {
- if !editingAreas[i].isImageArea() {
- isSameEditingArea = false
- break
- }
- }
- }
-
- if(isSameEditingArea) {
- if (firstEditingArea?.isTextArea() == true) {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- if listView.isSupportPastMatchStyle() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
- }
- if listView.isSupportPast() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
-
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
- } else if (firstEditingArea?.isImageArea() == true) {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
- }
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Aligning)
- }
- } else if editingAreas.count == 1 {
- if firstEditingArea?.isTextArea() == true {
- if !listView.isSelecteditAreaNotEdit() {
- if listView.isSupportPast() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
- } else {
- let editState = listView.editStatus()
- if (editState == .editSelectText) {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- if listView.isSupportPast() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- } else {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- if listView.isSupportPastMatchStyle() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
- }
- if listView.isSupportPast() {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
- }
- menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- }
- }
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Font)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_FontName)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_FontAlight)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- } else if firstEditingArea?.isImageArea() == true {
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Copy)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Cut)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Delete)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateLeft)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_RotateRight)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_VerticalMirror)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_HorizontalMirror)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Crop)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Replace)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Export)
- if(isShowPopUI){
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ShowPopUI)
- }
- }
- } else {
- if(listView.isSupportPast()) {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_NoStylePaste)
- }
- if(listView.isSupportPastMatchStyle()) {
- menuStringArr.append(PDFViewMenuIdentifier_Edit_Paste)
- }
-
- menuStringArr.append(PDFViewMenuIdentifier_Edit_SelectAll)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_AddText)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_AddImage)
- menuStringArr.append(PDFViewMenuIdentifier_Edit_AddLink)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_AddBook)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_ViewTools)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Scale)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageRotate)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_PageNum)
- menuStringArr.append(PDFViewMenuIdentifier_Space)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Search)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Print)
- menuStringArr.append(PDFViewMenuIdentifier_Normal_Properties)
- }
-
- let menuStruct = KMPDFMenuConfig.clickMenuUI(items: menuStringArr, theEvent: nil, listView: listView)
- groupListMenuGroup?.pagePoint = point
- groupListMenuGroup?.groupDelegate = self
- groupListMenuGroup?.frame = CGRectMake(0, 0, 180, menuStruct.viewHeight)
- groupListMenuGroup?.updateGroupInfo(menuStruct.menuitems)
-
- groupListMenuGroup?.showWithPoint(CGPoint(x: windowPoint.x, y: windowPoint.y - menuStruct.viewHeight), relativeTo: nil)
- }
-
- return []
- }
-
- func pdfListViewMobileAnnotationBegan(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
- toggleClosePopUIWindow()
- }
-
- func pdfListViewMobileAnnotationMove(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
- toggleClosePopUIWindow()
- }
-
- func pdfListViewMobileAnnotationEnd(_ point: CGPoint, for pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!) {
- reloadPopUIWindow()
- }
-
- func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
-
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(pdfPage.pageIndex()))
- KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
- botaViewController?.reloadData()
-
- alertTipViewController.reloadFormAlertUI()
- alertTipViewController.reloadDigitalAlertUI()
- alertTipViewController.reloadAlertUIFrame()
- }
-
- func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(pdfPage.pageIndex()))
- KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexes)
- botaViewController?.reloadData()
- alertTipViewController.reloadFormAlertUI()
- alertTipViewController.reloadAlertUIFrame()
- }
-
- func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
- if anotation.isKind(of: CPDFSignatureWidgetAnnotation.self) {
- if let signatureWidgetAnnotation = anotation as? CPDFSignatureWidgetAnnotation {
- let signature = signatureWidgetAnnotation.signature()
- if ((signature) != nil) {
- popUpSignatureWidgetState(signature!, listView)
- } else {
- let widget = CPDFSignatureWidgetAnnotation.init(PDFListViewNoteWith: listView.document)
- widget.bounds = NSMakeRect(-1000, -1000, 545, 178);
-
- anotation.page.addAnnotation(widget)
-
- let configWindowVC = DSignatureConfigWindowController.init(windowNibName: "DSignatureConfigWindowController")
- configWindowVC.viewType = .fileList;
- configWindowVC.appearanceWidget = widget;
- configWindowVC.isCreatDS = false
- configWindowVC.complentionHandle = {[weak self] isSign, dic, config, isLock in
- widget.page.removeAnnotation(widget)
- if isSign {
- if (dic.object(forKey: SAVEFILEPATH_KEY) != nil) {
- let p12Path = dic.object(forKey: SAVEFILEPATH_KEY) as! String
- let password = dic.object(forKey: PASSWORD_KEY)
- if p12Path.count > 0 {
- self?.writeSignatureToWidget(signatureWidgetAnnotation, p12Path, password as! String, config, isLock)
- }
- }
- } else {
- if signatureWidgetAnnotation.isSignSignatureAdd() == true {
- self?.listView.remove(anotation)
- }
- }
- }
- configWindowVC.actionBlock = {[weak self] controller, type in
- if (type == .cancel) {
- NSApplication.shared.stopModal()
- controller.window?.orderOut(nil)
- controller.window?.close()
- widget.page.removeAnnotation(widget)
-
- if signatureWidgetAnnotation.isSignSignatureAdd() == true {
- self?.listView.remove(anotation)
- } else {
- self?.listView.setNeedsDisplayAnnotationViewFor(anotation.page)
- }
- } else if (type == .confirm) {
- NSApplication.shared.stopModal()
- controller.window?.orderOut(nil)
- controller.window?.close()
- }
- }
- configWindowVC.window?.center()
- NSApplication.shared.runModal(for: configWindowVC.window!)
- }
- }
-
- } else if anotation.isKind(of: CPDFRedactAnnotation.self) {
- if let redactAnnotation = anotation as? CPDFRedactAnnotation {
- let properties = KMRedactPropertiesWindowController()
- properties.readactAnnotation = redactAnnotation
- properties.own_beginSheetModal(for: self.view.window) { result in
-
- }
- properties.callback = { [weak self] annotation in
- if let page = annotation?.page {
- self?.listView.setNeedsDisplayAnnotationViewFor(page)
- }
- }
-
- }
- }
- }
-
- func pdfListViewSplitModeShowBar() -> Bool {
- return viewManager.splitShowBottomBar
- }
-
- func pdfListViewSyncSplitView() -> Bool {
- return viewManager.splitSyncScroll
- }
-
- func pdfListViewEndEditMode(_ pdfListView: CPDFListView!) {
- let document = listView.document
- if(document != nil) {
- for i in 0..<document!.pageCount {
- let thumbnail = KMNThumbnail.init(document: document!, currentPageIndex: Int(i))
- thumbnail.removeCacheImage()
- }
- }
- botaViewController?.reloadData()
- }
-
- func pdfListViewAddEditAreaTypeChanged(_ pdfListView: CPDFListView!) {
- if self.listView.shouAddEditAreaType() != .text && self.listView.shouAddEditAreaType() != .image {
- if viewManager.subToolMode != .None {
- viewManager.subToolMode = .None
- pdfToolbarController?.cancelSelectedSecondToolbarItems(viewManager.toolMode)
- pdfToolbarController?.refreshSecondToolbarItemsState()
- }
- }
-
- }
-
-
- func pdfListViewChangedSelectionOrMagnification(_ pdfListView: CPDFListView!) {
- reloadPopUIWindow()
- }
-
- func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
- if (!self.listView.isEqual(to: pdfListView)) {
- return
- }
- if (self.listView.toolMode != .CSelectToolMode) {
- return
- }
- reloadPopUIWindow()
- }
-
- func pdfListViewHaveDocumentAttribute() -> Bool {
- if(!self.listView.document.allowsCopying) {
- self.removeOwnerPassword()
- return false
- }
- return true
- }
-
- func pdfListViewShowTipView() -> Bool {
- let popWindow = KMNAnnotationPopToolbarWindow.shared
- if popWindow.isVisible == true {
- return true
- }
-
- return false
- }
-
- func pdfListViewAnnotationEditModeChange(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
- reloadPopUIWindow()
- }
-
- func pdfListViewAnnotationChange(_ color: NSColor!, forActiveAnnotation annotation: CPDFAnnotation!) {
- rightSideController?.reloadData()
- NotificationCenter.default.post(name: toolbarImageColorChangedNotificationName, object: nil)
- }
-
-
- func pdfListViewAnnotationMeasureInfoChange(_ pdfListView: CPDFListView!, with annotation: CPDFAnnotation!) {
- guard let data = annotation else {
- if distanceMeasureInfoWindowController?.window?.isVisible == true {
- distanceMeasureInfoWindowController?.clearData()
- }
- return
- }
- if let lineAnnotation = annotation as? CPDFLineAnnotation {
- handleLineAnnotation(lineAnnotation)
- } else if let polylineAnnotation = annotation as? CPDFPolylineAnnotation {
- handlePolylineAnnotation(polylineAnnotation)
- } else if let polygonAnnotation = annotation as? CPDFPolygonAnnotation {
- handlePolygonAnnotation(polygonAnnotation)
- }
- }
-
- func pdfListViewMeasureCancel(_ pdfListView: CPDFListView!) {
- cancelMeasureType()
- }
-
- private func handleLineAnnotation(_ annotation: CPDFLineAnnotation) {
- if perimeterMeasureInfoWindowController?.window?.isVisible == true {
- perimeterMeasureInfoWindowController?.hideFloatingWindow()
- distanceMeasureInfoWindowController?.showWindow(self)
- } else if areaMeasureInfoWindowController?.window?.isVisible == true {
- areaMeasureInfoWindowController?.hideFloatingWindow()
- distanceMeasureInfoWindowController?.showWindow(self)
- } else if distanceMeasureInfoWindowController?.window?.isVisible == false {
- distanceMeasureInfoWindowController?.showWindow(self)
- }
-
- let measureInfo = annotation.measureInfo
- let startPoint = annotation.startPoint
- let endPoint = annotation.endPoint
- let angle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) * (180.0 / .pi)
-
- distanceMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
- distanceMeasureInfoWindowController?.xLabel.stringValue = String(format: "%.0f", abs(endPoint.x - startPoint.x))
- distanceMeasureInfoWindowController?.yLabel.stringValue = String(format: "%.0f", abs(endPoint.y - startPoint.y))
- distanceMeasureInfoWindowController?.reloadData(with: measureInfo!)
- }
-
- private func handlePolylineAnnotation(_ annotation: CPDFPolylineAnnotation) {
- if distanceMeasureInfoWindowController?.window?.isVisible == true {
- distanceMeasureInfoWindowController?.hideFloatingWindow()
- perimeterMeasureInfoWindowController?.showWindow(self)
- } else if areaMeasureInfoWindowController?.window?.isVisible == true {
- areaMeasureInfoWindowController?.hideFloatingWindow()
- perimeterMeasureInfoWindowController?.showWindow(self)
- } else if perimeterMeasureInfoWindowController?.window?.isVisible == false {
- perimeterMeasureInfoWindowController?.showWindow(self)
- }
-
- let measureInfo = annotation.measureInfo
- let savePoints = annotation.savePoints()
- var angle: CGFloat = 0
- if savePoints.count >= 3 {
- let count = savePoints.count
- let startPoint = savePoints[count - 3].pointValue
- let midPoint = savePoints[count - 2].pointValue
- let endPoint = savePoints.last!.pointValue
-
- angle = angleBetweenPoints(startPoint, midPoint, endPoint)
- }
- angle = 180 - angle
- perimeterMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
- perimeterMeasureInfoWindowController?.reloadData(with: measureInfo!)
- }
-
- private func handlePolygonAnnotation(_ annotation: CPDFPolygonAnnotation) {
- if distanceMeasureInfoWindowController?.window?.isVisible == true {
- distanceMeasureInfoWindowController?.hideFloatingWindow()
- areaMeasureInfoWindowController?.showWindow(self)
- } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
- perimeterMeasureInfoWindowController?.hideFloatingWindow()
- areaMeasureInfoWindowController?.showWindow(self)
- } else if areaMeasureInfoWindowController?.window?.isVisible == false {
- areaMeasureInfoWindowController?.showWindow(self)
- }
-
- let measureInfo = annotation.measureInfo
- let savePoints = annotation.savePoints
- var angle: CGFloat = 0
- if savePoints.count >= 3 {
- let count = savePoints.count
- let startPoint = (savePoints[count - 3] as AnyObject).pointValue
- let midPoint = (savePoints[count - 2] as AnyObject).pointValue
- let endPoint = (savePoints.lastObject as AnyObject).pointValue
-
- angle = angleBetweenPoints(startPoint!, midPoint!, endPoint!)
- }
- angle = 180 - angle
- areaMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
- areaMeasureInfoWindowController?.reloadData(measureInfo!)
- }
-
- private func angleBetweenPoints(_ startPoint: CGPoint, _ midPoint: CGPoint, _ endPoint: CGPoint) -> CGFloat {
- let vector1 = CGPoint(x: midPoint.x - startPoint.x, y: midPoint.y - startPoint.y)
- let vector2 = CGPoint(x: endPoint.x - midPoint.x, y: endPoint.y - midPoint.y)
- let dotProduct = vector1.x * vector2.x + vector1.y * vector2.y
- let magnitude1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
- let magnitude2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
-
- return acos(dotProduct / (magnitude1 * magnitude2)) * (180.0 / .pi)
- }
-
- @objc func pdfUpdatedFinish() {
- splitPDFController?.inPDFFirst = false
- splitPDFController?.outPDFFirst = false
-
- }
-
-
-
- @objc private func pdfViewScrollViewDidScroll(_ noti: Notification) {
- reloadPopUIWindow()
- if listView.popOver?.isShown == true {
- listView.popOver?.close()
- }
- }
-
- func pageCountChangedNotification(_ sender: Notification) {
- guard let document = sender.object as? CPDFDocument else {
- return
- }
- botaViewController?.pageCountChangedAction(document: document)
- }
-
- func annotationsAttributeHasChange(_ sender: Notification) {
- guard let dict = sender.object as? [String : Any] else {
- return
- }
-
- if let anno = dict["object"] as? CPDFAnnotation {
- let value = dict["keyPath"] as? String ?? ""
- let didEnd = dict["didEnd"] as? Bool ?? false
- if didEnd {
- if value == CPDFAnnotationBoundsKey {
- if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
- anno.contents = anno.page?.string(for: anno.bounds) ?? ""
- }
- }
- if anno.km_isMeasure() && anno.contents == nil {
- anno.contents = anno.string() ?? ""
- }
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(anno.page.pageIndex()))
- reloadIfThumData(pageIndexs: pageIndexes)
- reloadPopUIWindow()
- } else {
- if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey {
- var pageIndexes = IndexSet()
- pageIndexes.insert(Int(anno.page.pageIndex()))
- reloadIfThumData(pageIndexs: pageIndexes)
- reloadPopUIWindow()
- }
- }
- }
- }
-
- func reloadThumData(pageIndexs: IndexSet) {
- NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(reloadIfThumData), object: pageIndexs)
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
- self.reloadIfThumData(pageIndexs: pageIndexs)
- }
- }
-
- func reloadIfThumData(pageIndexs: IndexSet) {
- KMNThumbnailManager.reloadThumImage(document: self.listView.document, pageIndexs: pageIndexs)
- botaViewController?.reloadData()
- }
-
- @objc fileprivate func signatureStateChangeNoti(_ sender: Notification) {
- guard let objecListView = sender.object as? CPDFListView else {
- return
- }
- if listView == objecListView {
- reloadDigitalSigns()
-
- alertTipViewController.reloadDigitalAlertUI()
- alertTipViewController.reloadAlertUIFrame()
-
- let signatureWidget = listView.editAnnotation
- if let signatureWidgetAnnotation = signatureWidget as? CPDFSignatureWidgetAnnotation {
- let signature = signatureWidgetAnnotation.signature()
- if signature == nil {
- return
- }
- signaturestateVC.signature = signature
- signaturestateVC.reloadData()
- }
- }
- }
-
-
- }
- extension KMMainViewController: KMNThumbnailBaseViewDelegate {
- func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int) {
- exitPageEditMode()
- viewManager.isPageEditMode = false
- pdfToolbarController?.clickWithIdentify(KMPDFToolbar_PageEdit_Identifier)
- if listView.currentPageIndex != currentIndex {
- listView.go(toPageIndex: currentIndex, animated: true)
- }
- }
-
- func insertPDFThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, pdfDocment: CPDFDocument?) {
- if(pdfDocment != nil) {
- insertDocuments.insert(pdfDocment!)
- }
- }
-
- func changeIndexPathsThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, selectionIndexPaths: Set<IndexPath>, selectionStrings: String) {
- toolbarManager.page_pageInfo_Property.text = selectionStrings
-
- if(toolbarManager.page_pageInfo_Property.creatable == false) {
- toolbarManager.page_pageInfo_Property.creatable = true
- }
- pdfToolbarController?.refreshSecondToolbarItemsState()
- }
-
- func leftSideViewControllerThumbnailHaveChange(leftSideViewController: KMNLeftSideViewController) {
- if(self.pageEditViewController?.view.superview == nil) {
- listView.layoutDocumentView()
- botaViewController?.reloadData()
- }
- }
- }
- extension KMMainViewController: KMNLeftSideViewControllerDelegate {
- func enterPageEditLeftSideViewController(leftSideViewController: KMNLeftSideViewController) {
- if viewManager.isPageEditMode == false {
- viewManager.isPageEditMode = true
- if(pdfToolbarController != nil) {
- kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_PageEdit_Identifier)
- pdfToolbarController?.resetSecondToolbar()
- pageEditViewController?.selectionIndexPaths = leftSideViewController.thumnailViewController?.collectionView.selectionIndexPaths ?? []
- }
- }
- }
-
- func changeSelectePageLeftSideViewController(leftSideViewController: KMNLeftSideViewController, pageIndex: Int) {
- if(listView.currentPageIndex != pageIndex) {
- listView.go(toPageIndex: pageIndex, animated: true)
- }
- }
-
- func addBookmarkForLeftC(controller: KMNLeftSideViewController, bookmark: CPDFBookmark?, info: [String : Any]?) {
- if let result = info?["result"] as? Bool {
- if result == false {
- if let targetV = listView.superview {
- _ = 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))
- }
- }
- }
- }
-
- func switchSearchPopWindow(controller: KMNLeftSideViewController) {
- if(viewManager.pdfSideBarType == .search) {
- toggleCloseLeftSide()
- }
-
- let handdler = controller.searchViewC.handdler
- showSearchPopWindow(type: handdler.type, keyborad: handdler.searchKey, replaceText: handdler.replaceKey, results: handdler.searchResults)
- }
-
- func searchTypeDidChange(controller: KMNLeftSideViewController) {
- let handdler = controller.searchViewC.handdler
- if handdler.type == .replace {
- if viewManager.toolMode != .Edit {
- viewManager.toolMode = .Edit
- updatePDFViewAnnotationMode()
- pdfToolbarController?.reloadToolbarTabsView()
- }
- }
- }
- }
- extension KMMainViewController: ComponentGroupDelegate {
- func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
- if menuItemProperty?.identifier == PDFViewMenuIdentifier_PageNext {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if objectListView.canGoToNextPage() {
- objectListView.goToNextPage(nil)
- }
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PagePrevious) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if objectListView.canGoToPreviousPage() {
- objectListView.goToPreviousPage(nil)
- }
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageFirst) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if objectListView.canGoToFirstPage() {
- objectListView.goToFirstPage(nil)
- }
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_PageLast) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if objectListView.canGoToLastPage() {
- objectListView.goToLastPage(nil)
- }
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_LaserPoint) {
- listView.exitPresentationDrawMode()
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Brush) {
- listView.enterPresentationDrawMode()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Presentation_Exit) {
- self.exitFullScreen()
- } else if menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIRewrite {
- viewManager.pdfSideBarType = .aiTools
- sideBarController?.reloadData()
- if let sideVC = sideBarController {
- kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
- }
- botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
- botaViewController?.chooseAIFunctionWithType(.reWriting)
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AIProofread) {
- viewManager.pdfSideBarType = .aiTools
- sideBarController?.reloadData()
- if let sideVC = sideBarController {
- kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
- }
- botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
- botaViewController?.chooseAIFunctionWithType(.proofreading)
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AITranslate) {
- viewManager.pdfSideBarType = .aiTools
- sideBarController?.reloadData()
- if let sideVC = sideBarController {
- kmPDFSideBarControllerDidSidebarTypeUpdated(sideVC)
- }
- botaViewController?.setCurrentPDFSelection(self.listView.currentSelection.string())
- botaViewController?.chooseAIFunctionWithType(.translate)
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Past) {
- let theEvent = menuItemProperty?.representedObject
-
- if let currentEvent = theEvent as? NSEvent {
- var pagePoint = CGPoint.zero
- if let page = listView.pageAndPoint(&pagePoint, for: currentEvent, nearest: false) {
- listView.menuPointPaste(pagePoint, page: page, isRightPaste: true)
- }
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllText) {
- if self.listView.toolMode == .CRedactToolMode {
- if let dic = menuItemProperty?.representedObject as? NSDictionary {
- let objectListView = dic["Object"] as? CPDFListView
- let theEvent = dic["theEvent"] as? NSEvent
-
- if(objectListView != nil && theEvent != nil) {
- var pagePoint = CGPoint.zero
- if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
-
- self.selectAllRedactAnnotation(currentPage: page)
- }
- }
- }
- } else {
- listView.selectAll(nil)
- }
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddBook) {
- menuItemBookMarkClick_add(sender: nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TextTool) {
- listView.toolMode = .CTextToolMode
- listView.annotationType = .unkown
- viewManager.viewToolsType = .Select
- pdfToolbarController?.reloadToolsView()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MoveTool) {
- listView.toolMode = .CMoveToolMode
- listView.annotationType = .unkown
- viewManager.viewToolsType = .Scroll
-
- pdfToolbarController?.viewManager?.toolMode = .None
- pdfToolbarController?.viewManager?.subToolMode = .None
- refreshToolbarViewHeightInfo()
- pdfToolbarController?.reloadData()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectTool) {
- listView.toolMode = .CSelectToolMode
- listView.annotationType = .unkown
- viewManager.viewToolsType = .Content_Selection
-
- pdfToolbarController?.viewManager?.toolMode = .None
- pdfToolbarController?.viewManager?.subToolMode = .None
- refreshToolbarViewHeightInfo()
- pdfToolbarController?.reloadData()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_MagnifyTool) {
- listView.toolMode = .CMagnifyToolMode
- listView.annotationType = .unkown
- viewManager.viewToolsType = .Magnify
-
- pdfToolbarController?.viewManager?.toolMode = .None
- pdfToolbarController?.viewManager?.subToolMode = .None
- refreshToolbarViewHeightInfo()
- pdfToolbarController?.reloadData()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectZoomTool) {
- listView.toolMode = .CSelectZoomToolMode
- listView.annotationType = .unkown
- viewManager.viewToolsType = .AreaZoom
-
- pdfToolbarController?.viewManager?.toolMode = .None
- pdfToolbarController?.viewManager?.subToolMode = .None
- refreshToolbarViewHeightInfo()
- pdfToolbarController?.reloadData()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Single) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.menuItemClick_SinglePage(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SingleContinuous) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.menuItemClick_SinglePagesContinuous(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPages) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.menuItemClick_TwoPages(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TwoPagesContinuous) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.menuItemClick_TwoPagesContinuous(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BookMode) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.menuItemClick_BookMode(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ReadMode) {
- viewManager.isPDFReadMode = !viewManager.isPDFReadMode
- if viewManager.isPDFReadMode {
- openPDFReadMode()
- } else {
- exitPDFReadMode()
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleWidth) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- objectListView.autoScales = true
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScalePage) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- let pageHeight = objectListView.currentPage()!.size.height
- let pdfviewHeight = objectListView.bounds.size.height
- objectListView.scaleFactor = pdfviewHeight/pageHeight
- objectListView.autoScales = false
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleOrg) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if objectListView.scaleFactor != 1.0 {
- objectListView.scaleFactor = 1.0
- objectListView.autoScales = false
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomIn) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- var scale = objectListView.scaleFactor
- switch scale {
- case 0...0.25:
- scale += 0.25
- case 0.25...3:
- scale += 0.25
- case 3.1...10:
- scale += 0.4
- case 10.1...100:
- scale += 1
- default:
- scale += 1
- }
- objectListView.scaleFactor = scale
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ScaleZoomOut) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- var scale = objectListView.scaleFactor
- switch scale {
- case 0...0.25:
- scale = 0
- case 0.25...3:
- scale -= 0.25
- case 3.1...10:
- scale -= 0.4
- case 10.1...100:
- scale -= 1
- default:
- scale -= 1
- }
- objectListView.scaleFactor = scale
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateLeft) {
- if let dic = menuItemProperty?.representedObject as? NSDictionary {
- let objectListView = dic["Object"] as? CPDFListView
- let theEvent = dic["theEvent"] as? NSEvent
-
- if(objectListView != nil && theEvent != nil) {
- var pagePoint = CGPoint.zero
- if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
- rotateLeft(page: page, listView: objectListView)
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RotateRight) {
- if let dic = menuItemProperty?.representedObject as? NSDictionary {
- let objectListView = dic["Object"] as? CPDFListView
- let theEvent = dic["theEvent"] as? NSEvent
-
- if(objectListView != nil && theEvent != nil) {
- var pagePoint = CGPoint.zero
- if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
- rotateRight(page: page, listView: objectListView)
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_EnterPageNum) {
- gotoPage(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageBack) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if(objectListView.km_canGoBack() == true) {
- objectListView.km_goBack(nil)
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_PageForward) {
- if let objectListView = menuItemProperty?.representedObject as? CPDFListView {
- if(objectListView.km_canGoForward() == true) {
- objectListView.km_goForward(nil)
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AutoScroll) {
- toggleAutoFlow(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightForm) {
- highlightFormFiled(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HightLink) {
- highlightLinks(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RestForm) {
- resetForm(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Search) {
- if botaViewController != nil {
- switchSearchPopWindow(controller: botaViewController!)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Print) {
- menuItemAction_print(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Properties) {
- menuItemAction_property(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Copy) {
- if(listView.isEditing() == true) {
- listView.copyEditAreaAction()
- } else {
- listView.copy(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Hight) {
- if let currentSelect = listView.currentSelection {
- if(currentSelect.selectionType() == .text) {
- listView.addAnnotation(with: .highlight, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- listView.currentSelection = nil;
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Underline) {
- if let currentSelect = listView.currentSelection {
- if(currentSelect.selectionType() == .text) {
- listView.addAnnotation(with: .underline, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- listView.currentSelection = nil;
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Squiggly) {
- if let currentSelect = listView.currentSelection {
- if(currentSelect.selectionType() == .text) {
- listView.addAnnotation(with: .squiggly, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- listView.currentSelection = nil;
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_StrikeOut) {
- if let currentSelect = listView.currentSelection {
- if(currentSelect.selectionType() == .text) {
- listView.addAnnotation(with: .strikeOut, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- listView.currentSelection = nil;
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Square) {
- if let currentSelect = listView.currentSelection {
- listView.addAnnotation(with: .square, selection: currentSelect, page: currentSelect.page, bounds: currentSelect.bounds)
- listView.currentSelection = nil;
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Circle) {
- if let currentSelect = listView.currentSelection {
- listView.addAnnotation(with: .circle, selection: currentSelect, page: currentSelect.page, bounds: listView.currentSelection.bounds)
- listView.currentSelection = nil;
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_AddOutLine) {
- addOutLineItemAction()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TTS) {
- startSpeaking(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SearchText) {
- searchBaiduAction()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllForm) {
- if let dic = menuItemProperty?.representedObject as? NSDictionary {
-
- let objectListView = dic["Object"] as? CPDFListView
- let theEvent = dic["theEvent"] as? NSEvent
-
- if(objectListView != nil && theEvent != nil) {
- var pagePoint = CGPoint.zero
- if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
- selectAllFormAnnotation(currentPage: page)
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowFormName) {
- if(listView.showFormFieldName == true) {
- listView.showFormFieldName = false
- } else {
- listView.showFormFieldName = true
- }
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SelectAllAnnotation) {
- if let dic = menuItemProperty?.representedObject as? NSDictionary {
-
- let objectListView = dic["Object"] as? CPDFListView
- let theEvent = dic["theEvent"] as? NSEvent
-
- if(objectListView != nil && theEvent != nil) {
- var pagePoint = CGPoint.zero
- if let page = objectListView?.pageAndPoint(&pagePoint, for: theEvent, nearest: false) {
- selectAllNomerAnnotation(currentPage: page)
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowAnnotation) {
- let isHiden = listView.hideNotes
- listView.hideNotes = !isHiden
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_CopyText) {
- var copyText:String = ""
- let annotations = listView.activeAnnotations
- for i in 0 ..< (annotations?.count ?? 0){
- if let an = annotations?[i] as? CPDFMarkupAnnotation {
- let markupContent = an.markupContent()
- if markupContent.isEmpty == false {
- if copyText.isEmpty == true {
- copyText = markupContent
- } else {
- copyText = copyText + "\n" + markupContent
- }
- }
- }
- }
-
- let pboard = NSPasteboard.general
- if copyText.isEmpty == false {
- pboard.clearContents()
- pboard.writeObjects([copyText as NSPasteboardWriting])
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Cut) {
- if(listView.isEditing() == true) {
- listView.cutEditAreaAction()
- } else {
- listView.cut(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Delete) {
- if(listView.isEditing() == true) {
- listView.deleteEditAreaAction()
- } else {
- listView.delete(nil)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ShowPopUI) {
- UserDefaults.standard.setValue(true, forKey: settingsShowQuickActionBarKey)
- SettingsManager.sharedInstance.showQuickActionBar = true
- reloadPopUIWindow()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortFirstAnnotation) {
- let activeAnnotations = listView.activeAnnotations
- for i in 0 ..< (activeAnnotations?.count ?? 0){
- let object = activeAnnotations?[i]
- if let an = object as? CPDFAnnotation {
- listView.bringAnnotationFront(an, page: an.page)
- }
- }
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortTopAnnotation) {
- let activeAnnotations = listView.activeAnnotations
- for i in 0 ..< (activeAnnotations?.count ?? 0){
- let object = activeAnnotations?[i]
- if let an = object as? CPDFAnnotation {
- listView.bringAnnotationForward(an, page: an.page)
- }
- }
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortBottomAnnotation) {
- let activeAnnotations = listView.activeAnnotations
- for i in 0 ..< (activeAnnotations?.count ?? 0){
- let object = activeAnnotations?[i]
- if let an = object as? CPDFAnnotation {
- listView.sendAnnotationBackward(an, page: an.page)
- }
- }
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_SortLastAnnotation) {
- let activeAnnotations = listView.activeAnnotations
- for i in 0 ..< (activeAnnotations?.count ?? 0){
- let object = activeAnnotations?[i]
- if let an = object as? CPDFAnnotation {
- listView.sendAnnotationBack(an, page: an.page)
- }
- }
- listView.setNeedsDisplayAnnotationViewForVisiblePages()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_Content) {
- if let activeAnnotation = listView.activeAnnotation {
- listView.edit(activeAnnotation)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Apply) {
- redactApplyAction()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Multipage) {
- for activeAnnotation in listView.activeAnnotations {
- if let redactAnnotation = activeAnnotation as? CPDFRedactAnnotation {
- redactMultipageAction(redactAnnotation: redactAnnotation)
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Redact_Default) {
- if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation {
- setPropertiesDefault(annotation: redactAnnotation)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewSingleMode) {
- listView.viewSplitMode = .disable
- reloadPDFSplitInfo()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewVerticalMode) {
- listView.viewSplitMode = .vertical
- reloadPDFSplitInfo()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ViewHorizontalMode) {
- listView.viewSplitMode = .horizontal
- reloadPDFSplitInfo()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_Sync) {
- viewManager.splitSyncScroll = !viewManager.splitSyncScroll
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Split_ShowBar) {
- viewManager.splitShowBottomBar = !viewManager.splitShowBottomBar
- splitPDFController?.refreshToolbarState()
-
- reloadPDFPageNumberToolbar()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_LeftAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.left)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .left)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_VerticallyAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.vertical)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .vertical)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RightAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.right)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .right)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_TopAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.top)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .top)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_HorizontallyAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.horizontally)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .horizontally)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_BottomAlight) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.bottom)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .bottom)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeHorizontally) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.disHorizontally)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disHorizontally)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_DistributeVertically) {
- if(listView.isEditing()) {
- listView.changeEditingAreas(.disVertical)
- } else {
- listView.change(listView.activeAnnotations as? [CPDFAnnotation], alignmentType: .disVertical)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportJPG) {
- if(listView.isEditing() == true) {
- listView.exportEditingImageAreasAction(format: "jpg")
- } else {
- if let currentSelection = listView.currentSelection {
- if(currentSelection.selectionType() == .image) {
- listView.exprotSelection(currentSelection, type: 1)
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPNG) {
- if(listView.isEditing() == true) {
- listView.exportEditingImageAreasAction(format: "png")
- } else {
- if let currentSelection = listView.currentSelection {
- if(currentSelection.selectionType() == .image) {
- listView.exprotSelection(currentSelection, type: 0)
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_ExportPDF) {
- if(listView.isEditing() == true) {
- listView.exportEditingImageAreasAction(format: "pdf")
- } else {
- if let currentSelection = listView.currentSelection {
- if(currentSelection.selectionType() == .image) {
- listView.exprotSelection(currentSelection, type: 2)
- }
- }
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Paste) {
- let pointValue = NSValue(point: group?.pagePoint ?? CGPointZero)
- listView.pasteEditAreaMatchStyleActionWith(pointValue)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_NoStylePaste) {
- let pointValue = NSValue(point: group?.pagePoint ?? CGPointZero)
- listView.pasteEditAreaActionWith(pointValue)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_SelectAll) {
- if listView.km_EditingAreas().count <= 0 {
- listView.selectAllAreaAction()
- } else {
- listView.selectAllAction(with: listView.km_EditingAreas().first)
- }
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddLink) {
- pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_link_Identifier)
-
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddText) {
- pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_text_Identifier)
-
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_AddImage) {
- pdfToolbarController?.clickWithIdentify(KMPDFToolbar_edit_image_Identifier)
-
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontBold) {
- listView.setEditingTextarea_Bold()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontItalic) {
- listView.setEditingTextarea_Italic()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontUnderline) {
- listView.setEditingTextarea_Under()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontStrikeout) {
- listView.setEditingTextarea_Strikeout()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomIn) {
- listView.zoomInEditTextFontSize()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontZoomOut) {
- listView.zoomOutEditTextFontSize()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontColor) {
- let colorPanel = NSColorPanel.shared
- colorPanel.setTarget(self)
- colorPanel.setAction(#selector(editFontColorItemPanelAction(_:)))
- colorPanel.orderFront(nil)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH1Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h1)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH2Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h2)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontH3Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .h3)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB1Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b1)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB2Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b2)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontB3Name) {
- let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .b3)
- self.updateEditPDFTextFontModel(model)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontLeftAlight) {
- listView.setEditingTextarea_Alignment(align:.left)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontCenterAlight) {
- listView.setEditingTextarea_Alignment(align:.center)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontRightAlight) {
- listView.setEditingTextarea_Alignment(align:.right)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_FontJustAlight) {
- listView.setEditingTextarea_Alignment(align:.justified)
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateLeft) {
- listView.leftRotateAction()
- rightSideController?.reloadEditingAreas()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_RotateRight) {
- listView.rightRotateAction()
- rightSideController?.reloadEditingAreas()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_HorizontalMirror) {
- listView.reverseXAction()
- rightSideController?.reloadEditingAreas()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_VerticalMirror) {
- listView.reverseYAction()
- rightSideController?.reloadEditingAreas()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Crop) {
- listView.cropAction()
- rightSideController?.reloadEditingAreas()
- } else if(menuItemProperty?.identifier == PDFViewMenuIdentifier_Edit_Replace) {
- listView.replaceImageEdit()
- rightSideController?.reloadEditingAreas()
- } else if (menuItemProperty?.identifier == PDFViewMenuIdentifier_Normal_RedactProperties) {
- if let redactAnnotation = listView.activeAnnotation as? CPDFRedactAnnotation{
- showRedactProperty(readactAnnotation: redactAnnotation)
- }
- }
-
- }
-
- func componentGroupDidDismiss(group: ComponentGroup?) {
-
- }
-
-
- func updateEditPDFTextFontModel(_ model: KMEditPDFTextFontModel) {
-
- let fontName = model.fontName
- let fontStyle = model.fontStyle
- let fontSize = model.fontSize
- let bold = model.bold
- let italic = model.italic
- let alignment = model.alignment
- let font = CPDFFont(familyName: fontName, fontStyle: fontStyle)
-
- listView.setEditingTextarea_font(font: font)
- listView.setEditingTextarea_FontSize(size: fontSize)
- listView.setEditingTextarea(isBold: bold)
- listView.setEditingTextarea(isItalic: italic)
- listView.setEditingTextarea_Alignment(align: alignment)
-
- }
- }
-
- extension KMMainViewController: KMSnapshotWindowControllerDelegate {
- func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
-
- }
-
- func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
- return CGRectZero
- }
-
- func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
- }
- }
- extension KMMainViewController: CPDFDocumentDelegate {
- func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
- }
-
- func documentDidEndDocumentFind(_ document: CPDFDocument!) {
- }
- }
-
- extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
- func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, updateMeasureInfo measureInfo: CPDFMeasureInfo?) {
- if measureInfo != nil {
- if self.listView.activeAnnotations.count > 0 {
- if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
- self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo, withNewMeasure: measureInfo)
- } else if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
- self.updateMeasureInfo((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo, withNewMeasure: measureInfo)
- } else if let data = self.listView.activeAnnotation as? CPDFLineAnnotation, data.isMeasure {
- self.updateMeasureInfo(data.measureInfo, withNewMeasure: measureInfo)
- }
-
- self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
- }
-
- self.updateMeasureInfo(self.listView.distanceMeasureInfo, withNewMeasure: measureInfo)
- self.updateMeasureInfo(self.listView.perimeterMeasureInfo, withNewMeasure: measureInfo)
- self.updateMeasureInfo(self.listView.polygonAreaMeasureInfo, withNewMeasure: measureInfo)
- self.updateMeasureInfo(self.listView.squareAreaMeasureInfo, withNewMeasure: measureInfo)
- }
- }
-
- func updateMeasureInfo(_ measureInfo: CPDFMeasureInfo?, withNewMeasure newMeasure: CPDFMeasureInfo?) {
- guard let measureInfo = measureInfo else { return }
- guard let newMeasure = newMeasure else { return }
-
- measureInfo.rulerBase = newMeasure.rulerBase
- measureInfo.rulerTranslate = newMeasure.rulerTranslate
- measureInfo.rulerBaseUnit = newMeasure.rulerBaseUnit
- measureInfo.rulerTranslateUnit = newMeasure.rulerTranslateUnit
- measureInfo.factor = newMeasure.factor
- measureInfo.precision = newMeasure.precision
-
- }
- }
- extension KMMainViewController {
- func showRedactProperty(readactAnnotation: CPDFRedactAnnotation?) {
- let properties = KMRedactPropertiesWindowController()
- properties.readactAnnotation = readactAnnotation
-
- properties.own_beginSheetModal(for: self.view.window) { result in
-
- }
- }
-
- func redactApplyAction(needAlert: Bool = true) {
- if needAlert {
- DispatchQueue.main.async { [weak self] in
- guard let self = self else {
- return
- }
-
- if UserDefaults.standard.object(forKey: "kApplyRedactAlert") != nil {
- self.listView.document.applyRedactions()
- self.listView.layoutDocumentView()
- return
- }
- let alert = NSAlert()
- alert.alertStyle = .informational
- alert.messageText = KMLocalizedString("This action will permanently remove the redacted information from this document.")
- alert.informativeText = KMLocalizedString("""
- After you save this document, you will not be able to retrieve the redacted information.
- """)
- alert.addButton(withTitle: KMLocalizedString("Apply"))
- alert.addButton(withTitle: KMLocalizedString("Cancel"))
- alert.showsSuppressionButton = true
- let response = alert.runModal()
- if response.rawValue == 1000 {
- if alert.suppressionButton?.state == .on {
- UserDefaults.standard.set("YES", forKey: "kApplyRedactAlert")
- UserDefaults.standard.synchronize()
- }
-
- self.listView.document.applyRedactions()
- self.listView.layoutDocumentView()
- } else if response.rawValue == 1001 {
-
-
- }
- }
- } else {
- self.listView.document.applyRedactions()
- self.listView.layoutDocumentView()
- }
- }
-
- func redactMultipageAction(redactAnnotation:CPDFRedactAnnotation) {
- let pagesWindowController = KMRedactSelectPagesWindowController(document: listView.document)
- pagesWindowController.own_beginSheetModal(for: self.view.window) { result in
-
- }
- pagesWindowController.callback = { [weak self] pages in
- if pages.count > 0 {
- self?.listView.redactAddAnnotationPages(pages, redactAnnotation: redactAnnotation)
- }
- }
- }
-
- func setPropertiesDefault(annotation:CPDFRedactAnnotation) {
- CPDFRedactAnnotation.update_defaultOutlineColor(annotation.borderColor())
- CPDFRedactAnnotation.update_defaultFillColor(annotation.interiorColor())
- CPDFRedactAnnotation.update_defaultTextColor(annotation.fontColor())
- CPDFRedactAnnotation.update_defaultFontSize(annotation.fontSize)
-
- CPDFRedactAnnotation.update_defaultFontAlignment(annotation.alignment())
- CPDFRedactAnnotation.update_defaultOverlayText(annotation.overlayText())
- }
-
- func enterRedactAlert() {
- if UserDefaults.standard.object(forKey: "kRedact") != nil {
- return
- }
- let alert = NSAlert()
- alert.alertStyle = .informational
- alert.informativeText = KMLocalizedString("Redaction allows you to permanently mask and remove sensitive content.")
- alert.messageText = KMLocalizedString("""
- Redaction requires two steps:
- 1. Mark for Redaction
- 2. Apply Redactions
- Note: Redactions are not applied permanently until you select Apply Redactions.
- """)
- alert.addButton(withTitle: KMLocalizedString("OK"))
- alert.showsSuppressionButton = true
- let response = alert.runModal()
- if response.rawValue == 1000 {
- if alert.suppressionButton?.state == .on {
- UserDefaults.standard.set("YES", forKey: "kRedact")
- UserDefaults.standard.synchronize()
- }
- }
- }
- }
- extension KMMainViewController {
- func removeAllAnnotations() {
- let alert = NSAlert()
- alert.messageText = KMLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Yes", comment:""))
- alert.addButton(withTitle: KMLocalizedString("No", comment:""))
- if (alert.runModal() != .alertFirstButtonReturn) {
- return
- }
-
- DispatchQueue.main.async {
- self.removeAllAnnotationsStore.store(t: self.listView)
- }
- }
-
-
-
- func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
- if (self.document != nil) {
- AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
- } else {
- AIChatInfoManager.defaultManager.currentFilePath = ""
- }
-
- let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
- windowVC.chooseCurFileHandle = {[unowned self] windowVC in
- if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit: Bool = false
- var curDoc: KMMainDocument!
- for document in documentArray {
- if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
- didFileEdit = document.isDocumentEdited
- curDoc = document as! KMMainDocument
- break
- }
- }
- if didFileEdit {
- let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
- if FileManager.default.fileExists(atPath: tempFileURL.path) {
- do {
- try FileManager.default.removeItem(at: tempFileURL)
-
- } catch {
-
- }
- }
- if curDoc != nil {
- curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
- }
- }
- windowVC.window?.becomeMain()
- }
- }
- if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
-
- } else {
- var windowRect = windowVC.window?.frame
- windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
- windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
- windowVC.window?.setFrame(windowRect!, display: true)
-
- windowVC.didSetOriginFrame = true
- }
- windowVC.eventLabel = "AITools_Tbr"
- windowVC.showWindow(nil)
- if (aiConfigType != .none) {
- windowVC.eventLabel = "AITools_Start"
- if self.listView.currentSelection?.string()?.isEmpty == false {
- windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
- }
- windowVC.chooseAIFunctionWithType(aiConfigType)
- }
- }
-
- @objc func aiTipIconViewShowStateChangeNoti() {
-
- }
-
-
- func loadFunctionGuide() -> Void {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
- if self.view.window != nil {
- self.loadOpenFileFunctionGuide(.openFileNormal)
- }
- }
- }
-
- func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
- if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
-
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .openFileNormal
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.normalGuideFinishHandle = { [weak self] windowVC in
-
-
- }
- guideWC.finishHandle = { [weak self] windowVC, type in
- if type == .windowNewFinish ||
- type == . windowDigitalFinish {
- self?.checkFirstTrialController()
- }
- }
- guideWC.openFileToggleHandle = { [weak self] windowVC, type in
- self?.checkFirstTrialController()
- }
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .digitalSignGuide
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.finishHandle = { [weak self] windowVC, type in
- self?.checkFirstTrialController()
- }
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
-
- } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .pdfCompareGuide
-
-
- guard let win = self.view.window else {
- return
- }
-
- guideWC.finishHandle = { [weak self] winC, type in
- if type == .windowNewFinish {
- DispatchQueue.main.async {
- self?.loadOpenFileFunctionGuide(.measureGuide)
- }
- return
- }
- }
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
- guard let _ = self.view.window else {
- return
- }
-
- guideWC.type = .measureGuide
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- var rect = self.view.window?.frame ?? .zero
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .convertGuide
- guard let win = self.view.window else {
- return
- }
- guideWC.purchaseHandle = { [weak self] windowVC in
- #if VERSION_DMG
- if IAPProductsManager.default().isAvailableAllFunction() {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
-
-
- } else {
- let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
- limitWC.continueBlock = { windowController in
-
- }
- limitWC.window?.center()
- limitWC.showWindow(nil)
- }
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- #else
- if IAPProductsManager.default().isAvailableAllFunction() {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
-
- } else {
- var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
- vc.showWindow(nil)
- }
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- #endif
- }
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- var rect = self.view.window?.frame ?? .zero
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- } else {
-
- }
- }
-
- func checkFirstTrialController() -> Void {
- #if VERSION_DMG
-
- if VerificationManager.default().status == .none {
- let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
- let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
- if lastVersion.isEmpty || lastVersion != appVersion {
- UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
- UserDefaults.standard.synchronize()
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- }
- #endif
- }
-
-
-
- func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
- let url = URL(fileURLWithPath: filePath)
- guard let document = PDFDocument(url: url) else {
- return false
- }
-
- let pageCount = document.pageCount
- return pageCount > 30
- }
-
-
- internal func needSaveDocument() -> Bool {
- if (self.isPDFDocumentEdited) {
- return self.isPDFDocumentEdited
- }
- if (self.needSave) {
- return self.needSave
- }
-
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
- return false
- }
- return true
- }
-
- internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (overlook) {
- document?.save(nil)
- return
- }
- if (self.isPDFDocumentEdited) {
- self.needSave = false
- document?.save(nil)
- return
- }
- if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
- return
- }
-
- document?.save(nil)
- }
-
- internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (overlook) {
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- return
- }
- if (self.isPDFDocumentEdited) {
- self.needSave = false
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- return
- }
- if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
- callback()
- return
- }
-
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- }
-
- internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
-
- AutoSaveManager.manager.isSaving = true
- self.showProgressWindow(message: KMLocalizedString("Save", comment: "") + "PDF")
- self.progressC?.maxValue = 3.0
- self.progressC?.increment(by: 1.0)
-
- self.asyncSaveDocument { [weak self] params in
-
- self?.progressC?.increment(by: 1.0)
- self?.progressC?.increment(by: 1.0)
-
- DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
-
- self?.hiddenProgressWindow()
- DispatchQueue.main.asyncAfter(deadline: .now()+1) {
- AutoSaveManager.manager.isSaving = false
- }
-
- callback()
- }
- }
- }
- func SaveTempPDFDocumentToURLPath(tempPath: String) {
- self.document?.write(toFile: tempPath)
- }
-
-
- func addAutoSaveEvent() {
- if (self.autoSaveTimer != nil) {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- if self.document != nil, SettingsManager.sharedInstance.autoSaveFile == true {
- self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: 1 * 60, repeats: true, block: { [weak self] timer in
- self?.autoSaveTimerAction(timer)
- })
- }
- self.checkAutoSaveInfo()
- }
-
- func checkAutoSaveInfo() {
- guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
- return
- }
- if AutoSaveManager.manager.autoSaveAlertShow {
- return
- }
-
- AutoSaveManager.manager.autoSaveDidEndAction = false
- AutoSaveManager.manager.autoSaveAlertShow = true
-
- blockSaveWindow.cancelHandle = { [weak self] windowController in
- AutoSaveManager.manager.autoSaveDidEndAction = true
- AutoSaveManager.manager.clearCache()
-
- self?.view.window?.endSheet(windowController.window!)
- }
-
- blockSaveWindow.confirmHandle = { [weak self] windowController in
- self?.view.window?.endSheet(windowController.window!)
-
- self?.saveAutoSaveInfo()
- }
- self.view.window?.beginSheet(blockSaveWindow.window!)
- }
-
- func saveAutoSaveInfo() {
- let openPanel = NSOpenPanel()
- openPanel.canChooseDirectories = true
- openPanel.canChooseFiles = false
- openPanel.allowsMultipleSelection = false
- let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
- openPanel.beginSheetModal(for: win!) { result in
- if (result == .OK) {
- let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
- for path in AutoSaveManager.manager.opendPaths ?? [] {
- let _path = path as? String
- var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
- newPath = self.getValidFilePath(newPath)
- do {
- try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
- } catch {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
- }
- }
- AutoSaveManager.manager.clearCache()
- }
- AutoSaveManager.manager.autoSaveDidEndAction = true
- }
- }
-
- func autoSaveTimerAction(_ timer: Timer) {
- if (self.document == nil || self.listView.document?.documentURL.path == nil) {
- return
- }
- if AutoSaveManager.manager.autoSaveDidEndAction == false {
-
- return
- }
-
- if let data = self.document?.isLocked, data {
- return
- }
-
- if SettingsManager.sharedInstance.autoSaveFile == false {
- return
- }
-
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit = false
- for doc in documentArray {
- if doc.fileURL?.path == self.document?.documentURL.path {
- didFileEdit = doc.isDocumentEdited
- break
- }
- }
- if (didFileEdit == false) {
- return
- }
-
- AutoSaveManager.manager.isSaving = true
- let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView.document?.documentURL.path ?? "")
- if (!self.document!.isLocked) {
- self.document?.write(to: URL(fileURLWithPath: savePath))
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
- AutoSaveManager.manager.isSaving = false
- }
- }
-
- func removeAutoSaveInfo() {
- if self.autoSaveTimer != nil {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- if AutoSaveManager.manager.autoSaveDidEndAction == false {
-
- return
- }
- if SettingsManager.sharedInstance.autoSaveFile == false {
- return
- }
-
- if self.document == nil || self.listView.document?.documentURL.path == nil {
- return
- }
- AutoSaveManager.manager.removeAutoSavePath(self.listView.document?.documentURL.path ?? "")
- }
-
-
-
- @objc public func selectZoom(_ type: KMPDFZoomType) {
- switch type {
- case .width:
- self.listView.autoScales = true
- break
- case .fit:
- if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
- let pdfviewHeight = self.listView.bounds.size.height
- self.listView.scaleFactor = pdfviewHeight/pageHeight
- self.listView.autoScales = false
- }
-
- break
- case .actualSize:
- if self.listView.scaleFactor != 1.0 {
- self.listView.scaleFactor = 1.0
- self.listView.autoScales = false
- }
- break
- case .zoom_In:
- self.doZoomIn(nil)
-
- break
- case .zoom_Out:
- self.doZoomOut(nil)
-
- break
- }
- }
-
- func doZoomIn(_ sender: Any?) {
- if (self.listView.canZoomIn) {
- self.listView.zoomIn(nil)
- }
- }
-
- func doZoomOut(_ sender: Any?) {
- if (self.listView.canZoomOut) {
- self.listView.zoomOut(nil)
- }
- }
-
-
- private func addEventMonitor() {
- if (self.eventMonitor != nil) {
- self.removeEventMonitor()
- }
-
- self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown, .leftMouseUp]) { [weak self] event in
- if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) {
- self?.listView.magnifyWheel(event)
- return nil
- } else if event.type == .leftMouseDown {
- let point = event.locationInView(self?.listView ?? NSView())
- let presentationDrawView = self?.listView.presentationDrawView
- if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true {
- if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
- let can = self?.listView.canGoToNextPage() ?? false
- if can {
- self?.listView.goToNextPage(nil)
- }
- } else {
- let can = self?.listView.canGoToPreviousPage() ?? false
- if can {
- self?.listView.goToPreviousPage(nil)
- }
- }
-
- return nil
- }
- }
- return event
- }
- }
-
- private func removeEventMonitor() {
- if (self.eventMonitor != nil) {
- KMPrint("已移除事件监听")
-
- NSEvent.removeMonitor(self.eventMonitor as Any)
- self.eventMonitor = nil
- }
- }
-
- func addKeyEventMonitor() {
- if (self.keyEventMonitor != nil) {
- self.removeKeyEventMonitor()
- }
- keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
- if event.keyCode == 53 {
- if self?.listView.annotationType == .freeText {
- self?.listView.keyDown(with: event)
- }
- } else {
-
- }
- return event
- }
- }
-
- func removeKeyEventMonitor() {
- if (self.keyEventMonitor != nil) {
- KMPrint("removeKeyEventMonitor 已移除事件监听")
-
- NSEvent.removeMonitor(self.keyEventMonitor as Any)
- self.keyEventMonitor = nil
- }
- }
-
-
- override func mouseMoved(with event: NSEvent) {
- self.view.window?.mouseMoved(with: event)
- }
-
- override func keyDown(with event: NSEvent) {
- listView.keyDown(with: event)
-
- }
-
-
-
- func pdfViewCanHorizontalScroll() -> Bool {
- let scroll = self.listView.scroll()
- if (scroll == nil) {
- return false
- }
-
- return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
- }
-
- func pdfViewCanVerticalScroll() -> Bool {
- let scroll = self.listView.scroll()
- if (scroll == nil) {
- return false
- }
-
- return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
- }
-
-
-
- public func clearData() {
- KMThumbnailCache.shared.clearCache()
-
- self.removeNotifications()
- if (self.listView.spellingTag() > 0) {
- NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
- }
- self.removeAutoSaveInfo()
-
- self.myDocument = nil
-
- if textFieldSheet.window?.isVisible == true {
- textFieldSheet.close()
- }
-
- if NSColorPanel.shared.isVisible == true {
- NSColorPanel.shared.close()
- }
-
- if KMInfoWindowController.shared.window?.isVisible == true {
- KMInfoWindowController.shared.close()
- }
-
- }
-
- public func clearSecureOptions() {
- self._secureOptions = nil
- self.documentAttribute = nil
- }
-
- public func clearRemoveSecureFlag() {
- self._removeSecureFlag = false
- }
-
- public func recordIsPDFDocumentEdited() {
- km_synchronized(self) {
- self.model.isPDFDocumentEdited = true
-
- if let _document = self.myDocument {
- KMTools.setDocumentEditedState(document: _document)
- }
- }
- }
-
- public func clearIsPDFDocumentEdited() {
- km_synchronized(self) {
- self.model.isPDFDocumentEdited = false
- }
- }
-
- func showSnapshots(setups: NSArray?) {
- if self.listView.document != nil {
- for setup in setups ?? [] {
- let swc = KMSnapshotWindowController()
- swc.delegate = self
- swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
- swc.setForceOnTop(self.interactionMode != .normal)
- self.myDocument?.addWindowController(swc)
- }
- }
- }
-
-
- internal func documentDidUnlockNotification(_ sender: Notification) {
- if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
-
- if (self.myDocument == nil) {
- return
- }
- if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
- self.hiddenSecureLimitTip()
- }
-
- let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
- if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
- return
- }
-
- let type = SettingsManager.sharedInstance.keychainType
- if (type == .never) {
- return
- }
- if (type == .always) {
- self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
- return
- }
-
-
- let alert = NSAlert()
- alert.messageText = KMLocalizedString("Remember Password?", comment: "")
- alert.informativeText = KMLocalizedString("Do you want to save this password in your Keychain?", comment: "")
- alert.addButton(withTitle: KMLocalizedString("Yes", comment: ""))
- alert.addButton(withTitle: KMLocalizedString("No", comment: ""))
- if (alert.runModal() == .alertFirstButtonReturn) {
- self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
- return
- }
- }
- }
-
- internal func applicationWillTerminateNotification(_ sender: Notification) {
- self.savePageNumberIfNeed()
- self.saveDocument()
- }
-
- internal func pdfViewHighlightFormFiledUpdateNoti(_ sender: Notification) {
- self.alertTipViewController.reloadFormAlertUI()
-
- }
-
- func rename(_ sender: NSNotification) -> Void {
- if (self.view.window == nil || self.view.window!.isVisible == false) {
- return
- }
- let tabController = sender.object as? CTTabController
- if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
- if let doc = self.myDocument, doc.isDocumentEdited {
- Task {
- let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
- if resp != .alertFirstButtonReturn {
- return
- }
- doc.updateChangeCount(.changeCleared)
- self.document?.write(to: doc.fileURL)
- Task { @MainActor in
- self._renameForSavePanel(tabController)
- }
- }
- return
- }
-
- self._renameForSavePanel(tabController)
- }
- }
-
- func savePdfAlertView() {
- if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
- return
- }
- AutoSaveManager.manager.isSaveNoti = true
- var num = 0
- if self.listView.document != nil{
- num = Int(self.listView.document.pageCount)
- }
- if Thread.current.isMainThread {
- self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
- } else {
- DispatchQueue.main.async {
- self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
- }
- }
- }
-
- func savePdfFinishAlertView() {
- if !AutoSaveManager.manager.isSaveNoti{
- return
- }
- AutoSaveManager.manager.isSaveNoti = false
- if Thread.current.isMainThread {
- self.dismissProgressSheet()
- } else {
- DispatchQueue.main.async {
- self.dismissProgressSheet()
- }
- }
- }
-
- private func _renameForSavePanel(_ tabC: CTTabController?) {
- let outputSavePanel = NSSavePanel()
- outputSavePanel.title = NSLocalizedString("Rename", comment: "")
- outputSavePanel.allowedFileTypes = ["pdf"]
- outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
- outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
-
- let resp = outputSavePanel.runModal()
- if resp == .OK {
- let pdfDocument = CPDFDocument(url: self.document?.documentURL)
- let fileURL = pdfDocument?.documentURL
-
- let fileManager = FileManager.default
- let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
- var result = true
- do {
- try fileManager.moveItem(at: fileURL!, to: newFileURL)
- } catch {
- result = false
- KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
- }
- if (result) {
- tabC?.title = outputSavePanel.url!.lastPathComponent
- if let newPdfDocument = CPDFDocument(url: newFileURL) {
- self.model.isSaveKeyChain = false
- newPdfDocument.unlock(withPassword: self.document?.password)
- if (newPdfDocument.pageCount > 0) {
- self.setDocument = newPdfDocument
- }
- }
- }
- } else {
- outputSavePanel.close()
- }
- }
-
- func showInFinder(_ sender: Any) -> Void {
- if sender is NSNotification {
- let tabController = (sender as! NSNotification).object as? CTTabController
- let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
- if tabController?.title == path {
- if let file = self.myDocument?.fileURL {
- if FileManager.default.fileExists(atPath: file.path) {
- NSWorkspace.shared.activateFileViewerSelecting([file])
- }
- }
- }
- } else {
- guard let url = self.myDocument?.fileURL else { return }
- let file: URL = url
- if FileManager.default.fileExists(atPath: file.path) {
- NSWorkspace.shared.activateFileViewerSelecting([file])
- }
- }
- }
- }
- extension KMMainViewController {
-
- func cut(_ sender: Any?) {
- if viewManager.isPageEditMode {
- self.pageEditViewController?.cutMenuItemAciton()
- }
- }
- func copy(_ sender: Any?) {
- if viewManager.isPageEditMode {
- self.pageEditViewController?.copyMenuItemAciton()
- }
- }
- func paste(_ sender: Any?) {
- if viewManager.isPageEditMode {
-
- }
- }
- func delete(_ sender: Any?) {
- if viewManager.isPageEditMode {
- self.pageEditViewController?.deleteMenuItemAciton()
- }
- }
- }
|