KMMainViewController+Action.swift 258 KB

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