KMMainViewController+Action.swift 255 KB

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