KMMainViewController.swift 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. let MIN_SIDE_PANE_WIDTH: NSNumber = 264 // 最小值
  10. let CPDFViewIsReadModeKey = "kKMPDFViewIsReadMode"
  11. let CPDFViewLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  12. struct KMNMWCFlags {
  13. var settingUpWindow: Bool = true
  14. }
  15. @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate {
  16. @IBOutlet var contendBox: NSBox!
  17. @IBOutlet var toolbarBox: NSBox! //工具栏Box
  18. @IBOutlet var bottomContendBox: NSBox! //
  19. @IBOutlet var sidebarBox: NSBox! //左侧边栏Box
  20. @IBOutlet var infoContendSplitView: KMPDFSplitView!
  21. @IBOutlet var infoSplitLeftView: NSView!
  22. @IBOutlet var infoSplitRightView: NSView!
  23. @IBOutlet var infoSplitCenterView: NSView!
  24. @IBOutlet var pdfSplitView: NSSplitView!
  25. @IBOutlet var pdfSplitTopView: NSView!
  26. @IBOutlet var pdfSplitBottomView: NSView!
  27. @IBOutlet var toolbarBoxHeightConst: NSLayoutConstraint!
  28. @IBOutlet var infoSplitViewLeftConst: NSLayoutConstraint!
  29. @IBOutlet var infoSplitViewRightConst: NSLayoutConstraint!
  30. var viewManager: KMPDFViewManager = KMPDFViewManager.init()
  31. var toolbarManager: KMPDFToolbarManager = KMPDFToolbarManager.init()
  32. var listView: CPDFListView = CPDFListView.init()
  33. var document: CPDFDocument?
  34. var myDocument: NSDocument?
  35. var isFirstOpen: Bool = true
  36. var insertDocuments: Set<CPDFDocument> = [] //插入新文档时,SDK会出现崩溃,临时记录
  37. //工具栏
  38. private var pdfToolbarController: KMPDFToolbarController?
  39. //BOTA SideBar
  40. private var sideBarController: KMPDFSideBarController?
  41. //页面编辑
  42. private var pageEditViewController: KMNPageEditViewController?
  43. //DisplaySetting
  44. private var displaySettingController: KMNDisplayViewController?
  45. //SPlitPDF分屏视图
  46. private var splitPDFController: KMSplitPDFViewController?
  47. private var pdfBottomToolbar: KMSplitToolbar?
  48. //PPT操作界面
  49. var presentationTopViewController: KMPresentationTopViewController?
  50. //Edit
  51. var editToolbarView: KMEditToolbarView?
  52. //水印
  53. var watermarkViewController: KMWatermarkController?
  54. //背景
  55. var backgroundViewController: KMBackgroundController?
  56. //Header&Footer
  57. var headerFooterViewController: KMHeaderFooterController?
  58. //Bates
  59. var batesViewController: KMBatesController?
  60. //Crop
  61. var cropController: KMCropController?
  62. //左边
  63. var botaViewController: KMNLeftSideViewController?
  64. //右边
  65. var rightSideController: KMRightSideController?
  66. //MARK: - 旧代码,有需要用到的拿出来,写好备注
  67. @IBOutlet weak var leftView: NSView!
  68. var model = KMMainModel()
  69. //自动滚动
  70. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  71. //Search
  72. var searchIndex: Int = 0
  73. //Form
  74. var formAlertView: KMFormAlertView?
  75. //Secure
  76. var secureAlertView: KMSecureAlertView?
  77. //对比
  78. var isCompareModel: Bool = false {
  79. didSet {
  80. }
  81. }
  82. //合并
  83. var mergeWindowController: KMMergeWindowController?
  84. //密码弹窗
  85. var passwordWindow: KMPasswordInputWindow?
  86. //对比
  87. var compressWIndowControllerNew: KMCompressWIndowControllerNew?
  88. //
  89. var securityWindowController: KMSecurityWindowController?
  90. //引导
  91. var guideInfoWindowController: KMGuideInfoWindowController?
  92. //春季活动
  93. var recommondPopWindowVC: KMRecommondPopWindow?
  94. var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  95. private var _needSave = false
  96. var needSave: Bool {
  97. set {
  98. _needSave = newValue
  99. if (_needSave == false) {
  100. self.clearIsPDFDocumentEdited()
  101. }
  102. }
  103. get {
  104. return _needSave
  105. }
  106. }
  107. var isPDFDocumentEdited: Bool {
  108. get {
  109. return self.model.isPDFDocumentEdited
  110. }
  111. }
  112. var newMwcFlags = KMNMWCFlags(settingUpWindow: true)
  113. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  114. var searchResults: [KMSearchMode] = []
  115. var mwcFlags: MwcFlags = MwcFlags()
  116. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  117. var currentWindowController: NSWindowController!
  118. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  119. //数字签名
  120. var digitalSignController: KMPDFDigitalSignViewController?
  121. var redactController: KMPDFRedactViewController!
  122. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  123. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  124. var extract: KMExtractImageWindowController?
  125. var functionWidth: Double {
  126. get {
  127. if self.viewManager.isPDFReadMode {
  128. if !self.model.isShowBOTA {
  129. return 0
  130. }
  131. }
  132. return 48-4
  133. }
  134. }
  135. var pageNumber: UInt?
  136. var pdfEditController: KMPDFEditViewController? {
  137. get {
  138. return self.getPDFEditController()
  139. }
  140. }
  141. var autoSaveTimer: Timer?
  142. private var _documentFirstLoad: Bool = true
  143. var eventMonitor: Any?
  144. var keyEventMonitor: Any?
  145. var mouseRightMenuEvent: NSEvent?
  146. lazy private var homeVC: KMNHomeViewController? = {
  147. let vc = KMNHomeViewController()
  148. return vc
  149. }()
  150. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  151. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  152. get {
  153. return self._secureOptions
  154. }
  155. }
  156. var documentAttribute: [CPDFDocumentAttribute : Any]?
  157. fileprivate var _removeSecureFlag = false
  158. var removeSecureFlag: Bool {
  159. get {
  160. return self._removeSecureFlag
  161. }
  162. }
  163. fileprivate var _saveWatermarkFlag = false
  164. var saveWatermarkFlag: Bool {
  165. get {
  166. return self._saveWatermarkFlag
  167. }
  168. }
  169. private var mainWindow_: NSWindow?
  170. var mainWindow: NSWindow? {
  171. get {
  172. return self.mainWindow_
  173. }
  174. set {
  175. self.mainWindow_ = newValue
  176. }
  177. }
  178. var setDocument: CPDFDocument? {
  179. get {
  180. return document
  181. }
  182. set {
  183. if document != newValue {
  184. document = newValue
  185. }
  186. listView.document = document
  187. botaViewController?.changeDocument(document: document)
  188. }
  189. }
  190. var setPageNumber: UInt {
  191. get {
  192. return pageNumber!
  193. }
  194. set {
  195. let pageCount = listView.document?.pageCount ?? 0
  196. var value = newValue
  197. if value > pageCount {
  198. value = pageCount
  199. }
  200. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  201. listView.go(to: listView.document?.page(at: value-1))
  202. }
  203. if pageNumber != value {
  204. pageNumber = value
  205. }
  206. }
  207. }
  208. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  209. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  210. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  211. //MARK: - func
  212. deinit {
  213. NotificationCenter.default.removeObserver(self)
  214. self.listView.delegate = nil
  215. self.listView.document?.delegate = nil
  216. self.removeEventMonitor()
  217. self.removeKeyEventMonitor()
  218. }
  219. override func viewDidLoad() {
  220. super.viewDidLoad()
  221. // Do view setup here.
  222. setupData()
  223. setupUI()
  224. loadUserDefaultsData()
  225. }
  226. override func viewDidAppear() {
  227. super.viewDidAppear()
  228. }
  229. //MARK: - private
  230. func setupUI() {
  231. initPDFView()
  232. initToolbar()
  233. initSideBar()
  234. setUpSplitView()
  235. }
  236. func setupData() {
  237. toolbarManager.pdfViewManager = viewManager
  238. if (UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) != nil) {
  239. UserDefaults.standard.set(MIN_SIDE_PANE_WIDTH, forKey: CPDFViewLeftSidePaneWidthKey)
  240. UserDefaults.standard.synchronize()
  241. }
  242. newMwcFlags.settingUpWindow = true
  243. }
  244. //MARK: - document load成功
  245. private func documentLoadComplete() {
  246. loadUserDefaultsData()
  247. initLeftSideController()
  248. activityLoadMethod()
  249. let readModel = UserDefaults.standard.bool(forKey: CPDFViewIsReadModeKey)
  250. if readModel == true {
  251. self.openPDFReadMode()
  252. }
  253. toggleCloseLeftSide() //根据偏好设置显示左边栏状态
  254. newMwcFlags.settingUpWindow = false
  255. }
  256. //MARK: - 活动加载相关
  257. private func activityLoadMethod() {
  258. }
  259. private func loadUserDefaultsData() {
  260. applyLeftSideWidth(0, rightSideWidth: 0) //初始打开左边栏
  261. }
  262. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  263. infoContendSplitView.setPosition(infoContendSplitView.maxPossiblePositionOfDivider(at: 1) - infoContendSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  264. infoContendSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  265. }
  266. //MARK: - PDFView
  267. func initPDFView() {
  268. listView.autoresizingMask = [.width, .height]
  269. listView.autoScales = true
  270. listView.delegate = self
  271. listView.pdfListViewDelegate = self
  272. listView.document = self.document
  273. reloadPDFSplitInfo()
  274. }
  275. func updatePDFViewAnnotationMode() {
  276. let toolbarMode = viewManager.toolMode
  277. let subToolMode = viewManager.subToolMode
  278. listView.isHidden = false
  279. if toolbarMode == .None {
  280. listView.annotationType = .unkown
  281. listView.toolMode = .noteToolMode
  282. } else if toolbarMode == .Markup {
  283. //MARK: -Markup
  284. listView.toolMode = .noteToolMode
  285. if subToolMode == .None {
  286. listView.annotationType = .unkown
  287. } else if subToolMode == .Highlight {
  288. listView.annotationType = .highlight
  289. } else if subToolMode == .Underline {
  290. listView.annotationType = .underline
  291. } else if subToolMode == .Waveline {
  292. listView.annotationType = .squiggly
  293. } else if subToolMode == .Strikethrough {
  294. listView.annotationType = .strikeOut
  295. } else if subToolMode == .Text {
  296. listView.annotationType = .freeText
  297. } else if subToolMode == .Note {
  298. listView.annotationType = .anchored
  299. } else if subToolMode == .Pen {
  300. listView.annotationType = .ink
  301. } else if subToolMode == .Eraser {
  302. listView.annotationType = .eraser
  303. } else if subToolMode == .Rectangle {
  304. listView.annotationType = .square
  305. } else if subToolMode == .Circle {
  306. listView.annotationType = .circle
  307. } else if subToolMode == .Arrow {
  308. listView.annotationType = .arrow
  309. } else if subToolMode == .Line {
  310. listView.annotationType = .line
  311. } else if subToolMode == .Measure {
  312. listView.toolMode = .measureToolMode
  313. listView.annotationType = .line
  314. } else if subToolMode == .Stamp {
  315. listView.annotationType = .stamp
  316. } else if subToolMode == .Sign {
  317. listView.annotationType = .signSignature
  318. }
  319. } else if toolbarMode == .Edit {
  320. //MARK: -编辑
  321. if subToolMode == .None {
  322. if listView.toolMode != .editPDFToolMode {
  323. listView.toolMode = .editPDFToolMode
  324. listView.configPDFEditingInfo()
  325. }
  326. listView.annotationType = .editTextImage
  327. listView.setShouAddEdit([])
  328. listView.change([.text, .image])
  329. } else if subToolMode == .Edit_text {
  330. if listView.toolMode != .editPDFToolMode {
  331. listView.toolMode = .editPDFToolMode
  332. listView.configPDFEditingInfo()
  333. }
  334. listView.annotationType = .addText
  335. listView.setShouAddEdit([.text])
  336. listView.change(.text)
  337. } else if subToolMode == .Edit_Image {
  338. if listView.toolMode != .editPDFToolMode {
  339. listView.toolMode = .editPDFToolMode
  340. listView.configPDFEditingInfo()
  341. }
  342. listView.annotationType = .addImage
  343. listView.setShouAddEdit([.image])
  344. listView.change(.image)
  345. } else if subToolMode == .Edit_Link {
  346. listView.toolMode = .noteToolMode
  347. listView.annotationType = .link
  348. } else if subToolMode == .Edit_Crop {
  349. listView.isHidden = true
  350. }
  351. if viewManager.editType == .watermark ||
  352. viewManager.editType == .background ||
  353. viewManager.editType == .header_Footer ||
  354. viewManager.editType == .bates {
  355. listView.isHidden = true
  356. }
  357. if subToolMode != .Edit_Crop {
  358. removeCropController()
  359. }
  360. } else if toolbarMode == .Form {
  361. //MARK: -Form表单
  362. listView.toolMode = .formToolMode
  363. if subToolMode == .None {
  364. listView.annotationType = .unkown
  365. } else if subToolMode == .Form_text {
  366. listView.annotationType = .textField
  367. } else if subToolMode == .Form_checkbox {
  368. listView.annotationType = .checkBox
  369. } else if subToolMode == .Form_radio {
  370. listView.annotationType = .radioButton
  371. } else if subToolMode == .Form_list {
  372. listView.annotationType = .listMenu
  373. } else if subToolMode == .Form_dropdown {
  374. listView.annotationType = .comboBox
  375. } else if subToolMode == .Form_OK {
  376. listView.annotationType = .actionButton
  377. } else if subToolMode == .Form_digitalSign {
  378. }
  379. } else if toolbarMode == .Fill {
  380. //MARK: -填充
  381. listView.toolMode = .selfSignMode
  382. if subToolMode == .None {
  383. } else if subToolMode == .Fill_tick {
  384. listView.annotationType = .signTure
  385. } else if subToolMode == .fill_fork {
  386. listView.annotationType = .signFalse
  387. } else if subToolMode == .fill_rectangle {
  388. listView.annotationType = .signCircle
  389. } else if subToolMode == .fill_line {
  390. listView.annotationType = .signLine
  391. } else if subToolMode == .fill_dot {
  392. listView.annotationType = .signDot
  393. } else if subToolMode == .fill_date {
  394. listView.annotationType = .signDate
  395. } else if subToolMode == .fill_sign {
  396. listView.annotationType = .signSignature
  397. }
  398. } else if toolbarMode == .Convert {
  399. //MARK: -转档
  400. listView.toolMode = .textToolMode
  401. } else if toolbarMode == .Protect {
  402. //MARK: -Protect
  403. listView.toolMode = .textToolMode
  404. } else if toolbarMode == .Tools {
  405. //MARK: -工具
  406. listView.toolMode = .textToolMode
  407. }
  408. }
  409. //MARK: - SplitView
  410. func setUpSplitView() {
  411. infoContendSplitView.wantsLayer = true
  412. infoContendSplitView.layer?.backgroundColor = NSColor.clear.cgColor
  413. infoContendSplitView.delegate = self
  414. infoContendSplitView.layer?.masksToBounds = true
  415. }
  416. func setupSplitPDFController() {
  417. if splitPDFController == nil {
  418. splitPDFController = KMSplitPDFViewController.init()
  419. }
  420. splitPDFController?.view.frame = pdfSplitBottomView.bounds
  421. splitPDFController?.view.autoresizingMask = [.height, .width]
  422. splitPDFController?.viewManager = self.viewManager
  423. splitPDFController?.delegate = self
  424. splitPDFController?.reloadData()
  425. pdfSplitBottomView.addSubview(splitPDFController!.view)
  426. }
  427. //MARK: - 工具栏
  428. func initToolbar() {
  429. toolbarBox.borderWidth = 0
  430. if pdfToolbarController == nil {
  431. pdfToolbarController = KMPDFToolbarController.init()
  432. }
  433. pdfToolbarController?.view.frame = toolbarBox.bounds
  434. pdfToolbarController?.view.autoresizingMask = [.width, .height]
  435. pdfToolbarController?.delegate = self
  436. toolbarBox.contentView = pdfToolbarController?.view
  437. pdfToolbarController?.viewManager = viewManager
  438. pdfToolbarController?.toolbarManager = toolbarManager
  439. pdfToolbarController?.pdfView = listView
  440. pdfToolbarController?.setUpData()
  441. refreshToolbarView()
  442. }
  443. func refreshToolbarView() {
  444. let _manager = viewManager
  445. if _manager.isPageEditMode {
  446. toolbarBoxHeightConst.constant = 80
  447. } else if _manager.editType == .watermark || _manager.editType == .background || _manager.editType == .header_Footer || _manager.editType == .bates {
  448. toolbarBoxHeightConst.constant = 40
  449. } else if _manager.toolMode == .Markup ||
  450. _manager.toolMode == .Edit ||
  451. _manager.toolMode == .Form ||
  452. _manager.toolMode == .Fill ||
  453. _manager.toolMode == .Convert ||
  454. _manager.toolMode == .Protect ||
  455. _manager.toolMode == .Tools {
  456. toolbarBoxHeightConst.constant = 80
  457. } else {
  458. toolbarBoxHeightConst.constant = 40
  459. }
  460. }
  461. func toolbarViewModeChanged() {
  462. updatePDFViewAnnotationMode()
  463. if viewManager.showRightSide == true {
  464. toggleOpenRightSide()
  465. } else {
  466. toggleCloseRightSide()
  467. }
  468. }
  469. //MARK: - 侧边工具栏
  470. func initSideBar() {
  471. sidebarBox.borderWidth = 0
  472. if sideBarController == nil {
  473. sideBarController = KMPDFSideBarController.init()
  474. }
  475. sideBarController?.view.frame = sidebarBox.bounds
  476. sideBarController?.view.autoresizingMask = [.width, .height]
  477. sidebarBox.contentView = sideBarController?.view
  478. sideBarController?.pdfView = listView
  479. sideBarController?.delegate = self
  480. sideBarController?.pdfViewManager = viewManager
  481. sideBarController?.reloadData()
  482. }
  483. //MARK: - 左边侧边栏
  484. func initLeftSideController() {
  485. if botaViewController == nil {
  486. botaViewController = KMNLeftSideViewController(listView.document)
  487. }
  488. botaViewController?.leftSideViewDelegate = self
  489. botaViewController?.view.frame = infoSplitLeftView.bounds
  490. botaViewController?.view.autoresizingMask = [.width, .height]
  491. if botaViewController != nil {
  492. infoSplitLeftView?.addSubview(botaViewController!.view)
  493. }
  494. }
  495. private func leftSidePaneIsOpen() -> Bool {
  496. return !infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) //第一次点击时存在问题,待解决
  497. }
  498. private func toggleOpenLeftSide(pdfSideBarType: KMPDFSidebarType) {
  499. if(leftSidePaneIsOpen() == false) {
  500. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFViewLeftSidePaneWidthKey) as? NSNumber ?? MIN_SIDE_PANE_WIDTH
  501. infoContendSplitView.setPosition(MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 0) //暂时无法记录上一次打开的宽度
  502. }
  503. if pdfSideBarType == .search {
  504. botaViewController?.searchViewC.handdler.pdfView = listView
  505. botaViewController?.leftsideType = .search
  506. } else if pdfSideBarType == .thumbnail {
  507. botaViewController?.leftsideType = pdfSideBarType
  508. KMPrint(" thumbnail")
  509. } else if pdfSideBarType == .outline {
  510. botaViewController?.outlineViewC.handdler.pdfView = listView
  511. botaViewController?.leftsideType = pdfSideBarType
  512. } else if pdfSideBarType == .bookmark {
  513. botaViewController?.bookmarkViewC.handdler.pdfView = listView
  514. botaViewController?.leftsideType = pdfSideBarType
  515. } else if pdfSideBarType == .annotation {
  516. KMPrint(" annotation")
  517. }
  518. }
  519. private func toggleCloseLeftSide() {
  520. if(leftSidePaneIsOpen() == true) {
  521. infoContendSplitView.setPosition(0, ofDividerAt: 0)
  522. }
  523. }
  524. //MARK: - 右侧属性栏
  525. func initRightSideController() {
  526. if rightSideController == nil {
  527. rightSideController = KMRightSideController.init()
  528. rightSideController?.delegate = self
  529. }
  530. rightSideController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, 680)
  531. rightSideController?.view.autoresizingMask = [.height, .maxXMargin]
  532. }
  533. func removeRightSideController() {
  534. rightSideController?.view.removeFromSuperview()
  535. rightSideController = nil
  536. }
  537. @objc func toggleOpenRightSide() -> Void {
  538. initRightSideController()
  539. rightSideController?.view.frame = infoSplitRightView.bounds
  540. rightSideController?.view.autoresizingMask = [.width, .height]
  541. infoSplitRightView.addSubview(rightSideController!.view)
  542. infoContendSplitView.setPosition(CGRectGetWidth(view.frame)-MIN_SIDE_PANE_WIDTH.doubleValue, ofDividerAt: 1)
  543. rightSideController?.viewManager = self.viewManager
  544. rightSideController?.reloadDataWithPDFView(pdfView: listView)
  545. }
  546. @objc func toggleCloseRightSide() -> Void {
  547. removeRightSideController()
  548. infoContendSplitView.setPosition(CGRectGetWidth(view.frame), ofDividerAt: 1)
  549. }
  550. //MARK: - PDFDisplayView
  551. func updatePDFDisplaySettingView() {
  552. if viewManager.showDisplayView {
  553. infoSplitViewLeftConst.constant = MIN_SIDE_PANE_WIDTH.doubleValue
  554. } else {
  555. infoSplitViewLeftConst.constant = 44
  556. }
  557. if viewManager.showDisplayView {
  558. if displaySettingController == nil {
  559. displaySettingController = KMNDisplayViewController.init()
  560. }
  561. displaySettingController?.view.frame = CGRectMake(0, 0, MIN_SIDE_PANE_WIDTH.doubleValue, CGRectGetHeight(bottomContendBox.frame))
  562. displaySettingController?.view.autoresizingMask = [.height, .maxXMargin]
  563. bottomContendBox.addSubview(displaySettingController!.view)
  564. displaySettingController?.pdfView = self.listView
  565. displaySettingController?.viewManager = self.viewManager
  566. displaySettingController?.delegate = self
  567. displaySettingController?.reloadData()
  568. } else {
  569. displaySettingController?.view.removeFromSuperview()
  570. displaySettingController = nil
  571. }
  572. }
  573. //MARK: - 页面编辑
  574. func enterPageEditMode() {
  575. pageEditViewController = KMNPageEditViewController(self.document)
  576. if(pageEditViewController != nil) {
  577. bottomContendBox.addSubview(pageEditViewController!.view)
  578. pageEditViewController?.view.frame = bottomContendBox.bounds
  579. pageEditViewController?.thumbnailBaseViewDelegate = self
  580. pageEditViewController?.selectionIndexPaths = [IndexPath(item: listView.currentPageIndex, section: 0)]
  581. pageEditViewController?.view.autoresizingMask = [.width,.height]
  582. pageEditViewController?.currentUndoManager = listView.undoManager
  583. toolbarManager.page_pageInfo_Property.text = String(listView.currentPageIndex + 1)
  584. pdfToolbarController?.refreshSecondToolbarItemsState()
  585. }
  586. }
  587. func exitPageEditMode() {
  588. if pageEditViewController != nil {
  589. pageEditViewController?.view.removeFromSuperview()
  590. pageEditViewController = nil
  591. }
  592. }
  593. //MARK: - 阅读模式
  594. func openPDFReadMode() {
  595. if viewManager.showDisplayView {
  596. viewManager.showDisplayView = false
  597. pdfToolbarController?.reloadLeftIconView()
  598. updatePDFDisplaySettingView()
  599. }
  600. infoSplitViewLeftConst.constant = 0
  601. toolbarBoxHeightConst.constant = 0
  602. view.window?.makeFirstResponder(listView)
  603. var readModeMessage: ComponentMessage = ComponentMessage()
  604. readModeMessage.properties = ComponentMessageProperty(messageType: .normal_custom, title: KMLocalizedString("Read Mode On"))
  605. readModeMessage.frame = CGRectMake((CGRectGetWidth(self.view.frame) - readModeMessage.properties.propertyInfo.viewWidth)/2,
  606. CGRectGetHeight(self.view.frame) - readModeMessage.properties.propertyInfo.viewHeight - 8,
  607. readModeMessage.properties.propertyInfo.viewWidth,
  608. readModeMessage.properties.propertyInfo.viewHeight)
  609. readModeMessage.reloadData()
  610. readModeMessage.show(inView: self.view, autoHideSeconde: 2)
  611. }
  612. func exitPDFReadMode() {
  613. viewManager.isPDFReadMode = false
  614. updatePDFDisplaySettingView()
  615. refreshToolbarView()
  616. }
  617. //MARK: - PPT
  618. func togglePresentation(_ sender: Any?) {
  619. if self.canExitPresentation() {
  620. exitFullScreen()
  621. } else if self.canEnterPresentation() {
  622. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  623. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  624. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  625. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  626. view.window?.enterPresentation(provider: self)
  627. }
  628. }
  629. func enterPresentationMode() {
  630. let scrollView = listView.documentView().enclosingScrollView
  631. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: KMMainModel.Key.kHasHorizontalScroller)
  632. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: KMMainModel.Key.kHasVerticalsCroller)
  633. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: KMMainModel.Key.kAutoHidesScrollers)
  634. listView.backgroundColor = NSColor.clear
  635. listView.setDisplay(.singlePage)
  636. listView.autoScales = true
  637. listView.displayBox = .cropBox
  638. listView.displaysPageBreaks = false
  639. scrollView?.autohidesScrollers = true
  640. scrollView?.hasHorizontalScroller = false
  641. scrollView?.hasVerticalScroller = false
  642. listView.setCurrentSelection(nil, animate: true)
  643. }
  644. func exitPresentationMode() {
  645. NotificationCenter.default.removeObserver(self, name: NSWindow.willEnterInteractionModeNotification, object: nil)
  646. NotificationCenter.default.removeObserver(self, name: NSWindow.didEnterInteractionModeNotification, object: nil)
  647. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  648. NotificationCenter.default.removeObserver(self, name: NSWindow.willShowFullScreenNotification, object: nil)
  649. }
  650. func exitFullScreen() {
  651. if self.canExitPresentation() == true {
  652. let mainDocument = self.myDocument as? KMMainDocument
  653. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  654. browserWindowController?.exitFullscreen()
  655. }
  656. }
  657. func exitFullscreenMode() {
  658. if self.interactionMode == .presentation {
  659. self.exitPresentationMode()
  660. }
  661. self.applyPDFSettings(self.savedNormalSetup)
  662. self.savedNormalSetup.removeAllObjects()
  663. listView.layoutDocumentView()
  664. listView.requiresDisplay()
  665. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  666. listView.backgroundColor = backgroundColor
  667. }
  668. }
  669. func applyPDFSettings(_ setup: NSDictionary) {
  670. if let data = setup.object(forKey: KMMainModel.Key.kAutoScales) as? NSNumber {
  671. self.listView.autoScales = data.boolValue
  672. }
  673. if self.listView.autoScales == false {
  674. if let data = setup.object(forKey: KMMainModel.Key.kScaleFactor) as? NSNumber {
  675. self.listView.scaleFactor = data.floatValue.cgFloat
  676. }
  677. }
  678. if let data = setup.object(forKey: KMMainModel.Key.kDisplayMode) as? NSNumber {
  679. self.listView.setDisplay(CPDFDisplayViewMode(rawValue: data.intValue) ?? .singlePage)
  680. }
  681. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysAsBook) as? NSNumber {
  682. self.listView.displaysAsBook = data.boolValue
  683. }
  684. if let data = setup.object(forKey: KMMainModel.Key.kDisplaysPageBreaks) as? NSNumber {
  685. self.listView.displaysPageBreaks = data.boolValue
  686. }
  687. if let data = setup.object(forKey: KMMainModel.Key.kDisplayBox) as? NSNumber {
  688. }
  689. self.listView.layoutDocumentView()
  690. }
  691. func currentPDFSettings() -> NSDictionary {
  692. let setup = NSMutableDictionary()
  693. setup[KMMainModel.Key.kDisplaysPageBreaks] = NSNumber(value: listView.displaysPageBreaks)
  694. setup[KMMainModel.Key.kDisplaysAsBook] = NSNumber(value: listView.displaysAsBook)
  695. setup[KMMainModel.Key.kDisplayBox] = NSNumber(value: listView.displayBox.rawValue)
  696. setup[KMMainModel.Key.kScaleFactor] = NSNumber(value: listView.scaleFactor)
  697. setup[KMMainModel.Key.kAutoScales] = NSNumber(value: listView.autoScales)
  698. setup[KMMainModel.Key.kDisplayMode] = NSNumber(value: listView.fetchDisplayViewMode().rawValue)
  699. return setup
  700. }
  701. func canEnterFullscreen() -> Bool {
  702. if (mwcFlags.isSwitchingFullScreen != 0) {
  703. return false
  704. }
  705. if useNativeFullScreen() {
  706. return interactionMode == .normal || interactionMode == .presentation
  707. } else {
  708. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  709. }
  710. }
  711. override func canEnterPresentation() -> Bool {
  712. let can = super.canEnterPresentation()
  713. if can == false {
  714. return false
  715. }
  716. guard let doc = self.listView.document, doc.isLocked == false else {
  717. return false
  718. }
  719. return can
  720. }
  721. func fadeOutFullScreenWindow() {
  722. guard let fullScreenWindow = self.view.window as? KMFullScreenWindow else {
  723. NSSound.beep()
  724. return
  725. }
  726. let mainWindow = fullScreenWindow.interactionParent
  727. let collectionBehavior = mainWindow?.collectionBehavior
  728. mainWindow?.alphaValue = 0
  729. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  730. mainWindow?.animationBehavior = .none
  731. }
  732. // trick to make sure the main window shows up in the same space as the fullscreen window
  733. fullScreenWindow.addChildWindow(mainWindow!, ordered: .below)
  734. fullScreenWindow.removeChildWindow(mainWindow!)
  735. fullScreenWindow.level = .popUpMenu
  736. // these can change due to the child window trick
  737. mainWindow?.level = .normal
  738. mainWindow?.alphaValue = 1.0
  739. mainWindow?.collectionBehavior = collectionBehavior!
  740. mainWindow?.display()
  741. mainWindow?.makeFirstResponder(self.listView)
  742. mainWindow?.recalculateKeyViewLoop()
  743. // mainWindow?.delegate = self
  744. mainWindow?.makeKey()
  745. if let data = mainWindow?.responds(to: NSSelectorFromString("setAnimationBehavior:")), data {
  746. mainWindow?.animationBehavior = .default
  747. }
  748. NSApp.removeWindowsItem(fullScreenWindow)
  749. fullScreenWindow.fadeOut()
  750. }
  751. //MARK: - PDF分屏视图
  752. func reloadPDFSplitInfo() {
  753. if listView.viewSplitMode == .disable {
  754. pdfSplitView.isHidden = true
  755. listView.frame = infoSplitCenterView.bounds
  756. infoSplitCenterView.addSubview(listView)
  757. if splitPDFController != nil {
  758. splitPDFController = nil
  759. }
  760. } else {
  761. pdfSplitView.isHidden = false
  762. listView.frame = pdfSplitTopView.bounds
  763. pdfSplitTopView.addSubview(listView)
  764. setUpPDFBottomToolbar()
  765. setupSplitPDFController()
  766. if listView.viewSplitMode == .horizontal {
  767. pdfSplitView.isVertical = false
  768. } else if listView.viewSplitMode == .vertical {
  769. pdfSplitView.isVertical = true
  770. }
  771. }
  772. }
  773. func setUpPDFBottomToolbar() {
  774. if pdfBottomToolbar != nil {
  775. pdfBottomToolbar = nil
  776. }
  777. pdfBottomToolbar = KMSplitToolbar.init()
  778. pdfBottomToolbar?.frame = CGRectMake(CGRectGetWidth(pdfSplitTopView.frame)/2-144, 20, 288, 40)
  779. pdfBottomToolbar?.pdfView = self.listView
  780. pdfBottomToolbar?.reloadData()
  781. pdfSplitTopView.addSubview(pdfBottomToolbar!)
  782. }
  783. func reloadPDFBottomToolbar() {
  784. if viewManager.splitShowBottomBar {
  785. pdfBottomToolbar?.isHidden = false
  786. pdfBottomToolbar?.reloadData()
  787. } else {
  788. pdfBottomToolbar?.isHidden = true
  789. }
  790. }
  791. //MARK: - Edit模式
  792. func showEditToolbarView() {
  793. if editToolbarView == nil {
  794. editToolbarView = KMEditToolbarView()
  795. }
  796. editToolbarView?.frame = toolbarBox.bounds
  797. editToolbarView?.delegate = self
  798. editToolbarView?.autoresizingMask = [.width, .height]
  799. toolbarBox.contentView = editToolbarView
  800. }
  801. func exitEditToolbarView() {
  802. viewManager.editType = .none
  803. viewManager.subToolMode = .None
  804. editToolbarView?.removeFromSuperview()
  805. editToolbarView = nil
  806. watermarkViewController?.view.removeFromSuperview()
  807. watermarkViewController = nil
  808. backgroundViewController?.view.removeFromSuperview()
  809. backgroundViewController = nil
  810. headerFooterViewController?.view.removeFromSuperview()
  811. headerFooterViewController = nil
  812. batesViewController?.view.removeFromSuperview()
  813. batesViewController = nil
  814. refreshToolbarView()
  815. toolbarBox.contentView = pdfToolbarController?.view
  816. updatePDFViewAnnotationMode()
  817. }
  818. func updateEditModeDocumentWhenPageChanged() {
  819. if viewManager.editType == .watermark {
  820. updateWatermarkDocument()
  821. } else if viewManager.editType == .background {
  822. updateBackgroundDocument()
  823. } else if viewManager.editType == .header_Footer {
  824. updateHeaderFooterDocument()
  825. } else if viewManager.editType == .bates {
  826. updateBatesDocument()
  827. } else if viewManager.subToolMode == .Edit_Crop {
  828. updateCropDocument()
  829. }
  830. }
  831. //MARK: - Crop裁剪
  832. func showCropController() {
  833. if cropController == nil {
  834. cropController = KMCropController.init()
  835. cropController?.view.frame = infoSplitCenterView.bounds
  836. cropController?.view.autoresizingMask = [.width, .height]
  837. cropController?.delegate = self
  838. infoSplitCenterView.addSubview(cropController!.view)
  839. updateCropDocument()
  840. if viewManager.showRightSide == false {
  841. viewManager.showRightSide = true
  842. pdfToolbarController?.reloadRightToolsView()
  843. toggleOpenRightSide()
  844. }
  845. }
  846. }
  847. func updateCropDocument() {
  848. guard let controller = cropController else { return }
  849. controller.pdfDocument = nil
  850. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  851. let editDocument = CPDFDocument.init()
  852. editDocument?.insertPageObject(page, at: 0)
  853. if let editPage = editDocument?.page(at: 0) {
  854. editPage.setBounds(CGRectMake(0, 0, editPage.bounds(for: .mediaBox).size.width, editPage.bounds(for: .mediaBox).size.height), for: .cropBox)
  855. controller.selectionRect = page?.bounds(for: .cropBox) ?? .zero
  856. }
  857. controller.pdfDocument = editDocument
  858. controller.reloadData()
  859. }
  860. func removeCropController() {
  861. if cropController != nil {
  862. cropController?.view.removeFromSuperview()
  863. cropController = nil
  864. if viewManager.subToolMode == .None {
  865. viewManager.showRightSide = false
  866. pdfToolbarController?.reloadRightToolsView()
  867. toggleCloseRightSide()
  868. }
  869. }
  870. }
  871. //MARK: - Watermark水印
  872. func showWatermarkController() {
  873. viewManager.editType = .watermark
  874. showEditToolbarView()
  875. editToolbarView?.editType = .watermark
  876. if KMWatermarkManager.defaultManager.watermarks.count == 0 {
  877. editToolbarView?.editSubType = .add
  878. } else {
  879. editToolbarView?.editSubType = .template
  880. }
  881. editToolbarView?.reloadData()
  882. if watermarkViewController == nil {
  883. watermarkViewController = KMWatermarkController.init()
  884. }
  885. watermarkViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  886. watermarkViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  887. watermarkViewController?.delegate = self
  888. bottomContendBox.contentView?.addSubview(watermarkViewController!.view)
  889. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  890. updateWatermarkDocument()
  891. }
  892. func updateWatermarkDocument() {
  893. guard let controller = watermarkViewController else { return }
  894. var editDocument = CPDFDocument.init()
  895. if let vcDoc = controller.pdfDocument {
  896. editDocument = vcDoc
  897. }
  898. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  899. editDocument?.insertPageObject(page, at: 0)
  900. if editDocument?.pageCount == 2 {
  901. let theIndex = IndexSet(integer: 1)
  902. editDocument?.removePage(at: theIndex)
  903. }
  904. if watermarkViewController?.pdfDocument == nil {
  905. watermarkViewController?.pdfDocument = editDocument
  906. }
  907. watermarkViewController?.resetUI()
  908. watermarkViewController?.reloadData()
  909. }
  910. //移除文档水印
  911. func removePDFWatermark() {
  912. let watermarks = self.listView.document.watermarks()
  913. if (watermarks == nil || watermarks!.count <= 0) {
  914. let alert = NSAlert()
  915. alert.alertStyle = .warning
  916. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  917. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  918. alert.runModal()
  919. return
  920. }
  921. let alert = NSAlert()
  922. alert.alertStyle = .warning
  923. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  924. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  925. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  926. let result = alert.runModal()
  927. if (result == .alertFirstButtonReturn) {
  928. for watermark in watermarks! {
  929. listView.document.removeWatermark(watermark)
  930. }
  931. listView.layoutDocumentView()
  932. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Watermark removed"),
  933. type: .success,
  934. fromView: bottomContendBox,
  935. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  936. }
  937. }
  938. func batchAddWatermark() {
  939. }
  940. func batchRemoveWatermark() {
  941. }
  942. //MARK: - Background背景
  943. func showBackgroundController() {
  944. viewManager.editType = .background
  945. showEditToolbarView()
  946. editToolbarView?.editType = .background
  947. if KMBackgroundManager.defaultManager.datas.count == 0 {
  948. editToolbarView?.editSubType = .add
  949. } else {
  950. editToolbarView?.editSubType = .template
  951. }
  952. editToolbarView?.reloadData()
  953. if backgroundViewController == nil {
  954. backgroundViewController = KMBackgroundController.init()
  955. }
  956. backgroundViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  957. backgroundViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  958. backgroundViewController?.delegate = self
  959. bottomContendBox.contentView?.addSubview(backgroundViewController!.view)
  960. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  961. backgroundViewController?.resetUI()
  962. updateBackgroundDocument()
  963. }
  964. func updateBackgroundDocument() {
  965. guard let controller = backgroundViewController else { return }
  966. controller.pdfDocument = nil
  967. let editDocument = CPDFDocument.init()
  968. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  969. editDocument?.insertPageObject(page, at: 0)
  970. backgroundViewController?.pdfDocument = editDocument
  971. backgroundViewController?.reloadData()
  972. }
  973. func removePDFBackground() {
  974. let alert = NSAlert()
  975. alert.alertStyle = .warning
  976. alert.messageText = NSLocalizedString("Are you sure you want to remove the background?", comment: "")
  977. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  978. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  979. let result = alert.runModal()
  980. if (result == .alertFirstButtonReturn) {
  981. let background = listView.document.background()
  982. background?.clear()
  983. listView.document?.refreshPageData()
  984. listView.layoutDocumentView()
  985. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Background removed"),
  986. type: .success,
  987. fromView: bottomContendBox,
  988. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  989. }
  990. }
  991. func batchAddBackground() {
  992. }
  993. func batchRemoveBackground() {
  994. }
  995. //MARK: - header&footer
  996. func showHeaderFooterController() {
  997. viewManager.editType = .header_Footer
  998. showEditToolbarView()
  999. editToolbarView?.editType = .header_Footer
  1000. if KMHeaderFooterManager.defaultManager.headFooterObjects.count == 0 {
  1001. editToolbarView?.editSubType = .add
  1002. } else {
  1003. editToolbarView?.editSubType = .template
  1004. }
  1005. editToolbarView?.reloadData()
  1006. if headerFooterViewController == nil {
  1007. headerFooterViewController = KMHeaderFooterController.init()
  1008. }
  1009. headerFooterViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1010. headerFooterViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1011. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1012. headerFooterViewController?.delegate = self
  1013. bottomContendBox.contentView?.addSubview(headerFooterViewController!.view)
  1014. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1015. updateHeaderFooterDocument()
  1016. }
  1017. func updateHeaderFooterDocument() {
  1018. guard let controller = headerFooterViewController else { return }
  1019. controller.pdfDocument = nil
  1020. let editDocument = CPDFDocument.init()
  1021. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1022. editDocument?.insertPageObject(page, at: 0)
  1023. headerFooterViewController?.totalPDFCount = Int(listView.document.pageCount)
  1024. headerFooterViewController?.pdfDocument = editDocument
  1025. headerFooterViewController?.resetUI()
  1026. headerFooterViewController?.reloadData()
  1027. }
  1028. func removeHeaderFooter() {
  1029. let alert = NSAlert()
  1030. alert.alertStyle = .warning
  1031. alert.messageText = NSLocalizedString("Are you sure you want to remove the Header & Footer?", comment: "")
  1032. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1033. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1034. let result = alert.runModal()
  1035. if (result == .alertFirstButtonReturn) {
  1036. let headerFooter = listView.document.headerFooter()
  1037. headerFooter?.clear()
  1038. listView.document?.refreshPageData()
  1039. listView.layoutDocumentView()
  1040. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Header & Footer removed"),
  1041. type: .success,
  1042. fromView: bottomContendBox,
  1043. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1044. }
  1045. }
  1046. func batchAddHeaderFooter() {
  1047. }
  1048. func batchRemoveHeaderFooter() {
  1049. }
  1050. //MARK: - Bates
  1051. func showBatesController() {
  1052. viewManager.editType = .bates
  1053. showEditToolbarView()
  1054. editToolbarView?.editType = viewManager.editType
  1055. if KMBatesManager.defaultManager.datas.count == 0 {
  1056. editToolbarView?.editSubType = .add
  1057. } else {
  1058. editToolbarView?.editSubType = .template
  1059. }
  1060. editToolbarView?.reloadData()
  1061. if batesViewController == nil {
  1062. batesViewController = KMBatesController.init()
  1063. }
  1064. batesViewController?.view.frame = CGRectMake(44, 0, CGRectGetWidth(bottomContendBox.frame)-44, CGRectGetHeight(bottomContendBox.frame))
  1065. batesViewController?.view.autoresizingMask = [.maxXMargin, .width, .height]
  1066. batesViewController?.delegate = self
  1067. batesViewController?.totalPDFCount = Int(listView.document.pageCount)
  1068. bottomContendBox.contentView?.addSubview(batesViewController!.view)
  1069. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1070. updateBatesDocument()
  1071. batesViewController?.resetUI()
  1072. }
  1073. func updateBatesDocument() {
  1074. guard let controller = batesViewController else { return }
  1075. controller.pdfDocument = nil
  1076. let editDocument = CPDFDocument.init()
  1077. let page = listView.document.page(at: UInt(listView.currentPageIndex))
  1078. editDocument?.insertPageObject(page, at: 0)
  1079. batesViewController?.pdfDocument = editDocument
  1080. batesViewController?.reloadData()
  1081. }
  1082. func removePDFBates() {
  1083. let alert = NSAlert()
  1084. alert.alertStyle = .warning
  1085. alert.messageText = NSLocalizedString("Are you sure you want to remove the Bates?", comment: "")
  1086. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  1087. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1088. let result = alert.runModal()
  1089. if (result == .alertFirstButtonReturn) {
  1090. let bates = listView.document.bates()
  1091. bates?.clear()
  1092. listView.document?.refreshPageData()
  1093. listView.layoutDocumentView()
  1094. _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Bates removed"),
  1095. type: .success,
  1096. fromView: bottomContendBox,
  1097. point:CGPointMake(CGRectGetWidth(bottomContendBox.frame)/2, CGRectGetHeight(bottomContendBox.frame)-28))
  1098. }
  1099. }
  1100. func batchAddBates() {
  1101. }
  1102. func batchRemoveBates() {
  1103. }
  1104. //MARK: - Crop Action
  1105. // 白边距,统一大小
  1106. @objc func auto_cropPagesWhiteMargin(_ pageIndexs: [UInt]) {
  1107. var size = NSZeroSize
  1108. for i in pageIndexs {
  1109. let page = self.listView.document.page(at: i)
  1110. let rect = KMCropTools.getPageForegroundBox(page!)
  1111. size.width = fmax(size.width, NSWidth(rect))
  1112. size.height = fmax(size.height, NSHeight(rect))
  1113. }
  1114. var rectArray: Array<NSRect> = []
  1115. for i in pageIndexs {
  1116. progressC?.increment(by: Double(i))
  1117. progressC?.doubleValue = Double(i)
  1118. let page = self.listView.document.page(at: i)
  1119. var rect = KMCropTools.getPageForegroundBox(page!)
  1120. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1121. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1122. rect.origin.x = rect.maxX-size.width
  1123. }
  1124. rect.origin.y = rect.maxY-size.height
  1125. rect.size = size
  1126. if (NSWidth(rect) > NSWidth(bounds)) {
  1127. rect.size.width = NSWidth(bounds)
  1128. }
  1129. if (NSHeight(rect) > NSHeight(bounds)) {
  1130. rect.size.height = NSHeight(bounds)
  1131. }
  1132. if (NSMinX(rect) < NSMinX(bounds)) {
  1133. rect.origin.x = NSMinX(bounds)
  1134. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1135. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1136. }
  1137. if (NSMinY(rect) < NSMinY(bounds)) {
  1138. rect.origin.y = NSMinY(bounds)
  1139. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1140. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1141. }
  1142. rectArray.append(rect)
  1143. }
  1144. self.cropPages(atIndexs: pageIndexs, to: rectArray)
  1145. }
  1146. func cropPages(atIndexs pageIndexs: [UInt], to rects: Array<NSRect>) {
  1147. let currentPage = self.listView.currentPage()
  1148. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1149. var oldRectArray: Array<NSRect> = []
  1150. let rectCount = rects.count
  1151. for i in pageIndexs {
  1152. if let page = self.listView.document.page(at: i) {
  1153. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page.bounds(for: .mediaBox)))
  1154. let oldRect = page.bounds(for: .cropBox)
  1155. oldRectArray.append(oldRect)
  1156. page.setBounds(rect, for: .cropBox)
  1157. }
  1158. }
  1159. let undoManager = self.listView.undoManager
  1160. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(atIndexs: pageIndexs, to: oldRectArray)
  1161. /// 刷新预览视图
  1162. self.listView.layoutDocumentView()
  1163. self.listView.displayBox = .cropBox
  1164. self.listView.go(to: currentPage)
  1165. self.listView.go(to: visibleRect, on: currentPage)
  1166. }
  1167. //MARK: - Share Action
  1168. @objc private func shareDocument(sender: NSView) {
  1169. let document = self.listView.document ?? CPDFDocument()
  1170. if document?.documentURL == nil {
  1171. return
  1172. }
  1173. var doucumentURL : URL = self.listView.document.documentURL
  1174. if doucumentURL.path.count > 0 {
  1175. let docDir = NSTemporaryDirectory()
  1176. let documentName : String = doucumentURL.path.lastPathComponent
  1177. let path = docDir.stringByAppendingPathComponent(documentName)
  1178. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1179. if writeSuccess == false {
  1180. __NSBeep()
  1181. return;
  1182. }
  1183. doucumentURL = URL(fileURLWithPath: path)
  1184. }
  1185. let array = [doucumentURL]
  1186. let picker = NSSharingServicePicker.init(items: array)
  1187. if sender.window != nil {
  1188. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  1189. } else {
  1190. 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)
  1191. }
  1192. }
  1193. @objc private func shareFlatten(sender: NSView) {
  1194. let document = self.listView.document ?? CPDFDocument()
  1195. var path: String?
  1196. if document?.documentURL != nil {
  1197. path = document?.documentURL.path ?? ""
  1198. }
  1199. if path?.count ?? 0 > 0 {
  1200. let docDir = NSTemporaryDirectory()
  1201. let documentName : String = path?.lastPathComponent ?? ""
  1202. path = docDir.stringByAppendingPathComponent(documentName)
  1203. }
  1204. let pathFolder = path?.fileURL.deletingLastPathComponent().path
  1205. var tfileName = path?.deletingPathExtension.lastPathComponent
  1206. let tStdFileSuffix = "_flatten"
  1207. tfileName = (tfileName ?? "") + tStdFileSuffix + ".pdf"
  1208. path = (pathFolder ?? "") + "/" + (tfileName ?? "")
  1209. let success : Bool = document?.writeFlatten(to: URL(fileURLWithPath: path ?? "")) ?? false
  1210. if success {
  1211. let url = URL(fileURLWithPath: path ?? "")
  1212. let picker = NSSharingServicePicker.init(items: [url])
  1213. if sender.window != nil {
  1214. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  1215. } else {
  1216. 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)
  1217. }
  1218. }
  1219. }
  1220. @objc private func shareOriginalPDF(sender: NSView) {
  1221. guard let pdfDoc = self.listView.document else {
  1222. NSSound.beep()
  1223. return
  1224. }
  1225. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  1226. let alert = NSAlert()
  1227. alert.alertStyle = .critical
  1228. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1229. alert.runModal()
  1230. return
  1231. }
  1232. let document = self.listView.document ?? CPDFDocument()
  1233. var path: String?
  1234. if document?.documentURL != nil {
  1235. path = document?.documentURL.path ?? ""
  1236. }
  1237. if path?.count ?? 0 > 0 {
  1238. let docDir = NSTemporaryDirectory()
  1239. let documentName : String = path?.lastPathComponent ?? ""
  1240. path = docDir.stringByAppendingPathComponent(documentName)
  1241. }
  1242. var writeSuccess = document?.write(to: URL(fileURLWithPath: path ?? ""))
  1243. if writeSuccess == false {
  1244. __NSBeep()
  1245. return;
  1246. }
  1247. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path ?? ""))
  1248. let cnt = newDocument?.pageCount ?? 0
  1249. for i in 0 ..< cnt {
  1250. let page = newDocument!.page(at: i)
  1251. var annotations : [CPDFAnnotation] = []
  1252. for annotation in page!.annotations {
  1253. annotations.append(annotation)
  1254. }
  1255. for annotation in annotations {
  1256. annotation.page.removeAnnotation(annotation)
  1257. }
  1258. }
  1259. writeSuccess = newDocument?.write(to:URL(fileURLWithPath: path ?? ""))
  1260. if writeSuccess ?? false {
  1261. let url = URL(fileURLWithPath: path ?? "")
  1262. let picker = NSSharingServicePicker.init(items: [url])
  1263. if sender.window != nil {
  1264. picker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
  1265. } else {
  1266. 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)
  1267. }
  1268. }
  1269. }
  1270. @objc func shareFromService(sender: NSMenuItem) {
  1271. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  1272. return
  1273. }
  1274. var string = ""
  1275. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  1276. string = freeTextAnnotation.contents ?? ""
  1277. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  1278. if let page = markupAnnotation.page {
  1279. if let selection = page.selection(for: markupAnnotation.bounds) {
  1280. string = selection.string() ?? ""
  1281. }
  1282. }
  1283. } else {
  1284. string = listView.currentSelection?.string() ?? ""
  1285. }
  1286. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  1287. let model = windowControler.browser?.tabStripModel
  1288. if let cnt = model?.count(), cnt <= 0 {
  1289. return
  1290. }
  1291. if let data = model?.activeTabContents().isHome, data {
  1292. return
  1293. }
  1294. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  1295. if string.count > 0 {
  1296. let represent : NSSharingService = sender.representedObject as! NSSharingService
  1297. represent.perform(withItems: [string])
  1298. return
  1299. }
  1300. let represent = sender.representedObject as? NSSharingService
  1301. represent?.perform(withItems: [string])
  1302. }
  1303. // 搜索 & 替换
  1304. func showSearchPopWindow(type: KMNBotaSearchType, keyborad: String?, replaceText: String?, results: [KMSearchMode]) {
  1305. let toolMode = self.listView.toolMode ?? .none
  1306. let isEditing = self.listView.isEditing() ?? false
  1307. var winH: CGFloat = 112
  1308. if type == .replace {
  1309. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1310. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1311. winC?.kEventName = "Reading_ReplaceText_BuyNow"
  1312. winC?.showWindow(nil)
  1313. return
  1314. }
  1315. if toolMode == .editPDFToolMode && isEditing {
  1316. } else { // 进入内容编辑模式
  1317. viewManager.toolMode = .Edit
  1318. updatePDFViewAnnotationMode()
  1319. }
  1320. winH = 208
  1321. }
  1322. self.view.window?.makeFirstResponder(nil)
  1323. let winC = KMSearchReplaceWindowController(with: listView, type: type)
  1324. self.currentWindowController = winC
  1325. winC.replaceCallback = { [weak self] in
  1326. let toolMode = self?.listView.toolMode ?? .none
  1327. let isEditing = self?.listView.isEditing() ?? false
  1328. if toolMode == .editPDFToolMode && isEditing {
  1329. } else { // 进入内容编辑模式
  1330. self?.viewManager.toolMode = .Edit
  1331. self?.updatePDFViewAnnotationMode()
  1332. }
  1333. }
  1334. winC.itemClick = { [weak self] idx, params in
  1335. if idx == 1 {
  1336. self?.toggleOpenLeftSide(pdfSideBarType: .search)
  1337. guard let handdler = params.first as? KMNSearchHanddler else {
  1338. return
  1339. }
  1340. let viewC = self?.leftSideViewController.searchViewController
  1341. viewC?.update(keyborad: handdler.searchKey, replaceKey: handdler.replaceKey, results: handdler.searchResults)
  1342. }
  1343. }
  1344. let targetView = self.pdfToolbarController?.leftViewButton
  1345. let point = targetView?.convert(targetView?.frame.origin ?? .zero, to: nil) ?? .zero
  1346. // 200 248
  1347. let x = point.x + (self.view.window?.frame.origin.x ?? 0) - 32
  1348. let y = point.y + (self.view.window?.frame.origin.y ?? 0) - winH - 32
  1349. let winFramePoint = NSPoint(x: x, y: y)
  1350. winC.window?.setFrameOrigin(winFramePoint)
  1351. winC.update(keyborad: keyborad, replaceKey: replaceText, results: results)
  1352. self.view.window?.addChildWindow(winC.window!, ordered: .above)
  1353. }
  1354. }
  1355. //MARK: - NSSplitViewDelegate
  1356. extension KMMainViewController: NSSplitViewDelegate {
  1357. func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
  1358. if splitView == infoContendSplitView {
  1359. return subview.isEqual(to: infoSplitCenterView) == false
  1360. }
  1361. return false
  1362. }
  1363. func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
  1364. if splitView == infoContendSplitView {
  1365. if(subview.isEqual(to: infoSplitLeftView)) {
  1366. } else if(subview.isEqual(to: infoSplitRightView)) {
  1367. }
  1368. }
  1369. return false
  1370. }
  1371. func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
  1372. if splitView == infoContendSplitView {
  1373. return splitView == infoContendSplitView
  1374. } else if splitView == pdfSplitView {
  1375. return splitView == pdfSplitView
  1376. }
  1377. return false
  1378. }
  1379. func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  1380. if(splitView == infoContendSplitView && dividerIndex == 1) {
  1381. return proposedMaximumPosition - MIN_SIDE_PANE_WIDTH.doubleValue
  1382. }
  1383. return proposedMaximumPosition
  1384. }
  1385. func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  1386. if(splitView == infoContendSplitView && dividerIndex == 0) {
  1387. return proposedMinimumPosition + MIN_SIDE_PANE_WIDTH.doubleValue
  1388. }
  1389. return proposedMinimumPosition
  1390. }
  1391. func splitViewDidResizeSubviews(_ notification: Notification) {
  1392. let splitView = notification.object as? NSSplitView
  1393. if(splitView == infoContendSplitView) {
  1394. leftSplitViewResizeFinish()
  1395. if(newMwcFlags.settingUpWindow == false && self.view.window?.frameAutosaveName != nil) {
  1396. let leftWidth = infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) ? 0.0 : infoSplitLeftView.frame.width
  1397. UserDefaults.standard.set(leftWidth, forKey: CPDFViewLeftSidePaneWidthKey)
  1398. UserDefaults.standard.synchronize()
  1399. }
  1400. }
  1401. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(splitViewResizeFinish), object: nil)
  1402. self.perform(#selector(splitViewResizeFinish), with: nil, afterDelay: 0.15)
  1403. }
  1404. @objc func leftSplitViewResizeFinish() {
  1405. botaViewController?.changeLeftSideBounds()
  1406. }
  1407. @objc func splitViewResizeFinish() {
  1408. if infoContendSplitView.isSubviewCollapsed(infoSplitLeftView) {
  1409. if viewManager.pdfSideBarType != .none {
  1410. viewManager.pdfSideBarType = .none
  1411. sideBarController?.reloadBOTAData()
  1412. }
  1413. }
  1414. }
  1415. }
  1416. //MARK: - KMPDFSideBarControllerDelegate 左侧Sidebar代理
  1417. extension KMMainViewController: KMPDFSideBarControllerDelegate {
  1418. func kmPDFSideBarControllerDidSidebarTypeUpdated(_ view: KMPDFSideBarController) {
  1419. if viewManager.pdfSideBarType == .none {
  1420. toggleCloseLeftSide()
  1421. } else {
  1422. toggleOpenLeftSide(pdfSideBarType: viewManager.pdfSideBarType)
  1423. }
  1424. }
  1425. func kmPDFSideBarControllerDidGotoPage(_ view: KMPDFSideBarController, _ pageIndex: Int) {
  1426. listView.go(toPageIndex: pageIndex, animated: true)
  1427. }
  1428. }
  1429. //MARK: - KMPDFToolbarControllerDelegate 工具栏代理
  1430. extension KMMainViewController: KMPDFToolbarControllerDelegate {
  1431. //一级工具栏状态发生变化时调用
  1432. func kmPDFToolbarControllerDidToolModeChanged(_ controller: KMPDFToolbarController) {
  1433. refreshToolbarView()
  1434. toolbarViewModeChanged()
  1435. }
  1436. //MARK: -点击工具栏按钮
  1437. func kmPDFToolbarControllerDidToolbarItemClicked(_ controller: KMPDFToolbarController, _ itemIdentifier: String) {
  1438. print("toolbar点击", itemIdentifier)
  1439. if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_PageEdit_Identifier).contains(itemIdentifier) {
  1440. //MARK: -页面编辑
  1441. if itemIdentifier == KMPDFToolbar_PageEdit_InsertFile_Identifier {
  1442. pageEditViewController?.insertFromPDFAction()
  1443. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertBlank_Identifier {
  1444. pageEditViewController?.insertFromBlankAction()
  1445. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertClip_Identifier {
  1446. pageEditViewController?.insertFromClipboardAction()
  1447. } else if itemIdentifier == KMPDFToolbar_PageEdit_InsertScanner_Identifier {
  1448. pageEditViewController?.insertFromScannerAction()
  1449. } else if itemIdentifier == KMPDFToolbar_PageEdit_Extract_Identifier {
  1450. pageEditViewController?.extractPDFAction()
  1451. } else if itemIdentifier == KMPDFToolbar_PageEdit_Replace_Identifier {
  1452. pageEditViewController?.replacePDFAction()
  1453. } else if itemIdentifier == KMPDFToolbar_PageEdit_Split_Identifier {
  1454. pageEditViewController?.splitPDFAction()
  1455. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reverse_Identifier {
  1456. pageEditViewController?.reversePDFAction()
  1457. } else if itemIdentifier == KMPDFToolbar_PageEdit_LeftRotate_Identifier {
  1458. pageEditViewController?.rotatePageLeftAction()
  1459. } else if itemIdentifier == KMPDFToolbar_PageEdit_RightRotate_Identifier{
  1460. pageEditViewController?.rotatePageRightAction()
  1461. } else if itemIdentifier == KMPDFToolbar_PageEdit_Delete_Identifier {
  1462. pageEditViewController?.deletePageAction()
  1463. } else if itemIdentifier == KMPDFToolbar_PageEdit_Reduce_Identifier {
  1464. pageEditViewController?.zoomOutPageAction()
  1465. if(pageEditViewController?.canZoomInPageSize() == false) {
  1466. toolbarManager.page_Increase_Property.isDisabled = true
  1467. } else {
  1468. toolbarManager.page_Increase_Property.isDisabled = false
  1469. }
  1470. if(pageEditViewController?.canZoomOutPageSize() == false) {
  1471. toolbarManager.page_Reduce_Property.isDisabled = true
  1472. } else {
  1473. toolbarManager.page_Reduce_Property.isDisabled = false
  1474. }
  1475. controller.refreshSecondToolbarItemsState()
  1476. } else if itemIdentifier == KMPDFToolbar_PageEdit_Increase_Identifier {
  1477. pageEditViewController?.zoomInPageAction()
  1478. if(pageEditViewController?.canZoomInPageSize() == false) {
  1479. toolbarManager.page_Increase_Property.isDisabled = true
  1480. } else {
  1481. toolbarManager.page_Increase_Property.isDisabled = false
  1482. }
  1483. if(pageEditViewController?.canZoomOutPageSize() == false) {
  1484. toolbarManager.page_Reduce_Property.isDisabled = true
  1485. } else {
  1486. toolbarManager.page_Reduce_Property.isDisabled = false
  1487. }
  1488. controller.refreshSecondToolbarItemsState()
  1489. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_oddPage_Identifier {
  1490. pageEditViewController?.thumbnailChoosePageStyle = .odd
  1491. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  1492. toolbarManager.page_pageInfo_Property.creatable = false
  1493. controller.refreshSecondToolbarItemsState()
  1494. }
  1495. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_EvenPage_Identifier {
  1496. pageEditViewController?.thumbnailChoosePageStyle = .even
  1497. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  1498. toolbarManager.page_pageInfo_Property.creatable = false
  1499. controller.refreshSecondToolbarItemsState()
  1500. }
  1501. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_PortraitPage_Identifier {
  1502. pageEditViewController?.thumbnailChoosePageStyle = .horizontal
  1503. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  1504. toolbarManager.page_pageInfo_Property.creatable = false
  1505. controller.refreshSecondToolbarItemsState()
  1506. }
  1507. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_LandscapePage_Identifier {
  1508. pageEditViewController?.thumbnailChoosePageStyle = .vertical
  1509. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  1510. toolbarManager.page_pageInfo_Property.creatable = false
  1511. controller.refreshSecondToolbarItemsState()
  1512. }
  1513. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_AllPage_Identifier {
  1514. pageEditViewController?.thumbnailChoosePageStyle = .allPage
  1515. if(toolbarManager.page_pageInfo_Property.creatable == true) {
  1516. toolbarManager.page_pageInfo_Property.creatable = false
  1517. controller.refreshSecondToolbarItemsState()
  1518. }
  1519. } else if itemIdentifier == KMPDFToolbar_PageEdit_page_CustomPage_Identifier {
  1520. pageEditViewController?.thumbnailChoosePageStyle = .custom
  1521. toolbarManager.page_pageInfo_Property.text = nil
  1522. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  1523. toolbarManager.page_pageInfo_Property.creatable = true
  1524. }
  1525. controller.refreshSecondToolbarItemsState()
  1526. }
  1527. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Markup_Identifier).contains(itemIdentifier) {
  1528. //MARK: -Markup
  1529. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Edit_Identifier).contains(itemIdentifier) {
  1530. //MARK: -编辑
  1531. if itemIdentifier == KMPDFToolbar_edit_addWatermark_Identifier {
  1532. showWatermarkController()
  1533. } else if itemIdentifier == KMPDFToolbar_edit_removeWatermark_Identifier {
  1534. removePDFWatermark()
  1535. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddWatermark_Identifier {
  1536. batchAddWatermark()
  1537. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveWatermark_Identifier {
  1538. batchRemoveWatermark()
  1539. } else if itemIdentifier == KMPDFToolbar_edit_addBG_Identifier {
  1540. showBackgroundController()
  1541. } else if itemIdentifier == KMPDFToolbar_edit_removeBG_Identifier {
  1542. removePDFBackground()
  1543. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBG_Identifier {
  1544. batchAddBackground()
  1545. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBG_Identifier {
  1546. batchRemoveBackground()
  1547. } else if itemIdentifier == KMPDFToolbar_edit_addHF_Identifier {
  1548. showHeaderFooterController()
  1549. } else if itemIdentifier == KMPDFToolbar_edit_removeHF_Identifier {
  1550. removeHeaderFooter()
  1551. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddHF_Identifier {
  1552. batchAddHeaderFooter()
  1553. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveHF_Identifier {
  1554. batchRemoveHeaderFooter()
  1555. } else if itemIdentifier == KMPDFToolbar_edit_addBates_Identifier {
  1556. showBatesController()
  1557. } else if itemIdentifier == KMPDFToolbar_edit_removeBates_Identifier {
  1558. removePDFBates()
  1559. } else if itemIdentifier == KMPDFToolbar_edit_batch_AddBates_Identifier {
  1560. batchAddBates()
  1561. } else if itemIdentifier == KMPDFToolbar_edit_batchRemoveBates_Identifier {
  1562. batchRemoveBates()
  1563. } else if itemIdentifier == KMPDFToolbar_edit_crop_Identifier {
  1564. showCropController()
  1565. }
  1566. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Form_Identifier).contains(itemIdentifier) {
  1567. //MARK: -Form表单
  1568. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Fill_Identifier).contains(itemIdentifier) {
  1569. //MARK: -填充
  1570. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Convert_Identifier).contains(itemIdentifier) {
  1571. //MARK: -转档
  1572. if itemIdentifier == KMPDFToolbar_convert_word_Identifier {
  1573. let winC = KMConvertWordWindowController()
  1574. let model = KMDocumentModel(url: listView.document.documentURL)
  1575. winC.documentModel = model
  1576. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1577. } else if itemIdentifier == KMPDFToolbar_convert_ppt_Identifier {
  1578. let winC = KMConvertPPTsWindowController()
  1579. winC.subType = 1
  1580. let model = KMDocumentModel(url: listView.document.documentURL)
  1581. winC.documentModel = model
  1582. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1583. } else if itemIdentifier == KMPDFToolbar_convert_RTF_Identifier {
  1584. let winC = KMConvertPPTsWindowController()
  1585. winC.subType = 2
  1586. let model = KMDocumentModel(url: listView.document.documentURL)
  1587. winC.documentModel = model
  1588. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1589. } else if itemIdentifier == KMPDFToolbar_convert_Text_Identifier {
  1590. let winC = KMConvertPPTsWindowController()
  1591. winC.subType = 4
  1592. let model = KMDocumentModel(url: listView.document.documentURL)
  1593. winC.documentModel = model
  1594. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1595. } else if itemIdentifier == KMPDFToolbar_convert_CSV_Identifier {
  1596. let winC = KMConvertPPTsWindowController()
  1597. winC.subType = 5
  1598. let model = KMDocumentModel(url: listView.document.documentURL)
  1599. winC.documentModel = model
  1600. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1601. } else if itemIdentifier == KMPDFToolbar_convert_excel_Identifier {
  1602. let winC = KMConvertExcelWindowController()
  1603. let model = KMDocumentModel(url: listView.document.documentURL)
  1604. winC.documentModel = model
  1605. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1606. } else if itemIdentifier == KMPDFToolbar_convert_HTML_Identifier {
  1607. let winC = KMConvertHtmlWindowController()
  1608. let model = KMDocumentModel(url: listView.document.documentURL)
  1609. winC.documentModel = model
  1610. winC.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  1611. } else if itemIdentifier == KMPDFToolbar_convert_Json_Identifier {
  1612. let winC = KMConvertJsonWindowController()
  1613. let model = KMDocumentModel(url: listView.document.documentURL)
  1614. winC.documentModel = model
  1615. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  1616. } else if itemIdentifier == KMPDFToolbar_convert_image_Identifier {
  1617. let winC = KMConvertImageWindowController()
  1618. let model = KMDocumentModel(url: listView.document.documentURL)
  1619. winC.documentModel = model
  1620. winC.own_beginSheetModal(for: view.window, completionHandler: nil)
  1621. } else if itemIdentifier == KMPDFToolbar_convert_imageToPDF_Identifier {
  1622. NSApplication.ShowImageToPDFWindow()
  1623. }
  1624. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Protect_Identifier).contains(itemIdentifier) {
  1625. //MARK: -Protect
  1626. } else if toolbarManager.getSubToolItemIdentifys(KMPDFToolbar_Tools_Identifier).contains(itemIdentifier) {
  1627. //MARK: -工具
  1628. } else if itemIdentifier == KMPDFToolbar_ViewDisplay_Identifier {
  1629. //MARK: -Display
  1630. updatePDFDisplaySettingView()
  1631. } else if itemIdentifier == KMPDFToolbar_rightView_Identifier {
  1632. //MARK: -属性栏
  1633. } else if itemIdentifier == KMPDFToolbar_PageEdit_Identifier {
  1634. //MARK: -页面编辑
  1635. if viewManager.isPageEditMode == true {
  1636. enterPageEditMode()
  1637. } else {
  1638. exitPageEditMode()
  1639. }
  1640. } else if(itemIdentifier == KMPDFToolbar_undo_Identifier) {
  1641. //MARK: -Undo
  1642. listView.undoManager?.undo()
  1643. } else if(itemIdentifier == KMPDFToolbar_redo_Identifier) {
  1644. //MARK: -Redo
  1645. listView.undoManager?.redo()
  1646. } else if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier ||
  1647. itemIdentifier == KMPDFToolbar_share_Flattened_Identifier ||
  1648. itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  1649. //MARK: -Share
  1650. if(itemIdentifier == KMPDFToolbar_share_PDF_Identifier) {
  1651. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  1652. shareDocument(sender: view)
  1653. }
  1654. } else if(itemIdentifier == KMPDFToolbar_share_Flattened_Identifier) {
  1655. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  1656. shareFlatten(sender: view)
  1657. }
  1658. } else if(itemIdentifier == KMPDFToolbar_share_Original_Identifier) {
  1659. if let view = controller.findViewWith(KMPDFToolbar_share_Identifier) {
  1660. shareOriginalPDF(sender: view)
  1661. }
  1662. }
  1663. } else {
  1664. print("click else")
  1665. }
  1666. refreshToolbarView()
  1667. toolbarViewModeChanged()
  1668. }
  1669. func kmPDFToolbarControllerDidSelectTextDidBeginEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  1670. }
  1671. func kmPDFToolbarControllerDidSelectTextDidChange(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  1672. }
  1673. func kmPDFToolbarControllerDidSelectTextDidEndEditing(_ controller: KMPDFToolbarController, _ view: ComponentSelect) {
  1674. if view.properties == toolbarManager.page_pageInfo_Property {
  1675. if viewManager.isPageEditMode == true {
  1676. let fileAttribute = KMNFileAttribute()
  1677. fileAttribute.password = listView.document?.password ?? ""
  1678. fileAttribute.pdfDocument = listView.document
  1679. fileAttribute.filePath = listView.document?.documentURL.path ?? ""
  1680. fileAttribute.bAllPage = false
  1681. fileAttribute.pagesType = .PagesString
  1682. fileAttribute.pagesString = view.properties.text ?? ""
  1683. let fetchSelectPages = fileAttribute.fetchSelectPages()
  1684. if (fetchSelectPages.isEmpty) {
  1685. let alert = NSAlert()
  1686. alert.alertStyle = .critical
  1687. alert.messageText = String(format: "%@ %@", fileAttribute.filePath.lastPathComponent, KMLocalizedString("Invalid page range or the page number is out of range. Please try again."))
  1688. alert.runModal()
  1689. toolbarManager.page_pageInfo_Property.text = ""
  1690. controller.refreshSecondToolbarItemsState()
  1691. } else {
  1692. var tIndexPaths: Set<IndexPath> = []
  1693. for i in 0 ..< fetchSelectPages.count {
  1694. tIndexPaths.insert(IndexPath(item: (fetchSelectPages[i] - 1), section: 0))
  1695. }
  1696. pageEditViewController?.selectionIndexPaths = tIndexPaths
  1697. }
  1698. }
  1699. }
  1700. }
  1701. func kmPDFToolbarControllerDidExitPageEditMode(_ controller: KMPDFToolbarController) {
  1702. exitPageEditMode()
  1703. }
  1704. }
  1705. //MARK: - KMRightSideControllerDelegate右边属性栏代理
  1706. extension KMMainViewController: KMRightSideControllerDelegate {
  1707. func kmRightSideControllerDidContendVCUpdated(_ controller: KMRightSideController) {
  1708. //MARK: -Crop
  1709. if (controller.contentViewController is KMCropPropertyController) {
  1710. if let cropVC = rightSideController?.edit_cropController {
  1711. cropVC.pdfView = controller.pdfView
  1712. if cropVC.delegate == nil {
  1713. cropVC.delegate = cropController
  1714. }
  1715. cropVC.reloadData()
  1716. }
  1717. }
  1718. }
  1719. }
  1720. //MARK: - KMNDisplayViewControllerDelegate代理
  1721. extension KMMainViewController: KMNDisplayViewControllerDelegate {
  1722. //Display Mode
  1723. func displayViewControllerDidDisplayModeChanged(_ controller: KMNDisplayViewController) {
  1724. listView.layoutDocumentView()
  1725. }
  1726. //阅读模式
  1727. func displayViewControllerDidReadModeUpdated(_ controller: KMNDisplayViewController) {
  1728. if viewManager.isPDFReadMode {
  1729. openPDFReadMode()
  1730. } else {
  1731. exitPDFReadMode()
  1732. }
  1733. }
  1734. //PPT
  1735. func displayViewControllerDidGotoSlideShow(_ controller: KMNDisplayViewController) {
  1736. togglePresentation(nil)
  1737. }
  1738. //SplitView
  1739. func displayViewControllerDidSplitModeChanged(_ controller: KMNDisplayViewController) {
  1740. reloadPDFSplitInfo()
  1741. }
  1742. func displayViewControllerDidSplitFileChanged(_ controller: KMNDisplayViewController) {
  1743. splitPDFController?.reloadData()
  1744. }
  1745. func displayViewControllerDidToolbarStateChanged(_ controller: KMNDisplayViewController) {
  1746. splitPDFController?.refreshToolbarState()
  1747. reloadPDFBottomToolbar()
  1748. }
  1749. }
  1750. //MARK: - PPT
  1751. extension KMMainViewController: KMInteractionProviderProtocol {
  1752. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  1753. if(interactionMode == .presentation) {
  1754. if listView.presentationDrawView == nil {
  1755. listView.createPresentationDraw()
  1756. }
  1757. presentationTopViewController = KMPresentationTopViewController.init(nibName: "KMPresentationTopViewController", bundle: nil)
  1758. presentationTopViewController?.pdfView = listView
  1759. presentationTopViewController?.delegate = self
  1760. presentationTopViewController?.isSelectionPre = true
  1761. listView.isPresentationMode = true
  1762. presentationTopViewController?.view.frame = CGRect(x: 0, y: (fullScreenWindow.contentView?.bounds.height ?? 0) - 42, width: fullScreenWindow.contentView?.bounds.width ?? 0, height: 42)
  1763. if((presentationTopViewController) != nil) {
  1764. fullScreenWindow.contentView?.addSubview(presentationTopViewController!.view)
  1765. }
  1766. } else {
  1767. listView.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  1768. }
  1769. fullScreenWindow.contentView?.addSubview(listView)
  1770. if(interactionMode == .presentation) {
  1771. let frame = fullScreenWindow.frame
  1772. listView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-42)
  1773. listView.autoresizingMask = [.width, .maxYMargin]
  1774. }
  1775. return view
  1776. }
  1777. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  1778. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1779. return
  1780. }
  1781. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  1782. if interactionMode == .presentation {
  1783. let backgroundColor = NSColor.black
  1784. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  1785. let wasInteractionMode = self.interactionMode
  1786. if wasInteractionMode == .normal {
  1787. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  1788. }
  1789. if wasInteractionMode == .legacyFullScreen {
  1790. self.enterPresentationMode()
  1791. self.listView.frame = (self.view.window?.contentView?.bounds)!
  1792. self.view.window?.contentView?.addSubview(listView)
  1793. // self.view.window?.backgroundColor = backgroundColor
  1794. self.view.window?.level = level
  1795. self.listView.layoutDocumentView()
  1796. self.listView.requiresDisplay()
  1797. self.forceSubwindowsOnTop(false)
  1798. }
  1799. } else {
  1800. KMPrint("2")
  1801. }
  1802. }
  1803. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  1804. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1805. return
  1806. }
  1807. if self.interactionMode == .presentation {
  1808. self.listView.layoutDocumentView()
  1809. self.listView.requiresDisplay()
  1810. }
  1811. }
  1812. @objc func willShowFullScreenNotification(_ sender: Notification) {
  1813. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1814. return
  1815. }
  1816. if self.interactionMode == .presentation {
  1817. let view = self.view.window?.firstResponder as? NSView
  1818. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  1819. self.view.window?.makeFirstResponder(nil)
  1820. }
  1821. }
  1822. }
  1823. @objc func didShowFullScreenNotification(_ sender: Notification) {
  1824. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1825. return
  1826. }
  1827. if self.interactionMode == .presentation {
  1828. self.enterPresentationMode()
  1829. }
  1830. }
  1831. }
  1832. // MARK: -KMPresentationTopViewControllerDelegate (幻灯片)
  1833. extension KMMainViewController: KMPresentationTopViewControllerDelegate {
  1834. func presentationTopViewExit(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  1835. self.exitFullScreen()
  1836. }
  1837. func presentationTopViewClear(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  1838. listView.presentationDrawView?.clear()
  1839. }
  1840. func presentationTopViewUndo(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton) {
  1841. let presentationDrawView = listView.presentationDrawView
  1842. if presentationDrawView?.canUndo() == true {
  1843. presentationDrawView?.undo()
  1844. }
  1845. }
  1846. func presentationTopViewType(_ presentationTopViewController: KMPresentationTopViewController, withButton: NSButton, isSeletion: Bool) {
  1847. listView.isPresentationMode = isSeletion
  1848. if listView.isEnterPresentationDrawMode() == true {
  1849. listView.exitPresentationDrawMode()
  1850. }
  1851. }
  1852. func presentationTopViewDrawColor(_ presentationTopViewController: KMPresentationTopViewController, withView: NSView,color:NSColor?) {
  1853. if color == nil{
  1854. listView.exitPresentationDrawMode()
  1855. } else {
  1856. if listView.isEnterPresentationDrawMode() == false {
  1857. listView.enterPresentationDrawMode()
  1858. }
  1859. listView.changePresentationDrawModelColor(color)
  1860. }
  1861. }
  1862. }
  1863. //MARK: - KMSplitPDFViewControllerDelegate SplitPDFView分屏视图
  1864. extension KMMainViewController: KMSplitPDFViewControllerDelegate {
  1865. func splitPDFViewControllerDidUpdateFilePath(_ controller: KMSplitPDFViewController) {
  1866. displaySettingController?.reloadData()
  1867. }
  1868. func splitPDFViewControllerDidUpdatePDFScale(_ controller: KMSplitPDFViewController) {
  1869. if let scaleFactor = controller.pdfView?.scaleFactor {
  1870. listView.scaleFactor = scaleFactor
  1871. }
  1872. }
  1873. func splitPDFViewControllerDidUpdatePDFPageIndex(_ controller: KMSplitPDFViewController) {
  1874. if let pageIndex = controller.pdfView?.currentPageIndex {
  1875. listView.go(toPageIndex: pageIndex, animated: false)
  1876. }
  1877. }
  1878. }
  1879. //MARK: - Edit编辑相关代理
  1880. extension KMMainViewController: KMEditToolbarViewDelegate {
  1881. func kmEditToolbarViewDidUpdateMode(_ view: KMEditToolbarView) {
  1882. if view.editType == .watermark {
  1883. watermarkViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1884. watermarkViewController?.resetUI()
  1885. watermarkViewController?.reloadData()
  1886. } else if view.editType == .background {
  1887. backgroundViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1888. backgroundViewController?.resetUI()
  1889. backgroundViewController?.reloadData()
  1890. } else if view.editType == .header_Footer {
  1891. headerFooterViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1892. headerFooterViewController?.resetUI()
  1893. headerFooterViewController?.reloadData()
  1894. } else if view.editType == .bates {
  1895. batesViewController?.editSubType = editToolbarView?.editSubType ?? .template
  1896. batesViewController?.resetUI()
  1897. batesViewController?.reloadData()
  1898. }
  1899. }
  1900. func kmEditToolbarViewDidChooseBatch(_ view: KMEditToolbarView) {
  1901. }
  1902. func kmEditToolbarViewDidChooseApply(_ view: KMEditToolbarView) {
  1903. let pageIndex = view.getSelectedPageIndex(listView.document)
  1904. if pageIndex.isEmpty {
  1905. let alert = NSAlert()
  1906. alert.alertStyle = .critical
  1907. alert.messageText = KMLocalizedString("Invalid page range or the page number is out of range. Please try again.")
  1908. alert.runModal()
  1909. return
  1910. }
  1911. let pageString = view.getSelectedPageString(listView.document, pageIndex)
  1912. if view.editType == .watermark {
  1913. if let model = watermarkViewController?.currentWatermarkData {
  1914. let watermark = KMPDFWatermarkData.returnWaterMarkWith(model, listView.document)
  1915. watermark.pageString = pageString
  1916. listView.document.addWatermark(watermark)
  1917. listView.layoutDocumentView()
  1918. }
  1919. exitEditToolbarView()
  1920. } else if view.editType == .background {
  1921. if let model = backgroundViewController?.backgroundModel {
  1922. if let background = listView.document.background() {
  1923. KMBackgroundManager.defaultManager.updateBackground(background, withModel: model)
  1924. background.pageString = pageString
  1925. background.update()
  1926. listView.document?.refreshPageData()
  1927. listView.layoutDocumentView()
  1928. }
  1929. }
  1930. exitEditToolbarView()
  1931. } else if view.editType == .header_Footer {
  1932. if let model = headerFooterViewController?.headerFooterModel {
  1933. if let headerFooter = listView.document.headerFooter() {
  1934. KMHeaderFooterManager.defaultManager.updateCPDFHeaderFooter(headerFooter, withModel: model, Int(listView.document.pageCount))
  1935. headerFooter.pageString = pageString
  1936. headerFooter.update()
  1937. listView.document?.refreshPageData()
  1938. listView.layoutDocumentView()
  1939. }
  1940. }
  1941. exitEditToolbarView()
  1942. } else if view.editType == .bates {
  1943. exitEditToolbarView()
  1944. }
  1945. }
  1946. func kmEditToolbarViewDidChooseExit(_ view: KMEditToolbarView) {
  1947. if view.applyEnable {
  1948. let alert = NSAlert()
  1949. if view.editType == .watermark {
  1950. alert.messageText = NSLocalizedString("There are unapplied Watermark settings, do you want to apply them?", comment: "")
  1951. } else if view.editType == .background {
  1952. alert.messageText = NSLocalizedString("There are unapplied Background settings, do you want to apply them?", comment: "")
  1953. } else if view.editType == .header_Footer {
  1954. alert.messageText = NSLocalizedString("There are unapplied Header & Footer settings, do you want to apply them?", comment: "")
  1955. } else if view.editType == .bates {
  1956. alert.messageText = NSLocalizedString("There are unapplied Bates settings, do you want to apply them?", comment: "")
  1957. }
  1958. alert.informativeText = NSLocalizedString("If not, the changes will be lost.", comment: "")
  1959. alert.addButton(withTitle: NSLocalizedString("Apply", comment: ""))
  1960. alert.addButton(withTitle: NSLocalizedString("Don't Apply", comment: ""))
  1961. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  1962. let result = alert.runModal()
  1963. if (result == .alertFirstButtonReturn) {
  1964. self.kmEditToolbarViewDidChooseApply(view)
  1965. } else if (result == .alertSecondButtonReturn) {
  1966. //"Don't Apply"
  1967. exitEditToolbarView()
  1968. } else if (result == .alertThirdButtonReturn) {
  1969. //Cancel
  1970. }
  1971. } else {
  1972. exitEditToolbarView()
  1973. }
  1974. }
  1975. }
  1976. //MARK: - KMCropControllerDelegate 裁剪相关代理
  1977. extension KMMainViewController: KMCropControllerDelegate {
  1978. func kmCropControllerDidCrop(_ controller: KMCropController, _ cropRect: CGRect, _ view: KMPageRangeSelectView) {
  1979. let indexs = view.getSelectedPageIndex(listView.document)
  1980. var uIndexs: [UInt] = []
  1981. for index in indexs {
  1982. if index > 0 {
  1983. uIndexs.append(UInt(index-1))
  1984. }
  1985. }
  1986. cropPages(atIndexs: uIndexs, to: [cropRect])
  1987. removeCropController()
  1988. }
  1989. func kmCropControllerDidCropSeparate(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  1990. let indexs = view.getSelectedPageIndex(listView.document)
  1991. var rectArray: Array<NSRect> = []
  1992. var uIndexs: [UInt] = []
  1993. for index in indexs {
  1994. if index > 0 {
  1995. uIndexs.append(UInt(index-1))
  1996. let page = self.listView.document.page(at: UInt(index-1))
  1997. let rect = KMCropTools.getPageForegroundBox(page!)
  1998. rectArray.append(rect)
  1999. }
  2000. }
  2001. cropPages(atIndexs: uIndexs, to: rectArray)
  2002. removeCropController()
  2003. }
  2004. func kmCropControllerDidCropAuto(_ controller: KMCropController, _ view: KMPageRangeSelectView) {
  2005. let indexs = view.getSelectedPageIndex(listView.document)
  2006. var uIndexs: [UInt] = []
  2007. for index in indexs {
  2008. if index > 0 {
  2009. uIndexs.append(UInt(index-1))
  2010. }
  2011. }
  2012. auto_cropPagesWhiteMargin(uIndexs)
  2013. }
  2014. func kmCropControllerDidChangedSelectionOrMagnification(_ controller: KMCropController) {
  2015. if let cropVC = rightSideController?.edit_cropController {
  2016. if cropVC.pdfView != controller.pdfView {
  2017. cropVC.pdfView = controller.pdfView
  2018. }
  2019. cropVC.cropSeparateOn = false
  2020. cropVC.cropAutoOn = false
  2021. cropVC.reloadData()
  2022. }
  2023. }
  2024. }
  2025. //MARK: - KMWatermarkControllerDelegate 水印相关代理
  2026. extension KMMainViewController: KMWatermarkControllerDelegate {
  2027. func kmWatermarkControllerDidUpdateMode(_ view: KMWatermarkController) {
  2028. editToolbarView?.editSubType = view.editSubType
  2029. editToolbarView?.reloadData()
  2030. }
  2031. func kmWatermarkControllerDidWatermarkUpdated(_ view: KMWatermarkController) {
  2032. var applyEnable = true
  2033. if let model = view.currentWatermarkData {
  2034. if model.watermarkType == .text {
  2035. if model.text == nil || model.text?.count == 0 {
  2036. applyEnable = false
  2037. }
  2038. } else if model.watermarkType == .image {
  2039. if model.imagePath == nil {
  2040. applyEnable = false
  2041. }
  2042. }
  2043. } else {
  2044. applyEnable = false
  2045. }
  2046. editToolbarView?.applyEnable = applyEnable
  2047. editToolbarView?.reloadData()
  2048. }
  2049. }
  2050. //MARK: - KMBackgroundControllerDelegate 背景代理
  2051. extension KMMainViewController: KMBackgroundControllerDelegate {
  2052. func kmBackgroundControllerDidUpdateMode(_ view: KMBackgroundController) {
  2053. editToolbarView?.editSubType = view.editSubType
  2054. }
  2055. func kmBackgroundControllerDidWatermarkUpdated(_ view: KMBackgroundController) {
  2056. var applyEnable = true
  2057. if let model = view.backgroundModel {
  2058. if model.type == .image {
  2059. if model.imagePath == nil {
  2060. applyEnable = false
  2061. }
  2062. }
  2063. } else {
  2064. applyEnable = false
  2065. }
  2066. editToolbarView?.applyEnable = applyEnable
  2067. editToolbarView?.reloadData()
  2068. }
  2069. }
  2070. //MARK: - KMHeaderFooterControllerDelegate 页眉页脚代理
  2071. extension KMMainViewController: KMHeaderFooterControllerDelegate {
  2072. func kmHeaderFooterControllerDidUpdateMode(_ view: KMHeaderFooterController) {
  2073. editToolbarView?.editSubType = view.editSubType
  2074. }
  2075. func kmHeaderFooterControllerDidModelDataUpdated(_ view: KMHeaderFooterController) {
  2076. var applyEnable = true
  2077. if let model = view.headerFooterModel {
  2078. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  2079. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  2080. applyEnable = false
  2081. }
  2082. } else {
  2083. applyEnable = false
  2084. }
  2085. editToolbarView?.applyEnable = applyEnable
  2086. editToolbarView?.reloadData()
  2087. }
  2088. }
  2089. //MARK: - KMBatesControllerDelegate Bates贝茨码代理
  2090. extension KMMainViewController: KMBatesControllerDelegate {
  2091. func kmBatesControllerDidUpdateMode(_ view: KMBatesController) {
  2092. editToolbarView?.editSubType = view.editSubType
  2093. editToolbarView?.reloadData()
  2094. }
  2095. func kmBatesControllerDidModelDataUpdated(_ view: KMBatesController) {
  2096. var applyEnable = true
  2097. if let model = view.batesModel {
  2098. if model.topLeftString.count == 0 && model.topCenterString.count == 0 && model.topRightString.count == 0 &&
  2099. model.bottomLeftString.count == 0 && model.bottomCenterString.count == 0 && model.bottomRightString.count == 0 {
  2100. applyEnable = false
  2101. }
  2102. } else {
  2103. applyEnable = false
  2104. }
  2105. editToolbarView?.applyEnable = applyEnable
  2106. editToolbarView?.reloadData()
  2107. }
  2108. }
  2109. //MARK: - CPDFViewDelegate PDFView代理
  2110. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  2111. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  2112. sideBarController?.reloadPageTurnerData()
  2113. documentLoadComplete()
  2114. }
  2115. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  2116. sideBarController?.reloadPageTurnerData()
  2117. var indexpaths: Set<IndexPath> = []
  2118. indexpaths.insert(IndexPath(item: listView.currentPageIndex, section: 0))
  2119. botaViewController?.thumnailViewController?.selectionIndexPaths = indexpaths
  2120. //分屏视图
  2121. reloadPDFBottomToolbar()
  2122. if viewManager.splitSyncScroll {
  2123. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  2124. splitPDFController?.outPDFFirst = true
  2125. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  2126. var index = pdfView.currentPageIndex
  2127. if index > document.pageCount {
  2128. index = Int(splitPDFView.document.pageCount - 1)
  2129. }
  2130. splitPDFView.go(toPageIndex: index, animated: false)
  2131. }
  2132. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  2133. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  2134. } else if splitPDFController?.outPDFFirst == true {
  2135. if let splitPDFView = splitPDFController?.pdfView, let document = splitPDFView.document {
  2136. var index = pdfView.currentPageIndex
  2137. if index > document.pageCount {
  2138. index = Int(splitPDFView.document.pageCount - 1)
  2139. }
  2140. splitPDFView.go(toPageIndex: index, animated: false)
  2141. }
  2142. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  2143. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  2144. }
  2145. }
  2146. //水印
  2147. updateEditModeDocumentWhenPageChanged()
  2148. //
  2149. }
  2150. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  2151. pdfToolbarController?.reloadSelectZoomView()
  2152. reloadPDFBottomToolbar()
  2153. //分屏视图
  2154. if viewManager.splitSyncScroll {
  2155. if splitPDFController?.inPDFFirst == false && splitPDFController?.outPDFFirst == false {
  2156. splitPDFController?.outPDFFirst = true
  2157. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  2158. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  2159. } else if splitPDFController?.outPDFFirst == true {
  2160. if let splitPDFView = splitPDFController?.pdfView {
  2161. splitPDFView.scaleFactor = pdfView.scaleFactor
  2162. }
  2163. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(pdfUpdatedFinish), object: nil)
  2164. self.perform(#selector(pdfUpdatedFinish), with: nil, afterDelay: 0.35)
  2165. }
  2166. }
  2167. }
  2168. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  2169. if let urlString = url, urlString == kKMPurchaseProductURLString {
  2170. //跳转订阅比较表
  2171. return
  2172. }
  2173. if url.hasPrefix("smb://") {
  2174. NSWorkspace.shared.openFile(url)
  2175. } else {
  2176. KMTools.openURL(urlString: url)
  2177. }
  2178. }
  2179. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  2180. KMPrint("pdfViewPerformURL")
  2181. if content != nil {
  2182. NSWorkspace.shared.open(URL(string: content)!)
  2183. } else {
  2184. let alert = NSAlert()
  2185. alert.alertStyle = .critical
  2186. alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
  2187. alert.messageText = ""
  2188. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  2189. alert.runModal()
  2190. return
  2191. }
  2192. }
  2193. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  2194. KMPrint("pdfViewPerformPrint")
  2195. self.showPrintWindow()
  2196. }
  2197. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  2198. KMPrint("pdfViewPerformGo")
  2199. }
  2200. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  2201. KMPrint("pdfViewOpenPDF")
  2202. }
  2203. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  2204. KMPrint("pdfViewPerformReset")
  2205. pdfView.document?.resetForm()
  2206. }
  2207. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  2208. KMPrint("pdfViewEditingBlockDidChanged")
  2209. }
  2210. func pdfViewAsBookBookmark() -> NSImage! {
  2211. return NSImage(named: "KMImageNameBookmarkIcon")!
  2212. }
  2213. //MARK: -编辑模块
  2214. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  2215. // 文本区块 选中文本已经变化
  2216. }
  2217. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  2218. //编辑模块变化
  2219. rightSideController?.reloadDataWithPDFView(pdfView: (pdfView as! CPDFListView))
  2220. if pdfView is CPDFListView {
  2221. (pdfView as! CPDFListView).isEditImage = false
  2222. }
  2223. }
  2224. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  2225. if editArea != nil && (editArea is CPDFEditImageArea){
  2226. self.listView.cropAreas = editArea as? CPDFEditImageArea
  2227. }
  2228. }
  2229. //编辑PDF 创建图片区域回调
  2230. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  2231. if (pdfView as! CPDFListView).isEditImage {
  2232. return
  2233. }
  2234. if rect.size.width < 5 && rect.size.height < 5 {
  2235. pdfView.updateEditing([])
  2236. return
  2237. }
  2238. let panel = NSOpenPanel()
  2239. panel.allowsMultipleSelection = false
  2240. panel.allowedFileTypes = ["png","jpg"]
  2241. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  2242. if response == .OK {
  2243. var filePath = panel.url?.path
  2244. let image = NSImage.init(contentsOf: panel.url!)
  2245. //图片自适应范围
  2246. if image != nil {
  2247. var imageRect = rect
  2248. let imageSize = image!.size
  2249. var previewSize = rect.size
  2250. var isChangeSize = false
  2251. if previewSize.width == 0 && previewSize.height == 0 {
  2252. previewSize = CGSize(width: 500, height: 500)
  2253. isChangeSize = true
  2254. }
  2255. var scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  2256. if scale < 1 { // 大于 500
  2257. } else {
  2258. let wh = max(imageSize.width, imageSize.height)
  2259. if wh >= 72 {
  2260. scale = min(scale, 1)
  2261. } else {
  2262. scale = min(72 / imageSize.width, 72 / imageSize.height)
  2263. }
  2264. }
  2265. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  2266. if isChangeSize {
  2267. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  2268. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  2269. } else {
  2270. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  2271. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  2272. }
  2273. imageRect.size = newSize
  2274. let limitWidth = 1920.0
  2275. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  2276. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  2277. targetSize: CGSize(width: limitWidth, height: limitWidth),
  2278. maxSizeInBytes: 1024 * 1024 * 5,
  2279. targetCompression: 1.0)
  2280. }
  2281. //自适应page
  2282. let pageRect = self.listView.currentPage().bounds ?? .zero
  2283. if imageRect.width > pageRect.width ||
  2284. imageRect.height > pageRect.height {
  2285. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  2286. imageRect = CGRect(x: imageRect.origin.x,
  2287. y: imageRect.origin.y,
  2288. width: imageRect.width * pageScale,
  2289. height: imageRect.height * pageScale)
  2290. }
  2291. if imageRect.origin.x < 0 {
  2292. imageRect.origin.x = 5
  2293. }
  2294. if imageRect.origin.y < 0 {
  2295. imageRect.origin.y = 5
  2296. }
  2297. if imageRect.origin.x + imageRect.width > pageRect.width ||
  2298. imageRect.origin.y + imageRect.height > pageRect.height {
  2299. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  2300. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  2301. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  2302. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  2303. }
  2304. DispatchQueue.main.async {
  2305. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  2306. }
  2307. }
  2308. }
  2309. }
  2310. }
  2311. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  2312. if rect.size.width < 5 && rect.size.height < 5 {
  2313. let areas = self.listView.km_EditingAreas()
  2314. if let area = areas.last {
  2315. if let data = area as? CPDFEditTextArea {
  2316. if let str = data.editTextAreaString(), str.isEmpty {
  2317. self.listView.remove(with: area)
  2318. } else {
  2319. self.listView.updateEditing([])
  2320. }
  2321. }
  2322. }
  2323. return
  2324. }
  2325. var newRect = rect
  2326. if rect.size.equalTo(.zero) {
  2327. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  2328. } else {
  2329. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  2330. }
  2331. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  2332. let fontSize = model.fontSize
  2333. let fontColor = model.color
  2334. let fontAlign = model.alignment
  2335. NSColorPanel.shared.color = fontColor
  2336. let cfont = CPDFFont(familyName: model.fontName, fontStyle: model.fontStyle)
  2337. let fontNameZ = CPDFFont.convertAppleFont(cfont)
  2338. let font = NSFont(name: fontNameZ ?? "Helvetica", size: fontSize)
  2339. let attri = CEditAttributes()
  2340. attri.font = font!
  2341. attri.fontColor = fontColor
  2342. attri.alignment = fontAlign
  2343. attri.isBold = model.bold
  2344. attri.isItalic = model.italic
  2345. self.listView.createStringBounds(newRect, with: attri, page: page)
  2346. }
  2347. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  2348. rightSideController?.reloadEditingAreas()
  2349. }
  2350. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  2351. rightSideController?.reloadEditingAreas()
  2352. }
  2353. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  2354. rightSideController?.reloadEditingAreas()
  2355. }
  2356. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  2357. rightSideController?.reloadEditingAreas()
  2358. }
  2359. func pdfViewEditingExitCropMode(_ pdfView: CPDFView!, forEditing editingArea: CPDFEditImageArea!) {
  2360. rightSideController?.reloadEditingAreas()
  2361. }
  2362. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  2363. let areas = self.listView.km_editingImageAreas()
  2364. if areas.count == 1 {
  2365. if let data = areas.first as? CPDFEditImageArea {
  2366. let updating = self.listView.editAreaBoundUpdating
  2367. if updating {
  2368. self.listView.editAreaBoundUpdating = false
  2369. }
  2370. }
  2371. }
  2372. }
  2373. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  2374. }
  2375. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  2376. let command = theEvent.modifierFlags.contains(.command)
  2377. let control = theEvent.modifierFlags.contains(.control)
  2378. KMPrint(theEvent.keyCode)
  2379. if self.listView.isEditing() == true {
  2380. if control && theEvent.keyCode == 11 { // ctr + b
  2381. self.listView.setEditingTextarea_Bold()
  2382. rightSideController?.reloadEditingAreas()
  2383. return false
  2384. } else if control && theEvent.keyCode == 34 { // ctr +i
  2385. self.listView.setEditingTextarea_Italic()
  2386. rightSideController?.reloadEditingAreas()
  2387. return false
  2388. } else if theEvent.keyCode == 36 { // enter
  2389. if self.listView.isCropMode {
  2390. self.listView.cropComfirmAction()
  2391. rightSideController?.reloadEditingAreas()
  2392. return false
  2393. }
  2394. } else if theEvent.keyCode == 53 { // Cancel
  2395. if self.listView.isCropMode {
  2396. self.listView.cropCancelAction()
  2397. rightSideController?.reloadEditingAreas()
  2398. return false
  2399. }
  2400. }
  2401. }
  2402. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  2403. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  2404. return false
  2405. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  2406. return false
  2407. } else if (theEvent.keyCode == 123) { // 向左
  2408. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  2409. return false
  2410. } else {
  2411. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  2412. self.listView.goToPreviousPage(nil)
  2413. return false
  2414. }
  2415. }
  2416. } else if (theEvent.keyCode == 126) { // 向上
  2417. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  2418. return false
  2419. } else {
  2420. if (self.listView.isContinousScroll()) {
  2421. return true
  2422. }
  2423. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  2424. self.listView.goToPreviousPage(nil)
  2425. return false
  2426. }
  2427. }
  2428. } else if (theEvent.keyCode == 124) { // 向右
  2429. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  2430. return false
  2431. } else {
  2432. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  2433. self.listView.goToNextPage(nil)
  2434. return false
  2435. }
  2436. }
  2437. } else if (theEvent.keyCode == 125) { // 向下
  2438. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  2439. return false
  2440. } else {
  2441. if (self.listView.isContinousScroll()) {
  2442. return true
  2443. }
  2444. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  2445. self.listView.goToNextPage(nil)
  2446. return false
  2447. }
  2448. }
  2449. } else if (theEvent.keyCode == 36) {
  2450. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  2451. if self.listView.isEditImage {
  2452. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  2453. }
  2454. }
  2455. }
  2456. if theEvent.keyCode == 53 {
  2457. //ESC
  2458. // self.exitFullScreen()
  2459. if viewManager.isPDFReadMode {
  2460. self.exitPDFReadMode()
  2461. }
  2462. self.leftSideViewCancelSelect()
  2463. }
  2464. return true
  2465. }
  2466. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  2467. guard let action = menuItem.action else {
  2468. isTakesEffect.pointee = false
  2469. return false
  2470. }
  2471. if (KMSystemMenu.isEditSelector(sel: action)) {
  2472. if (KMSystemMenu.Edit.deleteSelector == action) {
  2473. isTakesEffect.pointee = true
  2474. return self.listView.activeAnnotations.count > 0
  2475. } else if (KMSystemMenu.Edit.copySelector == action) {
  2476. isTakesEffect.pointee = true
  2477. return true//self.listView.canCopy()
  2478. } else if (KMSystemMenu.Edit.cutSelector == action) {
  2479. isTakesEffect.pointee = true
  2480. return self.listView.canCopy()
  2481. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  2482. isTakesEffect.pointee = true
  2483. return self.listView.canPaste()
  2484. }
  2485. }
  2486. isTakesEffect.pointee = false
  2487. return false
  2488. }
  2489. //MARK: - CPDFListViewDelegate
  2490. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  2491. self.leftSideViewController.updateThumbnail(at: Int(pdfPage.pageIndex()))
  2492. }
  2493. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  2494. self.view.window?.makeFirstResponder(self.listView)
  2495. if isRightMenu {
  2496. } else if annotations.count > 0 {
  2497. if annotations.count > 1 {
  2498. let fristAnnotation = annotations.first
  2499. var isSameAnnotation = true
  2500. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  2501. for annotation in annotations {
  2502. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  2503. if (className == "CPDFSquareAnnotation") ||
  2504. (className == "CPDFCircleAnnotation") ||
  2505. (className == "CPDFLineAnnotation") {
  2506. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  2507. (cunrrentClassName != "CPDFCircleAnnotation") &&
  2508. (cunrrentClassName != "CPDFLineAnnotation") {
  2509. isSameAnnotation = false
  2510. }
  2511. } else {
  2512. if className != cunrrentClassName {
  2513. isSameAnnotation = false
  2514. }
  2515. }
  2516. }
  2517. if isSameAnnotation == false {
  2518. } else {
  2519. self.toggleOpenRightSide()
  2520. }
  2521. self.rightSideController?.reloadDataWithPDFView(pdfView: pdfListView)
  2522. } else {
  2523. let fristAnnotation = annotations.first
  2524. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  2525. if self.viewManager.isPDFReadMode {
  2526. toggleCloseRightSide()
  2527. } else {
  2528. if className != "CPDFStampAnnotation" &&
  2529. className != "CPDFSignatureAnnotation" &&
  2530. className != "CPDFListStampAnnotation" {
  2531. self.toggleOpenRightSide()
  2532. }
  2533. self.rightSideController?.reloadDataWithPDFView(pdfView: pdfListView)
  2534. }
  2535. }
  2536. if (listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self)) {
  2537. if (!(listView.activeAnnotation as! CPDFLineAnnotation).isMeasure) {
  2538. cancelMeasureType()
  2539. } else {
  2540. if distanceMeasureInfoWindowController == nil {
  2541. let measureInfo = CPDFDistanceMeasureInfo()
  2542. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2543. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2544. distanceMeasureInfoWindowController?.delegate = self
  2545. }
  2546. }
  2547. } else if (!listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) && !listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self)) {
  2548. cancelMeasureType()
  2549. } else if (listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) || listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self)) {
  2550. if perimeterMeasureInfoWindowController == nil {
  2551. let measureInfo = CPDFPerimeterMeasureInfo()
  2552. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2553. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2554. perimeterMeasureInfoWindowController?.delegate = self
  2555. }
  2556. if areaMeasureInfoWindowController == nil {
  2557. let measureInfo = CPDFAreaMeasureInfo()
  2558. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2559. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2560. areaMeasureInfoWindowController?.delegate = self
  2561. }
  2562. }
  2563. } else if (annotations.count == 0){
  2564. if pdfListView.annotationType == .unkown {
  2565. toggleCloseRightSide()
  2566. } else {
  2567. if self.viewManager.isPDFReadMode {
  2568. toggleCloseRightSide()
  2569. } else {
  2570. toggleOpenRightSide()
  2571. }
  2572. }
  2573. rightSideController?.reloadDataWithPDFView(pdfView: pdfListView)
  2574. }
  2575. }
  2576. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  2577. if(annotationType == .unkown) {
  2578. toggleCloseRightSide()
  2579. }
  2580. let aType = annotationType
  2581. if aType.isMarkup() || aType == .anchored || aType == .freeText || aType.isSquare() || aType == .link {
  2582. KMDataManager.ud_set(annotationType.rawValue, forKey: SKLastAnnotationModeKey)
  2583. }
  2584. }
  2585. ///开始定位链接注释
  2586. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  2587. }
  2588. ///刷新链接注释
  2589. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  2590. }
  2591. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  2592. if (listView.toolMode != CToolMode.editPDFToolMode) {
  2593. return menuItems
  2594. }
  2595. var tMenuItems = menuItems;
  2596. if(listView.isSelectEditCharRange() ||
  2597. listView.isSelecteditArea(with: point)) {
  2598. tMenuItems?.append(NSMenuItem.separator())
  2599. }
  2600. let areas = self.listView.editingAreas() ?? []
  2601. if areas.count == 1 {
  2602. let fristAreas = areas.first
  2603. if fristAreas is CPDFEditImageArea {
  2604. self.listView.selectImageAreas = fristAreas as? CPDFEditImageArea
  2605. if self.listView.isEditImage {
  2606. tMenuItems?.removeAll()
  2607. tMenuItems?.append(self.corpImageMenuItem())
  2608. tMenuItems?.append(self.cancelCorpImageMenuItem())
  2609. tMenuItems?.append(self.restoreCorpImageMenuItem())
  2610. } else {
  2611. tMenuItems?.append(NSMenuItem.separator())
  2612. tMenuItems?.append(self.cutImageArea())
  2613. tMenuItems?.append(self.replaceImageArea())
  2614. tMenuItems?.append(self.exportImageArea())
  2615. }
  2616. } else {
  2617. if tMenuItems?.count != 1 {
  2618. tMenuItems?.swapAt(0, 1)
  2619. }
  2620. }
  2621. } else if areas.count == 0 {
  2622. tMenuItems?.append(NSMenuItem.separator())
  2623. tMenuItems?.append(self.addText())
  2624. tMenuItems?.append(self.addImage())
  2625. }
  2626. return tMenuItems
  2627. }
  2628. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  2629. self.mouseRightMenuEvent = theEvent
  2630. var currentMenu : NSMenu = menu.pointee!
  2631. if let activeAnno = listView.activeAnnotation as? KMTableAnnotation {//Table
  2632. var pagePoint = NSPoint()
  2633. _ = self.listView.pageAndPoint(&pagePoint, for: theEvent, nearest: true)
  2634. currentMenu.removeAllItems()
  2635. let annotation = activeAnno
  2636. annotation.completeEditCellText()
  2637. if !(NSIsEmptyRect(annotation.drawRect)) {
  2638. annotation.drawLine(pagePoint)
  2639. NotificationCenter.default.post(name: NSNotification.Name.KMPDFViewTableAnnotationDidChange, object: self, userInfo: ["point": NSValue(point: pagePoint)])
  2640. }
  2641. if (annotation.rowNumber - annotation.currentCell.row - 1) < 0 {
  2642. return
  2643. }
  2644. currentMenu = tableMenu(currentMenu, withTable: listView.activeAnnotation as! KMTableAnnotation, point: pagePoint)
  2645. listView.needsDisplay = true
  2646. return
  2647. }
  2648. var pagePoint: NSPoint = .zero
  2649. if let page = self.listView.pageAndPoint(&pagePoint, for: theEvent, nearest: true) {
  2650. let anno = page.annotation(at: pagePoint)
  2651. let item1 = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(menuItemActionMeasureDelete), target: self)
  2652. item1.representedObject = anno
  2653. let item2 = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(menuItemActionMeasureEditNote), target: self)
  2654. item2.representedObject = anno
  2655. let item3 = NSMenuItem(title: NSLocalizedString("Settings", comment: ""), action: #selector(menuItemActionMeasureSetting), target: self)
  2656. item3.representedObject = anno
  2657. if let data = anno as? CPDFPolygonAnnotation { // 多变形
  2658. currentMenu.removeAllItems()
  2659. currentMenu.insertItem(item1, at: 0)
  2660. currentMenu.insertItem(item2, at: 1)
  2661. currentMenu.insertItem(item3, at: 2)
  2662. return
  2663. }
  2664. if let data = anno as? CPDFPolylineAnnotation {
  2665. currentMenu.removeAllItems()
  2666. currentMenu.insertItem(item1, at: 0)
  2667. currentMenu.insertItem(item2, at: 1)
  2668. currentMenu.insertItem(item3, at: 2)
  2669. return
  2670. }
  2671. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  2672. currentMenu.removeAllItems()
  2673. currentMenu.insertItem(item1, at: 0)
  2674. currentMenu.insertItem(item2, at: 1)
  2675. currentMenu.insertItem(item3, at: 2)
  2676. return
  2677. }
  2678. }
  2679. if (listView.toolMode == .selectToolMode){
  2680. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2681. currentMenu.insertItem(self.printingMenu(), at: 3)
  2682. currentMenu.insertItem(self.setTTSStype(), at: 3)
  2683. currentMenu.insertItem(self.setCropStype(), at: 3)
  2684. currentMenu.insertItem(self.setSnapshotStype(), at: 3)
  2685. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  2686. export.submenu = self.exportMenu()
  2687. currentMenu.insertItem(export, at: 3)
  2688. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2689. if listView.activeAnnotation == nil{
  2690. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  2691. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2692. }
  2693. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  2694. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  2695. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2696. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  2697. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  2698. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  2699. return
  2700. }
  2701. if (listView.toolMode == .moveToolMode || listView.toolMode == .magnifyToolMode){
  2702. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2703. currentMenu.insertItem(self.setTTSStype(), at: 0)
  2704. currentMenu.insertItem(self.setCropStype(), at: 0)
  2705. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  2706. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2707. currentMenu.insertItem(self.addOutlineStype(), at: 0)
  2708. currentMenu.insertItem(self.addBookmarkMenu(), at: 0)
  2709. if listView.activeAnnotation == nil{
  2710. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2711. currentMenu.insertItem(self.setAnnotationToolStype(), at: 0)
  2712. }
  2713. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2714. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  2715. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  2716. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  2717. return
  2718. }
  2719. if currentMenu.items.count > 3 {
  2720. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  2721. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  2722. }
  2723. if listView.currentSelection != nil && listView.activeAnnotations.count < 1{
  2724. if listView.currentSelection.selectionType() == .text {
  2725. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2726. currentMenu.insertItem(self.setSearchBaiduStype(), at: 3)
  2727. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2728. currentMenu.insertItem(self.setLookUpStype(), at: 3)
  2729. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2730. currentMenu.insertItem(self.addOutlineStype(), at: 3)
  2731. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2732. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  2733. currentMenu.insertItem(self.setTTSStype(), at: 3)
  2734. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2735. currentMenu.insertItem(self.setShareStype(), at: 3)
  2736. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2737. }
  2738. currentMenu.insertItem(self.enterAnnotationStype(), at: 3)
  2739. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  2740. if listView.currentSelection.selectionType() == .image{
  2741. currentMenu.insertItem(NSMenuItem.separator(), at: 6)
  2742. currentMenu.insertItem(self.addOutlineStype(), at: 6)
  2743. currentMenu.insertItem(NSMenuItem.separator(), at: 6)
  2744. currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
  2745. }
  2746. if listView.currentSelection.selectionType() == .text {
  2747. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  2748. currentMenu.insertItem(self.setTranslateStype(), at: currentMenu.items.count)
  2749. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  2750. }
  2751. }
  2752. if listView.activeAnnotation != nil || isMoveSelectAnno {
  2753. if let data = self.listView.activeAnnotation?.type?.lowercased(), data == "stamp"{
  2754. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  2755. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  2756. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  2757. }else{
  2758. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  2759. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  2760. if let anno = self.listView.activeAnnotation, anno.isKind(of: CPDFStampAnnotation.self) {
  2761. } else {
  2762. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  2763. currentMenu.insertItem(self.setShareStype(), at: currentMenu.items.count - 15)
  2764. }
  2765. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  2766. }
  2767. }
  2768. if listView.activeAnnotation == nil && listView.currentSelection == nil{
  2769. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  2770. if(listView.toolMode == .selectToolMode) {
  2771. if NSIsEmptyRect(listView.currentSelectionRect()) {
  2772. currentMenu.insertItem(self.zoomSelectionMenuItem(), at: 0)
  2773. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2774. }
  2775. currentMenu.insertItem(self.printingMenu(), at: 0)
  2776. currentMenu.insertItem(self.setTTSStype(), at: 0)
  2777. currentMenu.insertItem(self.setCropStype(), at: 0)
  2778. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  2779. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  2780. export.submenu = self.exportMenu()
  2781. currentMenu.insertItem(export, at: currentMenu.items.count)
  2782. }else{
  2783. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  2784. currentMenu.insertItem(self.setTTSStype(), at: 2)
  2785. currentMenu.insertItem(self.setCropStype(), at: 2)
  2786. currentMenu.insertItem(self.setSnapshotStype(), at: 2)
  2787. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  2788. currentMenu.insertItem(self.addOutlineStype(), at: 2)
  2789. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  2790. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  2791. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  2792. if(currentMenu.items.count > 4) {
  2793. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  2794. }
  2795. if(currentMenu.items.count > 5) {
  2796. currentMenu.insertItem(self.addBookmarkMenu(), at: 6)
  2797. }
  2798. currentMenu.insertItem(self.setAutoScrollStype(), at: currentMenu.items.count)
  2799. }
  2800. currentMenu.insertItem(self.setAnnotationToolStype(), at: 5)
  2801. }
  2802. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  2803. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  2804. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  2805. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  2806. for item in currentMenu.items {
  2807. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  2808. // 显示与隐藏注释 item action 截取
  2809. item.action = #selector(menuItemClick_HidenorShowNote)
  2810. item.target = self
  2811. break
  2812. }
  2813. }
  2814. }
  2815. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  2816. var addRedact = false
  2817. for anno in annotations {
  2818. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  2819. addRedact = true
  2820. } else if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  2821. anno.contents = pdfPage?.string(for: anno.bounds) ?? ""
  2822. }
  2823. }
  2824. self.model.hasAddRedact = addRedact
  2825. if self.listView.toolMode == .moveToolMode {
  2826. self.listView.toolMode = .textToolMode
  2827. self.listView.annotationType = .unkown
  2828. }
  2829. if (self.model.rightMouseEventing) {
  2830. self.model.rightMouseEventing = false
  2831. }
  2832. self.leftSideViewController.refreshUIForAddAnnotation(annos: annotations, page: pdfPage)
  2833. }
  2834. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  2835. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: annotations, page: pdfPage)
  2836. }
  2837. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  2838. if (!self.listView.isEqual(to: pdfListView)) {
  2839. return
  2840. }
  2841. if (self.listView.toolMode != .selectToolMode) {
  2842. return
  2843. }
  2844. }
  2845. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  2846. if(speedy == .right) {
  2847. self.toggleRightPane()
  2848. } else if (speedy == .left) {
  2849. self.menuItemAction_hiddenLeftSide(speedy)
  2850. }
  2851. }
  2852. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  2853. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  2854. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  2855. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  2856. } else {
  2857. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  2858. }
  2859. } else {
  2860. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  2861. }
  2862. }
  2863. func pdfListViewHaveDocumentAttribute() -> Bool {
  2864. if(!self.listView.document.allowsCopying) {
  2865. self.removeOwnerPassword()
  2866. return false
  2867. }
  2868. return true
  2869. }
  2870. func pdfListView(_ sender: CPDFListView!, showSnapshotAtPageNumber pageNum: Int, for rect: NSRect, scaleFactor: CGFloat, autoFits: Bool) {
  2871. let swc = KMSnapshotWindowController(windowNibName: "SnapshotWindow")
  2872. swc.delegate = self
  2873. swc.setPdfDocument(self.listView.document, goToPageNumber: pageNum, rect: rect, scaleFactor: scaleFactor, autoFits: autoFits)
  2874. swc.forceOnTop = self.interactionMode != .normal
  2875. self.myDocument?.addWindowController(swc)
  2876. }
  2877. func pdfListView(_ pdfView: CPDFListView!, documentDataDidChanged docData: Any!, withInfo info: [AnyHashable : Any]!) {
  2878. if let data = info?[CPDFListView.outlineKey] as? Bool, data { // 大纲改变
  2879. guard let ol = docData as? CPDFOutline else {
  2880. return
  2881. }
  2882. let add = info?[CPDFListView.outlineAddKey] as? Bool ?? false
  2883. let remove = info?[CPDFListView.outlineRemoveKey] as? Bool ?? false
  2884. if add {
  2885. self.leftSideViewController.addOutlineAfter(ol)
  2886. }
  2887. if remove {
  2888. self.leftSideViewController.removeOutlineAfter(ol)
  2889. }
  2890. let demote = info?[CPDFListView.outlineDemoteKey] as? Bool ?? false
  2891. let promote = info?[CPDFListView.outlinePromoteKey] as? Bool ?? false
  2892. if demote {
  2893. self.leftSideViewController.demoteOutlineAfter(ol)
  2894. }
  2895. if promote {
  2896. self.leftSideViewController.promoteOutlineAfter(ol)
  2897. }
  2898. }
  2899. }
  2900. //TextEdit
  2901. func pdfListViewDidTextFontChanged(_ pdfListView: CPDFListView!) {
  2902. }
  2903. func pdfListViewDidTextColorChanged(_ pdfListView: CPDFListView!, with color: NSColor!) {
  2904. }
  2905. func pdfListViewAnnotationMeasureInfoChange(_ pdfListView: CPDFListView!, with annotation: CPDFAnnotation!) {
  2906. guard let data = annotation else {
  2907. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2908. distanceMeasureInfoWindowController?.clearData()
  2909. }
  2910. return
  2911. }
  2912. if let lineAnnotation = annotation as? CPDFLineAnnotation {
  2913. handleLineAnnotation(lineAnnotation)
  2914. } else if let polylineAnnotation = annotation as? CPDFPolylineAnnotation {
  2915. handlePolylineAnnotation(polylineAnnotation)
  2916. } else if let polygonAnnotation = annotation as? CPDFPolygonAnnotation {
  2917. handlePolygonAnnotation(polygonAnnotation)
  2918. }
  2919. }
  2920. func pdfListViewMeasureCancel(_ pdfListView: CPDFListView!) {
  2921. cancelMeasureType()
  2922. }
  2923. func tableMenu(_ menu: NSMenu, withTable table: KMTableAnnotation, point: CGPoint) -> NSMenu {
  2924. if table.currentCell.row >= 0 && table.currentCell.column >= 0 {
  2925. let itemTitles = ["Edit", "", "Add Row Above", "Add Row Below", "", "Add Column Before", "Add Column After", "", "Delete Row", "Delete Column", "Delete Table", "Cut", "Copy", "Paste", "Paste and Match Style", "Delete Cell Contents", "Clear All"]
  2926. let actions = ["formAnnotTextEdit:", "", "addRowAbove:", "addRowBelow:", "", "addColumnBefore:", "addColumnAfter:", "", "deleteRow:", "deleteColumn:", "deleteTabel", "cutCell:", "copyCell:", "pasteCell:", "pasteAndMatchStyle:", "deleteCellContents:", "clearAll:"]
  2927. for i in 0..<itemTitles.count {
  2928. var item: NSMenuItem? = nil
  2929. if itemTitles[i] == "" {
  2930. item = NSMenuItem.separator()
  2931. menu.insertItem(item!, at: i)
  2932. } else {
  2933. item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  2934. item!.target = self
  2935. item!.action = NSSelectorFromString(actions[i])
  2936. if itemTitles[i] == "Paste" /*&& !_copyCellData*/ {
  2937. item!.action = nil
  2938. } else if itemTitles[i] == "Paste and Match Style" /*&& !_copyCellData */{
  2939. item!.action = nil
  2940. } else if itemTitles[i] == "Add Row Above" {
  2941. let path1 = table.crossLines[table.rowNumber - table.currentCell.row]
  2942. let path2 = table.crossLines[table.rowNumber - table.currentCell.row - 1]
  2943. if (path1 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.round && table.headerCount() >= 5 {
  2944. item!.action = nil
  2945. } else if (path2 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.bevel && table.footerCount() >= 5 {
  2946. item!.action = nil
  2947. }
  2948. }
  2949. item!.title = NSLocalizedString(item!.title, comment: "")
  2950. item!.representedObject = NSValue(point: point)
  2951. menu.insertItem(item!, at: i)
  2952. }
  2953. }
  2954. } else {
  2955. let itemTitles = ["Cut", "Copy", "Paste", "Delete"]
  2956. let actions = ["cut:", "copy:", "paste:", "delete:"]
  2957. for i in 0..<itemTitles.count {
  2958. let item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  2959. item.target = self
  2960. item.action = NSSelectorFromString(actions[i])
  2961. item.title = NSLocalizedString(item.title, comment: "")
  2962. menu.insertItem(item, at: i)
  2963. item.representedObject = NSValue(point: point)
  2964. }
  2965. }
  2966. return menu
  2967. }
  2968. private func handleLineAnnotation(_ annotation: CPDFLineAnnotation) {
  2969. if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2970. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2971. distanceMeasureInfoWindowController?.showWindow(self)
  2972. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2973. areaMeasureInfoWindowController?.hideFloatingWindow()
  2974. distanceMeasureInfoWindowController?.showWindow(self)
  2975. } else if distanceMeasureInfoWindowController?.window?.isVisible == false {
  2976. distanceMeasureInfoWindowController?.showWindow(self)
  2977. }
  2978. let measureInfo = annotation.measureInfo
  2979. let startPoint = annotation.startPoint
  2980. let endPoint = annotation.endPoint
  2981. let angle = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) * (180.0 / .pi)
  2982. distanceMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  2983. distanceMeasureInfoWindowController?.xLabel.stringValue = String(format: "%.0f", abs(endPoint.x - startPoint.x))
  2984. distanceMeasureInfoWindowController?.yLabel.stringValue = String(format: "%.0f", abs(endPoint.y - startPoint.y))
  2985. distanceMeasureInfoWindowController?.reloadData(with: measureInfo!)
  2986. }
  2987. private func handlePolylineAnnotation(_ annotation: CPDFPolylineAnnotation) {
  2988. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2989. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2990. perimeterMeasureInfoWindowController?.showWindow(self)
  2991. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2992. areaMeasureInfoWindowController?.hideFloatingWindow()
  2993. perimeterMeasureInfoWindowController?.showWindow(self)
  2994. } else if perimeterMeasureInfoWindowController?.window?.isVisible == false {
  2995. perimeterMeasureInfoWindowController?.showWindow(self)
  2996. }
  2997. let measureInfo = annotation.measureInfo
  2998. let savePoints = annotation.savePoints()
  2999. var angle: CGFloat = 0
  3000. if savePoints.count >= 3 {
  3001. let count = savePoints.count
  3002. let startPoint = savePoints[count - 3].pointValue
  3003. let midPoint = savePoints[count - 2].pointValue
  3004. let endPoint = savePoints.last!.pointValue
  3005. angle = angleBetweenPoints(startPoint, midPoint, endPoint)
  3006. }
  3007. angle = 180 - angle
  3008. perimeterMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  3009. perimeterMeasureInfoWindowController?.reloadData(with: measureInfo!)
  3010. }
  3011. private func handlePolygonAnnotation(_ annotation: CPDFPolygonAnnotation) {
  3012. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  3013. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3014. areaMeasureInfoWindowController?.showWindow(self)
  3015. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  3016. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3017. areaMeasureInfoWindowController?.showWindow(self)
  3018. } else if areaMeasureInfoWindowController?.window?.isVisible == false {
  3019. areaMeasureInfoWindowController?.showWindow(self)
  3020. }
  3021. let measureInfo = annotation.measureInfo
  3022. let savePoints = annotation.savePoints
  3023. var angle: CGFloat = 0
  3024. if savePoints.count >= 3 {
  3025. let count = savePoints.count
  3026. let startPoint = (savePoints[count - 3] as AnyObject).pointValue
  3027. let midPoint = (savePoints[count - 2] as AnyObject).pointValue
  3028. let endPoint = (savePoints.lastObject as AnyObject).pointValue
  3029. angle = angleBetweenPoints(startPoint!, midPoint!, endPoint!)
  3030. }
  3031. angle = 180 - angle
  3032. areaMeasureInfoWindowController?.angleLabel.stringValue = String(format: "%.2f°", abs(angle))
  3033. areaMeasureInfoWindowController?.reloadData(measureInfo!)
  3034. }
  3035. private func angleBetweenPoints(_ startPoint: CGPoint, _ midPoint: CGPoint, _ endPoint: CGPoint) -> CGFloat {
  3036. let vector1 = CGPoint(x: midPoint.x - startPoint.x, y: midPoint.y - startPoint.y)
  3037. let vector2 = CGPoint(x: endPoint.x - midPoint.x, y: endPoint.y - midPoint.y)
  3038. let dotProduct = vector1.x * vector2.x + vector1.y * vector2.y
  3039. let magnitude1 = sqrt(vector1.x * vector1.x + vector1.y * vector1.y)
  3040. let magnitude2 = sqrt(vector2.x * vector2.x + vector2.y * vector2.y)
  3041. return acos(dotProduct / (magnitude1 * magnitude2)) * (180.0 / .pi)
  3042. }
  3043. @objc func pdfUpdatedFinish() {
  3044. splitPDFController?.inPDFFirst = false
  3045. splitPDFController?.outPDFFirst = false
  3046. }
  3047. }
  3048. //MARK: - KMNThumbnailBaseViewDelegate
  3049. extension KMMainViewController: KMNThumbnailBaseViewDelegate {
  3050. func clickThumbnailViewControlle(pageEditVC:KMNThumbnailBaseViewController?,currentIndex:Int) {
  3051. exitPageEditMode()
  3052. viewManager.isPageEditMode = false
  3053. pdfToolbarController?.reloadPageEditView()
  3054. }
  3055. func insertPDFThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, pdfDocment: CPDFDocument?) {
  3056. if(pdfDocment != nil) {
  3057. insertDocuments.insert(pdfDocment!)
  3058. }
  3059. }
  3060. func changeIndexPathsThumbnailViewControlle(pageEditVC: KMNThumbnailBaseViewController?, selectionIndexPaths: Set<IndexPath>, selectionStrings: String) {
  3061. toolbarManager.page_pageInfo_Property.text = selectionStrings
  3062. if(toolbarManager.page_pageInfo_Property.creatable == false) {
  3063. toolbarManager.page_pageInfo_Property.creatable = true
  3064. }
  3065. pdfToolbarController?.refreshSecondToolbarItemsState()
  3066. }
  3067. }
  3068. extension KMMainViewController: KMNLeftSideViewControllerDelegate {
  3069. func enterPageEditLeftSideViewController(leftSideViewController: KMNLeftSideViewController) {
  3070. if viewManager.isPageEditMode == false {
  3071. viewManager.isPageEditMode = true
  3072. if(pdfToolbarController != nil) {
  3073. kmPDFToolbarControllerDidToolbarItemClicked(pdfToolbarController!, KMPDFToolbar_PageEdit_Identifier)
  3074. pdfToolbarController?.reloadSecondToolbar()
  3075. }
  3076. }
  3077. }
  3078. func changeSelectePageLeftSideViewController(leftSideViewController: KMNLeftSideViewController, pageIndex: Int) {
  3079. if(listView.currentPageIndex != pageIndex) {
  3080. listView.go(toPageIndex: pageIndex, animated: true)
  3081. }
  3082. }
  3083. func addBookmarkForLeftC(controller: KMNLeftSideViewController, bookmark: CPDFBookmark?, info: [String : Any]?) {
  3084. if let result = info?["result"] as? Bool {
  3085. if result == false {
  3086. let message = KMNCustomAlertView.alertView(message: KMLocalizedString("This page has been bookmarked"), type: .normal_custom, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
  3087. }
  3088. }
  3089. }
  3090. func switchSearchPopWindow(controller: KMNLeftSideViewController) {
  3091. closeLeftPane()
  3092. let handdler = controller.searchViewC.handdler
  3093. showSearchPopWindow(type: handdler.type, keyborad: handdler.searchKey, replaceText: handdler.replaceKey, results: handdler.searchResults)
  3094. }
  3095. }
  3096. //MARK: -
  3097. //MARK: -
  3098. //MARK: -
  3099. //MARK: - 旧代码,需要用到的内容需要拖出来,写好注释
  3100. extension KMMainViewController {
  3101. func awakeFromNibFunction() {
  3102. self.addBackgroundMaskView()
  3103. listView.delegate = self
  3104. listView.pdfListViewDelegate = self
  3105. if (document != nil) {
  3106. self.listView.document = self.document
  3107. self.listView.document?.delegate = self
  3108. let autoScale = listView.autoScales
  3109. if !autoScale {
  3110. listView.scaleFactor = 1.0
  3111. }
  3112. }
  3113. self.initPDFLeftViewVC()
  3114. self.leftSideViewController.mainViewController = self
  3115. }
  3116. func viewDidAppearFunction() {
  3117. //春季活动
  3118. if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
  3119. if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
  3120. let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
  3121. if KMAdvertisementManager.checkAdvertisementValid(info!) {
  3122. self.loadRecommondPopWindow()
  3123. }
  3124. }
  3125. }
  3126. self.addEventMonitor()
  3127. self.view.window?.makeFirstResponder(self.listView)
  3128. // 更新属性页面的信息
  3129. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  3130. self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
  3131. if (self.document == nil) {
  3132. return
  3133. }
  3134. if (self.document == nil || self.document!.isLocked == false) {
  3135. self.loadFunctionGuide()
  3136. }
  3137. if (self.document?.isLocked == false) {
  3138. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  3139. self.showConvertNotesProgress()
  3140. }
  3141. return
  3142. }
  3143. if (self.view.window == nil) {
  3144. return
  3145. }
  3146. if (self.model.password != nil) {
  3147. if let data = self.listView.document?.unlock(withPassword: self.model.password), data {
  3148. self.model.isSaveKeyChain = false
  3149. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  3150. self.showConvertNotesProgress()
  3151. }
  3152. return
  3153. }
  3154. }
  3155. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  3156. if self.view.window != nil && self.tabViewIsDragging() == false {
  3157. self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [weak self] result , password in
  3158. if (result == .cancel) {
  3159. (self?.myDocument as? KMMainDocument)?.browser?.closeTab()
  3160. return
  3161. }
  3162. self?.model.isSaveKeyChain = true
  3163. self?.listView.document = self?.document
  3164. self?.document?.unlock(withPassword: password)
  3165. }
  3166. } else {
  3167. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  3168. self.showConvertNotesProgress()
  3169. }
  3170. }
  3171. }
  3172. }
  3173. func viewWillDisappearFunction() {
  3174. if self.interactionMode != .presentation {
  3175. self.removeEventMonitor()
  3176. }
  3177. }
  3178. func viewWillLayoutFunction() {
  3179. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  3180. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  3181. } else {
  3182. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  3183. }
  3184. if let guideWC = self.guideInfoWindowController{
  3185. var rect = self.view.window!.frame
  3186. rect.size.height -= 20
  3187. guideWC.window?.setFrame(rect, display: false)
  3188. guideWC.window?.minSize = rect.size
  3189. guideWC.window?.maxSize = rect.size
  3190. guideWC.show()
  3191. }
  3192. }
  3193. func viewDidLoadOld() {
  3194. mwcFlags.settingUpWindow = 1
  3195. self.initToolbar()
  3196. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  3197. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  3198. UserDefaults.standard.synchronize()
  3199. }
  3200. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  3201. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  3202. UserDefaults.standard.synchronize()
  3203. }
  3204. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  3205. if (self.listView.document != nil) {
  3206. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document?.documentURL.path ?? "")
  3207. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document?.documentURL.path ?? "")
  3208. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < (self.listView.document?.pageCount ?? 0)) {
  3209. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  3210. if (pageScale != nil) {
  3211. self.listView.scaleFactor = CGFloat(pageScale!)
  3212. }
  3213. self.listView.go(toPageIndex: pageNumber!, animated: false)
  3214. }
  3215. } else {
  3216. self._goToFirstPageForFristAppear()
  3217. }
  3218. }
  3219. } else {
  3220. self._goToFirstPageForFristAppear()
  3221. }
  3222. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  3223. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  3224. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  3225. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  3226. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  3227. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  3228. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  3229. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  3230. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  3231. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
  3232. NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
  3233. NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
  3234. NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
  3235. NotificationCenter.default.addObserver(self, selector: #selector(didRemoveAnnotationNotification), name: NSNotification.Name.CPDFPageDidRemoveAnnotation, object: nil)
  3236. Task {
  3237. self.addAutoSaveEvent()
  3238. }
  3239. self.toggleCloseRightSide()
  3240. self.addKeyEventMonitor()
  3241. self.addAdsBannerView()
  3242. var snapshotSetups: NSArray?
  3243. if KMPreferenceManager.shared.rememberSnapshot {
  3244. if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
  3245. snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
  3246. }
  3247. }
  3248. if let cnt = snapshotSetups?.count, cnt > 0 {
  3249. if let data = self.listView.document?.isLocked, data {
  3250. self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
  3251. } else {
  3252. self.showSnapshots(setups: snapshotSetups)
  3253. }
  3254. }
  3255. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  3256. if readModel == true {
  3257. self.openPDFReadMode()
  3258. }
  3259. let hasWindowSetup = savedNormalSetup.count > 0
  3260. if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
  3261. let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
  3262. self.applyPDFSettings(pdfSettings)
  3263. } else {
  3264. self.applyPDFSettings(savedNormalSetup)
  3265. }
  3266. //文字
  3267. let fontManager = NSFontManager.shared
  3268. fontManager.target = self
  3269. fontManager.action = #selector(changeFont(_:))
  3270. }
  3271. //MARK: - PDFListView
  3272. func initPDFLeftViewVC() {
  3273. var frame = self.leftView.frame
  3274. frame.size.width += 44
  3275. self.leftView.frame = frame
  3276. leftSideViewController.isFirst = true
  3277. leftSideViewController.listView = self.listView
  3278. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  3279. leftSideViewController.view.autoresizingMask = [.height,.width]
  3280. leftSideViewController.delegate = self
  3281. self.leftView.addSubview(leftSideViewController.view)
  3282. }
  3283. func addAdsBannerView() {
  3284. #if VERSION_FREE
  3285. if !IAPProductsManager.default().isAvailableAllFunction(){
  3286. guard let document = self.listView.document else {
  3287. return
  3288. }
  3289. if !document.isLocked {
  3290. }
  3291. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  3292. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  3293. }
  3294. #endif
  3295. }
  3296. // MARK: Private Methods
  3297. private func _isArabicLanguage() -> Bool {
  3298. return NSLocalizedString("Right click a color and select “Change Color...“.", comment: "") == "انقر بزر الماوس الأيمن فوق اللون وحدد \"تغيير اللون...\"."
  3299. }
  3300. internal func removeNotifications() {
  3301. NotificationCenter.default.removeObserver(self)
  3302. self.leftSideViewController.clearAnnotationFilterData()
  3303. self.leftSideViewController.clearNotification()
  3304. }
  3305. func checkShouldAutoOpenLeftVC() {
  3306. if KMPreference.shared.showLeftSideBar == false {
  3307. return
  3308. }
  3309. if self.model.leftPanelOpen {
  3310. return
  3311. }
  3312. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  3313. if readModel == true {
  3314. return
  3315. }
  3316. DispatchQueue.main.async {
  3317. self.leftSideViewController.showThumbnail()
  3318. }
  3319. }
  3320. func removeAllAnnotations() {
  3321. let alert = NSAlert()
  3322. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  3323. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  3324. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  3325. if (alert.runModal() != .alertFirstButtonReturn) {
  3326. return
  3327. }
  3328. DispatchQueue.main.async {
  3329. self.removeAllAnnotationsStore.store(t: self.listView)
  3330. }
  3331. }
  3332. @objc func cancelMeasureType() {
  3333. self.hideMeasureFloatingWindows()
  3334. }
  3335. func hideMeasureFloatingWindows() {
  3336. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  3337. distanceMeasureInfoWindowController?.hideFloatingWindow()
  3338. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  3339. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  3340. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  3341. areaMeasureInfoWindowController?.hideFloatingWindow()
  3342. }
  3343. }
  3344. func showMeasureFloatingWindowsIfNeed() {
  3345. let toolMode = self.listView.toolMode
  3346. if toolMode != .measureToolMode {
  3347. return
  3348. }
  3349. let type = self.listView.annotationType
  3350. if type == .line {
  3351. self.distanceMeasureInfoWindowController?.window?.orderFront(nil)
  3352. } else if type == .polyLine {
  3353. self.perimeterMeasureInfoWindowController?.window?.orderFront(nil)
  3354. } else if type == .polyGon {
  3355. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  3356. } else if type == .square {
  3357. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  3358. }
  3359. }
  3360. // MARK: - 标记密文
  3361. func enterRedact() {
  3362. if !IAPProductsManager.default().isAvailableAllFunction(){
  3363. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3364. winC?.kEventName = "Reading_Redact_BuyNow"
  3365. winC?.showWindow(nil)
  3366. return
  3367. }
  3368. if self.listView.document?.allowsPrinting == false || self.listView.document?.allowsCopying == false {
  3369. Task {
  3370. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted."))
  3371. }
  3372. return
  3373. }
  3374. if self.hasEnterRedact() {
  3375. self.exitRedact()
  3376. return
  3377. }
  3378. self.leftSideViewController.thumbnailTableView.isEnabled = false
  3379. self.leftSideViewController.tocOutlineView.isEnabled = false
  3380. self.leftSideViewController.noteOutlineView.isEnabled = false
  3381. self.leftSideViewController.findTableView.isEnabled = false
  3382. self.leftSideViewController.groupedFindTableView.isEnabled = false
  3383. self.leftSideViewController.snapshotTableView.isEnabled = false
  3384. let ttsWindowC = KMTTSWindowController.share
  3385. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  3386. if let data = ttsWindowC.window?.isVisible, data {
  3387. ttsWindowC.stopSpeaking()
  3388. ttsWindowC.close()
  3389. }
  3390. }
  3391. NSColorPanel.shared.showsAlpha = false
  3392. redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document?.password)
  3393. self.addChild(redactController)
  3394. redactController.view.autoresizingMask = [.width, .height]
  3395. self.listView.isHidden = true
  3396. redactController.scaleFactor = self.listView.scaleFactor
  3397. redactController.titleBack = { [weak self] title in
  3398. self?.view.window?.title = title
  3399. }
  3400. redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
  3401. self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
  3402. if result == false { // 退出
  3403. self?.exitRedact()
  3404. return
  3405. }
  3406. let controller = self?._getPDFRedactController()
  3407. controller?.redactPdfView.newAddAnnotation.removeAll()
  3408. self?.exitRedact()
  3409. if saveResult {
  3410. let newDocument = CPDFDocument(url: saveUrl)
  3411. if let data = newDocument?.isLocked, data {
  3412. newDocument?.unlock(withPassword: self?.listView.document?.password ?? "")
  3413. }
  3414. self?.document = newDocument
  3415. self?.listView.document = newDocument
  3416. self?.listView.layoutDocumentView()
  3417. }
  3418. }
  3419. redactController.setCurrentPageIndex(self.listView.currentPageIndex)
  3420. }
  3421. func exitRedact() {
  3422. self.leftSideViewController.thumbnailTableView.isEnabled = true
  3423. self.leftSideViewController.tocOutlineView.isEnabled = true
  3424. self.leftSideViewController.noteOutlineView.isEnabled = true
  3425. self.leftSideViewController.findTableView.isEnabled = true
  3426. self.leftSideViewController.groupedFindTableView.isEnabled = true
  3427. self.leftSideViewController.snapshotTableView.isEnabled = true
  3428. let controller = self._getPDFRedactController()
  3429. if let data = controller {
  3430. if data.redactPdfView.newAddAnnotation.count > 0 {
  3431. KMAlertTool.runModel(message: "", informative: KMLocalizedString("There are unapplied redactions in this file. Exit will not save redaction."), buttons: [KMLocalizedString("Exit"), KMLocalizedString("Cancel")]) { response in
  3432. if response == .alertFirstButtonReturn {
  3433. controller?.redactPdfView.newAddAnnotation.removeAll()
  3434. self.exitRedact()
  3435. }
  3436. }
  3437. return
  3438. }
  3439. }
  3440. NSColorPanel.shared.showsAlpha = true
  3441. controller?.redactPdfView.resignMonitor()
  3442. controller?.view.removeFromSuperview()
  3443. controller?.removeFromParent()
  3444. self.listView.isHidden = false
  3445. self.listView.annotationType = .unkown
  3446. }
  3447. func hasEnterRedact() -> Bool {
  3448. return self._getPDFRedactController() != nil
  3449. }
  3450. //MARK: - AI
  3451. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  3452. if (self.document != nil) {
  3453. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  3454. } else {
  3455. AIChatInfoManager.defaultManager.currentFilePath = ""
  3456. }
  3457. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  3458. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  3459. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  3460. let documentArray = NSDocumentController.shared.documents
  3461. var didFileEdit: Bool = false
  3462. var curDoc: KMMainDocument!
  3463. for document in documentArray {
  3464. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  3465. didFileEdit = document.isDocumentEdited
  3466. curDoc = document as! KMMainDocument
  3467. break
  3468. }
  3469. }
  3470. if didFileEdit {
  3471. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  3472. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  3473. do {
  3474. try FileManager.default.removeItem(at: tempFileURL)
  3475. } catch {
  3476. }
  3477. }
  3478. if curDoc != nil {
  3479. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  3480. }
  3481. }
  3482. windowVC.window?.becomeMain()
  3483. }
  3484. }
  3485. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  3486. } else {
  3487. var windowRect = windowVC.window?.frame
  3488. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  3489. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  3490. windowVC.window?.setFrame(windowRect!, display: true)
  3491. windowVC.didSetOriginFrame = true
  3492. }
  3493. windowVC.eventLabel = "AITools_Tbr"
  3494. windowVC.showWindow(nil)
  3495. if (aiConfigType != .none) {
  3496. windowVC.eventLabel = "AITools_Start"
  3497. if self.listView.currentSelection?.string()?.isEmpty == false {
  3498. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  3499. }
  3500. windowVC.chooseAIFunctionWithType(aiConfigType)
  3501. }
  3502. }
  3503. @objc func aiTipIconViewShowStateChangeNoti() {
  3504. }
  3505. //MARK: - 引导
  3506. func loadFunctionGuide() -> Void {
  3507. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  3508. if self.view.window != nil {
  3509. self.loadOpenFileFunctionGuide(.openFileNormal)
  3510. }
  3511. }
  3512. }
  3513. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  3514. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  3515. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  3516. guard let guideWC = self.guideInfoWindowController else { return }
  3517. guideWC.type = .openFileNormal
  3518. // guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  3519. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  3520. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  3521. }
  3522. guideWC.finishHandle = { [weak self] windowVC, type in
  3523. if type == .windowNewFinish ||
  3524. type == . windowDigitalFinish {
  3525. self?.checkFirstTrialController()
  3526. }
  3527. }
  3528. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  3529. self?.checkFirstTrialController()
  3530. }
  3531. var rect = self.view.window!.frame
  3532. rect.size.height -= 20
  3533. guideWC.window?.setFrame(rect, display: false)
  3534. guideWC.window?.minSize = rect.size
  3535. guideWC.window?.maxSize = rect.size
  3536. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  3537. guideWC.show()
  3538. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  3539. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  3540. guard let guideWC = self.guideInfoWindowController else { return }
  3541. guideWC.type = .digitalSignGuide
  3542. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  3543. guideWC.finishHandle = { [weak self] windowVC, type in
  3544. self?.checkFirstTrialController()
  3545. }
  3546. var rect = self.view.window!.frame
  3547. rect.size.height -= 20
  3548. guideWC.window?.setFrame(rect, display: false)
  3549. guideWC.window?.minSize = rect.size
  3550. guideWC.window?.maxSize = rect.size
  3551. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  3552. guideWC.show()
  3553. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  3554. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  3555. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  3556. guard let guideWC = self.guideInfoWindowController else { return }
  3557. guideWC.type = .pdfCompareGuide
  3558. guard let win = self.view.window else {
  3559. return
  3560. }
  3561. guideWC.finishHandle = { [weak self] winC, type in
  3562. if type == .windowNewFinish {
  3563. DispatchQueue.main.async {
  3564. self?.loadOpenFileFunctionGuide(.measureGuide)
  3565. }
  3566. return
  3567. }
  3568. }
  3569. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  3570. var rect = self.view.window!.frame
  3571. rect.size.height -= 20
  3572. guideWC.window?.setFrame(rect, display: false)
  3573. guideWC.window?.minSize = rect.size
  3574. guideWC.window?.maxSize = rect.size
  3575. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  3576. guideWC.show()
  3577. }
  3578. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  3579. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  3580. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  3581. guard let guideWC = self.guideInfoWindowController else { return }
  3582. guard let _ = self.view.window else {
  3583. return
  3584. }
  3585. guideWC.type = .measureGuide
  3586. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  3587. var rect = self.view.window?.frame ?? .zero
  3588. rect.size.height -= 20
  3589. guideWC.window?.setFrame(rect, display: false)
  3590. guideWC.window?.minSize = rect.size
  3591. guideWC.window?.maxSize = rect.size
  3592. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  3593. guideWC.show()
  3594. }
  3595. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  3596. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  3597. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  3598. guard let guideWC = self.guideInfoWindowController else { return }
  3599. guideWC.type = .convertGuide
  3600. guard let win = self.view.window else {
  3601. return
  3602. }
  3603. guideWC.purchaseHandle = { [weak self] windowVC in
  3604. #if VERSION_DMG
  3605. if IAPProductsManager.default().isAvailableAllFunction() {
  3606. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  3607. //Convert:
  3608. self?.showAllConvertWindow(convertT: .Word)
  3609. } else {
  3610. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  3611. limitWC.continueBlock = { windowController in
  3612. }
  3613. limitWC.window?.center()
  3614. limitWC.showWindow(nil)
  3615. }
  3616. } else {
  3617. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3618. }
  3619. #else
  3620. if IAPProductsManager.default().isAvailableAllFunction() {
  3621. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  3622. //Convert:
  3623. } else {
  3624. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  3625. vc.showWindow(nil)
  3626. }
  3627. } else {
  3628. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3629. }
  3630. #endif
  3631. }
  3632. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  3633. var rect = self.view.window?.frame ?? .zero
  3634. rect.size.height -= 20
  3635. guideWC.window?.setFrame(rect, display: false)
  3636. guideWC.window?.minSize = rect.size
  3637. guideWC.window?.maxSize = rect.size
  3638. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  3639. guideWC.show()
  3640. }
  3641. } else {
  3642. }
  3643. }
  3644. func checkFirstTrialController() -> Void {
  3645. #if VERSION_DMG
  3646. //打开文档后引导相关
  3647. if VerificationManager.default().status == .none {
  3648. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  3649. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  3650. if lastVersion.isEmpty || lastVersion != appVersion {
  3651. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  3652. UserDefaults.standard.synchronize()
  3653. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3654. }
  3655. }
  3656. #endif
  3657. }
  3658. // MARK: - 页面编辑
  3659. open func enterPageEdit(_ pages: [Int] = []) {
  3660. if let doc = self.listView.document {
  3661. if doc.allowsCopying == false || doc.allowsPrinting == false {
  3662. KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
  3663. if result && pwd.isEmpty == false {
  3664. self.listView.document?.unlock(withPassword: pwd)
  3665. Task { @MainActor in
  3666. self.enterPageEdit(pages)
  3667. }
  3668. } else {
  3669. self.exitPageEdit()
  3670. }
  3671. }
  3672. return
  3673. }
  3674. }
  3675. //选中page
  3676. var tPages = pages
  3677. if tPages.count == 0 {
  3678. if self.leftSideViewController.type.methodType == .Thumbnail {
  3679. tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
  3680. }
  3681. }
  3682. if (hasEnterPageEdit()) {
  3683. exitPageEdit()
  3684. return
  3685. }
  3686. let controller = KMPDFEditViewController(self.listView.document)
  3687. controller.selectedPages = tPages
  3688. controller.listView = self.listView
  3689. self.addChild(controller)
  3690. controller.view.autoresizingMask = [.width,.height]
  3691. self.listView.isHidden = true
  3692. controller.itemClick = { [weak self] index, params in
  3693. if (index == 1) { /// 双击退出
  3694. self?.enterEditMode(self!.leftSideViewController, [])
  3695. DispatchQueue.main.async {
  3696. let pageIndex: Int = params.first as! Int
  3697. self?.listView.go(toPageIndex: pageIndex, animated: true)
  3698. }
  3699. } else if (index == 2) { // 打印
  3700. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  3701. }
  3702. }
  3703. controller.documentEditedCallback = { [weak self] params in
  3704. self?.recordIsPDFDocumentEdited()
  3705. }
  3706. controller.selectionDidChange = { selectedIndexs in
  3707. var indexSet = IndexSet()
  3708. for indexPath in selectedIndexs {
  3709. indexSet.insert(indexPath.item)
  3710. }
  3711. if indexSet.count != 0 {
  3712. }
  3713. }
  3714. }
  3715. open func exitPageEdit() {
  3716. let editController = getPDFEditController()
  3717. if (editController == nil) {
  3718. return
  3719. }
  3720. self.listView.annotationType = .highlight
  3721. // FIXME: - sdk修复插入特定文档crash后,这行代码可以去掉
  3722. self.leftSideViewController.model.insertedDocumentSet.formUnion(editController?.model.insertedDocumentSet ?? [])
  3723. editController?.view.removeFromSuperview()
  3724. editController?.removeFromParent()
  3725. self.listView.isHidden = false
  3726. self.listView.layoutDocumentView()
  3727. self.view.window?.makeFirstResponder(self.listView)
  3728. self.listView.annotationType = .unkown
  3729. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  3730. if let data = editController?.isEdited, data {
  3731. self.leftSideViewController.reloadThumbnailDataIfNeed()
  3732. self.leftSideViewController.note_reloadDataIfNeed()
  3733. self.leftSideViewController.refreshUIOfOutlineIfNeed()
  3734. self.leftSideViewController.refreshUIOfSeachListIfNeed()
  3735. self.leftSideViewController.refreshUIOfBookmarkIfNeed()
  3736. }
  3737. }
  3738. open func hasEnterPageEdit() -> Bool {
  3739. return self.getPDFEditController() != nil
  3740. }
  3741. // MARK: - 数字签名
  3742. func hasShowDigitalSign() -> Bool {
  3743. return self.digitalSignController?.view.superview != nil
  3744. }
  3745. func canEnterDigitalSign() -> Bool {
  3746. guard let doc = self.listView.document else {
  3747. return false
  3748. }
  3749. return doc.allowsPrinting && doc.allowsCopying
  3750. }
  3751. func enterDigitalSign() {
  3752. self.listView.toolMode = .textToolMode
  3753. if self.hasShowDigitalSign() {
  3754. self.exitDigitalSign()
  3755. } else {
  3756. if self.needSaveDocument() {
  3757. self.saveDocumentWithProgressAlert { [unowned self] params in
  3758. if (self.listView.document != nil) {
  3759. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  3760. }
  3761. }
  3762. return
  3763. }
  3764. if (self.listView.document != nil) {
  3765. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  3766. }
  3767. }
  3768. }
  3769. func exitDigitalSign() {
  3770. self.digitalSignController?.view.removeFromSuperview()
  3771. // KMDocumentDigitalSignToolbarItemIdentifier
  3772. }
  3773. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  3774. if !IAPProductsManager.default().isAvailableAllFunction(){
  3775. let winC = KMPurchaseCompareWindowController.sharedInstance()
  3776. winC?.kEventName = "Reading_DigitalSign_BuyNow"
  3777. winC?.showWindow(nil)
  3778. return
  3779. }
  3780. if hasShowDigitalSign() {
  3781. self.exitDigitalSign()
  3782. }
  3783. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  3784. var password: String = ""
  3785. password = listView.document?.password ?? ""
  3786. digitalSignController = KMPDFDigitalSignViewController()
  3787. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  3788. digitalSignController?.url = listView.document?.documentURL
  3789. digitalSignController?.password = password
  3790. digitalSignController?.scaleFactor = listView.scaleFactor
  3791. digitalSignController?.titleChangeBlock = { title, index in
  3792. currentPageIndex = UInt(index)
  3793. }
  3794. digitalSignController?.buttonActionBlock = { [weak self] type, isChanged in
  3795. if type == .cancel {
  3796. if let page = self?.listView.document?.page(at: currentPageIndex) {
  3797. self?.listView.go(to: page)
  3798. }
  3799. self?.exitDigitalSign()
  3800. }
  3801. }
  3802. }
  3803. // MARK: - Toolbar
  3804. func toolbarItemClickForExitMode(_ toolbarItem: KMToolbarItemView) {
  3805. if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
  3806. if (hasEnterPageEdit()) {
  3807. self.exitPageEdit()
  3808. }
  3809. }
  3810. if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
  3811. if self.hasEnterRedact() {
  3812. self.exitRedact()
  3813. }
  3814. }
  3815. if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3816. if self.hasShowDigitalSign() {
  3817. self.exitDigitalSign()
  3818. }
  3819. }
  3820. if toolbarItem.itemIdentifier != KMDocumentEditToolbarItemIdentifier && toolbarItem.itemIdentifier != KMRightControlToolbarItemIdentifier && toolbarItem.itemIdentifier != KMLeftControlToolbarItemIdentifier {
  3821. }
  3822. }
  3823. // MARK: - Private Methods
  3824. private func getPDFEditController() -> KMPDFEditViewController? {
  3825. var editController: KMPDFEditViewController?
  3826. for controller in self.children {
  3827. if (controller.isKind(of: KMPDFEditViewController.self)) {
  3828. editController = (controller as! KMPDFEditViewController)
  3829. break
  3830. }
  3831. }
  3832. return editController
  3833. }
  3834. private func _getPDFRedactController() -> KMPDFRedactViewController? {
  3835. var controller: KMPDFRedactViewController?
  3836. for childC in self.children {
  3837. if (childC.isKind(of: KMPDFRedactViewController.self)) {
  3838. controller = (childC as! KMPDFRedactViewController)
  3839. break
  3840. }
  3841. }
  3842. return controller
  3843. }
  3844. private func addBackgroundMaskView() {
  3845. self.removeBackgroundMaskView()
  3846. }
  3847. private func removeBackgroundMaskView() {
  3848. }
  3849. private func _goToFirstPageForFristAppear() {
  3850. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  3851. self.listView.go(toPageIndex: 0, animated: false)
  3852. }
  3853. }
  3854. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  3855. let url = URL(fileURLWithPath: filePath)
  3856. guard let document = PDFDocument(url: url) else {
  3857. return false
  3858. }
  3859. let pageCount = document.pageCount
  3860. return pageCount > 30
  3861. }
  3862. // MARK: - Redact 【标记密文】
  3863. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  3864. let windowController = KMRedactConfirmWindowController(type)
  3865. self.currentWindowController = windowController
  3866. self.view.window?.beginSheet(windowController.window!)
  3867. windowController.itemClick = { [weak self] index in
  3868. if (index == 2) { /// 取消
  3869. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3870. self?.currentWindowController = nil
  3871. callback()
  3872. return
  3873. }
  3874. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3875. self?.currentWindowController = nil
  3876. let panel = NSSavePanel()
  3877. panel.nameFieldStringValue = "[新文件]"+((self?.listView.document?.documentURL.lastPathComponent) ?? "")
  3878. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  3879. button.state = .on
  3880. panel.accessoryView = button
  3881. panel.isExtensionHidden = true
  3882. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  3883. if response != .OK {
  3884. callback()
  3885. return
  3886. }
  3887. if (type == .redactOne) {
  3888. let anno = self!.listView.activeAnnotation
  3889. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  3890. callback()
  3891. return
  3892. }
  3893. (anno as! CPDFRedactAnnotation).applyRedaction()
  3894. } else if (type == .redactAll) {
  3895. self?.listView.document?.applyRedactions()
  3896. } else if (type == .eraserOne) {
  3897. let anno = self!.listView.activeAnnotation
  3898. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  3899. callback()
  3900. return
  3901. }
  3902. anno?.page.erasureRedact(from: anno!.bounds)
  3903. } else if (type == .eraserAll) {
  3904. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  3905. if (result == false) {
  3906. callback()
  3907. return
  3908. }
  3909. }
  3910. }
  3911. self!.listView.document?.write(to: panel.url)
  3912. if (button.state == .on) {
  3913. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  3914. }
  3915. } else {
  3916. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  3917. }
  3918. callback()
  3919. }
  3920. }
  3921. }
  3922. // MARK: - Secure 【安全】
  3923. public func showSecureLimitTip() {
  3924. self.hiddenSecureLimitTip()
  3925. if self.secureAlertView == nil {
  3926. self.secureAlertView = KMSecureAlertView()
  3927. self.secureAlertView?.show(in: self.listView)
  3928. self.secureAlertView?.closeAction = { [unowned self] view in
  3929. self.hiddenSecureLimitTip()
  3930. self.removeFromAlertView()
  3931. self.showFormAlertView()
  3932. }
  3933. self.secureAlertView?.passwordAction = { [unowned self] view in
  3934. self.removeOwnerPassword()
  3935. self.removeFromAlertView()
  3936. self.showFormAlertView()
  3937. }
  3938. }
  3939. }
  3940. func removeOwnerPassword() {
  3941. guard let doc = self.listView.document else {
  3942. NSSound.beep()
  3943. return
  3944. }
  3945. if doc.allowsCopying && doc.allowsPrinting {
  3946. NSSound.beep()
  3947. return
  3948. }
  3949. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  3950. if result == .cancel { /// 关闭
  3951. return
  3952. }
  3953. /// 解密成功
  3954. self?.hiddenSecureLimitTip()
  3955. self?.model.isSaveKeyChain = false
  3956. self?.listView.document?.unlock(withPassword: password)
  3957. }
  3958. }
  3959. public func hiddenSecureLimitTip() {
  3960. self.secureAlertView?.removeFromSuperview()
  3961. self.secureAlertView = nil
  3962. }
  3963. //MARK: - Form
  3964. func showFormAlertView() {
  3965. if (formAlertView == nil) {
  3966. formAlertView = KMFormAlertView()
  3967. formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
  3968. formAlertView?.showInView(self.listView)
  3969. } else {
  3970. self.removeFromAlertView()
  3971. }
  3972. }
  3973. func removeFromAlertView() {
  3974. formAlertView?.removeFromSuperview()
  3975. formAlertView = nil
  3976. }
  3977. override func mouseMoved(with event: NSEvent) {
  3978. self.view.window?.mouseMoved(with: event)
  3979. }
  3980. func savePageNumberIfNeed() {
  3981. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  3982. let scaleFactor = self.listView.scaleFactor ?? 0
  3983. if scaleFactor <= 0 {
  3984. return
  3985. }
  3986. if self.listView.document != nil {
  3987. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  3988. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  3989. }
  3990. }
  3991. }
  3992. // MARK: - 显示合并窗口
  3993. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  3994. DispatchQueue.main.async {
  3995. var documentURL = url
  3996. if documentURL == nil {
  3997. documentURL = self.listView.document?.documentURL
  3998. }
  3999. guard let _url = documentURL else { return }
  4000. guard let document = PDFDocument(url: _url) else { return }
  4001. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  4002. self.mergeWindowController!.oriDucumentUrl = self.listView.document?.documentURL
  4003. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  4004. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  4005. self.view.window?.endSheet(mergeWindowController!.window!)
  4006. }
  4007. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  4008. self.view.window?.endSheet(mergeWindowController!.window!)
  4009. }
  4010. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  4011. }
  4012. }
  4013. // MARK: - 显示加密弹窗
  4014. public func showSecureWindow(_ url: URL) {
  4015. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  4016. guard let securityWindowController = securityWindowController else { return }
  4017. securityWindowController.documentURL = self.listView.document?.documentURL
  4018. securityWindowController.batchAction = { [unowned self] controller, files in
  4019. self.view.window?.endSheet((securityWindowController.window)!)
  4020. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4021. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  4022. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  4023. batchWindowController.window?.makeKeyAndOrderFront("")
  4024. }
  4025. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  4026. let openPanel = NSOpenPanel()
  4027. openPanel.canChooseFiles = false
  4028. openPanel.canChooseDirectories = true
  4029. openPanel.canCreateDirectories = true
  4030. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  4031. if result == NSApplication.ModalResponse.OK {
  4032. for fileURL in openPanel.urls {
  4033. let document = CPDFDocument(url: self.document?.documentURL)
  4034. if document != nil {
  4035. document!.setDocumentAttributes(attribute)
  4036. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  4037. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  4038. if success {
  4039. self.view.window?.endSheet((securityWindowController.window)!)
  4040. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  4041. }
  4042. }
  4043. }
  4044. }
  4045. }
  4046. }
  4047. securityWindowController.cancelAction = { [unowned self] controller in
  4048. self.view.window?.endSheet((securityWindowController.window)!)
  4049. }
  4050. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  4051. }
  4052. // MARK: - 保存文档
  4053. internal func needSaveDocument() -> Bool {
  4054. if (self.isPDFDocumentEdited) {
  4055. return self.isPDFDocumentEdited
  4056. }
  4057. if (self.needSave) {
  4058. return self.needSave
  4059. }
  4060. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  4061. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  4062. return false
  4063. }
  4064. return true
  4065. }
  4066. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  4067. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  4068. if (overlook) {
  4069. document?.save(nil)
  4070. return
  4071. }
  4072. if (self.isPDFDocumentEdited) {
  4073. self.clearIsPDFDocumentEdited()
  4074. self.needSave = false
  4075. document?.save(nil)
  4076. return
  4077. }
  4078. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  4079. return
  4080. }
  4081. document?.save(nil)
  4082. }
  4083. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  4084. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  4085. if (overlook) {
  4086. DispatchQueue.main.async {
  4087. document?.save(nil)
  4088. callback()
  4089. }
  4090. return
  4091. }
  4092. if (self.isPDFDocumentEdited) {
  4093. self.clearIsPDFDocumentEdited()
  4094. self.needSave = false
  4095. DispatchQueue.main.async {
  4096. document?.save(nil)
  4097. callback()
  4098. }
  4099. return
  4100. }
  4101. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  4102. callback()
  4103. return
  4104. }
  4105. DispatchQueue.main.async {
  4106. document?.save(nil)
  4107. callback()
  4108. }
  4109. }
  4110. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  4111. // 显示进度
  4112. AutoSaveManager.manager.isSaving = true
  4113. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  4114. self.progressC?.maxValue = 3.0
  4115. self.progressC?.increment(by: 1.0)
  4116. // 保存文档
  4117. self.asyncSaveDocument { [weak self] params in
  4118. // 执行进度 [假进度]
  4119. self?.progressC?.increment(by: 1.0)
  4120. self?.progressC?.increment(by: 1.0)
  4121. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  4122. // 隐藏进度
  4123. self?.hiddenProgressWindow()
  4124. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  4125. AutoSaveManager.manager.isSaving = false
  4126. }
  4127. // 回调
  4128. callback()
  4129. }
  4130. }
  4131. }
  4132. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  4133. self.document?.write(toFile: tempPath)
  4134. }
  4135. // MARK: - 定时保存
  4136. func addAutoSaveEvent() {
  4137. if (self.autoSaveTimer != nil) {
  4138. self.autoSaveTimer?.invalidate()
  4139. self.autoSaveTimer = nil
  4140. }
  4141. if self.document != nil {
  4142. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  4143. self?.autoSaveTimerAction(timer)
  4144. })
  4145. }
  4146. self.checkAutoSaveInfo()
  4147. }
  4148. func checkAutoSaveInfo() {
  4149. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  4150. return
  4151. }
  4152. if AutoSaveManager.manager.autoSaveAlertShow {
  4153. return
  4154. }
  4155. AutoSaveManager.manager.autoSaveDidEndAction = false
  4156. AutoSaveManager.manager.autoSaveAlertShow = true
  4157. let blockSaveWindow = AutoSavePopController()
  4158. blockSaveWindow.cancelHandle = { [weak self] windowController in
  4159. AutoSaveManager.manager.autoSaveDidEndAction = true
  4160. AutoSaveManager.manager.clearCache()
  4161. self?.km_quick_endSheet()
  4162. }
  4163. blockSaveWindow.confirmHandle = { [weak self] windowController in
  4164. self?.km_quick_endSheet()
  4165. self?.saveAutoSaveInfo()
  4166. }
  4167. self.km_beginSheet(windowC: blockSaveWindow)
  4168. }
  4169. func saveAutoSaveInfo() {
  4170. let openPanel = NSOpenPanel()
  4171. openPanel.canChooseDirectories = true
  4172. openPanel.canChooseFiles = false
  4173. openPanel.allowsMultipleSelection = false
  4174. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  4175. openPanel.beginSheetModal(for: win!) { result in
  4176. if (result == .OK) {
  4177. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  4178. for path in AutoSaveManager.manager.opendPaths ?? [] {
  4179. let _path = path as? String
  4180. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  4181. newPath = self.getValidFilePath(newPath)
  4182. do {
  4183. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  4184. } catch {
  4185. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  4186. }
  4187. }
  4188. AutoSaveManager.manager.clearCache()
  4189. }
  4190. AutoSaveManager.manager.autoSaveDidEndAction = true
  4191. }
  4192. }
  4193. func autoSaveTimerAction(_ timer: Timer) {
  4194. if (self.document == nil || self.listView.document?.documentURL.path == nil) {
  4195. return
  4196. }
  4197. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  4198. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  4199. return
  4200. }
  4201. if let data = self.document?.isLocked, data {
  4202. return
  4203. }
  4204. if AutoSaveManager.manager.autoSaveEnabled == false {
  4205. return
  4206. }
  4207. let documentArray = NSDocumentController.shared.documents
  4208. var didFileEdit = false
  4209. for doc in documentArray {
  4210. if doc.fileURL?.path == self.document?.documentURL.path {
  4211. didFileEdit = doc.isDocumentEdited
  4212. break
  4213. }
  4214. }
  4215. if (didFileEdit == false) {
  4216. return
  4217. }
  4218. AutoSaveManager.manager.isSaving = true
  4219. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView.document?.documentURL.path ?? "")
  4220. if (!self.document!.isLocked) {
  4221. self.document?.write(to: URL(fileURLWithPath: savePath))
  4222. }
  4223. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  4224. AutoSaveManager.manager.isSaving = false
  4225. }
  4226. }
  4227. func removeAutoSaveInfo() {
  4228. if self.autoSaveTimer != nil {
  4229. self.autoSaveTimer?.invalidate()
  4230. self.autoSaveTimer = nil
  4231. }
  4232. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  4233. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  4234. return
  4235. }
  4236. if AutoSaveManager.manager.autoSaveEnabled == false {
  4237. return
  4238. }
  4239. if self.document == nil || self.listView.document?.documentURL.path == nil {
  4240. return
  4241. }
  4242. AutoSaveManager.manager.removeAutoSavePath(self.listView.document?.documentURL.path ?? "")
  4243. }
  4244. // MARK: - 选择 PDFDisplay 模式
  4245. public func setPDFDisplay(pdfViewMode: CPDFDisplayViewMode) {
  4246. listView.setDisplay(pdfViewMode)
  4247. }
  4248. // MARK: - 选择缩放模式
  4249. @objc public func selectZoom(_ type: KMPDFZoomType) {
  4250. switch type {
  4251. case .width:
  4252. self.listView.autoScales = true
  4253. break
  4254. case .fit:
  4255. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  4256. let pdfviewHeight = self.listView.bounds.size.height
  4257. self.listView.scaleFactor = pdfviewHeight/pageHeight
  4258. self.listView.autoScales = false
  4259. }
  4260. break
  4261. case .actualSize:
  4262. if self.listView.scaleFactor != 1.0 {
  4263. self.listView.scaleFactor = 1.0
  4264. self.listView.autoScales = false
  4265. }
  4266. break
  4267. }
  4268. }
  4269. internal func createPdf(index:Int) {
  4270. }
  4271. // MARK - Event 监听
  4272. private func addEventMonitor() {
  4273. if (self.eventMonitor != nil) {
  4274. self.removeEventMonitor()
  4275. }
  4276. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown, .leftMouseUp]) { [weak self] event in
  4277. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  4278. self?.listView.magnifyWheel(event)
  4279. return nil
  4280. } else if event.type == .leftMouseDown {
  4281. let point = event.locationInView(self?.listView ?? NSView())
  4282. let presentationDrawView = self?.listView.presentationDrawView
  4283. if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true { // 幻灯片模式下
  4284. if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
  4285. let can = self?.listView.canGoToNextPage() ?? false
  4286. if can {
  4287. self?.listView.goToNextPage(nil)
  4288. }
  4289. } else {
  4290. let can = self?.listView.canGoToPreviousPage() ?? false
  4291. if can {
  4292. self?.listView.goToPreviousPage(nil)
  4293. }
  4294. }
  4295. return nil
  4296. }
  4297. }
  4298. return event
  4299. }
  4300. }
  4301. func addKeyEventMonitor() {
  4302. if (self.keyEventMonitor != nil) {
  4303. self.removeKeyEventMonitor()
  4304. }
  4305. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  4306. if event.keyCode == 53 {
  4307. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  4308. self?.exitFullScreen()
  4309. return event
  4310. }
  4311. if self?.listView.toolMode == .editPDFToolMode {
  4312. if self != nil {
  4313. //使用editingSelectionString获取内容文字
  4314. if self!.listView.editingAreas() != nil {
  4315. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  4316. self!.listView.clearEditingSelectCharItem()
  4317. } else if self!.listView.editingAreas().count > 0 {
  4318. if self?.listView.annotationType == .addImage ||
  4319. self?.listView.annotationType == .addText {
  4320. }
  4321. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  4322. self?.listView.updateEditing([])
  4323. self?.listView.isEditImage = false
  4324. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  4325. if self?.listView.annotationType == .addImage {
  4326. self?.listView.change([.text, .image])
  4327. }
  4328. self?.listView.annotationType = .editTextImage
  4329. self?.toggleCloseRightSide()
  4330. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  4331. if self?.listView.annotationType == .addImage ||
  4332. self?.listView.annotationType == .addText {
  4333. }
  4334. self?.listView.setShouAddEdit([])
  4335. self?.listView.change([.text, .image])
  4336. self?.listView.annotationType = .editTextImage
  4337. self?.toggleCloseRightSide()
  4338. }
  4339. } else {
  4340. if self?.listView.annotationType == .addImage ||
  4341. self?.listView.annotationType == .addText {
  4342. }
  4343. }
  4344. }
  4345. }
  4346. } else {
  4347. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  4348. self?.listView.keyDown(with: event)
  4349. return event
  4350. } else {
  4351. let cmd = event.modifierFlags.contains(.command)
  4352. let shift = event.modifierFlags.contains(.shift)
  4353. if event.keyCode == 6 { // z
  4354. let editPDFIng = self?.listView.isEditing() ?? false
  4355. if cmd && shift { // 恢复
  4356. let can = self?.listView.canEditTextRedo() ?? false
  4357. if can == false {
  4358. return event
  4359. }
  4360. if editPDFIng {
  4361. _ = CustomAlertView.alertView(message: NSLocalizedString("Redo", comment: ""), fromView: self!.view, withStyle: .black)
  4362. }
  4363. } else if cmd { // 撤回
  4364. let can = self?.listView.canEditTextUndo() ?? false
  4365. if can == false {
  4366. return event
  4367. }
  4368. if editPDFIng {
  4369. _ = CustomAlertView.alertView(message: NSLocalizedString("Undo", comment: ""), fromView: self!.view, withStyle: .black)
  4370. }
  4371. }
  4372. }
  4373. }
  4374. }
  4375. return event
  4376. }
  4377. }
  4378. func removeKeyEventMonitor() {
  4379. if (self.keyEventMonitor != nil) {
  4380. KMPrint("removeKeyEventMonitor 已移除事件监听")
  4381. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  4382. self.keyEventMonitor = nil
  4383. }
  4384. }
  4385. private func removeEventMonitor() {
  4386. if (self.eventMonitor != nil) {
  4387. KMPrint("已移除事件监听")
  4388. NSEvent.removeMonitor(self.eventMonitor as Any)
  4389. self.eventMonitor = nil
  4390. }
  4391. }
  4392. // MARK: - Tools
  4393. func pdfViewCanHorizontalScroll() -> Bool {
  4394. let scroll = self.listView.scroll()
  4395. if (scroll == nil) {
  4396. return false
  4397. }
  4398. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  4399. }
  4400. func pdfViewCanVerticalScroll() -> Bool {
  4401. let scroll = self.listView.scroll()
  4402. if (scroll == nil) {
  4403. return false
  4404. }
  4405. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  4406. }
  4407. // MARK: - Public Methods
  4408. // 清理数据 [eg. 通知]
  4409. public func clearData() {
  4410. KMThumbnailCache.shared.clearCache()
  4411. self.removeNotifications()
  4412. if (self.listView.spellingTag() > 0) {
  4413. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  4414. }
  4415. self.removeAutoSaveInfo()
  4416. self.myDocument = nil
  4417. }
  4418. public func clearSecureOptions() {
  4419. self._secureOptions = nil
  4420. self.documentAttribute = nil
  4421. }
  4422. public func recordRemoveSecureFlag() {
  4423. self._removeSecureFlag = true
  4424. self.clearSecureOptions()
  4425. self.recordIsPDFDocumentEdited(type: .removePassword)
  4426. self._needSave = true
  4427. }
  4428. public func clearRemoveSecureFlag() {
  4429. self._removeSecureFlag = false
  4430. }
  4431. public func clearSaveWatermarkFlag() {
  4432. km_synchronized(self) {
  4433. self._saveWatermarkFlag = false
  4434. }
  4435. }
  4436. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  4437. km_synchronized(self) {
  4438. self.model.isPDFDocumentEdited = true
  4439. if type == .editText || type == .editImage {
  4440. self.leftSideViewController.updateThumbnail(at: self.listView.currentPageIndex)
  4441. }
  4442. if let _document = self.myDocument {
  4443. KMTools.setDocumentEditedState(document: _document)
  4444. }
  4445. }
  4446. }
  4447. public func clearIsPDFDocumentEdited() {
  4448. km_synchronized(self) {
  4449. self.model.isPDFDocumentEdited = false
  4450. }
  4451. }
  4452. func showSnapshots(setups: NSArray?) {
  4453. if self.listView.document != nil {
  4454. for setup in setups ?? [] {
  4455. let swc = KMSnapshotWindowController()
  4456. swc.delegate = self
  4457. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  4458. swc.setForceOnTop(self.interactionMode != .normal)
  4459. self.myDocument?.addWindowController(swc)
  4460. }
  4461. }
  4462. }
  4463. func dealDocumentDidLoaded() {
  4464. self.removeBackgroundMaskView()
  4465. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  4466. self.showSecureLimitTip()
  4467. }
  4468. if self.model.needConvertNotes {
  4469. self.showConvertNotesProgress()
  4470. }
  4471. if (self._documentFirstLoad) {
  4472. self.checkShouldAutoOpenLeftVC()
  4473. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  4474. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document?.documentURL.path ?? "")
  4475. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document?.documentURL.path ?? "")
  4476. if (pageScale != nil) {
  4477. self.listView.scaleFactor = CGFloat(pageScale!)
  4478. }
  4479. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < (self.listView.document?.pageCount ?? 0)) {
  4480. self.listView.go(toPageIndex: pageNumber!, animated: false)
  4481. } else {
  4482. self._goToFirstPageForFristAppear()
  4483. }
  4484. } else {
  4485. self._goToFirstPageForFristAppear()
  4486. }
  4487. self._documentFirstLoad = false
  4488. }
  4489. }
  4490. func tabViewIsDragging() -> Bool {
  4491. let level = self.view.window?.level ?? .normal
  4492. return level == .floating
  4493. }
  4494. // MARK: - Noti Actions
  4495. internal func documentDidUnlockNotification(_ sender: Notification) {
  4496. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  4497. if (self.myDocument == nil) {
  4498. return
  4499. }
  4500. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  4501. self.hiddenSecureLimitTip()
  4502. }
  4503. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  4504. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  4505. return
  4506. }
  4507. let type = KMPreferenceManager.shared.savePasswordType
  4508. if (type == .never) {
  4509. return
  4510. }
  4511. if (type == .always) {
  4512. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  4513. return
  4514. }
  4515. // 保存到钥匙串
  4516. let alert = NSAlert()
  4517. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  4518. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  4519. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  4520. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  4521. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  4522. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  4523. return
  4524. }
  4525. }
  4526. }
  4527. func annotationsAttributeHasChange(_ sender: Notification) {
  4528. guard let dict = sender.object as? [String : Any] else {
  4529. return
  4530. }
  4531. if let anno = dict["object"] as? CPDFAnnotation {
  4532. let value = dict["keyPath"] as? String ?? ""
  4533. let didEnd = dict["didEnd"] as? Bool ?? false
  4534. if didEnd {
  4535. if value == CPDFAnnotationBoundsKey {
  4536. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  4537. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  4538. }
  4539. }
  4540. if anno.km_isMeasure() && anno.contents == nil {
  4541. anno.contents = anno.string() ?? ""
  4542. }
  4543. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  4544. } else {
  4545. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  4546. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  4547. }
  4548. }
  4549. }
  4550. }
  4551. internal func applicationWillTerminateNotification(_ sender: Notification) {
  4552. self.savePageNumberIfNeed()
  4553. self.saveDocument()
  4554. }
  4555. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  4556. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(nil, attributes: nil)
  4557. }
  4558. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  4559. var editSelectd = false
  4560. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  4561. editSelectd = true
  4562. }
  4563. if self.listView.toolMode == .editPDFToolMode {
  4564. if editSelectd {
  4565. }
  4566. }
  4567. }
  4568. @objc func handlePageChangedNotification(_ sender: Notification) {
  4569. if self.mwcFlags.isSwitchingFullScreen > 0 {
  4570. return
  4571. }
  4572. let page = self.listView.currentPage()
  4573. let pageIndex = page?.pageIndex() ?? 0
  4574. self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
  4575. self.leftSideViewController.thumbnailTableView.needsDisplay = true
  4576. self.leftSideViewController.tocOutlineView.needsDisplay = true
  4577. }
  4578. @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
  4579. self.leftSideViewController.reloadThumbnailDataIfNeed()
  4580. }
  4581. }