KMMainViewController+Action.swift 255 KB

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