KMMainViewController+Action.swift 259 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true) {
  10. let document = self.listView.document
  11. if let data = document?.isFinding, data {
  12. document?.cancelFindString()
  13. }
  14. if searchString == "" {
  15. self.searchResults = []
  16. self.leftSideViewController.searchResults = self.searchResults
  17. self.listView.setHighlightedSelections([])
  18. self.listView.setHighlightedSelection(nil, animated: false)
  19. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  20. } else {
  21. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  22. var findArray : [[CPDFSelection]]
  23. if isCase {
  24. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  25. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  26. } else {
  27. findArray = self.listView.document.findString(searchString) ?? []
  28. }
  29. } else {
  30. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  31. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  32. } else {
  33. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  34. }
  35. }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in findArray {
  39. for selection in selections {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = selection
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  43. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  44. self.searchResults.insert(mode, at: self.searchResults.count)
  45. _selections.append(selection)
  46. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  47. // self.listView.setHighlight(selection, forBorderColor: .yellow, fill: .red, animated: false)
  48. }
  49. // self.listView.setHighlightedSelections(selections )
  50. }
  51. self.listView.setHighlightedSelections(_selections)
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. }
  58. if display {
  59. if self.leftSideViewController.findPaneState == .singular {
  60. self.leftSideViewController.displayFindViewAnimating(true)
  61. } else {
  62. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  63. }
  64. }
  65. }
  66. func removeSignatures(signatures:[CPDFSignature]) {
  67. for signature in signatures {
  68. self.listView.document.removeSignature(signature)
  69. }
  70. for i in 0..<self.listView.document.pageCount {
  71. let page : CPDFPage = self.listView.document.page(at: i)
  72. let annotations : [CPDFAnnotation] = page.annotations
  73. for j in 0..<annotations.count {
  74. let annotation = annotations[j]
  75. if annotation is CPDFSignatureWidgetAnnotation {
  76. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  77. }
  78. }
  79. }
  80. self.listView.setNeedsDisplayForVisiblePages()
  81. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  82. var mSignatures : [CPDFSignature] = []
  83. for sign in tSignatures {
  84. if sign.signers.count > 0 {
  85. mSignatures.append(sign)
  86. }
  87. }
  88. // self.leftSideViewController.signatureViewController.signatures = signatures
  89. // self.leftSideViewController.signatureViewController.reloadData()
  90. }
  91. //MARK: menu菜单
  92. func fontColorMenuItem()->NSMenuItem {
  93. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  94. return fontColorItem;
  95. }
  96. func fontSizeMenuItem()->NSMenuItem {
  97. let currentFontSize = self.listView.editingTextFontSize()
  98. let fontSizes = self.fontSizes()
  99. let submenu = NSMenu(title: "")
  100. for i in 0 ... fontSizes.count - 1 {
  101. let fontSize : String = fontSizes.object(at: i) as! String
  102. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  103. item.target = self
  104. item.tag = i
  105. submenu.addItem(item)
  106. if (Int(currentFontSize) == Int(fontSize)) {
  107. item.state = .on
  108. }
  109. }
  110. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  111. fontSizeItem.submenu = submenu
  112. return fontSizeItem;
  113. }
  114. func corpImageMenuItem()->NSMenuItem {
  115. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  116. return corpImageItem
  117. }
  118. func cancelCorpImageMenuItem()->NSMenuItem {
  119. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  120. return cancelCorpImageItem
  121. }
  122. func restoreCorpImageMenuItem()->NSMenuItem {
  123. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  124. return cancelCorpImageItem
  125. }
  126. func cutImageArea()->NSMenuItem {
  127. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  128. return deleteItem
  129. }
  130. func editAddBlanMenu(menu:NSMenu){
  131. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  132. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  133. }
  134. func addText() -> NSMenuItem {
  135. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  136. return addTextItem
  137. }
  138. func addImage() -> NSMenuItem {
  139. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  140. return addImageItem
  141. }
  142. func replaceImageArea()->NSMenuItem {
  143. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  144. return replaceItem
  145. }
  146. func exportImageArea()->NSMenuItem {
  147. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  148. return exportItem
  149. }
  150. func exportImageStampItem()->NSMenuItem {
  151. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  152. let menu = NSMenu()
  153. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  154. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  155. exportItem.submenu = menu
  156. return exportItem
  157. }
  158. func exportMenu() -> NSMenu {
  159. let menu = NSMenu()
  160. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  161. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  162. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  163. return menu
  164. }
  165. func cropMenu() -> NSMenu {
  166. let menu = NSMenu()
  167. _ = menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  168. _ = menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  169. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  170. _ = menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(smartAutoCropAll), target: self, at: 2)
  171. return menu
  172. }
  173. func zoomSelectionMenuItem() -> NSMenuItem {
  174. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  175. return item
  176. }
  177. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  178. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  179. return item
  180. }
  181. func enterAnnotationStype() -> NSMenuItem {
  182. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  183. let stypeMenu = NSMenu()
  184. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  185. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  186. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  187. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  188. stypeMenu.addItem(NSMenuItem.separator())
  189. }
  190. // stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  191. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  192. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  193. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  194. stypeMenu.addItem(NSMenuItem.separator())
  195. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  196. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  197. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  198. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  199. // stypeMenu.insertItem(NSMenuItem.separator(), at: 10000)
  200. if self.isReadMode {
  201. } else {
  202. stypeMenu.addItem(NSMenuItem.separator())
  203. // _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  204. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  205. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  206. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  207. }
  208. stypItem.submenu = stypeMenu
  209. if self.listView.annotationType == .ink {
  210. stypeMenu.item(at: 0)?.state = .on
  211. } else if self.listView.annotationType == .freeText {
  212. stypeMenu.item(at: 1)?.state = .on
  213. } else if self.listView.annotationType == .anchored {
  214. stypeMenu.item(at: 2)?.state = .on
  215. } else if self.listView.annotationType == .square {
  216. stypeMenu.item(at: 3)?.state = .on
  217. } else if self.listView.annotationType == .circle {
  218. stypeMenu.item(at: 4)?.state = .on
  219. } else if self.listView.annotationType == .arrow {
  220. stypeMenu.item(at: 5)?.state = .on
  221. } else if self.listView.annotationType == .line {
  222. stypeMenu.item(at: 6)?.state = .on
  223. } else if self.listView.annotationType == .link {
  224. stypeMenu.item(at: 7)?.state = .on
  225. } else if self.listView.annotationType == .stamp {
  226. stypeMenu.item(at: 8)?.state = .on
  227. } else if self.listView.annotationType == .signSignature {
  228. stypeMenu.item(at: 9)?.state = .on
  229. }
  230. return stypItem
  231. }
  232. func setAnnotationToolStype() -> NSMenuItem {
  233. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  234. let stypeMenu = NSMenu()
  235. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  236. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  237. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  238. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  239. // stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  240. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  241. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  242. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  243. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  246. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  247. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  248. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  249. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  250. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  252. stypItem.submenu = stypeMenu
  253. if self.toolbarController.toolbarType == .Annatiton {
  254. stypeMenu.item(at: 0)?.state = .on
  255. } else if self.toolbarController.toolbarType == .Move {
  256. stypeMenu.item(at: 1)?.state = .on
  257. } else if self.toolbarController.toolbarType == .Magnify {
  258. stypeMenu.item(at: 2)?.state = .on
  259. } else if self.toolbarController.toolbarType == .Select {
  260. stypeMenu.item(at: 3)?.state = .on
  261. } else if self.toolbarController.toolbarType == .SelectZoom {
  262. stypeMenu.item(at: 4)?.state = .on
  263. }
  264. return stypItem
  265. }
  266. func addReadModelStype() -> NSMenuItem {
  267. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  268. if self.isReadMode {
  269. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  270. }
  271. return stypItem
  272. }
  273. func addOutlineStype() -> NSMenuItem {
  274. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  275. return stypItem
  276. }
  277. func setTTSStype() -> NSMenuItem {
  278. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  279. return stypItem
  280. }
  281. func setShareStype() -> NSMenuItem {
  282. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  283. var string = ""
  284. if listView.activeAnnotation != nil {
  285. string = listView.activeAnnotation.contents
  286. }
  287. string = listView.currentSelection.string()
  288. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  289. return stypItem
  290. }
  291. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  292. var number = 0
  293. var indexN = 0
  294. guard str.count > 0 else {return (0, 0)}
  295. for i in 0...str.count - 1 {
  296. let c: unichar = (str as NSString).character(at: i)
  297. if (c >= 0x4E00) {
  298. number += 2
  299. }else {
  300. number += 1
  301. }
  302. if number > 56{
  303. indexN = i
  304. number = 100
  305. break
  306. }
  307. }
  308. return (number, indexN)
  309. }
  310. func setLookUpStype() -> NSMenuItem {
  311. let str = listView?.currentSelection?.string() ?? ""//String(format: "Look Up %@", listView?.currentSelection?.string() ?? "")
  312. let dic = numberOfChars(str)
  313. var newStr = str
  314. if dic.num == 100{
  315. newStr = str.prefix(dic.indexN) + "..."
  316. }
  317. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  318. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  319. return stypItem
  320. }
  321. func setSearchBaiduStype() -> NSMenuItem {
  322. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  323. return stypItem
  324. }
  325. func setCutStype() -> NSMenuItem {
  326. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  327. return stypItem
  328. }
  329. func setDeleteStype() -> NSMenuItem {
  330. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  331. return stypItem
  332. }
  333. func setColorsStype() -> NSMenuItem {
  334. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  335. return stypItem
  336. }
  337. func setLinesStype() -> NSMenuItem {
  338. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  339. return stypItem
  340. }
  341. func setEditNoteStype() -> NSMenuItem {
  342. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  343. return stypItem
  344. }
  345. func setRotateStype() -> NSMenuItem {
  346. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  347. let stypeMenu = NSMenu()
  348. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  349. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  350. stypItem.submenu = stypeMenu
  351. if self.toolbarController.toolbarType == .Annatiton {
  352. stypeMenu.item(at: 0)?.state = .on
  353. } else if self.toolbarController.toolbarType == .Move {
  354. stypeMenu.item(at: 1)?.state = .on
  355. }
  356. return stypItem
  357. }
  358. func setNextPageStype() -> NSMenuItem {
  359. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  360. stypItem.isEnabled = false
  361. if listView.canGoToNextPage() {
  362. stypItem.isEnabled = true
  363. }
  364. return stypItem
  365. }
  366. func setPreviousPageStype() -> NSMenuItem {
  367. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  368. stypItem.isEnabled = false
  369. if listView.canGoToPreviousPage() {
  370. stypItem.isEnabled = true
  371. }
  372. return stypItem
  373. }
  374. func setTranslateStype() -> NSMenuItem {
  375. let str = listView?.currentSelection?.string() ?? ""//String(format: "Translate %@", listView?.currentSelection?.string() ?? "")
  376. let dic = numberOfChars(str)
  377. var newStr = str
  378. if dic.num == 100{
  379. newStr = str.prefix(dic.indexN) + "..."
  380. }
  381. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  382. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  383. return stypItem
  384. }
  385. func setAutoScrollStype() -> NSMenuItem {
  386. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  387. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  388. return stypItem
  389. }
  390. func setSnapshotStype() -> NSMenuItem {
  391. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  392. let stypeMenu = NSMenu()
  393. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  394. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  395. stypItem.submenu = stypeMenu
  396. // if self.toolbarController.toolbarType == .Annatiton {
  397. // stypeMenu.item(at: 0)?.state = .on
  398. // } else if self.toolbarController.toolbarType == .Move {
  399. // stypeMenu.item(at: 1)?.state = .on
  400. // }
  401. return stypItem
  402. }
  403. func setServicesStype() -> NSMenuItem {
  404. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  405. let stypeMenu = NSMenu()
  406. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  407. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  408. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  409. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  410. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  411. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  412. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  413. stypItem.submenu = stypeMenu
  414. // if self.toolbarController.toolbarType == .Annatiton {
  415. // stypeMenu.item(at: 0)?.state = .on
  416. // } else if self.toolbarController.toolbarType == .Move {
  417. // stypeMenu.item(at: 1)?.state = .on
  418. // }
  419. return stypItem
  420. }
  421. func setCropStype() -> NSMenuItem {
  422. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  423. let stypeMenu = NSMenu()
  424. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  425. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  426. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  427. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  428. if NSIsEmptyRect(listView.selectionRect){
  429. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  430. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  431. }
  432. stypItem.submenu = stypeMenu
  433. // if self.toolbarController.toolbarType == .Annatiton {
  434. // stypeMenu.item(at: 0)?.state = .on
  435. // } else if self.toolbarController.toolbarType == .Move {
  436. // stypeMenu.item(at: 1)?.state = .on
  437. // } else if self.toolbarController.toolbarType == .Magnify {
  438. // stypeMenu.item(at: 2)?.state = .on
  439. // } else if self.toolbarController.toolbarType == .Select {
  440. // stypeMenu.item(at: 3)?.state = .on
  441. // } else if self.toolbarController.toolbarType == .SelectZoom {
  442. // stypeMenu.item(at: 4)?.state = .on
  443. // }
  444. return stypItem
  445. }
  446. func setAITranslateStype() -> NSMenuItem {
  447. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  448. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  449. return stypItem
  450. }
  451. func setAIProofreadStype() -> NSMenuItem {
  452. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  453. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  454. return stypItem
  455. }
  456. func setAIRewriteStype() -> NSMenuItem {
  457. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  458. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  459. return stypItem
  460. }
  461. func addHighlightLinksStype() -> NSMenuItem {
  462. let highlightLink = KMPreferenceManager.shared.highlightLinks
  463. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  464. if highlightLink {
  465. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  466. }
  467. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  468. return highlightLinksItem
  469. }
  470. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  471. if item == nil {
  472. return
  473. }
  474. let menu = NSMenu()
  475. item?.submenu = menu
  476. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  477. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  478. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  479. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  480. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  481. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  482. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  483. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  484. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  485. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  486. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  487. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  488. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  489. if listView.currentSelection.selectionType() != .image {
  490. menu.insertItem(height, at: menu.items.count)
  491. menu.insertItem(underline, at: menu.items.count)
  492. menu.insertItem(strickout, at: menu.items.count)
  493. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  494. }
  495. if self.isReadMode {
  496. } else {
  497. if listView.currentSelection.selectionType() != .image &&
  498. listView.currentSelection.selectionType() != .text {
  499. menu.insertItem(text, at: menu.items.count)
  500. menu.insertItem(note, at: menu.items.count)
  501. }
  502. }
  503. if self.isReadMode {
  504. } else {
  505. if listView.currentSelection.selectionType() != .image {
  506. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  507. menu.insertItem(rectangle, at: menu.items.count)
  508. menu.insertItem(oval, at: menu.items.count)
  509. }
  510. }
  511. if self.isReadMode {
  512. } else {
  513. if listView.currentSelection.selectionType() != .image &&
  514. listView.currentSelection.selectionType() != .text {
  515. menu.insertItem(line, at: menu.items.count)
  516. }
  517. }
  518. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  519. if self.isReadMode {
  520. } else {
  521. menu.insertItem(link, at: menu.items.count)
  522. }
  523. if self.isReadMode {
  524. } else {
  525. if listView.currentSelection.selectionType() != .image {
  526. menu.insertItem(outline, at: menu.items.count)
  527. }
  528. }
  529. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  530. if self.isReadMode {
  531. } else {
  532. if (listView.currentSelection.selectionType() != .image) {
  533. menu.insertItem(aiTranslation, at: menu.items.count)
  534. }
  535. }
  536. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  537. }
  538. func addBookmarkMenu() -> NSMenuItem {
  539. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  540. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  541. return bookMarkItem
  542. } else {
  543. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  544. return bookMarkItem
  545. }
  546. }
  547. func findStringMenu() -> NSMenuItem {
  548. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  549. menuItem.keyEquivalent = "f"
  550. return menuItem
  551. }
  552. func printingMenu() -> NSMenuItem {
  553. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  554. return menuItem
  555. }
  556. func fontSizes()->NSArray {
  557. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  558. }
  559. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  560. if interactionMode == .presentation {
  561. listView.goToPreviousPage(nil)
  562. return true
  563. }
  564. return false
  565. }
  566. func canEnterFullscreen() -> Bool {
  567. if (mwcFlags.isSwitchingFullScreen != 0) {
  568. return false
  569. }
  570. if useNativeFullScreen() {
  571. return interactionMode == .normal || interactionMode == .presentation
  572. } else {
  573. return !self.listView.document.isLocked && (interactionMode == .normal || interactionMode == .presentation) && self.view.window?.tabbedWindows?.count ?? 0 < 2
  574. }
  575. }
  576. override func canEnterPresentation() -> Bool {
  577. let can = super.canEnterPresentation()
  578. if can == false {
  579. return false
  580. }
  581. guard let doc = self.listView?.document, doc.isLocked == false else {
  582. return false
  583. }
  584. return can
  585. }
  586. func useNativeFullScreen() -> Bool {
  587. var isFull = false
  588. // NSWindow.instancesRespond(toSelector: #selector(toggleFullScreen:))
  589. let sel = NSSelectorFromString("toggleFullscreen:")
  590. if NSWindow.instancesRespond(to: sel) && UserDefaults.standard.bool(forKey: "SKUseLegacyFullScreenKey"){
  591. isFull = true
  592. }
  593. return isFull
  594. }
  595. func enterPresentation() {
  596. self.view.window?.enterPresentation(provider: self)
  597. }
  598. func removeBlankingWindows() {
  599. // blankingWindows.makeObjectsPerform(#selector(fadeOut))
  600. // blankingWindows = nil
  601. }
  602. func hideLeftSideWindow() {
  603. // if leftSideViewController.view.window == leftSideWindow {
  604. // self.leftView.remove()
  605. // if leftSideWindow.firstResponder()?.isDescendant(of: leftSideController.view()) {
  606. // leftSideWindow.makeFirstResponder(nil)
  607. // }
  608. // leftSideController.view().setFrame(SKShrinkRect(NSInsetRect(leftSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  609. // leftSideContentView.addSubview(leftSideController.view())
  610. //
  611. // if self.interactionMode() == SKPresentationMode {
  612. // self.setLeftSidePaneState(mwcFlags.savedLeftSidePaneState)
  613. // }
  614. //
  615. // leftSideWindow = nil
  616. // }
  617. }
  618. func hideRightSideWindow() {
  619. // if rightSideController.view().window() == rightSideWindow {
  620. // rightSideWindow.remove()
  621. // if rightSideWindow.firstResponder()?.isDescendant(of: rightSideController.view()) {
  622. // rightSideWindow.makeFirstResponder(nil)
  623. // }
  624. // rightSideController.view().setFrame(SKShrinkRect(NSInsetRect(rightSideContentView.bounds, -1.0, -1.0), 1.0, .maxYEdge))
  625. // rightSideContentView.addSubview(rightSideController.view())
  626. //
  627. // rightSideWindow = nil
  628. // }
  629. }
  630. func forceSubwindowsOnTop(_ flag: Bool) {
  631. // let winC: NSWindowController = self.kmCurrentWindowC!
  632. // for wc in winC.document!.windowControllers {
  633. // let sel = NSSelectorFromString("setForceOnTop:")
  634. // if wc.responds(to: sel){
  635. // wc.
  636. // }
  637. // }
  638. }
  639. func enterPresentationMode() {
  640. let scrollView = listView.documentView().enclosingScrollView
  641. savedNormalSetup.setValue(scrollView?.hasHorizontalScroller, forKey: HASHORIZONTALSCROLLER_KEY)
  642. savedNormalSetup.setValue(scrollView?.hasVerticalScroller, forKey: HASVERTICALSCROLLER_KEY)
  643. savedNormalSetup.setValue(scrollView?.autohidesScrollers, forKey: AUTOHIDESSCROLLERS_KEY)
  644. // Set up presentation mode
  645. // if RUNNING(version: 10_12) {
  646. // pdfView.setBackgroundColor(NSColor.black)
  647. // } else {
  648. listView.backgroundColor = NSColor.clear
  649. // }
  650. listView.autoScales = true
  651. // listView.setDisplayMode(kPDFDisplaySinglePage)
  652. listView.setDisplay(.singlePage)
  653. // listView.setDisplayBox(kPDFDisplayBoxCropBox)
  654. listView.displayBox = .cropBox
  655. // listView.setDisplaysPageBreaks(false)
  656. listView.displaysPageBreaks = false
  657. // scrollView.setAutohidesScrollers(true)
  658. scrollView?.autohidesScrollers = true
  659. // scrollView.setHasHorizontalScroller(false)
  660. scrollView?.hasHorizontalScroller = false
  661. // scrollView.setHasVerticalScroller(false)
  662. scrollView?.hasVerticalScroller = false
  663. listView.setCurrentSelection(nil, animate: true)
  664. // if listView.hasReadingBar() {
  665. // listView.toggleReadingBar()
  666. // }
  667. // myDocument!.currentPage(presentationNotesDocument.pdfDocument().page(at: listView.currentPage().pageIndex()))
  668. // Prevent sleep
  669. // if activityAssertionID == kIOPMNullAssertionID && kIOReturnSuccess != IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, "Skim" as CFString, &activityAssertionID) {
  670. // activityAssertionID = kIOPMNullAssertionID
  671. // }
  672. }
  673. func exitFullscreenMode() {
  674. if self.interactionMode == .presentation {
  675. self.exitPresentationMode()
  676. }
  677. self.applyPDFSettings(self.savedNormalSetup)
  678. self.savedNormalSetup.removeAllObjects()
  679. self.listView.layoutDocumentView()
  680. self.listView.requiresDisplay()
  681. // if ([[[self pdfView] currentPage] isEqual:page] == NO)
  682. // [[self pdfView] goToPage:page];
  683. if let backgroundColor = UserDefaults.standard.color(forKey: KMBackgroundColorKey) {
  684. self.listView.backgroundColor = backgroundColor
  685. self.secondaryPdfView?.backgroundColor = backgroundColor
  686. }
  687. }
  688. func applyPDFSettings(_ setup: NSDictionary) {
  689. if let data = setup.object(forKey: AUTOSCALES_KEY) as? NSNumber {
  690. self.listView.autoScales = data.boolValue
  691. }
  692. if self.listView.autoScales == false {
  693. if let data = setup.object(forKey: SCALEFACTOR_KEY) as? NSNumber {
  694. self.listView.scaleFactor = data.floatValue.cgFloat
  695. }
  696. }
  697. if let data = setup.object(forKey: DISPLAYSPAGEBREAKS_KEY) as? NSNumber {
  698. self.listView.displaysPageBreaks = data.boolValue
  699. }
  700. if let data = setup.object(forKey: DISPLAYSASBOOK_KEY) as? NSNumber {
  701. self.listView.displaysAsBook = data.boolValue
  702. }
  703. if let data = setup.object(forKey: DISPLAYMODE_KEY) as? NSNumber {
  704. self.listView.displayMode = CPDFDisplayMode(rawValue: data.intValue) ?? .normal
  705. }
  706. if let data = setup.object(forKey: DISPLAYBOX_KEY) as? NSNumber {
  707. self.listView.displayBox = CPDFDisplayBox(rawValue: data.intValue) ?? .cropBox
  708. }
  709. }
  710. func exitPresentationMode() {
  711. // if (activityAssertionID != kIOPMNullAssertionID && kIOReturnSuccess == IOPMAssertionRelease(activityAssertionID))
  712. // activityAssertionID = kIOPMNullAssertionID;
  713. //
  714. // NSScrollView *scrollView = [[pdfView documentView] enclosingScrollView];
  715. // [scrollView setHasHorizontalScroller:[[savedNormalSetup objectForKey:HASHORIZONTALSCROLLER_KEY] boolValue]];
  716. // [scrollView setHasVerticalScroller:[[savedNormalSetup objectForKey:HASVERTICALSCROLLER_KEY] boolValue]];
  717. // [scrollView setAutohidesScrollers:[[savedNormalSetup objectForKey:AUTOHIDESSCROLLERS_KEY] boolValue]];
  718. }
  719. func currentPDFSettings() -> NSDictionary {
  720. var setup = NSMutableDictionary()
  721. setup[DISPLAYSPAGEBREAKS_KEY] = NSNumber(value: listView.displaysPageBreaks)
  722. setup[DISPLAYSASBOOK_KEY] = NSNumber(value: listView.displaysAsBook)
  723. setup[DISPLAYBOX_KEY] = NSNumber(value: listView.displayBox.rawValue)
  724. setup[SCALEFACTOR_KEY] = NSNumber(value: listView.scaleFactor)
  725. setup[AUTOSCALES_KEY] = NSNumber(value: listView.autoScales)
  726. setup[DISPLAYMODE_KEY] = NSNumber(value: listView.displayMode.rawValue)
  727. return setup
  728. }
  729. //MARK: menuItem Action
  730. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  731. let color = listView.editingSelectionFontColor()
  732. let panel = NSColorPanel.shared
  733. panel.setTarget(self)
  734. panel.setAction(#selector(fontColorChangeAction))
  735. panel.orderFront(nil)
  736. panel.showsAlpha = false
  737. panel.color = color ?? NSColor.black
  738. }
  739. @objc func fontColorChangeAction(sender: NSColorPanel) {
  740. self.listView.setEditingSelectionFontColor(sender.color)
  741. }
  742. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  743. let fontSize = self.fontSizes().object(at: sender.tag)
  744. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  745. }
  746. @objc func addImageText(sender: NSMenuItem) {
  747. let event = NSApp.currentEvent
  748. let clickLocation = event?.locationInWindow
  749. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  750. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  751. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  752. point = point2
  753. if sender.tag == 0 {
  754. KMPrint("添加文字")
  755. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  756. if !isSelect {
  757. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  758. }
  759. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  760. } else if sender.tag == 1 {
  761. KMPrint("添加图片")
  762. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  763. if !isSelect {
  764. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  765. }
  766. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  767. } else if sender.tag == 2 {
  768. KMPrint("粘贴")
  769. }
  770. }
  771. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  772. if self.rightSideViewController.eidtPDFImageProperty != nil {
  773. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  774. } else {
  775. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  776. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  777. }
  778. }
  779. }
  780. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  781. if self.rightSideViewController.eidtPDFImageProperty != nil {
  782. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  783. } else {
  784. self.listView.exitCrop(with: self.listView.selectImageAreas)
  785. self.listView.cropAreas = nil
  786. self.listView.isEditImage = false
  787. }
  788. }
  789. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  790. if self.rightSideViewController.eidtPDFImageProperty != nil {
  791. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  792. } else {
  793. self.listView.resetCrop(with: self.listView.selectImageAreas)
  794. }
  795. }
  796. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  797. if self.listView.selectImageAreas != nil {
  798. self.listView.isEditImage = true
  799. self.listView.enterCrop(with: self.listView.selectImageAreas)
  800. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  801. }
  802. }
  803. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  804. if self.listView.selectImageAreas == nil {
  805. return
  806. }
  807. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  808. let panel = NSOpenPanel()
  809. panel.allowsMultipleSelection = false
  810. panel.allowedFileTypes = ["png","jpg"]
  811. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  812. if response == .OK {
  813. let openPath = panel.url?.path
  814. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  815. if s {
  816. }
  817. }
  818. }
  819. }
  820. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  821. if self.listView.selectImageAreas == nil {
  822. return
  823. }
  824. let panel = NSSavePanel()
  825. // panel.nameFieldStringValue = "[新文件].png"
  826. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  827. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  828. // button.state = .on
  829. // panel.accessoryView = button
  830. panel.isExtensionHidden = true
  831. let response = panel.runModal()
  832. if response == .OK {
  833. let url = panel.url
  834. if FileManager.default.fileExists(atPath: url!.path) {
  835. try?FileManager.default.removeItem(atPath: url!.path)
  836. }
  837. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  838. if result {
  839. NSWorkspace.shared.activateFileViewerSelecting([url!])
  840. // if button.state == .on { /// 开启文档
  841. // NSWorkspace.shared.openFile(url!.path)
  842. // } else {
  843. //
  844. // }
  845. }
  846. }
  847. }
  848. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  849. }
  850. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  851. }
  852. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  853. }
  854. @objc func OpenItemAction(sender: NSMenuItem) {
  855. }
  856. @objc func cropAllPageItem(sender: NSMenuItem) {
  857. self.cropAll(nil)
  858. }
  859. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  860. self.crop(nil)
  861. }
  862. @objc func autoCropAllItem(sender: NSMenuItem) {
  863. self.autoCropAll(nil)
  864. }
  865. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  866. self.smartAutoCropAll(nil)
  867. }
  868. @objc func customCropModel(sender: NSMenuItem) {
  869. let pdfDoc: CPDFDocument = self.listView.document
  870. if !pdfDoc.allowsCopying || !pdfDoc.allowsPrinting {
  871. let alert = NSAlert()
  872. alert.alertStyle = .critical
  873. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  874. alert.runModal()
  875. return
  876. }
  877. let window = NSWindow.currentWindow()
  878. let currentPage = pdfDoc.index(for: self.listView.currentPage())
  879. let cropVC = KMPDFCropWindowController(document: pdfDoc, pwd: "", currentPage: Int(currentPage), cropSize: CGRectMake(100, 100, 50, 80), selectPageString: "\(currentPage)")
  880. window.km_beginSheet(windowC: cropVC)
  881. cropVC.cropWindowCloseBlock = { [weak self] doc in
  882. window.km_quick_endSheet()
  883. let isSuccessful = doc.write(to: self?.listView.document.documentURL)
  884. if isSuccessful {
  885. if let documen = CPDFDocument(url: self?.document?.documentURL) {
  886. if documen.isLocked {
  887. documen.unlock(withPassword: pdfDoc.password)
  888. }
  889. self?.document = documen
  890. self?.listView.document = self?.document
  891. self?.listView.layoutDocumentView()
  892. }
  893. }
  894. }
  895. }
  896. @objc func rotateRightAction(sender: NSMenuItem) {
  897. }
  898. @objc func rotateLeftAction(sender: NSMenuItem) {
  899. }
  900. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  901. self.listView.toolMode = .noteToolMode
  902. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  903. var model : KMToolbarViewType = .None
  904. switch sender.tag {
  905. case 0:
  906. identifier = KMDocumentAnnotationToolbarItemIdentifier
  907. model = .Annatiton
  908. case 1:
  909. identifier = KMToolbarMoveToolModeItemIdentifier
  910. model = .Move
  911. case 2:
  912. identifier = KMToolbarMagnifyToolModeItemIdentifier
  913. model = .Magnify
  914. case 3:
  915. identifier = KMToolbarSelectToolModeItemIdentifier
  916. model = .Select
  917. case 4:
  918. identifier = KMToolbarZoomToSelectionItemIdentifier
  919. model = .SelectZoom
  920. default:
  921. break
  922. }
  923. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  924. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  925. }
  926. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  927. var itemId: String?
  928. if sender.tag == CAnnotationType.highlight.rawValue {
  929. itemId = KMToolbarHighlightAnnotationItemIdentifier
  930. } else if sender.tag == CAnnotationType.underline.rawValue {
  931. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  932. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  933. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  934. } else if sender.tag == CAnnotationType.ink.rawValue {
  935. itemId = KMToolbarInkAnnotationItemIdentifier
  936. } else if sender.tag == CAnnotationType.freeText.rawValue {
  937. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  938. } else if sender.tag == CAnnotationType.anchored.rawValue {
  939. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  940. } else if sender.tag == CAnnotationType.square.rawValue {
  941. itemId = KMToolbarSquareAnnotationItemIdentifier
  942. } else if sender.tag == CAnnotationType.circle.rawValue {
  943. itemId = KMToolbarCircleAnnotationItemIdentifier
  944. } else if sender.tag == CAnnotationType.arrow.rawValue {
  945. itemId = KMToolbarArrowAnnotationItemIdentifier
  946. } else if sender.tag == CAnnotationType.line.rawValue {
  947. itemId = KMToolbarLineAnnotationItemIdentifier
  948. } else if sender.tag == CAnnotationType.link.rawValue {
  949. itemId = KMToolbarLinkAnnotationItemIdentifier
  950. }
  951. if let data = itemId {
  952. self.toolbarController.clickItem(data)
  953. }
  954. }
  955. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  956. var annotationType : CAnnotationType = .unkown
  957. switch sender.tag {
  958. case 0:
  959. annotationType = .highlight
  960. case 1:
  961. annotationType = .underline
  962. case 2:
  963. annotationType = .strikeOut
  964. case 3:
  965. annotationType = .freeText
  966. case 4:
  967. annotationType = .anchored
  968. case 5:
  969. annotationType = .square
  970. case 6:
  971. annotationType = .circle
  972. case 7:
  973. annotationType = .line
  974. case 8:
  975. annotationType = .link
  976. case 9:
  977. // var newOutline : CPDFOutline = CPDFOutline()
  978. // newOutline.label = "11111111"
  979. // let des = self.listView.currentDestination
  980. // if "\(des?.point.x ?? 0)" != "nan" {
  981. // newOutline.destination = self.listView.currentDestination
  982. // } else {
  983. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  984. // newOutline.destination = destination
  985. // }
  986. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  987. // let parent = current.parent ?? CPDFOutline()
  988. // let index = current.index + 1
  989. // parent.insertChild(newOutline, at: index)
  990. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  991. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  992. }
  993. // self.leftSideViewController.outlineViewController.addItemAction()
  994. return
  995. case 10:
  996. annotationType = .unkown
  997. default:
  998. break
  999. }
  1000. if (annotationType != .link) {
  1001. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  1002. self.listView.currentSelection = nil;
  1003. return
  1004. }
  1005. // link
  1006. let selection = self.listView.currentSelection
  1007. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  1008. DispatchQueue.main.async {
  1009. Task { @MainActor in
  1010. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  1011. self.listView.currentSelection = nil;
  1012. if (annotation != nil) {
  1013. self.listView.updateActiveAnnotations([annotation!])
  1014. }
  1015. }
  1016. }
  1017. }
  1018. @objc func aiTranslationAction(sender: NSMenuItem) {
  1019. let content = self.listView.currentSelection.string() ?? ""
  1020. let origin = self.listView.currentSelection.bounds.origin
  1021. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  1022. self.aiTranslationWindow?.content = content
  1023. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  1024. self.aiTranslationWindow!.window?.center()
  1025. }
  1026. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  1027. Task { @MainActor in
  1028. let idx = sender.tag
  1029. if idx == 10 {
  1030. if IAPProductsManager.default().isAvailableAllFunction() == false {
  1031. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1032. return
  1033. }
  1034. }
  1035. var point = mouseRightMenuEvent?.locationInWindow
  1036. if (point == nil) {
  1037. point = NSZeroPoint
  1038. }
  1039. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  1040. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  1041. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  1042. var annotation: CPDFAnnotation?
  1043. if self.isReadMode {
  1044. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1045. self.listView.toolMode = .noteToolMode
  1046. }
  1047. switch sender.tag {
  1048. case 0:
  1049. self.listView.annotationType = CAnnotationType.ink
  1050. case 1:
  1051. // self.listView.annotationType = CAnnotationType.freeText
  1052. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1053. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1054. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1055. if ((annotation) != nil) {
  1056. self.listView.updateActiveAnnotations([annotation!])
  1057. self.listView.edit(annotation)
  1058. }
  1059. case 2:
  1060. // self.listView.annotationType = CAnnotationType.anchored
  1061. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1062. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1063. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1064. self.listView.edit(annotation)
  1065. case 3:
  1066. // self.listView.annotationType = CAnnotationType.square
  1067. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1068. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1069. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1070. case 4:
  1071. // self.listView.annotationType = CAnnotationType.circle
  1072. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1073. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1074. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1075. case 5:
  1076. // self.listView.annotationType = CAnnotationType.arrow
  1077. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1078. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1079. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1080. case 6:
  1081. // self.listView.annotationType = CAnnotationType.line
  1082. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1083. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1084. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1085. case 7:
  1086. self.listView.annotationType = CAnnotationType.link
  1087. self.openRightPane()
  1088. case 8:
  1089. self.listView.annotationType = CAnnotationType.stamp
  1090. self.openRightPane()
  1091. case 9:
  1092. self.listView.annotationType = CAnnotationType.signSignature
  1093. self.openRightPane()
  1094. default:
  1095. break
  1096. }
  1097. self.rightSideViewController.isHidden = true
  1098. self.rightSideViewController.subViewType = .AnnotationProperts
  1099. } else {
  1100. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  1101. if(self.toolbarController.toolbarType == .None) {
  1102. self.toolbarController.toolbarType = .Annatiton
  1103. }
  1104. self.listView.toolMode = .noteToolMode
  1105. }
  1106. switch sender.tag {
  1107. case 0:
  1108. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  1109. self.rightMouseEventing = true
  1110. if(self.toolbarController.toolbarType == .None) {
  1111. self.toolbarController.toolbarType = .Annatiton
  1112. }
  1113. self.listView.toolMode = .noteToolMode
  1114. self.listView.annotationType = CAnnotationType.ink
  1115. case 1:
  1116. // self.listView.annotationType = CAnnotationType.freeText
  1117. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  1118. if (pagePoint.x - defaultSize.width > 0){
  1119. pagePoint.x -= defaultSize.width;
  1120. }else{
  1121. pagePoint.x = 0;
  1122. }
  1123. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1124. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  1125. // self.view.window?.makeFirstResponder()
  1126. if ((annotation) != nil) {
  1127. // self.listView.updateActiveAnnotations([annotation!])
  1128. self.listView.edit(annotation)
  1129. }
  1130. case 2:
  1131. // self.listView.annotationType = CAnnotationType.anchored
  1132. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  1133. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1134. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  1135. self.listView.edit(annotation)
  1136. case 3:
  1137. // self.listView.annotationType = CAnnotationType.square
  1138. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  1139. if (pagePoint.x - defaultSize.width > 0){
  1140. pagePoint.x -= defaultSize.width;
  1141. }else{
  1142. pagePoint.x = 0;
  1143. }
  1144. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1145. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  1146. case 4:
  1147. // self.listView.annotationType = CAnnotationType.circle
  1148. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  1149. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1150. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  1151. case 5:
  1152. // self.listView.annotationType = CAnnotationType.arrow
  1153. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  1154. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1155. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  1156. case 6:
  1157. // self.listView.annotationType = CAnnotationType.line
  1158. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  1159. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  1160. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  1161. case 7:
  1162. self.listView.annotationType = CAnnotationType.link
  1163. self.openRightPane()
  1164. case 8:
  1165. self.listView.annotationType = CAnnotationType.stamp
  1166. self.openRightPane()
  1167. case 9:
  1168. self.listView.annotationType = CAnnotationType.signSignature
  1169. self.openRightPane()
  1170. case 10:
  1171. self.addImgAnnotationToView(center: pagePoint)
  1172. default:
  1173. break
  1174. }
  1175. // self.rightSideViewController.view.isHidden = false
  1176. self.rightSideViewController.isHidden = false
  1177. // self.openRightPane()
  1178. self.rightSideViewController.subViewType = .AnnotationProperts
  1179. }
  1180. if (annotation != nil) {
  1181. self.listView.updateIsRightActiveAnnotations([annotation!])
  1182. }
  1183. }
  1184. }
  1185. func addImgAnnotationToView(center: NSPoint) {
  1186. let accessoryCtr = KMImageAccessoryController()
  1187. let openPanel = NSOpenPanel()
  1188. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1189. openPanel.allowsMultipleSelection = false
  1190. openPanel.accessoryView = accessoryCtr.view
  1191. openPanel.isAccessoryViewDisclosed = true
  1192. openPanel.beginSheetModal(for: self.view.window!) { result in
  1193. if result == .OK {
  1194. let fileURL = openPanel.urls.first
  1195. let filePath = fileURL!.path
  1196. if filePath.pathExtension == "pdf" {
  1197. let pdf = CPDFDocument(url: fileURL)
  1198. if pdf!.isEncrypted {
  1199. NSSound.beep()
  1200. return
  1201. }
  1202. }
  1203. let img = NSImage(contentsOfFile: filePath)
  1204. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  1205. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  1206. }
  1207. }
  1208. }
  1209. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  1210. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  1211. let index = self.listView.currentPageIndex
  1212. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  1213. self.listView.setNeedsDisplayForVisiblePages()
  1214. } else {
  1215. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1216. self.listView.setNeedsDisplayForVisiblePages()
  1217. }
  1218. if self.isReadMode {
  1219. } else {
  1220. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  1221. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  1222. }
  1223. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  1224. if bookMark != nil {
  1225. let item = KMBookMarkItem()
  1226. item.bookMark = bookMark!
  1227. item.label = (bookMark?.label)!
  1228. item.index = UInt(bookMark!.pageIndex)
  1229. // self.leftSideViewController.bookViewController.reloadData()
  1230. // self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  1231. } else {
  1232. // self.leftSideViewController.bookViewController.reloadData()
  1233. }
  1234. }
  1235. }
  1236. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  1237. self.leftSideViewController.refreshMethodType(methodType: .Search)
  1238. }
  1239. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  1240. let rect = listView.currentSelectionRect()
  1241. let page = listView.currentPage()
  1242. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  1243. copyPage.setBounds(rect, for: .cropBox)
  1244. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  1245. // let pdfDocument : PDFDocument = PDFDocument()
  1246. // let newpage : PDFPage = PDFPage(image: image)!
  1247. // pdfDocument.insert(newpage, at: 0)
  1248. // 执行右键操作后,需要取消框选区域
  1249. if self.listView.toolMode == .selectToolMode {
  1250. objc_sync_enter(self)
  1251. self.listView.selectionRect = NSZeroRect
  1252. self.listView.selectionPageIndex = UInt(NSNotFound)
  1253. objc_sync_exit(self)
  1254. }
  1255. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1256. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1257. if (result == .cancel) {
  1258. return
  1259. }
  1260. // 解除权限
  1261. self?.isSaveKeyChain = false
  1262. self?.listView.document.unlock(withPassword: password)
  1263. // 隐藏提示
  1264. self?.hiddenSecureLimitTip()
  1265. // 去打印
  1266. KMPrintWindowController.printImage(image: image)
  1267. }
  1268. return
  1269. }
  1270. KMPrintWindowController.printImage(image: image)
  1271. }
  1272. func splitView(withTag tag: Int) {
  1273. if tag == 0 {
  1274. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1275. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1276. } else if tag == 1 {
  1277. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1278. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1279. } else if tag == 2 {
  1280. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1281. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1282. }
  1283. self.listView.needsDisplay = true
  1284. }
  1285. // MARK: - 幻灯片
  1286. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1287. let view: NSView = self.view.window!.firstResponder as! NSView
  1288. if view.isDescendant(of: pdfSplitView){
  1289. self.view.window?.makeFirstResponder(nil)
  1290. }
  1291. self._mainWindow = self.view.window
  1292. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1293. fullScreenWindow.interactionParent = self.view.window
  1294. self.mainWindow?.delegate = nil
  1295. fullScreenWindow.fadeInBlocking()
  1296. self.browserWindowController?.window = fullScreenWindow
  1297. fullScreenWindow.makeKey()
  1298. // NSApp.updatePresentationOptions(for: fullScreenWindow)
  1299. let sel = NSSelectorFromString("setAnimationBehavior:")
  1300. if self.mainWindow?.responds(to: sel) ?? false{
  1301. self.mainWindow?.animationBehavior = .none
  1302. }
  1303. self.mainWindow?.orderOut(nil)
  1304. if self.mainWindow?.responds(to: sel) ?? false{
  1305. self.mainWindow?.animationBehavior = .default
  1306. }
  1307. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1308. fullScreenWindow.orderFront(nil)
  1309. // NSApp.addWindowsItem(fullScreenWindow, title: windowTitleForDocumentDisplayName(self.document?.displayName) ?? "", filename: false)
  1310. }
  1311. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1312. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1313. return
  1314. }
  1315. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1316. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1317. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1318. fullScreenWindow.contentView?.addSubview(view)
  1319. self.listView.layoutDocumentView()
  1320. self.listView.requiresDisplay()
  1321. fullScreenWindow.makeFirstResponder(self.listView)
  1322. fullScreenWindow.recalculateKeyViewLoop()
  1323. fullScreenWindow.delegate = self.browserWindowController
  1324. // if (RUNNING_BEFORE(10_7))
  1325. // [fullScreenWindow display];
  1326. fullScreenWindow.display()
  1327. fadeWindow.fadeOut()
  1328. }
  1329. // MARK: Redact 【密文标记】
  1330. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1331. self.listView.remove(self.listView.activeAnnotation)
  1332. }
  1333. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1334. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1335. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1336. self.view.window?.beginSheet(windowController.window!)
  1337. self.currentWindowController = windowController
  1338. windowController.itemClick = { [weak self] index, value in
  1339. if (index == 1) { /// 取消
  1340. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1341. self?.currentWindowController = nil
  1342. return
  1343. }
  1344. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1345. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1346. annotaton.setBorderColor(windowController_redact.outsideColor)
  1347. annotaton.setInteriorColor(windowController_redact.fillColor)
  1348. if (windowController_redact.isOver) {
  1349. annotaton.setFontColor(windowController_redact.fontColor)
  1350. annotaton.setAlignment(windowController_redact.aligement)
  1351. annotaton.setFont(windowController_redact.font)
  1352. annotaton.setOverlayText(windowController_redact.overText)
  1353. }
  1354. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1355. self?.currentWindowController = nil
  1356. }
  1357. }
  1358. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1359. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1360. return
  1361. }
  1362. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1363. let model = CPDFAnnotationModel(annotationType: .redact)
  1364. model?.setColor(annotation.borderColor())
  1365. model?.setInteriorColor(annotation.interiorColor())
  1366. let overlayText: String = annotation.overlayText()
  1367. if (overlayText.isEmpty) {
  1368. model?.setIsOverlayText(false)
  1369. } else {
  1370. model?.setIsOverlayText(true)
  1371. model?.setOverlayText(overlayText)
  1372. model?.setFontColor(annotation.fontColor())
  1373. model?.setAlignment(annotation.alignment())
  1374. model?.setFontName(annotation.font().fontName)
  1375. model?.setFontSize(annotation.font().pointSize)
  1376. }
  1377. }
  1378. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1379. let anno = self.listView.activeAnnotation
  1380. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1381. return
  1382. }
  1383. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1384. windowController.pageCount = Int(self.listView.document.pageCount)
  1385. self.currentWindowController = windowController
  1386. self.view.window?.beginSheet(windowController.window!)
  1387. windowController.itemClick = { [weak self] index, value in
  1388. if (index == 1) {
  1389. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1390. self!.currentWindowController = nil
  1391. return
  1392. }
  1393. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1394. let pageType = windowController_mutilPageFlag.pageType
  1395. let pageString = windowController_mutilPageFlag.pageString
  1396. if (pageType == 4) { /// 自定义页面
  1397. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  1398. if (array.count == 0) {
  1399. let alert = NSAlert()
  1400. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1401. alert.runModal()
  1402. return
  1403. }
  1404. }
  1405. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1406. self!.currentWindowController = nil
  1407. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  1408. if (indexs.count == 0) {
  1409. return
  1410. }
  1411. for i in indexs {
  1412. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  1413. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1414. self?.listView.add(redactAnno, to: page)
  1415. }
  1416. }
  1417. }
  1418. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1419. self.exeRedactConfirm(.redactOne) {}
  1420. }
  1421. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1422. self.exeRedactConfirm(.eraserOne) {}
  1423. }
  1424. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1425. }
  1426. @objc func exportStampImage(sender:NSMenuItem) {
  1427. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1428. var image : NSImage = NSImage()
  1429. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1430. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1431. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1432. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1433. }
  1434. let data = image.tiffRepresentation
  1435. if sender.tag == 0 {
  1436. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1437. imageRep.size = image.size
  1438. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1439. let savePanel = NSSavePanel()
  1440. savePanel.allowedFileTypes = ["png"]
  1441. savePanel.beginSheetModal(for: self.view.window!) { response in
  1442. if (response != .OK) {
  1443. return
  1444. }
  1445. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1446. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1447. }
  1448. }
  1449. } else {
  1450. let pdfdocument = CPDFDocument()
  1451. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1452. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1453. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1454. let savePanel = NSSavePanel()
  1455. savePanel.allowedFileTypes = ["pdf"]
  1456. savePanel.beginSheetModal(for: self.view.window!) { response in
  1457. if (response != .OK) {
  1458. return
  1459. }
  1460. if pdfdocument!.write(to: savePanel.url!) {
  1461. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. }
  1468. @objc func exportCorpImage(sender:NSMenuItem) {
  1469. let rect = NSIntegralRect(listView.currentSelectionRect())
  1470. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1471. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1472. page.setBounds(rect, for: .cropBox)
  1473. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1474. let data = image.tiffRepresentation
  1475. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1476. imageRep.size = rect.size
  1477. let savePanel = NSSavePanel()
  1478. switch sender.tag {
  1479. case 0:
  1480. savePanel.allowedFileTypes = ["png"]
  1481. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1482. savePanel.beginSheetModal(for: self.view.window!) { response in
  1483. if (response != .OK) {
  1484. return
  1485. }
  1486. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1487. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1488. }
  1489. }
  1490. case 1:
  1491. savePanel.allowedFileTypes = ["jpg"]
  1492. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1493. savePanel.beginSheetModal(for: self.view.window!) { response in
  1494. if (response != .OK) {
  1495. return
  1496. }
  1497. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1498. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1499. }
  1500. }
  1501. case 2:
  1502. savePanel.allowedFileTypes = ["pdf"]
  1503. let pdfdocument = CPDFDocument()
  1504. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1505. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1506. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1507. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1508. savePanel.beginSheetModal(for: self.view.window!) { response in
  1509. if (response != .OK) {
  1510. return
  1511. }
  1512. if pdfdocument!.write(to: savePanel.url!) {
  1513. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1514. }
  1515. }
  1516. }
  1517. default:
  1518. break
  1519. }
  1520. // 执行右键操作后,需要取消框选区域
  1521. if self.listView.toolMode == .selectToolMode {
  1522. objc_sync_enter(self)
  1523. self.listView.selectionRect = NSZeroRect
  1524. self.listView.selectionPageIndex = UInt(NSNotFound)
  1525. objc_sync_exit(self)
  1526. }
  1527. }
  1528. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1529. let rect = listView.currentSelectionRect()
  1530. let page = listView.currentPage()
  1531. if NSIsEmptyRect(rect) == false && page != nil {
  1532. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1533. var bounds = listView.bounds
  1534. var scale = 1.0
  1535. if isLegacy {
  1536. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1537. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1538. }
  1539. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1540. scale = NSHeight(bounds) / NSHeight(rect)
  1541. } else {
  1542. scale = NSWidth(bounds) / NSWidth(rect)
  1543. }
  1544. listView.setScaleFactor(scale, animated: false)
  1545. let scrollView = listView.scroll()
  1546. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1547. if ((scrollView?.hasVerticalScroller) != nil) {
  1548. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1549. }
  1550. if ((scrollView?.hasHorizontalScroller) != nil) {
  1551. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1552. }
  1553. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1554. scale = NSHeight(bounds) / NSHeight(rect)
  1555. } else {
  1556. scale = NSWidth(bounds) / NSWidth(rect)
  1557. }
  1558. listView.setScaleFactor(scale, animated: false)
  1559. }
  1560. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1561. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1562. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1563. };
  1564. }
  1565. // 执行右键操作后,需要取消框选区域
  1566. if self.listView.toolMode == .selectToolMode {
  1567. objc_sync_enter(self)
  1568. self.listView.selectionRect = NSZeroRect
  1569. self.listView.selectionPageIndex = UInt(NSNotFound)
  1570. objc_sync_exit(self)
  1571. }
  1572. }
  1573. private func cropPagesToRects(rects:NSPointerArray) {
  1574. }
  1575. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1576. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1577. switch sender.tag {
  1578. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1579. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1580. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1581. var red: CGFloat = 0.0
  1582. var green: CGFloat = 0.0
  1583. var blue: CGFloat = 0.0
  1584. var alpha: CGFloat = 0.0
  1585. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1586. if sender.tag == CAnnotationType.highlight.rawValue {
  1587. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1588. } else if sender.tag == CAnnotationType.underline.rawValue {
  1589. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1590. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1591. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1592. }
  1593. case CAnnotationType.ink.rawValue:
  1594. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1595. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1596. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1597. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1598. var red: CGFloat = 0.0
  1599. var green: CGFloat = 0.0
  1600. var blue: CGFloat = 0.0
  1601. var alpha: CGFloat = 0.0
  1602. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1603. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1604. case CAnnotationType.freeText.rawValue:
  1605. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1606. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1607. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1608. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1609. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1610. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1611. var red: CGFloat = 0.0
  1612. var green: CGFloat = 0.0
  1613. var blue: CGFloat = 0.0
  1614. var alpha: CGFloat = 0.0
  1615. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1616. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1617. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1618. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1619. UserDefaults.standard.synchronize()
  1620. }
  1621. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1622. if (alignment == .left || alignment == .center || alignment == .right) {
  1623. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1624. UserDefaults.standard.synchronize()
  1625. }
  1626. case CAnnotationType.anchored.rawValue:
  1627. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1628. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1629. var red: CGFloat = 0.0
  1630. var green: CGFloat = 0.0
  1631. var blue: CGFloat = 0.0
  1632. var alpha: CGFloat = 0.0
  1633. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1634. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1635. case CAnnotationType.square.rawValue:
  1636. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1637. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1638. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1639. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1640. var red: CGFloat = 0.0
  1641. var green: CGFloat = 0.0
  1642. var blue: CGFloat = 0.0
  1643. var alpha: CGFloat = 0.0
  1644. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1645. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1646. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1647. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1648. case CAnnotationType.circle.rawValue:
  1649. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1650. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1651. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1652. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1653. var red: CGFloat = 0.0
  1654. var green: CGFloat = 0.0
  1655. var blue: CGFloat = 0.0
  1656. var alpha: CGFloat = 0.0
  1657. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1658. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1659. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1660. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1661. default:
  1662. break
  1663. }
  1664. }
  1665. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1666. self.showOrHideNotes()
  1667. }
  1668. //MARK: - action
  1669. @objc func cropCurrentPage() {
  1670. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1671. var page: CPDFPage?
  1672. if let data = self.listView.currentSelectionPage() {
  1673. page = data
  1674. } else {
  1675. page = self.listView.currentPage()
  1676. }
  1677. if (NSIsEmptyRect(rect)) {
  1678. rect = KMCropTools.getPageForegroundBox(page!)
  1679. }
  1680. let index: UInt = (page?.pageIndex()) ?? 0
  1681. self._cropPage(at: index, in: rect)
  1682. // 执行右键操作后,需要取消框选区域
  1683. if self.listView.toolMode == .selectToolMode {
  1684. objc_sync_enter(self)
  1685. self.listView.selectionRect = NSZeroRect
  1686. self.listView.selectionPageIndex = UInt(NSNotFound)
  1687. objc_sync_exit(self)
  1688. }
  1689. self.handlePageBoundsDidChange(page: page, action: CPDFPage.Action.crop)
  1690. }
  1691. @objc private func _cropPage(at index: UInt, in rect: NSRect) {
  1692. let oldRect = self.listView?.document?.page(at: index)?.bounds(for: .cropBox) ?? .zero
  1693. let undoManager = self.listView.undoManager
  1694. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)?._cropPage(at: index, in: oldRect)
  1695. let page = self.listView.document.page(at: index)
  1696. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox)) ?? .zero)
  1697. page?.setBounds(newRect, for: .cropBox)
  1698. /// 刷新预览视图
  1699. self.listView.layoutDocumentView()
  1700. self.listView.displayBox = .cropBox
  1701. }
  1702. func beginProgressSheet(with message: String, maxValue: UInt) {
  1703. let progress = SKProgressController()
  1704. progress.window?.backgroundColor = NSColor.km_init(hex: "#ffffff")
  1705. progress.window?.contentView?.wantsLayer = true
  1706. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#ffffff").cgColor
  1707. progress.progressField.textColor = NSColor.black
  1708. progress.message = NSLocalizedString("Converting...", comment: "")
  1709. progressController = progress
  1710. progressController?.message = message
  1711. if maxValue > 0 {
  1712. progressController?.indeterminate = false
  1713. progressController?.maxValue = Double(maxValue)
  1714. } else {
  1715. progressController?.indeterminate = true
  1716. }
  1717. if maxValue > 0 {
  1718. progressController?.indeterminate = false
  1719. progressController?.maxValue = Double(maxValue)
  1720. } else {
  1721. progressController?.indeterminate = true
  1722. }
  1723. self.km_beginSheet(windowC: progressController!)
  1724. }
  1725. // 白边距
  1726. @objc func smart_cropAllPage() {
  1727. var size = NSZeroSize
  1728. for i in 0 ..< self.listView.document.pageCount {
  1729. let page = self.listView.document.page(at: i)
  1730. let rect = KMCropTools.getPageForegroundBox(page!)
  1731. size.width = fmax(size.width, NSWidth(rect))
  1732. size.height = fmax(size.height, NSHeight(rect))
  1733. }
  1734. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1735. var rectArray: Array<NSRect> = []
  1736. for i in 0 ..< self.listView.document.pageCount {
  1737. progressController?.increment(by: Double(i))
  1738. progressController?.doubleValue = Double(i)
  1739. let page = self.listView.document.page(at: i)
  1740. var rect = KMCropTools.getPageForegroundBox(page!)
  1741. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1742. // if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1743. // rect.origin.x = rect.maxX-size.width
  1744. // }
  1745. // rect.origin.y = rect.maxY-size.height
  1746. // rect.size = size
  1747. // if (NSWidth(rect) > NSWidth(bounds)) {
  1748. // rect.size.width = NSWidth(bounds)
  1749. // }
  1750. // if (NSHeight(rect) > NSHeight(bounds)) {
  1751. // rect.size.height = NSHeight(bounds)
  1752. // }
  1753. //
  1754. // if (NSMinX(rect) < NSMinX(bounds)) {
  1755. // rect.origin.x = NSMinX(bounds)
  1756. // } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1757. // rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1758. // }
  1759. //
  1760. // if (NSMinY(rect) < NSMinY(bounds)) {
  1761. // rect.origin.y = NSMinY(bounds)
  1762. // } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1763. // rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1764. // }
  1765. rectArray.append(rect)
  1766. }
  1767. cropPages(to: rectArray)
  1768. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1769. }
  1770. // 自动
  1771. @objc func auto_cropAllPage() {
  1772. var size = NSZeroSize
  1773. for i in 0 ..< self.listView.document.pageCount {
  1774. let page = self.listView.document.page(at: i)
  1775. let rect = KMCropTools.getPageForegroundBox(page!)
  1776. size.width = fmax(size.width, NSWidth(rect))
  1777. size.height = fmax(size.height, NSHeight(rect))
  1778. }
  1779. beginProgressSheet(with: KMLocalizedString("Cropping Pages", "Message for progress sheet"), maxValue: min(18, self.listView.document.pageCount))
  1780. var rectArray: Array<NSRect> = []
  1781. for i in 0 ..< self.listView.document.pageCount {
  1782. progressController?.increment(by: Double(i))
  1783. progressController?.doubleValue = Double(i)
  1784. let page = self.listView.document.page(at: i)
  1785. var rect = KMCropTools.getPageForegroundBox(page!)
  1786. let bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1787. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1788. rect.origin.x = rect.maxX-size.width
  1789. }
  1790. rect.origin.y = rect.maxY-size.height
  1791. rect.size = size
  1792. if (NSWidth(rect) > NSWidth(bounds)) {
  1793. rect.size.width = NSWidth(bounds)
  1794. }
  1795. if (NSHeight(rect) > NSHeight(bounds)) {
  1796. rect.size.height = NSHeight(bounds)
  1797. }
  1798. if (NSMinX(rect) < NSMinX(bounds)) {
  1799. rect.origin.x = NSMinX(bounds)
  1800. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1801. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1802. }
  1803. if (NSMinY(rect) < NSMinY(bounds)) {
  1804. rect.origin.y = NSMinY(bounds)
  1805. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1806. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1807. }
  1808. rectArray.append(rect)
  1809. }
  1810. cropPages(to: rectArray)
  1811. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1812. }
  1813. @objc func cropAllPage() {
  1814. var rect = [NSIntegralRect(self.listView?.currentSelectionRect() ?? .zero), .zero]
  1815. var rectArray: Array<NSRect> = []
  1816. let emptySelection = NSIsEmptyRect(rect.first ?? .zero)
  1817. if (emptySelection) {
  1818. guard let count = self.listView?.document?.pageCount, count > 0 else {
  1819. KMPrint("listView | document is nil.", beep: true)
  1820. return
  1821. }
  1822. rect[0] = .zero
  1823. rect[1] = .zero
  1824. self.beginProgressSheet(withMessage: NSLocalizedString("Cropping Pages", comment: "Message for progress sheet"), maxValue: min(18, count))
  1825. if (count == 1) {
  1826. if let page = self.listView.document.page(at: 0) {
  1827. rect[0] = KMCropTools.getPageForegroundBox(page)
  1828. }
  1829. progressController?.increment(by: 1)
  1830. } else if (count < 19) {
  1831. for i in 0 ..< 19 {
  1832. if let page = self.listView.document.page(at: UInt(i)) {
  1833. rect[i % 2] = NSUnionRect(rect[i % 2], KMCropTools.getPageForegroundBox(page))
  1834. progressController?.increment(by: Double(i))
  1835. }
  1836. }
  1837. } else {
  1838. let start = [1, (count - 5) / 2, count - 6]
  1839. var cnt = 0
  1840. for j in 0 ..< 3 {
  1841. for i in 0 ..< 6 {
  1842. let k = Int(start[j] + UInt(i))
  1843. if let page = self.listView.document.page(at: UInt(k)) {
  1844. rect[k % 2] = NSUnionRect(rect[k % 2], KMCropTools.getPageForegroundBox(page))
  1845. cnt += 1
  1846. progressController?.increment(by: Double(cnt))
  1847. }
  1848. }
  1849. }
  1850. }
  1851. let w = fmax(NSWidth(rect[0]), NSWidth(rect[1]))
  1852. let h = fmax(NSHeight(rect[0]), NSHeight(rect[1]))
  1853. for j in 0 ..< 2 {
  1854. rect[j] = NSMakeRect(floor(NSMidX(rect[j]) - 0.5 * w), floor(NSMidY(rect[j]) - 0.5 * h), w, h)
  1855. }
  1856. rectArray.append(rect.first ?? .zero)
  1857. rectArray.append(rect.last ?? .zero)
  1858. } else {
  1859. rectArray.append(rect.first ?? .zero)
  1860. }
  1861. self.cropPages(to: rectArray)
  1862. // 执行右键操作后,需要取消框选区域
  1863. if self.listView.toolMode == .selectToolMode {
  1864. objc_sync_enter(self)
  1865. self.listView.selectionRect = NSZeroRect
  1866. self.listView.selectionPageIndex = UInt(NSNotFound)
  1867. objc_sync_exit(self)
  1868. }
  1869. self.handlePageBoundsDidChange(page: nil, action: CPDFPage.Action.crop)
  1870. }
  1871. func cropPages(to rects: Array<NSRect>) {
  1872. let currentPage = self.listView.currentPage()
  1873. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1874. var oldRectArray: Array<NSRect> = []
  1875. let rectCount = rects.count
  1876. for i in 0 ..< self.listView.document.pageCount {
  1877. let page = self.listView.document.page(at: i)
  1878. let rect = NSIntersectionRect(rects[Int(i) % rectCount], (page?.bounds(for: .mediaBox))!)
  1879. let oldRect = page?.bounds(for: .cropBox)
  1880. oldRectArray.append(oldRect!)
  1881. page?.setBounds(rect, for: .cropBox)
  1882. }
  1883. let undoManager = self.listView.undoManager
  1884. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1885. /// 刷新预览视图
  1886. self.listView.layoutDocumentView()
  1887. self.listView.displayBox = .cropBox
  1888. self.listView.go(to: currentPage)
  1889. self.listView.go(to: visibleRect, on: currentPage)
  1890. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1891. self.dismissProgressSheet()
  1892. }
  1893. }
  1894. private func cropCustomArea() {
  1895. self.listView.toolMode = .selectToolMode
  1896. self.listView.autoScales = true
  1897. self.listView.autoScales = false
  1898. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1899. if (self.listView.displaysPageBreaks) {
  1900. pageHeight += 8
  1901. }
  1902. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1903. // if (scaleFactor < self.preView.scaleFactor) {
  1904. self.listView.scaleFactor = scaleFactor
  1905. // }
  1906. let tipView = KMCropTipView()
  1907. tipView.setString(string: "请框选裁剪区域")
  1908. tipView.frame = self.topTipBox.contentView!.frame
  1909. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1910. self.addTopTip(tipView)
  1911. tipView.enterAction = {
  1912. () in
  1913. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1914. if (NSIsEmptyRect(rect)) {
  1915. return
  1916. }
  1917. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1918. self.view.window?.beginSheet(window.window!)
  1919. self.cropSettingWindowController = window
  1920. window.itemClick = { [self]
  1921. (index: Int) in
  1922. if (index == 1) { /// 取消
  1923. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1924. self.cropSettingWindowController = nil
  1925. return
  1926. }
  1927. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1928. let pageCount: Int = Int(self.listView.document.pageCount)
  1929. var pages: Array<Int> = []
  1930. if (pageRangeType == 0) { /// 当前页面
  1931. pages.append(self.listView.currentPageIndex)
  1932. } else if (pageRangeType == 1) { /// 全部页面
  1933. for i in 0 ..< pageCount {
  1934. pages.append(i)
  1935. }
  1936. } else if (pageRangeType == 2) { /// 奇数页面
  1937. var string: String = ""
  1938. for i in 0 ..< pageCount {
  1939. if (i % 2 == 1) {
  1940. continue
  1941. }
  1942. pages.append(i)
  1943. }
  1944. } else if (pageRangeType == 3) { /// 偶数页面
  1945. var string: String = ""
  1946. for i in 0 ..< pageCount {
  1947. if (i % 2 == 0) {
  1948. continue
  1949. }
  1950. pages.append(i)
  1951. }
  1952. } else { /// 自定义
  1953. for i in self.cropSettingWindowController.pageRangePages {
  1954. pages.append(i)
  1955. }
  1956. }
  1957. if (pages.count < 0) {
  1958. let alert = NSAlert()
  1959. alert.messageText = "请选择页面"
  1960. alert.runModal()
  1961. return
  1962. }
  1963. var pageSize: NSSize = NSZeroSize
  1964. if (self.cropSettingWindowController.pageSize == "None") {
  1965. } else {
  1966. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1967. }
  1968. for i in pages {
  1969. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1970. var rect = NSIntegralRect(self.listView.selectionRect)
  1971. if (NSIsEmptyRect(rect)) {
  1972. rect = KMCropTools.getPageForegroundBox(page)
  1973. }
  1974. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1975. page.setBounds(newRect, for: .cropBox)
  1976. if (pageSize.width == 0 && pageSize.height == 0) {
  1977. } else {
  1978. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1979. let index: UInt = (page.pageIndex())
  1980. // let newPage: CPDFPage = nil
  1981. // self.listView.document.removePage(at: index)
  1982. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1983. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1984. let result = self.listView.document.insertPage(pageSize, at: index)
  1985. }
  1986. }
  1987. /// 保存到临时路径
  1988. let toPath: String = self.listView.document.documentURL.path
  1989. let documentPath = NSTemporaryDirectory()
  1990. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1991. if (FileManager.default.fileExists(atPath: tempPath)) {
  1992. try?FileManager.default.removeItem(atPath: tempPath)
  1993. }
  1994. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1995. if (result) {
  1996. if (FileManager.default.fileExists(atPath: toPath)) {
  1997. try?FileManager.default.removeItem(atPath: toPath)
  1998. }
  1999. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  2000. } else {
  2001. try?FileManager.default.removeItem(atPath: tempPath)
  2002. }
  2003. DispatchQueue.main.async {
  2004. self.listView.toolMode = .textToolMode
  2005. /// 刷新预览视图
  2006. self.listView.layoutDocumentView()
  2007. self.listView.displayBox = .cropBox
  2008. }
  2009. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  2010. self.cropSettingWindowController = nil
  2011. self.addTopTip(nil)
  2012. }
  2013. }
  2014. }
  2015. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  2016. if (limit) {
  2017. var doucumentURL : URL = self.listView.document.documentURL
  2018. if doucumentURL != nil {
  2019. let docDir = NSTemporaryDirectory()
  2020. let documentName : String = doucumentURL.path.lastPathComponent
  2021. let path = docDir.stringByAppendingPathComponent(documentName)
  2022. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2023. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2024. let writeSuccess = data != nil
  2025. if writeSuccess == false {
  2026. __NSBeep()
  2027. return;
  2028. }
  2029. doucumentURL = URL(fileURLWithPath: path)
  2030. }
  2031. let array = [doucumentURL]
  2032. let picker = NSSharingServicePicker.init(items: array)
  2033. if sender.shareButton.window != nil {
  2034. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2035. } else {
  2036. 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)
  2037. }
  2038. return
  2039. }
  2040. var doucumentURL : URL = self.listView.document.documentURL
  2041. if doucumentURL != nil {
  2042. let docDir = NSTemporaryDirectory()
  2043. let documentName : String = doucumentURL.path.lastPathComponent
  2044. let path = docDir.stringByAppendingPathComponent(documentName)
  2045. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  2046. if writeSuccess == false {
  2047. __NSBeep()
  2048. return;
  2049. }
  2050. doucumentURL = URL(fileURLWithPath: path)
  2051. }
  2052. let array = [doucumentURL]
  2053. let picker = NSSharingServicePicker.init(items: array)
  2054. if sender.shareButton.window != nil {
  2055. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2056. } else {
  2057. 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)
  2058. }
  2059. }
  2060. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  2061. if (limit) {
  2062. let document = self.listView.document ?? CPDFDocument()
  2063. var path = document!.documentURL.path
  2064. if path != nil {
  2065. let docDir = NSTemporaryDirectory()
  2066. let documentName : String = path.lastPathComponent
  2067. path = docDir.stringByAppendingPathComponent(documentName)
  2068. }
  2069. let pathFolder = path.fileURL.deletingLastPathComponent().path
  2070. var tfileName = path.deletingPathExtension.lastPathComponent
  2071. let tStdFileSuffix = "_flatten"
  2072. tfileName = tfileName + tStdFileSuffix + ".pdf"
  2073. path = pathFolder + "/" + tfileName
  2074. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  2075. let success = data != nil
  2076. if success {
  2077. let url = URL(fileURLWithPath: path)
  2078. let picker = NSSharingServicePicker.init(items: [url])
  2079. if sender.shareButton.window != nil {
  2080. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2081. } else {
  2082. 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)
  2083. }
  2084. }
  2085. return
  2086. }
  2087. let document = self.listView.document ?? CPDFDocument()
  2088. var path = document!.documentURL.path
  2089. if path != nil {
  2090. let docDir = NSTemporaryDirectory()
  2091. let documentName : String = path.lastPathComponent
  2092. path = docDir.stringByAppendingPathComponent(documentName)
  2093. }
  2094. let pathFolder = path.fileURL.deletingLastPathComponent().path
  2095. var tfileName = path.deletingPathExtension.lastPathComponent
  2096. let tStdFileSuffix = "_flatten"
  2097. tfileName = tfileName + tStdFileSuffix + ".pdf"
  2098. path = pathFolder + "/" + tfileName
  2099. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  2100. if success {
  2101. let url = URL(fileURLWithPath: path)
  2102. let picker = NSSharingServicePicker.init(items: [url])
  2103. if sender.shareButton.window != nil {
  2104. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2105. } else {
  2106. 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)
  2107. }
  2108. }
  2109. }
  2110. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  2111. if (limit) {
  2112. let document = self.listView.document ?? CPDFDocument()
  2113. var path = document!.documentURL.path
  2114. if path != nil {
  2115. let docDir = NSTemporaryDirectory()
  2116. let documentName : String = path.lastPathComponent
  2117. path = docDir.stringByAppendingPathComponent(documentName)
  2118. }
  2119. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2120. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  2121. var writeSuccess = data != nil
  2122. if writeSuccess == false {
  2123. __NSBeep()
  2124. return;
  2125. }
  2126. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  2127. for i in 0 ... newDocument.pageCount-1 {
  2128. let page = newDocument.page(at: i)
  2129. var annotations : [CPDFAnnotation] = []
  2130. for annotation in page!.annotations {
  2131. annotations.append(annotation)
  2132. }
  2133. for annotation in annotations {
  2134. annotation.page.removeAnnotation(annotation)
  2135. }
  2136. }
  2137. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  2138. if writeSuccess {
  2139. let url = URL(fileURLWithPath: path)
  2140. let picker = NSSharingServicePicker.init(items: [url])
  2141. if sender.shareButton.window != nil {
  2142. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2143. } else {
  2144. 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)
  2145. }
  2146. }
  2147. return
  2148. }
  2149. let document = self.listView.document ?? CPDFDocument()
  2150. var path = document!.documentURL.path
  2151. if path != nil {
  2152. let docDir = NSTemporaryDirectory()
  2153. let documentName : String = path.lastPathComponent
  2154. path = docDir.stringByAppendingPathComponent(documentName)
  2155. }
  2156. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  2157. if writeSuccess == false {
  2158. __NSBeep()
  2159. return;
  2160. }
  2161. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  2162. for i in 0 ... newDocument.pageCount-1 {
  2163. let page = newDocument.page(at: i)
  2164. var annotations : [CPDFAnnotation] = []
  2165. for annotation in page!.annotations {
  2166. annotations.append(annotation)
  2167. }
  2168. for annotation in annotations {
  2169. annotation.page.removeAnnotation(annotation)
  2170. }
  2171. }
  2172. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  2173. if writeSuccess {
  2174. let url = URL(fileURLWithPath: path)
  2175. let picker = NSSharingServicePicker.init(items: [url])
  2176. if sender.shareButton.window != nil {
  2177. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  2178. } else {
  2179. 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)
  2180. }
  2181. }
  2182. }
  2183. // 开启/关闭左边栏
  2184. @objc func toggleLeftPane() -> Void {
  2185. // if lastLeftPanWidth >= functionWidth {
  2186. leftPanelOpen = true
  2187. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  2188. // } else {
  2189. // leftPanelOpen = false
  2190. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2191. // }
  2192. }
  2193. // 开启左边栏
  2194. @objc func openLeftPane() -> Void {
  2195. leftPanelOpen = true
  2196. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  2197. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  2198. }
  2199. // 关闭左边栏
  2200. @objc func closeLeftPane() -> Void {
  2201. leftPanelOpen = false
  2202. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  2203. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = false
  2204. }
  2205. // 开启/关闭右边栏
  2206. @objc func toggleRightPane() -> Void {
  2207. if lastRightPanWidth > 5 {
  2208. self.rightPanelIsOpen = false
  2209. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  2210. } else {
  2211. self.rightPanelIsOpen = true
  2212. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  2213. }
  2214. }
  2215. @objc func openRightPane() -> Void {
  2216. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2217. if self.rightPanelIsOpen {
  2218. return
  2219. }
  2220. self.rightPanelIsOpen = true
  2221. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  2222. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  2223. }
  2224. }
  2225. @objc func closeRightPane() -> Void {
  2226. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  2227. self.rightPanelIsOpen = false
  2228. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  2229. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  2230. }
  2231. }
  2232. func rename(_ sender: NSNotification) -> Void {
  2233. if (self.view.window == nil || self.view.window!.isVisible == false) {
  2234. return
  2235. }
  2236. let tabController = sender.object as? CTTabController
  2237. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2238. let outputSavePanel = NSSavePanel()
  2239. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  2240. outputSavePanel.allowedFileTypes = ["pdf"]
  2241. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  2242. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  2243. let result = outputSavePanel.runModal()
  2244. if result == .OK {
  2245. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  2246. let fileURL = pdfDocument?.documentURL
  2247. let fileManager = FileManager.default
  2248. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  2249. var result = true
  2250. do {
  2251. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  2252. } catch {
  2253. result = false
  2254. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  2255. }
  2256. if (result) {
  2257. tabController?.title = outputSavePanel.url!.lastPathComponent
  2258. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  2259. self.isSaveKeyChain = false
  2260. newPdfDocument.unlock(withPassword: self.document?.password)
  2261. if (newPdfDocument.pageCount > 0) {
  2262. self.setDocument = newPdfDocument
  2263. }
  2264. }
  2265. }
  2266. } else {
  2267. outputSavePanel.close()
  2268. }
  2269. }
  2270. }
  2271. func showInFinder(_ sender: Any) -> Void {
  2272. if sender is NSNotification {
  2273. let tabController = (sender as! NSNotification).object as? CTTabController
  2274. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2275. let file: URL = (self.myDocument?.fileURL)!
  2276. if FileManager.default.fileExists(atPath: file.path) {
  2277. NSWorkspace.shared.activateFileViewerSelecting([file])
  2278. }
  2279. }
  2280. } else {
  2281. let file: URL = (self.myDocument?.fileURL)!
  2282. if FileManager.default.fileExists(atPath: file.path) {
  2283. NSWorkspace.shared.activateFileViewerSelecting([file])
  2284. }
  2285. }
  2286. }
  2287. func showOrHideNotes() {
  2288. self.listView.hideNotes = !self.listView.hideNotes
  2289. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  2290. //BOTA 注释列表显示隐藏
  2291. // self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2292. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  2293. }
  2294. func closeTab(_ sender: NSNotification) -> Void {
  2295. let tabController = sender.object as? CTTabController
  2296. if tabController?.title == self.document?.documentURL.lastPathComponent {
  2297. print("closeTab")
  2298. self.leftSideViewController.clearAnnotationFilterData()
  2299. self.leftSideViewController.clearNotification()
  2300. }
  2301. }
  2302. @IBAction func toggleSplitPDF(_ sender: Any) {
  2303. if let menuItem = sender as? NSMenuItem {
  2304. splitView(withTag: menuItem.tag)
  2305. }
  2306. }
  2307. @IBAction func readMode(_ sender: Any) {
  2308. isReadMode = !isReadMode
  2309. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  2310. UserDefaults.standard.synchronize()
  2311. if isReadMode {
  2312. CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2313. } else {
  2314. CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: (view.window?.contentView)!, withStyle: .black)
  2315. }
  2316. }
  2317. func handlePageBoundsDidChange(page: CPDFPage?, action: String) {
  2318. // NSDictionary *info = [notification userInfo];
  2319. // PDFPage *page = [info objectForKey:SKPDFPagePageKey];
  2320. // NSString *action = [info objectForKey:SKPDFPageActionKey];
  2321. // BOOL displayChanged = [action isEqualToString:SKPDFPageActionCrop] == NO || [pdfView displayBox] == kPDFDisplayBoxCropBox;
  2322. let displayChanged = action == CPDFPage.Action.crop || self.listView.displayBox == .cropBox
  2323. // if self.listView.displayBox == .cropBox {
  2324. // KMPrint("cropBox")
  2325. // } else if self.listView.displayBox == .artBox {
  2326. // KMPrint("artBox")
  2327. // } else if self.listView.displayBox == .trimBox {
  2328. // KMPrint("trimBox")
  2329. // } else if self.listView.displayBox == .bleedBox {
  2330. // KMPrint("bleedBox")
  2331. // } else if self.listView.displayBox == .mediaBox {
  2332. // KMPrint("mediaBox")
  2333. // } else {
  2334. // KMPrint("other \(self.listView.displayBox.rawValue)")
  2335. // }
  2336. if (displayChanged) {
  2337. self.listView.layoutDocumentView()
  2338. }
  2339. if (page != nil) {
  2340. let idx = page!.pageIndex()
  2341. if (displayChanged) {
  2342. self.leftSideViewController.updateThumbnail(at: Int(idx))
  2343. }
  2344. } else {
  2345. if (displayChanged) {
  2346. self.leftSideViewController.allThumbnailsNeedUpdate()
  2347. }
  2348. }
  2349. self.leftSideViewController.updateSnapshotsIfNeed(for: page)
  2350. // [secondaryPdfView requiresDisplay];
  2351. self.secondaryPdfView?.setNeedsDisplayForVisiblePages()
  2352. //
  2353. if UserDefaults.standard.bool(forKey: SKDisplayPageBoundsKey) {
  2354. // [self updateRightStatus];
  2355. }
  2356. }
  2357. func changeLineAttribute(_ sender: Any?) {
  2358. var inspector = sender as? KMLineInspector
  2359. if inspector == nil {
  2360. inspector = KMLineInspector.shared
  2361. }
  2362. let action = inspector?.currentLineChangeAction ?? .no
  2363. for annotation in self.listView.activeAnnotations {
  2364. guard let anno = annotation as? CPDFAnnotation else {
  2365. continue
  2366. }
  2367. if anno.hasBorder() {
  2368. // if (mwcFlags.updatingLine == 0 && [annotation hasBorder]) {
  2369. // mwcFlags.updatingLine = 1;
  2370. switch (action) {
  2371. case .lineWidth:
  2372. anno.setLineWidth(inspector?.lineWidth ?? 0)
  2373. break
  2374. case .style:
  2375. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  2376. break
  2377. case .dashPattern:
  2378. anno.setDashPattern(inspector?.dashPattern ?? [])
  2379. break
  2380. case .startLineStyle:
  2381. if anno.isLine() {
  2382. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  2383. }
  2384. break
  2385. case .endLineStyle:
  2386. if anno.isLine() {
  2387. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  2388. }
  2389. break
  2390. case .no:
  2391. break
  2392. }
  2393. // mwcFlags.updatingLine = 0;
  2394. // in case one property changes another, e.g. when adding a dashPattern the borderStyle can change
  2395. }
  2396. }
  2397. // [self updateLineInspector];
  2398. }
  2399. // MARK: -
  2400. // MARK: 显示窗口
  2401. internal func showCompressWindow(url: URL? = nil) {
  2402. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  2403. KMPrint("压缩窗口已显示")
  2404. return
  2405. }
  2406. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  2407. self.view.window?.beginSheet(windowController.window!)
  2408. self.currentWindowController = windowController
  2409. windowController.password = self.listView?.document?.password ?? ""
  2410. // if let _url = url {
  2411. // windowController.oriDocumentUrl = self.listView.document.documentURL
  2412. // windowController.documentURL = _url
  2413. // } else {
  2414. windowController.documentURL = self.listView.document.documentURL
  2415. // }
  2416. windowController.itemClick = { [weak self] in
  2417. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2418. self?.currentWindowController = nil
  2419. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2420. }
  2421. windowController.batchAction = { [weak self] view, filePaths in
  2422. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2423. self?.currentWindowController = nil
  2424. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2425. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2426. // batchWindowController.window?.makeKeyAndOrderFront("")
  2427. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  2428. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  2429. batchWindowController.window?.makeKeyAndOrderFront("")
  2430. }
  2431. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  2432. if (result) {
  2433. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2434. self?.currentWindowController = nil
  2435. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2436. if (openDocument) {
  2437. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  2438. } else {
  2439. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  2440. }
  2441. } else {
  2442. let alert = NSAlert()
  2443. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  2444. alert.runModal()
  2445. }
  2446. }
  2447. }
  2448. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  2449. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  2450. KMPrint("转档窗口已显示")
  2451. return
  2452. }
  2453. var convertT: KMConvertType = .Word
  2454. var windowController: KMConvertBaseWindowController?
  2455. if (type == .word) { /// Word
  2456. convertT = .Word
  2457. } else if (type == .excel) {
  2458. convertT = .Excel
  2459. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  2460. if (type == .ppt) {
  2461. convertT = .PPT
  2462. } else if (type == .rtf) {
  2463. convertT = .RTF
  2464. } else if (type == .html) {
  2465. convertT = .HTML
  2466. } else if (type == .conversion_text) {
  2467. convertT = .Text
  2468. }
  2469. } else if (type == .csv) {
  2470. convertT = .CSV
  2471. } else if (type == .conversion_image) {
  2472. windowController = KMConvertImageWindowController()
  2473. convertT = .JPEG
  2474. }
  2475. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  2476. var url: URL?
  2477. if (documentUrl != nil) {
  2478. url = documentUrl
  2479. windowController?.oriDocumentUrl = self.listView.document.documentURL
  2480. } else {
  2481. url = self.listView.document.documentURL
  2482. }
  2483. self.showAllConvertWindow(convertT: convertT)
  2484. }
  2485. //MARK: 转档 -
  2486. func showAllConvertWindow(convertT: KMConvertType) {
  2487. self.ConvertTrackEvent(type: convertT)
  2488. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  2489. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  2490. var type: KMConvertWithPDFType = .WordAdvance
  2491. switch convertT {
  2492. case .Word:
  2493. break
  2494. case .Excel:
  2495. type = .Excel
  2496. case .PPT:
  2497. type = .PowerPoint
  2498. case .RTF:
  2499. type = .RTF
  2500. case .CSV:
  2501. type = .CSV
  2502. case .HTML:
  2503. type = .HTML
  2504. case .Text:
  2505. type = .Text
  2506. case .JPEG:
  2507. type = .JPEG
  2508. case .PNG:
  2509. type = .PNG
  2510. case .GIF:
  2511. type = .GIF
  2512. case .JPG:
  2513. type = .JPG
  2514. case .TIFF:
  2515. type = .TIFF
  2516. case .TGA:
  2517. type = .TGA
  2518. case .BMP:
  2519. type = .BMP
  2520. case .JP2:
  2521. type = .JPEG2000
  2522. case .AdvancedWord:
  2523. break
  2524. default:
  2525. break
  2526. }
  2527. // let document = self.document
  2528. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2529. var needShowHint = false
  2530. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  2531. needShowHint = true
  2532. } else {
  2533. var needContinue = false
  2534. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  2535. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  2536. let ss = self.document?.documentURL.path
  2537. if arr.contains(ss!) {
  2538. needContinue = false
  2539. }else {
  2540. needContinue = true
  2541. }
  2542. }else {
  2543. needContinue = true
  2544. }
  2545. if needContinue {
  2546. let ss = self.document?.documentURL.path
  2547. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  2548. file.password = document?.password ?? ""
  2549. KMBatchOperateManager.defaultManager.files?.append(file)
  2550. }
  2551. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  2552. batchWindowController.switchToConvertType(convertType: type)
  2553. }
  2554. batchWindowController.window?.makeKeyAndOrderFront(nil)
  2555. if needShowHint {
  2556. batchWindowController.showIsConvertingHint()
  2557. } else {
  2558. }
  2559. }
  2560. }
  2561. self.km_beginSheet(windowC: convertWC)
  2562. }
  2563. func ConvertTrackEvent(type: KMConvertType) {
  2564. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  2565. switch type {
  2566. case .Word:
  2567. eventStr = "Btn_SubTbr_Converter_ToWord"
  2568. break
  2569. case .Excel:
  2570. eventStr = "Btn_SubTbr_Converter_ToExcel"
  2571. case .PPT:
  2572. eventStr = "Btn_SubTbr_Converter_ToPPT"
  2573. case .RTF:
  2574. eventStr = "Btn_SubTbr_Converter_ToRTF"
  2575. case .CSV:
  2576. eventStr = "Btn_SubTbr_Converter_ToCSV"
  2577. case .HTML:
  2578. eventStr = "Btn_SubTbr_Converter_ToHTML"
  2579. case .Text:
  2580. eventStr = "Btn_SubTbr_Converter_ToText"
  2581. case .JPEG:
  2582. eventStr = "Btn_SubTbr_Converter_ToImage"
  2583. case .PNG:
  2584. eventStr = "Btn_SubTbr_Converter_ToImage"
  2585. case .GIF:
  2586. eventStr = "Btn_SubTbr_Converter_ToImage"
  2587. case .JPG:
  2588. eventStr = "Btn_SubTbr_Converter_ToImage"
  2589. case .TIFF:
  2590. eventStr = "Btn_SubTbr_Converter_ToImage"
  2591. case .TGA:
  2592. eventStr = "Btn_SubTbr_Converter_ToImage"
  2593. case .BMP:
  2594. eventStr = "Btn_SubTbr_Converter_ToImage"
  2595. case .JP2:
  2596. eventStr = "Btn_SubTbr_Converter_ToImage"
  2597. case .AdvancedWord:
  2598. eventStr = "Btn_SubTbr_Converter_ToWord"
  2599. break
  2600. default:
  2601. break
  2602. }
  2603. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  2604. }
  2605. //MARK: 转档 - OCR
  2606. func showOCRWindow() {
  2607. if !IAPProductsManager.default().isAvailableAllFunction(){
  2608. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2609. return
  2610. }
  2611. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  2612. self.km_beginSheet(windowC: com)
  2613. }
  2614. //MARK: 数字签名
  2615. func hasShowDigitalSign() -> Bool {
  2616. return self.digitalSignController?.view.superview != nil
  2617. }
  2618. func exitDigitalSign() {
  2619. self.digitalSignController?.view.removeFromSuperview()
  2620. self.digitalSignController = nil
  2621. }
  2622. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  2623. if !IAPProductsManager.default().isAvailableAllFunction(){
  2624. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2625. return
  2626. }
  2627. if hasShowDigitalSign() {
  2628. self.exitDigitalSign()
  2629. }
  2630. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  2631. var password: String = ""
  2632. self.toolbarController.toolbarType = .None
  2633. if digitalSignController == nil {
  2634. password = listView.document?.password ?? ""
  2635. digitalSignController = KMPDFDigitalSignViewController()
  2636. }
  2637. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  2638. digitalSignController?.url = listView.document.documentURL
  2639. digitalSignController?.password = password
  2640. digitalSignController?.scaleFactor = listView.scaleFactor
  2641. digitalSignController?.titleChangeBlock = { [weak self] title, index in
  2642. currentPageIndex = UInt(index)
  2643. }
  2644. digitalSignController?.buttonActionBlock = { [unowned self] type, isChanged in
  2645. if type == .cancel {
  2646. // self.toolbarController?.digitalSignModeButtonAction(nil)
  2647. if let page = self.listView.document?.page(at: currentPageIndex) {
  2648. self.listView.go(to: page)
  2649. }
  2650. self.digitalSignController?.view.removeFromSuperview()
  2651. self.digitalSignController = nil
  2652. }
  2653. }
  2654. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  2655. digitalSignView.frame = splitViewSuperview.bounds
  2656. digitalSignView.autoresizingMask = [.width, .height]
  2657. splitViewSuperview.addSubview(digitalSignView)
  2658. }
  2659. }
  2660. //MARK: 导出图片
  2661. func extractImageAction(num: Int) {
  2662. if !IAPProductsManager.default().isAvailableAllFunction(){
  2663. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2664. return
  2665. }
  2666. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  2667. let alert = NSAlert()
  2668. alert.alertStyle = .critical
  2669. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2670. alert.runModal()
  2671. return
  2672. }
  2673. // if sender is KMToolbarItem {
  2674. // (sender as! KMToolbarItem).isSelected = false
  2675. // }
  2676. let document = self.listView.document
  2677. var fileURL = document?.documentURL
  2678. if num == 1 {
  2679. let pageCount = self.document?.pageCount ?? 0
  2680. var indeSet = NSMutableIndexSet()
  2681. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  2682. if indeSet.count == 0 {
  2683. return
  2684. }
  2685. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  2686. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  2687. let outputSavePanel = NSSavePanel()
  2688. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  2689. outputSavePanel.allowsOtherFileTypes = true
  2690. outputSavePanel.isExtensionHidden = true
  2691. outputSavePanel.canCreateDirectories = true
  2692. outputSavePanel.nameFieldStringValue = tFileName
  2693. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  2694. if result == NSApplication.ModalResponse.OK {
  2695. DispatchQueue.main.async {
  2696. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  2697. let tDestFile = outputSavePanel.url!.path
  2698. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  2699. let pdfconverter = PDFConvertObject()
  2700. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  2701. self.dismissProgressSheet()
  2702. let fileManager = FileManager.default
  2703. if fileManager.fileExists(atPath: tDestFile) {
  2704. let workspace = NSWorkspace.shared
  2705. let url = URL(fileURLWithPath: tDestFile)
  2706. workspace.activateFileViewerSelecting([url])
  2707. }
  2708. }
  2709. }
  2710. })
  2711. return
  2712. }
  2713. if fileURL != nil {
  2714. self.myDocument?.save(nil)
  2715. } else {
  2716. let myDocument = self.myDocument
  2717. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  2718. let writeSuccess = self.document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2719. if writeSuccess {
  2720. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  2721. fileURL = self.document?.documentURL
  2722. } else {
  2723. NSSound.beep()
  2724. return
  2725. }
  2726. }
  2727. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  2728. extract.docPath = fileURL?.path ?? ""
  2729. extract.password = document?.password ?? ""
  2730. extract.currentPage = self.listView.currentPageIndex
  2731. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  2732. self.km_beginSheet(windowC: extract)
  2733. extract.selectCurrentPageBtn()
  2734. // self.showCreateStamp()
  2735. // self.showAddSignature()
  2736. }
  2737. //MARK: 创建文字图章示例实际上不会在这里使用
  2738. func showCreateStamp() {
  2739. let stampCreaterWindowController = KMStampCreaterWindowController()
  2740. stampCreaterWindowController.window?.backgroundColor = .clear
  2741. self.km_beginSheet(windowC: stampCreaterWindowController)
  2742. stampCreaterWindowController.beginSheetModal(for: self.view.window) { [weak self] result in
  2743. if result == 1 {
  2744. }
  2745. }
  2746. }
  2747. //MARK: 添加签名示例实际上不会在这里使用
  2748. func showAddSignature() {
  2749. let signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")//[[KMSignatureWindowController alloc] initWithWindowNibName:@"KMSignatureWindowController"];
  2750. // signatureWindowController.window?.backgroundColor = .clear
  2751. signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  2752. }
  2753. }
  2754. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  2755. // if progressController == nil {
  2756. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  2757. // }
  2758. let progress = SKProgressController()
  2759. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2760. progress.window?.contentView?.wantsLayer = true
  2761. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2762. progress.progressField.textColor = NSColor.white
  2763. progress.message = NSLocalizedString("Converting...", comment: "")
  2764. progressController = progress
  2765. progressController?.message = message
  2766. if maxValue > 0 {
  2767. progressController?.indeterminate = false
  2768. progressController?.maxValue = Double(maxValue)
  2769. } else {
  2770. progressController?.indeterminate = true
  2771. }
  2772. self.km_beginSheet(windowC: progressController!)
  2773. }
  2774. func dismissProgressSheet() {
  2775. progressController?.stopAnimation()
  2776. self.km_endSheet()
  2777. progressController = nil
  2778. }
  2779. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2780. let newArr = NSMutableArray()
  2781. for item in files {
  2782. newArr.add(item.filePath)
  2783. }
  2784. return newArr as! [String]
  2785. }
  2786. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2787. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2788. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2789. if (result == .cancel) {
  2790. return
  2791. }
  2792. // 解除权限
  2793. self?.listView.document.unlock(withPassword: password)
  2794. // 隐藏提示
  2795. self?.hiddenSecureLimitTip()
  2796. // 去打印
  2797. if let data = self?.saveWatermarkFlag, !data {
  2798. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2799. return
  2800. }
  2801. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2802. _ = CPDFDocument(url: _url)
  2803. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2804. } else {
  2805. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2806. }
  2807. }
  2808. return
  2809. }
  2810. if (!self.saveWatermarkFlag) {
  2811. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2812. return
  2813. }
  2814. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2815. let _document = CPDFDocument(url: _url)
  2816. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2817. } else {
  2818. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2819. }
  2820. }
  2821. // MARK: - 图片注释
  2822. @IBAction func imageAnnotation(_ sender: Any) {
  2823. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  2824. changeAnnotationMode(sender)
  2825. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2826. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2827. return
  2828. }
  2829. let accessoryCtr = KMImageAccessoryController()
  2830. let openPanel = NSOpenPanel()
  2831. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  2832. openPanel.allowsMultipleSelection = false
  2833. openPanel.accessoryView = accessoryCtr.view
  2834. // if #available(macOS 10.11, *) {
  2835. openPanel.canSelectHiddenExtension = true
  2836. // }
  2837. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  2838. if result == .OK {
  2839. guard let url = openPanel.url else {
  2840. return
  2841. }
  2842. let filePath = url.path
  2843. if filePath.pathExtension.lowercased() == "pdf" {
  2844. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  2845. NSSound.beep()
  2846. return
  2847. }
  2848. }
  2849. let image = NSImage(contentsOfFile: url.path)
  2850. let isDamageImage: Bool = self.isDamageImage(image!, imagePath: url.path)
  2851. if isDamageImage {
  2852. let alert = NSAlert()
  2853. alert.alertStyle = .critical
  2854. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2855. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2856. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2857. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2858. if response == .alertFirstButtonReturn {
  2859. // Handle cancel button clicked
  2860. }
  2861. }
  2862. }
  2863. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2864. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2865. }
  2866. }
  2867. }
  2868. @IBAction func tableAnnotation(_ sender: Any) {
  2869. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2870. changeAnnotationMode(sender)
  2871. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2872. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2873. return
  2874. }
  2875. listView.addAnnotationWithTable()
  2876. openRightPane()
  2877. }
  2878. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2879. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2880. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2881. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2882. }
  2883. if let data = image.tiffRepresentation,
  2884. let imageRep = NSBitmapImageRep(data: data) {
  2885. imageRep.size = image.size
  2886. var imageData: Data?
  2887. if path.lowercased() == "png" {
  2888. imageData = imageRep.representation(using: .png, properties: [:])
  2889. } else {
  2890. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2891. }
  2892. if let imageData = imageData {
  2893. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2894. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2895. return true
  2896. } else {
  2897. return false
  2898. }
  2899. }
  2900. }
  2901. return false
  2902. }
  2903. func tagString() -> String {
  2904. let dateFormatter = DateFormatter()
  2905. dateFormatter.dateFormat = "yyMMddHHmmss"
  2906. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2907. }
  2908. // MARK: - Split View
  2909. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2910. }
  2911. @objc func removeSecondaryPdfContentView(_ sender: Notification?) {
  2912. if let _ = sender {
  2913. NotificationCenter.default.removeObserver(self, name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2914. }
  2915. self.secondaryPdfContentView?.removeFromSuperview()
  2916. self.newPDFSplitView.adjustSubviews()
  2917. }
  2918. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2919. if !isSinglePage && isHorizontal {
  2920. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2921. }
  2922. if (!isSinglePage && !isHorizontal) {
  2923. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2924. }
  2925. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2926. }
  2927. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2928. if isSinglePage {
  2929. if self.newPDFSplitView.animating {
  2930. return
  2931. }
  2932. if self.secondaryPdfContentView?.window != nil {
  2933. self.lastSplitPDFHeight = self.lastSplitPDFHeightFloat(self.secondaryPdfContentView?.frame ?? .zero)
  2934. self.newPDFSplitView.setPosition(self.newPDFSplitView.maxPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: true)
  2935. if self.newPDFSplitView.animating {
  2936. NotificationCenter.default.addObserver(self, selector: #selector(removeSecondaryPdfContentView), name: KMSplitView.animationDidEndNotification, object: self.newPDFSplitView)
  2937. } else {
  2938. self.removeSecondaryPdfContentView(nil)
  2939. }
  2940. }
  2941. self.view.window?.recalculateKeyViewLoop()
  2942. if self.interactionMode == .legacyFullScreen {
  2943. self.view.window?.makeFirstResponder(self.listView)
  2944. }
  2945. } else {
  2946. if self.newPDFSplitView.animating {
  2947. return
  2948. }
  2949. self.newPDFSplitView.dividerStyle = .paneSplitter
  2950. self.newPDFSplitView.isVertical = isHorizontal
  2951. if self.secondaryPdfView?.window == nil {
  2952. let frame = self.newPDFSplitView.bounds
  2953. if (self.lastSplitPDFHeight <= 0.0) {
  2954. var DEFAULT_SPLIT_PDF_FACTOR: Float = 0.3
  2955. self.lastSplitPDFHeight = floorf(DEFAULT_SPLIT_PDF_FACTOR * self.lastSplitPDFHeightFloat(frame))
  2956. }
  2957. var position = self.lastSplitPDFHeightFloat(frame)-self.lastSplitPDFHeight-Float(self.newPDFSplitView.dividerThickness)
  2958. var point: NSPoint = .zero
  2959. var page: CPDFPage?
  2960. self.newPDFSplitView.setPosition(position.cgFloat, ofDividerAt: 0, animate: true)
  2961. if (self.secondaryPdfContentView == nil) {
  2962. // secondaryPdfContentView = [[SKGradientView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 200.0, 20.0)];
  2963. self.secondaryPdfContentView = NSView(frame: NSMakeRect(0, 0, 200, 20))
  2964. self.secondaryPdfView = KMSecondaryPDFView(frame: self.secondaryPdfContentView?.bounds ?? .zero)
  2965. self.secondaryPdfView?.autoresizingMask = [.width, .height]
  2966. // self.secondaryPdfContentView?.isHidden = true
  2967. self.secondaryPdfContentView?.addSubview(self.secondaryPdfView!)
  2968. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  2969. // self.newPDFSplitView.addArrangedSubview(self.secondaryPdfContentView!)
  2970. // // Because of a PDFView bug, display properties can not be changed before it is placed in a window
  2971. self.secondaryPdfView?.synchronizedPDFView = self.listView
  2972. self.secondaryPdfView?.backgroundColor = self.listView.backgroundColor
  2973. // [secondaryPdfView applyDefaultPageBackgroundColor];
  2974. self.secondaryPdfView?.displaysPageBreaks = false
  2975. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  2976. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  2977. self.secondaryPdfView?.setGreekingThreshold(KMPreference.shared.greekThreshold.cgFloat)
  2978. self.secondaryPdfView?.setSynchronizeZoom(true)
  2979. // // [secondaryPdfView setDocument:[pdfView document]];
  2980. point = NSMakePoint(NSMinX(frame), NSMaxY(frame) - position.cgFloat - self.newPDFSplitView.dividerThickness)
  2981. page = self.listView.page(for: point, nearest: true)
  2982. //
  2983. let controlView = self.secondaryPdfView?.controlView
  2984. var color = NSColor(calibratedWhite: 0.97, alpha: 1.0)
  2985. if KMAppearance.isDarkMode() {
  2986. color = KMAppearance.Layout.l0Color()
  2987. }
  2988. // [(SKGradientView *)secondaryPdfContentView setGradient:[[[NSGradient alloc] initWithStartingColor:color endingColor:color] autorelease]];
  2989. // [(SKGradientView *)secondaryPdfContentView setAlternateGradient:nil];
  2990. var pdfRect: NSRect = .zero
  2991. var controlRect: NSRect = .zero
  2992. NSDivideRect(self.secondaryPdfContentView?.bounds ?? .zero, &controlRect, &pdfRect, NSHeight(controlView?.frame ?? .zero), .minY)
  2993. controlRect.size.width = NSWidth(controlView?.frame ?? .zero)
  2994. controlView?.frame = controlRect
  2995. controlView?.autoresizingMask = [.maxXMargin, .maxYMargin, .width]
  2996. // [(SKGradientView *)secondaryPdfContentView setMinSize:controlRect.size];
  2997. self.secondaryPdfView?.frame = pdfRect
  2998. self.secondaryPdfContentView?.addSubview(controlView!)
  2999. self.openSecondaryPdfView = KMSecondaryViewController()
  3000. self.openSecondaryPdfView?.view.frame = self.secondaryPdfContentView?.frame ?? .zero
  3001. self.secondaryPdfContentView?.addSubview(self.openSecondaryPdfView!.view)
  3002. self.openSecondaryPdfView?.secondaryView.receivedFileUrlBlock = { [weak self] fileUrl in
  3003. if let docUrl = fileUrl {
  3004. _ = self?.displaySecondaryPDFView(withUrl: docUrl)
  3005. self?.openSecondaryPdfView?.view.removeFromSuperview()
  3006. self?.openSecondaryPdfView = nil
  3007. }
  3008. }
  3009. self.openSecondaryPdfView?.delegate = self
  3010. if (!isHorizontal) {
  3011. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  3012. }
  3013. } else {
  3014. self.secondaryPdfContentView?.isHidden = true
  3015. self.newPDFSplitView.addSubview(self.secondaryPdfContentView!)
  3016. }
  3017. // self.newPDFSplitView.setPosition(self.secondaryPdfContentView?.bounds.size.width ?? 120, ofDividerAt: 1, animate: true)
  3018. if (page != nil) {
  3019. self.secondaryPdfView?.go(toPageIndex: Int(page!.pageIndex()), animated: false)
  3020. // point = [secondaryPdfView convertPoint:[secondaryPdfView convertPoint:[pdfView convertPoint:point toPage:page] fromPage:page] toView:[secondaryPdfView documentView]];
  3021. let tmpP = self.listView.convert(point, to: page)
  3022. let conP = self.secondaryPdfView?.convert(tmpP, from: page) ?? .zero
  3023. point = self.secondaryPdfView?.convert(conP, to: self.secondaryPdfView?.documentView()) ?? .zero
  3024. if let docView = self.secondaryPdfView?.documentView(), docView.contentView.isFlipped == false {
  3025. point.y -= docView.isFlipped ? -NSHeight(docView.visibleRect) : NSHeight(docView.visibleRect)
  3026. }
  3027. self.secondaryPdfView?.documentView()?.scroll(point)
  3028. self.secondaryPdfView?.layoutDocumentView()
  3029. }
  3030. }
  3031. self.view.window?.recalculateKeyViewLoop()
  3032. if self.interactionMode == .legacyFullScreen {
  3033. self.view.window?.makeFirstResponder(self.listView)
  3034. }
  3035. if self.secondaryPdfView?.document == nil {
  3036. self.openSecondaryPdfView?.viewHighlyAdaptive()
  3037. }
  3038. }
  3039. }
  3040. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  3041. if (self.newPDFSplitView.isVertical) {
  3042. return Float(NSWidth(rect))
  3043. } else {
  3044. return Float(NSHeight(rect))
  3045. }
  3046. }
  3047. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  3048. let document = CPDFDocument.init(url: url)
  3049. if document != nil {
  3050. self.secondaryPdfView?.document = nil
  3051. self.secondaryPdfView?.document = document
  3052. return true
  3053. } else {
  3054. return false
  3055. }
  3056. }
  3057. func updateNextAndPreViousButtonState() {
  3058. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3059. let view = item?.customizeView as? KMToolbarPreviousNextItemView
  3060. if let can = self.listView?.canGoToPreviousPage() {
  3061. view?.previousButton.isEnabled = can
  3062. } else {
  3063. view?.previousButton.isEnabled = false
  3064. }
  3065. if let can = self.listView?.canGoToNextPage() {
  3066. view?.nextButton.isEnabled = can
  3067. } else {
  3068. view?.nextButton.isEnabled = false
  3069. }
  3070. }
  3071. func updateBackAndForwardButtonState() {
  3072. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  3073. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  3074. if self.listView.km_canGoBack() {
  3075. item?.unEnabled = false
  3076. } else {
  3077. item?.unEnabled = true
  3078. }
  3079. if self.listView.km_canGoForward() {
  3080. toItem?.unEnabled = false
  3081. } else {
  3082. toItem?.unEnabled = true
  3083. }
  3084. }
  3085. func updateZoomInOutButtonState() {
  3086. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  3087. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  3088. if self.listView.canZoomIn {
  3089. item.unEnabled = false
  3090. } else {
  3091. item.unEnabled = true
  3092. }
  3093. if self.listView.canZoomOut {
  3094. toItem.unEnabled = false
  3095. } else {
  3096. toItem.unEnabled = true
  3097. }
  3098. }
  3099. }
  3100. // MARK: -
  3101. // MARK: - KMSecondaryViewControllerDelegate
  3102. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  3103. func receivedFileUrl(_ url: URL!) {
  3104. let state = self.displaySecondaryPDFView(withUrl: url)
  3105. if !state {
  3106. let alert = NSAlert()
  3107. alert.alertStyle = .critical
  3108. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3109. alert.runModal()
  3110. return
  3111. } else {
  3112. self.openSecondaryPdfView?.view.removeFromSuperview()
  3113. self.openSecondaryPdfView = nil
  3114. }
  3115. }
  3116. func controllerDidClose(_ controller: KMSecondaryViewController!) {
  3117. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  3118. }
  3119. }
  3120. // MARK: -
  3121. // MARK: - KMMainToolbarControllerDelegate
  3122. extension KMMainViewController : KMMainToolbarControllerDelegate {
  3123. func changeModelAction(mode: CToolMode) {
  3124. self.listView.toolMode = mode
  3125. if mode == .editPDFToolMode {
  3126. self.childToolbarController.updateType(newType: .editPDF)
  3127. }
  3128. }
  3129. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  3130. switch selectedTag {
  3131. case 2:
  3132. if self.listView.scaleFactor != 1.0 {
  3133. self.listView.scaleFactor = 1.0
  3134. self.listView.autoScales = false
  3135. }
  3136. break
  3137. case 1:
  3138. let pageHeight = self.listView.currentPage()!.size.height
  3139. let pdfviewHeight = self.listView.bounds.size.height
  3140. self.listView.scaleFactor = pdfviewHeight/pageHeight
  3141. self.listView.autoScales = false
  3142. break
  3143. case 0:
  3144. // self.listView.autoScales = !self.listView.autoScales
  3145. self.listView.autoScales = true
  3146. break
  3147. case 3:
  3148. self.listView.scaleFactor = 0.1
  3149. break
  3150. case 4:
  3151. self.listView.scaleFactor = 0.25
  3152. break
  3153. case 5:
  3154. self.listView.scaleFactor = 0.5
  3155. break
  3156. case 6:
  3157. self.listView.scaleFactor = 0.75
  3158. break
  3159. case 7:
  3160. self.listView.scaleFactor = 1.0
  3161. break
  3162. case 8:
  3163. self.listView.scaleFactor = 1.5
  3164. break
  3165. case 9:
  3166. self.listView.scaleFactor = 2.0
  3167. break
  3168. case 10:
  3169. self.listView.scaleFactor = 4.0
  3170. break
  3171. case 11:
  3172. self.listView.scaleFactor = 8.0
  3173. break
  3174. case 12:
  3175. self.listView.scaleFactor = 16.0
  3176. break
  3177. case 13:
  3178. self.listView.scaleFactor = 32.0
  3179. break
  3180. case 14:
  3181. self.listView.scaleFactor = 64.0
  3182. break
  3183. case 15:
  3184. self.listView.scaleFactor = 100.0
  3185. break
  3186. default:
  3187. break
  3188. }
  3189. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3190. }
  3191. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  3192. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3193. if scale > 100 {
  3194. scale = 100
  3195. }
  3196. if (scale <= 0.101) {
  3197. self.listView.scaleFactor = self.listView.minScaleFactor()
  3198. } else {
  3199. self.listView.scaleFactor = scale
  3200. }
  3201. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3202. DispatchQueue.main.async {
  3203. self.updateZoomInOutButtonState()
  3204. }
  3205. }
  3206. func changePDFViewZoomInAction() {
  3207. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3208. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3209. switch scale {
  3210. case 0...0.25:
  3211. scale += 0.25
  3212. case 0.25...3:
  3213. scale += 0.25
  3214. case 3.1...10:
  3215. scale += 0.4
  3216. case 10.1...100:
  3217. scale += 1
  3218. default:
  3219. scale += 1
  3220. }
  3221. self.listView.scaleFactor = scale
  3222. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  3223. // self.listView.zoomIn(nil)
  3224. }
  3225. func changePDFViewZoomOutAction() {
  3226. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  3227. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  3228. switch scale {
  3229. case 0...0.25:
  3230. scale = 0
  3231. case 0.25...3:
  3232. scale -= 0.25
  3233. case 3.1...10:
  3234. scale -= 0.4
  3235. case 10.1...100:
  3236. scale -= 1
  3237. default:
  3238. scale -= 1
  3239. }
  3240. self.listView.scaleFactor = scale
  3241. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  3242. // self.listView.zoomOut(nil)
  3243. // self.updateZoomInOutButtonState()
  3244. }
  3245. func changePDFViewGotoNextPageAction() {
  3246. self.listView.km_goBack(nil)
  3247. if (self.listView.canGoToNextPage()) {
  3248. self.listView.goToNextPage(nil)
  3249. }
  3250. self.updateNextAndPreViousButtonState()
  3251. }
  3252. func changePDFViewGoToPreviousPageAction() {
  3253. if (self.listView.canGoToPreviousPage()) {
  3254. self.listView.goToPreviousPage(nil)
  3255. }
  3256. self.updateNextAndPreViousButtonState()
  3257. }
  3258. func changePDFViewGotoBackAction() {
  3259. self.listView.km_goBack(nil)
  3260. self.updateBackAndForwardButtonState()
  3261. }
  3262. func changePDFViewGoToForwardAction() {
  3263. self.listView.km_goForward(nil)
  3264. self.updateBackAndForwardButtonState()
  3265. }
  3266. func aiTranslationPDFFileAction() {
  3267. #if VERSION_DMG
  3268. #else
  3269. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  3270. KMLoginWindowController.show(window: NSApp.mainWindow!)
  3271. return
  3272. }
  3273. #endif
  3274. self.trackEvent_aiTranslate()
  3275. self._aiTranslationPDFFileAction()
  3276. // Task { @MainActor in
  3277. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3278. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  3279. // if (isClose) {
  3280. // return
  3281. // }
  3282. // if (isSub) {
  3283. // self._aiTranslationPDFFileAction()
  3284. // return
  3285. // }
  3286. // }
  3287. // return
  3288. // }
  3289. //
  3290. // self._aiTranslationPDFFileAction()
  3291. // }
  3292. }
  3293. private func _aiTranslationPDFFileAction() {
  3294. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  3295. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  3296. let alert = NSAlert()
  3297. alert.alertStyle = .critical
  3298. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  3299. alert.runModal()
  3300. return
  3301. } else if isExceedsLimit {
  3302. let alert = NSAlert()
  3303. alert.alertStyle = .critical
  3304. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  3305. alert.runModal()
  3306. return
  3307. }
  3308. let alert = NSAlert()
  3309. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  3310. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  3311. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3312. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  3313. if (result == .alertFirstButtonReturn) {
  3314. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  3315. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  3316. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  3317. } else if result == .alertSecondButtonReturn {
  3318. return
  3319. }
  3320. }
  3321. }
  3322. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  3323. self.trackEvent_share()
  3324. }
  3325. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  3326. if (!self.saveWatermarkFlag) {
  3327. self.shareDocument(sender: viewController)
  3328. return
  3329. }
  3330. Task { @MainActor in
  3331. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3332. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  3333. if (isClose) {
  3334. return
  3335. }
  3336. if (isSubscribeSuccess) {
  3337. self.shareDocument(sender: viewController)
  3338. return
  3339. }
  3340. if (isWaterMarkExport) {
  3341. self.shareDocument(sender: viewController, limit: true)
  3342. return
  3343. }
  3344. }
  3345. return
  3346. }
  3347. self.shareDocument(sender: viewController)
  3348. }
  3349. }
  3350. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  3351. if IAPProductsManager.default().isAvailableAllFunction() == false {
  3352. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3353. return
  3354. }
  3355. self.shareFlatten(sender: viewController)
  3356. }
  3357. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  3358. if (!self.saveWatermarkFlag) {
  3359. self.shareOriginalPDF(sender: viewController)
  3360. return
  3361. }
  3362. Task { @MainActor in
  3363. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3364. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  3365. if (isClose) {
  3366. return
  3367. }
  3368. if (isSubscribeSuccess) {
  3369. self.shareOriginalPDF(sender: viewController)
  3370. return
  3371. }
  3372. if (isWaterMarkExport) {
  3373. self.shareOriginalPDF(sender: viewController, limit: true)
  3374. return
  3375. }
  3376. }
  3377. return
  3378. }
  3379. self.shareOriginalPDF(sender: viewController)
  3380. }
  3381. }
  3382. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  3383. if(0 == selectedTag) {
  3384. // self.documentAIViewController?.enteredIncreaseAllPage()
  3385. // self.documentAIViewController?.updateToolState(false)
  3386. } else {
  3387. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  3388. // self.documentAIViewController?.recognitionPartModel(with: .english)
  3389. // self.documentAIViewController?.updateToolState(true)
  3390. }
  3391. // 0 : Scan 1:OCR Text
  3392. }
  3393. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  3394. if beforeType == .editPDF {
  3395. // self.asyncSaveDocument { params in
  3396. //
  3397. // }
  3398. }
  3399. // 埋点
  3400. // self.trackEvent(toolType: type)
  3401. if(type != .Page) {
  3402. if (hasEnterPageEdit()) {
  3403. self.exitPageEdit()
  3404. }
  3405. }
  3406. if type != .redact {
  3407. if self.hasEnterRedact() {
  3408. self.exitRedact()
  3409. }
  3410. }
  3411. if item.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  3412. if self.hasShowDigitalSign() {
  3413. self.exitDigitalSign()
  3414. }
  3415. }
  3416. if(type != .Form) {
  3417. formAlertView?.removeFromSuperview()
  3418. formAlertView = nil
  3419. }
  3420. if (type == .Page) {
  3421. if (hasEnterPageEdit()) {
  3422. self.exitPageEdit()
  3423. } else {
  3424. self.enterPageEdit(pages)
  3425. }
  3426. } else if type == .editPDF {
  3427. self.listView.annotationType = .editTextImage
  3428. } else if type == .Annatiton {
  3429. self.rightSideViewController.subViewType = .AnnotationProperts
  3430. } else if type == .redact {
  3431. self.enterRedact()
  3432. } else if type == .Tool {
  3433. self.loadOpenFileFunctionGuide(.pdfCompareGuide)
  3434. } else if type == . Conversion {
  3435. self.loadOpenFileFunctionGuide(.convertGuide)
  3436. }else if type == .Form {
  3437. if (formAlertView == nil) {
  3438. formAlertView = KMFormAlertView()
  3439. formAlertView?.showInView(self.listView)
  3440. } else {
  3441. formAlertView?.removeFromSuperview()
  3442. formAlertView = nil
  3443. }
  3444. }
  3445. }
  3446. func clickChildTool(type: KMToolbarType, index: Int) {
  3447. if (type == .secure) {
  3448. if (index == 1) {
  3449. self.trackEvent_setPassword()
  3450. } else if (index == 2) {
  3451. self.trackEvent_removePassword()
  3452. }
  3453. } else {
  3454. self.trackEvent(toolBarType: type)
  3455. }
  3456. Task { @MainActor in
  3457. if (type == .compress) { /// 压缩
  3458. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3459. // self.view.window?.contentView?.superview?.beginLoading()
  3460. let document = self.listView.document
  3461. let secureOptions = self.secureOptions
  3462. let removeSecureFlag = self.removeSecureFlag
  3463. // DispatchQueue.global().async { [unowned self] in
  3464. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  3465. // DispatchQueue.main.async {
  3466. // self.view.window?.contentView?.superview?.endLoading()
  3467. // }
  3468. return
  3469. }
  3470. // DispatchQueue.main.async {
  3471. // self.view.window?.contentView?.superview?.endLoading()
  3472. self.showCompressWindow(url: _url)
  3473. // }
  3474. // }
  3475. return
  3476. }
  3477. if (self.needSaveDocument()) {
  3478. self.saveDocumentWithProgressAlert { [unowned self] params in
  3479. self.showCompressWindow()
  3480. }
  3481. return
  3482. }
  3483. self.showCompressWindow()
  3484. return
  3485. }
  3486. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  3487. var identifier: String?
  3488. if (type == .word) { /// Word
  3489. identifier = KMToolbarConversionWordItemIdentifier
  3490. } else if (type == .excel) {
  3491. identifier = KMToolbarConversionExcelItemIdentifier
  3492. } else if (type == .ppt) {
  3493. identifier = KMToolbarConversionPPTItemIdentifier
  3494. } else if (type == .rtf) {
  3495. identifier = KMToolbarConversionRTFItemIdentifier
  3496. } else if (type == .html) {
  3497. identifier = KMToolbarConversionHTMLItemIdentifier
  3498. } else if (type == .conversion_text) {
  3499. identifier = KMToolbarConversionTextItemIdentifier
  3500. } else if (type == .csv) {
  3501. identifier = KMToolbarConversionCSVItemIdentifier
  3502. } else if (type == .conversion_image) {
  3503. identifier = KMToolbarConversionImageItemIdentifier
  3504. }
  3505. if (self.needSaveDocument()) {
  3506. self.saveDocumentWithProgressAlert { [unowned self] params in
  3507. self.showConvertWindow(type: type, identifier: identifier)
  3508. }
  3509. return
  3510. }
  3511. self.showConvertWindow(type: type, identifier: identifier)
  3512. return
  3513. }
  3514. if (type == .merge) { /// 合并
  3515. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  3516. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  3517. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3518. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  3519. if (result == .cancel) {
  3520. return
  3521. }
  3522. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  3523. return
  3524. }
  3525. self.showMergeWindow(url: _url, password)
  3526. }
  3527. return
  3528. }
  3529. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  3530. if (result == .cancel) {
  3531. return
  3532. }
  3533. if (self.needSaveDocument()) {
  3534. self.saveDocumentWithProgressAlert { [unowned self] params in
  3535. self.showMergeWindow(password)
  3536. }
  3537. return
  3538. }
  3539. self.showMergeWindow(password)
  3540. }
  3541. return
  3542. }
  3543. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  3544. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  3545. return
  3546. }
  3547. self.showMergeWindow(url: _url, password)
  3548. return
  3549. }
  3550. if (self.needSaveDocument()) {
  3551. self.saveDocumentWithProgressAlert { [unowned self] params in
  3552. self.showMergeWindow(self.listView.document.password)
  3553. }
  3554. return
  3555. }
  3556. self.showMergeWindow(self.listView.document.password)
  3557. return
  3558. }
  3559. if (type == .bates || type == .headerAndFooter) {
  3560. if !IAPProductsManager.default().isAvailableAllFunction(){
  3561. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3562. return
  3563. }
  3564. if (index == 1) {
  3565. var windowController: KMBaseWindowController = KMBaseWindowController()
  3566. if (type == .bates) {
  3567. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3568. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3569. let file = KMFileAttribute()
  3570. file.filePath = (self.document?.documentURL.path)!
  3571. self.showBatchWindow(type: .AddBates, files: [file])
  3572. }
  3573. windowController.isBates = true
  3574. } else if (type == .headerAndFooter) {
  3575. windowController = KMHeaderFooterWindowController(windowNibName: "KMHeaderFooterWindowController")
  3576. (windowController as! KMHeaderFooterWindowController).operateCallBack = { [unowned self] controller, headerFooter in
  3577. let file = KMFileAttribute()
  3578. file.filePath = (self.document?.documentURL.path)!
  3579. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  3580. }
  3581. } else if (type == .background) {
  3582. // controller = KMBackgroundController()
  3583. } else if (type == .watermark) {
  3584. // controller = KMWatermarkViewController()
  3585. }
  3586. windowController.pdfDocument = self.listView.document
  3587. windowController.cancelAction = { [unowned self] controller in
  3588. self.view.window?.endSheet((self.currentWindowController.window)!)
  3589. self.currentWindowController = nil
  3590. }
  3591. self.currentWindowController = windowController
  3592. await self.view.window?.beginSheet(windowController.window!)
  3593. return
  3594. }
  3595. if (index == 1) { /// 取消
  3596. self.toolbarController.exitWatermarkAdjective()
  3597. // self.rightSideViewController.view.isHidden = true
  3598. self.rightSideViewController.isHidden = true
  3599. self.rightSideViewController.subViewType = .None
  3600. self.closeRightPane()
  3601. return
  3602. } else if index == 3 {
  3603. let file = KMFileAttribute()
  3604. file.filePath = (self.document?.documentURL.path)!
  3605. if type == .bates {
  3606. self.showBatchWindow(type: .AddBates, files: [file])
  3607. } else {
  3608. self.showBatchWindow(type: .AddHeaderFooter, files: [file])
  3609. }
  3610. } else if index == 4 {
  3611. let file = KMFileAttribute()
  3612. file.filePath = (self.document?.documentURL.path)!
  3613. if type == .bates {
  3614. self.showBatchWindow(type: .RemoveBates, files: [file])
  3615. } else {
  3616. self.showBatchWindow(type: .RemoveHeaderFooter, files: [file])
  3617. }
  3618. } else if (index == 2) { //// 移除
  3619. if type == .headerAndFooter {
  3620. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3621. let savePanel = NSSavePanel()
  3622. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3623. savePanel.allowedFileTypes = ["pdf"]
  3624. savePanel.accessoryView = savePanelAccessoryViewController.view
  3625. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3626. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3627. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooter(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3628. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3629. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3630. }
  3631. } else {
  3632. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3633. }
  3634. }
  3635. }
  3636. }
  3637. } else if type == .bates {
  3638. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3639. let savePanel = NSSavePanel()
  3640. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  3641. savePanel.allowedFileTypes = ["pdf"]
  3642. savePanel.accessoryView = savePanelAccessoryViewController.view
  3643. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  3644. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  3645. KMHeaderFooterView.saveAsPDFRemoveAllHeaderFooterBates(document!, password: document?.password, toPath: savePanel.url!.path) { success in
  3646. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  3647. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePanel.url!.path), display: true) { _, _, _ in
  3648. }
  3649. } else {
  3650. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  3651. }
  3652. }
  3653. }
  3654. }
  3655. }
  3656. return
  3657. } else if (index == 2) { /// 应用
  3658. let model = self.rightSideViewController.model
  3659. if (type == .bates || type == .headerAndFooter) {
  3660. if (model == nil || (model?.isKind(of: KMHeaderFooterObject.self) == false)) {
  3661. let alert = NSAlert()
  3662. alert.alertStyle = .critical
  3663. alert.messageText = "没有找到模型"
  3664. alert.runModal()
  3665. return
  3666. }
  3667. if ((model as! KMHeaderFooterObject).hasVaild == false) {
  3668. let alert = NSAlert()
  3669. alert.alertStyle = .critical
  3670. alert.messageText = "没有找到内容"
  3671. alert.runModal()
  3672. return
  3673. }
  3674. }
  3675. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  3676. result in
  3677. DispatchQueue.main.async {
  3678. self.listView.layoutDocumentView()
  3679. self.listView.setNeedsDisplayForVisiblePages()
  3680. }
  3681. if (result) {
  3682. let alert = NSAlert()
  3683. alert.alertStyle = .warning
  3684. alert.messageText = "成功"
  3685. alert.runModal()
  3686. } else {
  3687. let alert = NSAlert()
  3688. alert.alertStyle = .critical
  3689. alert.messageText = "失败"
  3690. alert.runModal()
  3691. }
  3692. }
  3693. return
  3694. } else if index == 5 {
  3695. self.rightSideViewController.isHidden = false
  3696. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3697. self.openRightPane()
  3698. }
  3699. } else if (type == .redact) { /// 标记密文
  3700. if !IAPProductsManager.default().isAvailableAllFunction(){
  3701. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3702. return
  3703. }
  3704. if (index == 1) { /// 取消
  3705. if (self.hasAddRedact) {
  3706. let alert = NSAlert()
  3707. alert.messageText = NSLocalizedString("You can save a document with unapplied cipher text and edit it again. If you do not save, all changes will be lost.", comment: "")
  3708. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  3709. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3710. let result = alert.runModal()
  3711. if (result == .alertFirstButtonReturn) {
  3712. self.listView.toolMode = .moveToolMode
  3713. self.toolbarController.exitRedact()
  3714. }
  3715. return
  3716. }
  3717. self.listView.toolMode = .moveToolMode
  3718. self.toolbarController.exitRedact()
  3719. return
  3720. }
  3721. if (index == 2) { /// 擦除
  3722. self.exeRedactConfirm(.eraserAll) {}
  3723. return
  3724. }
  3725. if (index == 3) { /// 应用
  3726. self.exeRedactConfirm(.redactAll) {}
  3727. return
  3728. }
  3729. if (index == 4) { /// 文本&图像
  3730. self.listView.toolMode = .redactToolMode
  3731. return
  3732. }
  3733. if (index == 5) { /// 页面
  3734. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  3735. await self.view.window?.beginSheet(windowController.window!)
  3736. self.currentWindowController = windowController
  3737. windowController.itemClick = { [weak self] index, value in
  3738. if (index == 1) {
  3739. let topBarView = self?.toolbarController.fetchTopBarView()
  3740. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  3741. return
  3742. }
  3743. (topBarView as! KMRedactTopToolBar).selectItem(0)
  3744. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  3745. self?.currentWindowController = nil
  3746. return
  3747. }
  3748. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  3749. let pageType = windowController_pageRange.pageType
  3750. let pageString = windowController_pageRange.pageString
  3751. if (pageType == 5) { /// 自定义页面
  3752. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  3753. if (array.count == 0) {
  3754. let alert = NSAlert()
  3755. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  3756. alert.runModal()
  3757. return
  3758. }
  3759. }
  3760. self!.view.window?.endSheet(self!.currentWindowController.window!)
  3761. self!.currentWindowController = nil
  3762. var indexs: IndexSet = []
  3763. if (pageType == 1) { /// 当前页面
  3764. indexs.insert((self?.listView.currentPageIndex)!)
  3765. } else {
  3766. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  3767. }
  3768. if (indexs.count == 0) {
  3769. return
  3770. }
  3771. for i in indexs {
  3772. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  3773. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  3774. redactAnno.bounds = page.bounds
  3775. self?.listView.add(redactAnno, to: page)
  3776. }
  3777. }
  3778. return
  3779. }
  3780. } else if (type == .secure) { /// 安全
  3781. if (index == 1) { /// 设置密码
  3782. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3783. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  3784. if (result == .cancel) {
  3785. return
  3786. }
  3787. self?.isSaveKeyChain = false
  3788. self?.listView.document.unlock(withPassword: password)
  3789. self?.hiddenSecureLimitTip()
  3790. self?.showSecureWindow((self?.listView.document.documentURL)!)
  3791. }
  3792. return
  3793. }
  3794. self.showSecureWindow(self.listView.document.documentURL)
  3795. return
  3796. } else if index == 2 {
  3797. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  3798. let alert = NSAlert()
  3799. alert.alertStyle = .warning
  3800. alert.messageText = NSLocalizedString("Warning", comment: "")
  3801. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3802. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  3803. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  3804. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  3805. if returnCode == .alertSecondButtonReturn {
  3806. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3807. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3808. if success {
  3809. self.document?.unlock(withPassword: resultPassword)
  3810. self.clickChildTool(type: .secure, index: 2)
  3811. }
  3812. }
  3813. }
  3814. }
  3815. }
  3816. } else {
  3817. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  3818. controller.pdfDocument = self.document
  3819. self.currentWindowController = controller
  3820. controller.batchAction = { [unowned self] controller, files in
  3821. self.view.window?.endSheet((self.currentWindowController.window)!)
  3822. self.currentWindowController = nil
  3823. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  3824. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  3825. // batchWindowController.window?.makeKeyAndOrderFront("")
  3826. // let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  3827. // batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  3828. // batchWindowController.window?.makeKeyAndOrderFront("")
  3829. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  3830. if #available(macOS 10.13, *) {
  3831. baseWindowController.window?.makeKeyAndOrderFront(nil)
  3832. } else {
  3833. baseWindowController.showWindow(nil)
  3834. }
  3835. let arr = NSMutableArray()
  3836. let file = KMBatchOperateFile(filePath: self.listView!.document!.documentURL!.path, type: .RemovePassword)
  3837. arr.add(file)
  3838. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .RemovePassword, files: arr as! [KMBatchOperateFile])
  3839. }
  3840. controller.cancelAction = { [unowned self] controller in
  3841. self.view.window?.endSheet((self.currentWindowController.window)!)
  3842. self.currentWindowController = nil
  3843. }
  3844. controller.doneAction = { [unowned self] controller in
  3845. self.view.window?.endSheet((self.currentWindowController.window)!)
  3846. self.currentWindowController = nil
  3847. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  3848. if success {
  3849. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3850. let savePanel = NSSavePanel()
  3851. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  3852. savePanel.allowedFileTypes = ["pdf"]
  3853. savePanel.accessoryView = savePanelAccessoryViewController.view
  3854. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  3855. guard result == .OK else { return }
  3856. /// 删除安全性设置
  3857. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  3858. self.isSaveKeyChain = false
  3859. self.listView.document.unlock(withPassword: resultPassword)
  3860. }
  3861. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  3862. guard let document = document else { return }
  3863. document.unlock(withPassword: resultPassword)
  3864. let success = document.writeDecrypt(to: savePanel.url)
  3865. if success {
  3866. self.hiddenSecureLimitTip()
  3867. let tip = KMRemovePasswordResultTipView()
  3868. tip.result = .success
  3869. tip.showInView(superView: (self.listView.superview)!)
  3870. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3871. } else {
  3872. self.hiddenSecureLimitTip()
  3873. let tip = KMRemovePasswordResultTipView()
  3874. tip.result = .failure
  3875. tip.showInView(superView: (self.listView.superview)!)
  3876. }
  3877. }
  3878. }
  3879. }
  3880. }
  3881. await NSWindow.currentWindow().beginSheet(controller.window!)
  3882. }
  3883. return
  3884. }
  3885. } else if type == .comparison {
  3886. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  3887. if !IAPProductsManager.default().isAvailableAllFunction(){
  3888. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3889. return
  3890. }
  3891. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  3892. self.currentWindowController = controller
  3893. controller.password = self.document?.password ?? ""
  3894. controller.filePath = (self.document?.documentURL.path)!
  3895. controller.cancelAction = { [unowned self] controller in
  3896. self.view.window?.endSheet((self.currentWindowController.window)!)
  3897. self.currentWindowController = nil
  3898. }
  3899. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  3900. DispatchQueue.main.async {
  3901. self.view.window?.endSheet((controller.window)!)
  3902. self.currentWindowController = nil
  3903. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  3904. }
  3905. }
  3906. controller.coveringComplete = { [unowned self] controller, document in
  3907. self.view.window?.endSheet((controller.window)!)
  3908. self.currentWindowController = nil
  3909. self.openCoveringCompareVC(with: document)
  3910. }
  3911. if index == 1 {
  3912. controller.fileType = .content
  3913. } else {
  3914. controller.fileType = .coverting
  3915. }
  3916. await NSWindow.currentWindow().beginSheet(controller.window!)
  3917. } else if type == .watermark {
  3918. if !IAPProductsManager.default().isAvailableAllFunction(){
  3919. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  3920. return
  3921. }
  3922. if index == 1 {
  3923. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  3924. self.currentWindowController = controller
  3925. controller.pdfDocument = self.document
  3926. controller.cancelAction = { [unowned self] controller in
  3927. self.view.window?.endSheet((self.currentWindowController.window)!)
  3928. self.currentWindowController = nil
  3929. }
  3930. controller.operateCallBack = { [unowned self] controller, watermark, countType in
  3931. let file = KMFileAttribute()
  3932. file.filePath = (self.document?.documentURL.path)!
  3933. self.showBatchWindow(type: .AddWatermark, files: [file])
  3934. }
  3935. // NSWindow.currentWindow().beginSheet(controller.window!)
  3936. NSWindow.currentWindow().beginSheet(controller.window!, completionHandler: nil)
  3937. } else if index == 2 {
  3938. let watermarks = self.listView.document.watermarks()
  3939. if (watermarks == nil || watermarks!.count <= 0) {
  3940. let alert = NSAlert()
  3941. alert.alertStyle = .warning
  3942. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Reader Pro添加的,因此无法被检测到。", comment: "")
  3943. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  3944. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3945. alert.runModal()
  3946. return
  3947. }
  3948. let alert = NSAlert()
  3949. alert.alertStyle = .warning
  3950. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  3951. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  3952. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  3953. let result = alert.runModal()
  3954. if (result != .alertFirstButtonReturn) {
  3955. return
  3956. }
  3957. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  3958. let savePanel = NSSavePanel()
  3959. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  3960. savePanel.allowedFileTypes = ["pdf"]
  3961. savePanel.accessoryView = savePanelAccessoryViewController.view
  3962. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  3963. guard result == .OK else { return }
  3964. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  3965. KMWatermarkAdjectiveTools.delete(oType, self.listView, savePanel.url!.path) {
  3966. result in
  3967. DispatchQueue.main.async {
  3968. self.listView.layoutDocumentView()
  3969. self.listView.setNeedsDisplayForVisiblePages()
  3970. }
  3971. if (result) {
  3972. let alert = NSAlert()
  3973. alert.alertStyle = .warning
  3974. alert.messageText = "成功"
  3975. alert.runModal()
  3976. } else {
  3977. let alert = NSAlert()
  3978. alert.alertStyle = .critical
  3979. alert.messageText = "失败"
  3980. alert.runModal()
  3981. }
  3982. }
  3983. }
  3984. } else if index == 3 {
  3985. let file = KMFileAttribute()
  3986. file.filePath = (self.document?.documentURL.path)!
  3987. self.showBatchWindow(type: .AddWatermark, files: [file])
  3988. } else if index == 4 {
  3989. let file = KMFileAttribute()
  3990. file.filePath = (self.document?.documentURL.path)!
  3991. self.showBatchWindow(type: .RemoveWatermark, files: [file])
  3992. } else if index == 5 {
  3993. self.rightSideViewController.isHidden = false
  3994. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  3995. self.openRightPane()
  3996. return
  3997. }
  3998. } else if type == .background {
  3999. if !IAPProductsManager.default().isAvailableAllFunction(){
  4000. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  4001. return
  4002. }
  4003. if index == 1 {
  4004. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  4005. self.currentWindowController = controller
  4006. controller.pdfDocument = self.document
  4007. controller.cancelAction = { [unowned self] controller in
  4008. self.view.window?.endSheet((self.currentWindowController.window)!)
  4009. self.currentWindowController = nil
  4010. }
  4011. controller.operateCallBack = { [unowned self] controller, background, countType in
  4012. let file = KMFileAttribute()
  4013. file.filePath = (self.document?.documentURL.path)!
  4014. self.showBatchWindow(type: .AddBackground, files: [file])
  4015. }
  4016. await NSWindow.currentWindow().beginSheet(controller.window!)
  4017. } else if index == 2 {
  4018. guard let document = self.document else { return }
  4019. if !document.allowsPrinting || !document.allowsCopying {
  4020. let alert = NSAlert()
  4021. alert.alertStyle = .critical
  4022. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  4023. alert.runModal()
  4024. return
  4025. }
  4026. guard let documentURL = document.documentURL else { return }
  4027. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  4028. let savePanel = NSSavePanel()
  4029. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  4030. savePanel.allowedFileTypes = ["pdf"]
  4031. savePanel.accessoryView = savePanelAccessoryViewController.view
  4032. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  4033. guard result == .OK else { return }
  4034. KMAddBackgroundView.saveAsPDFRemoveAllBackground(PDFDocument: document, password: document.password, toPath: savePanel.url!.path, completionHandler: { [unowned self] success in
  4035. if success == 1 {
  4036. if savePanelAccessoryViewController.openAutomaticButton.state == .on {
  4037. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { _, _, _ in }
  4038. } else {
  4039. NSWorkspace.shared.selectFile(savePanel.url!.path, inFileViewerRootedAtPath: "")
  4040. }
  4041. }
  4042. })
  4043. }
  4044. } else if index == 3 {
  4045. let file = KMFileAttribute()
  4046. file.filePath = (self.document?.documentURL.path)!
  4047. self.showBatchWindow(type: .AddBackground, files: [file])
  4048. } else if index == 4 {
  4049. let file = KMFileAttribute()
  4050. file.filePath = (self.document?.documentURL.path)!
  4051. self.showBatchWindow(type: .RemoveBackground, files: [file])
  4052. } else if index == 5 {
  4053. self.rightSideViewController.isHidden = false
  4054. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  4055. self.openRightPane()
  4056. return
  4057. }
  4058. }
  4059. }
  4060. }
  4061. func showBatchWindow(type: KMBatchOperationType, files: [KMFileAttribute]?) {
  4062. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  4063. // batchWindowController.window?.makeKeyAndOrderFront("")
  4064. var array: [KMBatchOperateFile] = []
  4065. for file in files! {
  4066. let batchOperateFile = KMBatchOperateFile(filePath: file.filePath, type: type)
  4067. array.append(batchOperateFile)
  4068. }
  4069. batchWindowController.switchToOperateType(type, files: array)
  4070. batchWindowController.window?.makeKeyAndOrderFront("")
  4071. }
  4072. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  4073. if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
  4074. if (hasEnterPageEdit()) {
  4075. self.exitPageEdit()
  4076. }
  4077. }
  4078. if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
  4079. if self.hasEnterRedact() {
  4080. self.exitRedact()
  4081. }
  4082. }
  4083. if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  4084. if self.hasShowDigitalSign() {
  4085. self.exitDigitalSign()
  4086. }
  4087. }
  4088. if let itemID = toolbarItem.itemIdentifier {
  4089. if isMainToolItem(itemID) {
  4090. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  4091. openNewWindowAlertWindow()
  4092. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  4093. self.changePDFViewGoToPreviousPageAction()
  4094. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  4095. self.changePDFViewGotoNextPageAction()
  4096. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4097. let isSelected = toolbarItem.isSelected
  4098. self.toolbarController.toolbarType = isSelected ? .None : .viewSetting
  4099. toolbarItem.isSelected = !isSelected
  4100. if toolbarItem.isSelected {
  4101. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_PageDisplay"])
  4102. }
  4103. self.toolbarController.clickItem(KMToolbarViewSettingIdentifier)
  4104. let rightItem = self.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  4105. if isSelected {
  4106. rightItem?.isSelected = false
  4107. } else {
  4108. rightItem?.isSelected = true
  4109. }
  4110. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  4111. toolbarItem.isSelected = !toolbarItem.isSelected
  4112. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  4113. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4114. toolbarItem.isSelected = !toolbarItem.isSelected
  4115. self.toggleRightPane()
  4116. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  4117. self.listView.toolMode = .redactToolMode
  4118. self.enterRedact()
  4119. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  4120. showOCRWindow()
  4121. } else if itemID == KMDocumentDigitalSignToolbarItemIdentifier {
  4122. self.listView.toolMode = .textToolMode
  4123. toolbarItem.isSelected = !toolbarItem.isSelected
  4124. self.toolbarController.lastItemBox = toolbarItem
  4125. if toolbarItem.isSelected {
  4126. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn": "Btn_Tbr_DigitalSignature"])
  4127. }
  4128. if self.hasShowDigitalSign() {
  4129. self.exitDigitalSign()
  4130. } else {
  4131. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  4132. }
  4133. }
  4134. } else {
  4135. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  4136. let windowC = KMToolbarCustomWindowController()
  4137. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  4138. self.km_beginSheet(windowC: windowC)
  4139. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  4140. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  4141. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  4142. self.trackEvent_print()
  4143. self.showPrintWindow()
  4144. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  4145. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  4146. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Fill&Sign", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Fill&Sign_Profile"])
  4147. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  4148. windowC.callBack = { [weak self] string in
  4149. if (string.isEmpty == false) {
  4150. self?.listView.addTextField(subType: .profile, string: string)
  4151. }
  4152. self?.km_endSheet()
  4153. }
  4154. self.km_beginSheet(windowC: windowC)
  4155. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  4156. toolbarItem.isSelected = !toolbarItem.isSelected
  4157. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_ViewSetting"])
  4158. rightSideViewController.mainController = self
  4159. self.rightSideViewController.isHidden = false
  4160. self.rightSideViewController.subViewType = .ViewSettings
  4161. self.toggleRightPane()
  4162. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  4163. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Snapshot"])
  4164. self.listView.takeSnapshot(nil)
  4165. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  4166. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  4167. self.showTTSWindow()
  4168. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4169. self.showOCRWindow()
  4170. } else if toolbarItem.itemIdentifier == KMAnnotationImageToolbarItemIdentifier {
  4171. toolbarItem.isSelected = false
  4172. self.imageAnnotation(toolbarItem)
  4173. } else if toolbarItem.itemIdentifier == KMAnnotationTableToolbarItemIdentifier {
  4174. self.tableAnnotation(toolbarItem)
  4175. }
  4176. }
  4177. }
  4178. }
  4179. func openNewWindowAlertWindow() {
  4180. var needShowChooseWindow = false
  4181. //#if VERSION_FREE
  4182. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  4183. needShowChooseWindow = true
  4184. }
  4185. //#endif
  4186. if needShowChooseWindow {
  4187. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  4188. if preferenceNoteShow {
  4189. menuItemAction_newTagPageToNewWindow("")
  4190. } else {
  4191. if !KMDataManager.default.isTabbingWin{
  4192. KMDataManager.default.isTabbingWin = true
  4193. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  4194. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  4195. KMDataManager.default.isTabbingWin = false
  4196. if continueOrNot {
  4197. self?.reopenDocument(forPaths: [])
  4198. } else {
  4199. }
  4200. }
  4201. self.km_beginSheet(windowC: tabbingWin)
  4202. }
  4203. }
  4204. }else{
  4205. handleTabbingLogic()
  4206. }
  4207. }
  4208. func reopenDocument(forPaths paths: [String]) -> Void {
  4209. let browser = KMBrowser.init() as KMBrowser
  4210. browser.windowController = KMBrowserWindowController.init(browser: browser)
  4211. browser.addHomeTabContents()
  4212. browser.windowController.showWindow(self)
  4213. }
  4214. func handleTabbingLogic() {
  4215. self.browserWindowController?.browser.selectTabContents(at: 0, userGesture: true)
  4216. self.toolbarController.findItem(KMDocumentHomeToolbarItemIdentifier)?.isSelected = false
  4217. }
  4218. func showTTSWindow() {
  4219. var lastPDFView: CPDFView?
  4220. let ttsView = KMTTSWindowController.share
  4221. if (ttsView.window?.isVisible ?? false) {
  4222. lastPDFView = ttsView.pdfView
  4223. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  4224. lastPDFView = nil
  4225. ttsView.window?.orderOut(nil)
  4226. } else {
  4227. ttsView.pdfView = self.listView
  4228. ttsView.showWindow(nil)
  4229. }
  4230. } else {
  4231. ttsView.pdfView = self.listView
  4232. ttsView.showWindow(nil)
  4233. }
  4234. // weak var blockSelf = self
  4235. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  4236. if isCloseWindow {
  4237. // for item in blockSelf?.toolbar.items ?? [] {
  4238. // if item.itemIdentifier == KMToolbarTTSViewItemIdentifier {
  4239. // item.isSelected = false
  4240. // }
  4241. // }
  4242. }
  4243. }
  4244. if let currentSelection = self.listView.currentSelection {
  4245. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  4246. ttsView.startSpeakingPDFSelection(currentSelection)
  4247. }
  4248. }
  4249. if let lastPDFView = lastPDFView {
  4250. lastPDFView.setHighlightedSelections([])
  4251. ttsView.stopSpeaking()
  4252. }
  4253. }
  4254. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  4255. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  4256. self.clickChildTool(type: .watermark, index: index)
  4257. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Watermark"])
  4258. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  4259. self.clickChildTool(type: .background, index: index)
  4260. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Background"])
  4261. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  4262. self.clickChildTool(type: .headerAndFooter, index: index)
  4263. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Header&Footer"])
  4264. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  4265. self.clickChildTool(type: .bates, index: index)
  4266. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_BatesNumber"])
  4267. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  4268. self.clickChildTool(type: .comparison, index: index)
  4269. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  4270. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  4271. convertToImg(index: index)
  4272. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToImage"])
  4273. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  4274. extractImageAction(num: index)
  4275. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  4276. self.createPdf(index: index)
  4277. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  4278. if index == 2 { // 裁剪当前页面
  4279. self.cropCurrentPage()
  4280. } else if index == 3 { // Auto Crop – Separate
  4281. self.smart_cropAllPage()
  4282. } else if index == 4 { // Auto Crop – Combined
  4283. self.auto_cropAllPage()
  4284. } else if index == 5 { // Select Area
  4285. self.toolbarController.clickItem(KMToolbarSelectToolModeItemIdentifier)
  4286. }
  4287. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_Crop"])
  4288. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  4289. self.clickChildTool(type: .secure, index: index)
  4290. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Security"])
  4291. } else if toolbarItem.itemIdentifier == KMDocumentSearchToolbarItemIdentifier {
  4292. self.toolbarController.showFindBar()
  4293. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  4294. toolbarItem.isSelected = !toolbarItem.isSelected
  4295. self.toggleRightPane()
  4296. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  4297. self.toolbarController.toolbarType = .viewSetting
  4298. } else if toolbarItem.itemIdentifier == KMToolbarConversionOCRIdentifier {
  4299. self.showOCRWindow()
  4300. } else if toolbarItem.itemIdentifier == KMToolbarAIItemIdentifier {
  4301. if index == 1 {
  4302. self.loadAIConfigWindowWithType(.summarize)
  4303. } else if index == 2 {
  4304. self.loadAIConfigWindowWithType(.reWriting)
  4305. } else if index == 3 {
  4306. self.loadAIConfigWindowWithType(.proofreading)
  4307. } else if index == 4 {
  4308. self.loadAIConfigWindowWithType(.translate)
  4309. }
  4310. } else if toolbarItem.itemIdentifier == KMDocumentScanOCRToolbarItemIdentifier {
  4311. self.showOCRWindow()
  4312. }
  4313. }
  4314. func convertToImg(index: Int) {
  4315. var convertT: KMConvertType = .JPEG
  4316. switch index {
  4317. case 7:
  4318. convertT = .JPEG
  4319. case 8:
  4320. convertT = .JPG
  4321. case 9:
  4322. convertT = .PNG
  4323. case 10:
  4324. convertT = .GIF
  4325. case 11:
  4326. convertT = .TIFF
  4327. case 12:
  4328. convertT = .TGA
  4329. case 13:
  4330. convertT = .BMP
  4331. default:
  4332. convertT = .JPEG
  4333. }
  4334. showAllConvertWindow(convertT: convertT)
  4335. }
  4336. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String, forward: Bool) {
  4337. if self.searchResults.count == 0 {
  4338. self.search(searchString: searchString, isCase: true, display: false)
  4339. }
  4340. var row = max(searchIndex - 1, 0)
  4341. if forward {
  4342. row = searchIndex + 1
  4343. }
  4344. if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4345. let model = self.searchResults[row]
  4346. if model.selection != nil {
  4347. self.listView.go(to: model.selection, animated: true)
  4348. self.listView.setHighlightedSelection(model.selection, animated: true)
  4349. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4350. searchIndex = row
  4351. }
  4352. }
  4353. }
  4354. func toolbarViewController(_ viewController: KMToolbarViewController, searchAllAction searchString: String, forward: Bool) {
  4355. // if self.searchResults.count == 0 {
  4356. self.leftSideViewController.showSearchMode(searchString)
  4357. // }
  4358. // var row = max(searchIndex - 1, 0)
  4359. // if forward {
  4360. // row = searchIndex + 1
  4361. // }
  4362. // if row >= 0 && row < self.searchResults.count && self.searchResults.count != 0 {
  4363. // let model = self.searchResults[row]
  4364. // if model.selection != nil {
  4365. // self.listView.go(to: model.selection, animated: true)
  4366. // self.listView.setHighlightedSelection(model.selection, animated: true)
  4367. // self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  4368. //
  4369. // searchIndex = row
  4370. // }
  4371. // }
  4372. }
  4373. }
  4374. // MARK: -
  4375. // MARK: - Mouse
  4376. extension KMMainViewController {
  4377. override func mouseDown(with event: NSEvent) {
  4378. super.mouseDown(with: event)
  4379. // KMPrint("KMMainViewController mouseDown")
  4380. self.leftSideViewCancelSelect()
  4381. self.pageNumberDisplayView.isEdit = false
  4382. }
  4383. }
  4384. //MARK: LeftSideViewController
  4385. extension KMMainViewController {
  4386. func leftSideViewCancelSelect() {
  4387. // switch self.leftSideViewController.type.methodType {
  4388. // case .Thumbnail:
  4389. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  4390. // break
  4391. // case .Outline:
  4392. //// self.leftSideViewController.outlineViewController.cancelSelect()
  4393. // break
  4394. // case .BookMark:
  4395. //// self.leftSideViewController.bookViewController.cancelSelect()
  4396. // break
  4397. // case .Search:
  4398. //// self.leftSideViewController.searchViewController.cancelSelect()
  4399. // break
  4400. // case .Annotation:
  4401. //// self.leftSideViewController.annotationViewController.cancelSelect()
  4402. // break
  4403. // default:
  4404. if self.listView.isEditing() {
  4405. if self.listView.editingAreas() != nil &&
  4406. self.listView.editingAreas().count != 0 {
  4407. let areas = self.listView.editingAreas().first
  4408. if areas is CPDFEditTextArea {
  4409. self.listView.clearEditingSelectCharItem()
  4410. self.listView.updateEditing([])
  4411. KMPrint("取消选中")
  4412. }
  4413. }
  4414. }
  4415. // KMPrint("其他")
  4416. // }
  4417. }
  4418. }
  4419. extension KMMainViewController: KMReadModelViewDelegate {
  4420. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4421. self.listView.goToFirstPage(nil)
  4422. }
  4423. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  4424. self.listView.goToPreviousPage(nil)
  4425. }
  4426. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4427. self.listView.goToNextPage(nil)
  4428. }
  4429. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  4430. self.listView.goToLastPage(nil)
  4431. }
  4432. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  4433. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  4434. }
  4435. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  4436. var scale: Double = 1.0
  4437. switch type {
  4438. case .fitWidth:
  4439. self.listView.autoScales = !self.listView.autoScales
  4440. scale = self.listView.scaleFactor
  4441. break
  4442. case .actualSize:
  4443. if self.listView.scaleFactor != 1.0 {
  4444. self.listView.scaleFactor = 1.0
  4445. self.listView.autoScales = false
  4446. }
  4447. scale = self.listView.scaleFactor
  4448. break
  4449. case .autoSize:
  4450. self.listView.autoScales = true
  4451. self.listView.autoScales = false
  4452. scale = self.listView.scaleFactor
  4453. break
  4454. case ._10:
  4455. scale = 0.1
  4456. break
  4457. case ._25:
  4458. scale = 0.25
  4459. break
  4460. case ._50:
  4461. scale = 0.5
  4462. break
  4463. case ._100:
  4464. scale = 1.0
  4465. break
  4466. case ._150:
  4467. scale = 1.5
  4468. break
  4469. case ._200:
  4470. scale = 2.0
  4471. break
  4472. case ._400:
  4473. scale = 4.0
  4474. break
  4475. case ._800:
  4476. scale = 8.0
  4477. break
  4478. default:
  4479. break
  4480. }
  4481. self.listView.scaleFactor = scale
  4482. self.toolbarController.mainViewController?.childToolbarController.zoomTextField?.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  4483. }
  4484. func cancelReadModel(view: KMReadModelView, sender: Any) {
  4485. if self.isReadMode {
  4486. self.closeReadModel()
  4487. }
  4488. }
  4489. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  4490. // if self.readModelViewWidthConstraint.constant != width {
  4491. self.readModelViewWidthConstraint.constant = width
  4492. // }
  4493. }
  4494. }
  4495. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  4496. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  4497. self.listView.go(toPageIndex: pageIndex, animated: true)
  4498. }
  4499. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  4500. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  4501. self.tipCurrentPageBoxWidthConstraint.constant = width
  4502. }
  4503. }
  4504. func commitEditingIfNeed() {
  4505. let isEdited = self.listView?.isEdited() ?? false
  4506. if isEdited || self.isPDFTextImageEdited {
  4507. self.listView.commitEditing()
  4508. }
  4509. }
  4510. }
  4511. extension KMMainViewController: KMInteractionProviderProtocol {
  4512. func providerContentView(fullScreenWindow: NSWindow, inset: CGFloat) -> NSView? {
  4513. let view = self.listView
  4514. view?.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, 0, 0)
  4515. if let v = view {
  4516. fullScreenWindow.contentView?.addSubview(v)
  4517. }
  4518. return view
  4519. }
  4520. }
  4521. // MARK: - Analytics (埋点)
  4522. extension KMMainViewController {
  4523. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  4524. if (type == .Annatiton) {
  4525. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  4526. } else if (type == .editPDF) {
  4527. } else if (type == .Page) {
  4528. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  4529. } else if (type == .Conversion) {
  4530. } else if (type == .Tool) {
  4531. }
  4532. }
  4533. func trackEvent_aiTranslate() -> Void {
  4534. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  4535. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4536. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4537. }
  4538. func trackEvent_print() -> Void {
  4539. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  4540. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4541. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4542. }
  4543. func trackEvent_share() -> Void {
  4544. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  4545. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4546. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4547. }
  4548. func trackEvent_upgrade() -> Void {
  4549. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  4550. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  4551. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  4552. }
  4553. func trackEvent(annotationType type: CAnnotationType) -> Void {
  4554. if (type == .highlight) {
  4555. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  4556. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  4557. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4558. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4559. } else if (type == .underline) {
  4560. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  4561. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  4562. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4563. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4564. } else if (type == .strikeOut) {
  4565. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  4566. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  4567. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4568. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4569. } else if (type == .ink) {
  4570. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  4571. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  4572. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4573. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4574. } else if (type == .freeText) {
  4575. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  4576. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  4577. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4578. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4579. } else if (type == .anchored) {
  4580. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  4581. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  4582. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4583. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4584. } else if (type == .square) {
  4585. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  4586. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  4587. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4588. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4589. } else if (type == .link) {
  4590. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  4591. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  4592. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4593. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4594. } else if (type == .stamp) {
  4595. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  4596. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  4597. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4598. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4599. } else if (type == .signSignature) {
  4600. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  4601. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  4602. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4603. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4604. } else if (type == .circle) {
  4605. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  4606. } else if (type == .arrow) {
  4607. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  4608. } else if (type == .line) {
  4609. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  4610. } else if (type == .addText) {
  4611. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  4612. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4613. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4614. } else if (type == .addImage) {
  4615. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  4616. // KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  4617. // KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  4618. // KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4619. } else if (type == .textField) {
  4620. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  4621. } else if (type == .checkBox) {
  4622. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  4623. } else if (type == .radioButton) {
  4624. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  4625. } else if (type == .listMenu) {
  4626. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  4627. } else if (type == .comboBox) {
  4628. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  4629. } else if (type == .actionButton) {
  4630. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4631. } else if (type == .actionButton) {
  4632. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  4633. } else if (type == .signature) {
  4634. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  4635. } else {
  4636. }
  4637. }
  4638. func trackEvent(toolMode mode: CToolMode) -> Void {
  4639. if (mode == .selectToolMode) {
  4640. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  4641. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4642. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4643. } else if (mode == .moveToolMode) {
  4644. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  4645. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  4646. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4647. }
  4648. }
  4649. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  4650. if (type == .word) {
  4651. } else if (type == .excel) {
  4652. } else if (type == .ppt) {
  4653. } else if (type == .rtf) {
  4654. } else if (type == .csv) {
  4655. } else if (type == .html) {
  4656. } else if (type == .conversion_text) {
  4657. } else if (type == .conversion_image) {
  4658. } else if (type == .compress) {
  4659. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  4660. } else if (type == .merge) {
  4661. } else if (type == .secure) {
  4662. } else if (type == .crop) {
  4663. }
  4664. }
  4665. func trackEvent_setPassword() -> Void {
  4666. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  4667. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4668. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4669. }
  4670. func trackEvent_removePassword() -> Void {
  4671. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  4672. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  4673. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  4674. }
  4675. }
  4676. extension KMMainViewController {
  4677. //文件对比
  4678. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  4679. self.isCompareModel = true
  4680. let compareContentView = KMCompareContentView()
  4681. compareContentView.oldDocument = oldDocument
  4682. compareContentView.document = document
  4683. compareContentView.compareResults = results
  4684. compareContentView.saveHandle = { [unowned self] view in
  4685. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  4686. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  4687. self.currentWindowController = saveController
  4688. saveController.cancelHandle = { [unowned self] controller in
  4689. self.view.window!.endSheet(controller.window!)
  4690. self.currentWindowController = nil
  4691. }
  4692. saveController.saveHandle = { [unowned self] controller, saveType in
  4693. let folderPath = controller.fileSaveFolderPath
  4694. if folderPath != nil {
  4695. if !FileManager.default.fileExists(atPath: folderPath) {
  4696. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  4697. }
  4698. #if VERSION_DMG
  4699. #else
  4700. let url = URL(fileURLWithPath: folderPath)
  4701. let fileAccess = AppSandboxFileAccess()
  4702. fileAccess?.persistPermissionURL(url)
  4703. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  4704. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  4705. let urlString = url.path
  4706. let _url = URL(fileURLWithPath: urlString)
  4707. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  4708. }
  4709. #endif
  4710. var savePath: String
  4711. switch saveType {
  4712. case 0:
  4713. let filePath = oldDocument.documentURL.path
  4714. let fileName = filePath.deletingPathExtension.lastPathComponent
  4715. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4716. savePath = self.getValidFilePath(savePath)
  4717. oldDocument.write(to: URL(fileURLWithPath: savePath))
  4718. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4719. case 1:
  4720. let filePath = document.documentURL.path
  4721. let fileName = filePath.deletingPathExtension.lastPathComponent
  4722. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  4723. savePath = self.getValidFilePath(savePath)
  4724. document.write(to: URL(fileURLWithPath: savePath))
  4725. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4726. case 2:
  4727. let filePath = oldDocument.documentURL.path
  4728. let fileName = filePath.deletingPathExtension.lastPathComponent
  4729. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  4730. savePath = self.getValidFilePath(savePath)
  4731. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  4732. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  4733. default:
  4734. break
  4735. }
  4736. }
  4737. self.view.window!.endSheet(controller.window!)
  4738. self.currentWindowController = nil
  4739. }
  4740. NSWindow.currentWindow().beginSheet(saveController.window!)
  4741. }
  4742. }
  4743. compareContentView.closeHandle = { [unowned self] view in
  4744. // self.view.window!.endSheet(controller.window!)
  4745. self.isCompareModel = false
  4746. view.removeFromSuperview()
  4747. }
  4748. self.PDFContendView.addSubview(compareContentView)
  4749. compareContentView.frame = self.PDFContendView.bounds
  4750. compareContentView.autoresizingMask = [.width,.height]
  4751. }
  4752. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  4753. self.isCompareModel = true
  4754. let coveringView = KMCompareCoveringView()
  4755. coveringView.pdfDocument = pdfDocument
  4756. coveringView.closeHandle = { [unowned self] view in
  4757. self.isCompareModel = false
  4758. view.removeFromSuperview()
  4759. }
  4760. coveringView.saveHandle = { [unowned self] view in
  4761. let savePanel = NSSavePanel()
  4762. savePanel.nameFieldStringValue = "untitled"
  4763. savePanel.allowedFileTypes = ["pdf"]
  4764. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  4765. if result == .OK {
  4766. pdfDocument.write(to: savePanel.url!)
  4767. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  4768. }
  4769. }
  4770. }
  4771. self.PDFContendView.addSubview(coveringView)
  4772. coveringView.frame = self.PDFContendView.bounds
  4773. coveringView.autoresizingMask = [.width,.height]
  4774. }
  4775. func getValidFilePath(_ oldPath: String) -> String {
  4776. let fileManager = FileManager.default
  4777. do {
  4778. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  4779. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  4780. return oldPath
  4781. }
  4782. var i = 1
  4783. var newPath = oldPath
  4784. while fileManager.fileExists(atPath: newPath) {
  4785. if fileType == FileAttributeType.typeDirectory.rawValue {
  4786. newPath = oldPath + "(\(i))"
  4787. } else {
  4788. let fileExtension = (oldPath as NSString).pathExtension
  4789. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  4790. }
  4791. i += 1
  4792. }
  4793. return newPath
  4794. } catch {
  4795. print("Error getting file attributes: \(error)")
  4796. return oldPath
  4797. }
  4798. }
  4799. }