KMMainViewController+Action.swift 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool, display: Bool = true, needShowAll: Bool = false) {
  10. let isEditing = self.listView.isEditing() ?? false
  11. if isEditing {
  12. if searchString.isEmpty {
  13. self.listView.setHighlightedSelection(nil, animated: false)
  14. self.leftSideViewController.searchResults = []
  15. if display {
  16. if self.leftSideViewController.findPaneState == .singular {
  17. self.leftSideViewController.displayFindViewAnimating(true)
  18. } else {
  19. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  20. }
  21. }
  22. return
  23. }
  24. let isWholeWord = self.leftSideViewController.mwcFlags.wholeWordSearch == 1
  25. var opt = CPDFSearchOptions()
  26. if isCase == false {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. let datas = self.listView.document.findEditAllPageString(searchString, with: opt) ?? []
  33. // if let sel = datas.first?.first {
  34. // self.srHanddler.showSelection(sel)
  35. // }
  36. self.searchResults.removeAll()
  37. var _selections: [CPDFSelection] = []
  38. for selections in datas {
  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. }
  48. }
  49. if needShowAll {
  50. self.listView.setHighlightedSelections(_selections)
  51. }
  52. if _selections.isEmpty {
  53. self.listView.setHighlightedSelection(nil, animated: false)
  54. }
  55. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  56. self.leftSideViewController.searchResults = self.searchResults
  57. if display {
  58. if self.leftSideViewController.findPaneState == .singular {
  59. self.leftSideViewController.displayFindViewAnimating(true)
  60. } else {
  61. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  62. }
  63. }
  64. return
  65. }
  66. let document = self.listView.document
  67. if let data = document?.isFinding, data {
  68. document?.cancelFindString()
  69. }
  70. if searchString == "" {
  71. self.searchResults = []
  72. self.leftSideViewController.searchResults = self.searchResults
  73. self.listView.setHighlightedSelections([])
  74. self.listView.setHighlightedSelection(nil, animated: false)
  75. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  76. } else {
  77. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  78. var findArray : [[CPDFSelection]]
  79. if isCase {
  80. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  81. findArray = self.listView.document.findString(searchString, with: .matchWholeWord) ?? []
  82. } else {
  83. findArray = self.listView.document.findString(searchString) ?? []
  84. }
  85. } else {
  86. if self.leftSideViewController.mwcFlags.wholeWordSearch == 1 {
  87. findArray = self.listView.document.findString(searchString, with: [.caseSensitive, .matchWholeWord]) ?? []
  88. } else {
  89. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  90. }
  91. }
  92. self.searchResults.removeAll()
  93. var _selections: [CPDFSelection] = []
  94. for selections in findArray {
  95. for selection in selections {
  96. let mode : KMSearchMode = KMSearchMode()
  97. mode.selection = selection
  98. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  99. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  100. self.searchResults.insert(mode, at: self.searchResults.count)
  101. _selections.append(selection)
  102. selection.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  103. }
  104. }
  105. if needShowAll {
  106. self.listView.setHighlightedSelections(_selections)
  107. }
  108. if _selections.isEmpty {
  109. self.listView.setHighlightedSelection(nil, animated: false)
  110. }
  111. self.listView.setNeedsDisplayAnnotationViewForVisiblePages()
  112. self.leftSideViewController.searchResults = self.searchResults
  113. }
  114. if display {
  115. if self.leftSideViewController.findPaneState == .singular {
  116. self.leftSideViewController.displayFindViewAnimating(true)
  117. } else {
  118. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  119. }
  120. }
  121. }
  122. func removeSignatures(signatures:[CPDFSignature]) {
  123. for signature in signatures {
  124. self.listView.document.removeSignature(signature)
  125. }
  126. for i in 0..<self.listView.document.pageCount {
  127. guard let page = self.listView.document.page(at: i) else {
  128. continue
  129. }
  130. let annotations : [CPDFAnnotation] = page.annotations
  131. for j in 0..<annotations.count {
  132. let annotation = annotations[j]
  133. if annotation is CPDFSignatureWidgetAnnotation {
  134. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  135. }
  136. }
  137. }
  138. self.listView.setNeedsDisplayForVisiblePages()
  139. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  140. var mSignatures : [CPDFSignature] = []
  141. for sign in tSignatures {
  142. if sign.signers.count > 0 {
  143. mSignatures.append(sign)
  144. }
  145. }
  146. }
  147. //MARK: menu菜单
  148. func fontColorMenuItem()->NSMenuItem {
  149. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  150. return fontColorItem;
  151. }
  152. func fontSizeMenuItem()->NSMenuItem {
  153. let currentFontSize = self.listView.editingTextFontSize()
  154. let fontSizes = self.fontSizes()
  155. let submenu = NSMenu(title: "")
  156. for i in 0 ... fontSizes.count - 1 {
  157. let fontSize : String = fontSizes.object(at: i) as! String
  158. let item = NSMenuItem(title:fontSize , action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  159. item.target = self
  160. item.tag = i
  161. submenu.addItem(item)
  162. if (Int(currentFontSize) == Int(fontSize)) {
  163. item.state = .on
  164. }
  165. }
  166. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  167. fontSizeItem.submenu = submenu
  168. return fontSizeItem;
  169. }
  170. func corpImageMenuItem()->NSMenuItem {
  171. let corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  172. return corpImageItem
  173. }
  174. func cancelCorpImageMenuItem()->NSMenuItem {
  175. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  176. return cancelCorpImageItem
  177. }
  178. func restoreCorpImageMenuItem()->NSMenuItem {
  179. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  180. return cancelCorpImageItem
  181. }
  182. func cutImageArea()->NSMenuItem {
  183. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  184. return deleteItem
  185. }
  186. func editAddBlanMenu(menu:NSMenu){
  187. _ = menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  188. _ = menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  189. }
  190. func addText() -> NSMenuItem {
  191. let addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  192. return addTextItem
  193. }
  194. func addImage() -> NSMenuItem {
  195. let addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  196. return addImageItem
  197. }
  198. func replaceImageArea()->NSMenuItem {
  199. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  200. return replaceItem
  201. }
  202. func exportImageArea()->NSMenuItem {
  203. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  204. let menu = NSMenu()
  205. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  206. let item2 = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(menuItemEditingClick_ExportImage), target: self, tag:1, at: 1)
  207. let item3 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 2)
  208. exportItem.submenu = menu
  209. return exportItem
  210. }
  211. func exportImageStampItem()->NSMenuItem {
  212. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  213. let menu = NSMenu()
  214. let item1 = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  215. let item2 = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  216. exportItem.submenu = menu
  217. return exportItem
  218. }
  219. func exportMenu() -> NSMenu {
  220. let menu = NSMenu()
  221. _ = menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  222. _ = menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  223. _ = menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  224. return menu
  225. }
  226. func cropMenu() -> NSMenu {
  227. let menu = NSMenu()
  228. return menu
  229. }
  230. func zoomSelectionMenuItem() -> NSMenuItem {
  231. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  232. return item
  233. }
  234. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  235. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  236. return item
  237. }
  238. func enterAnnotationStype() -> NSMenuItem {
  239. let stypItem = NSMenuItem(title: NSLocalizedString("Annotate", comment: ""), action: nil, target: self)
  240. let stypeMenu = NSMenu()
  241. if listView.currentSelection != nil && listView.currentSelection.selectionType() == .text {
  242. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  243. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  244. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  245. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  246. stypeMenu.addItem(NSMenuItem.separator())
  247. }
  248. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  249. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  250. stypeMenu.addItem(NSMenuItem.separator())
  251. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  252. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  253. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  254. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  255. if viewManager.isPDFReadMode {
  256. } else {
  257. stypeMenu.addItem(NSMenuItem.separator())
  258. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  259. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Image", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 10)
  260. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  261. }
  262. stypItem.submenu = stypeMenu
  263. if self.listView.annotationType == .ink {
  264. stypeMenu.item(withTitle: NSLocalizedString("Freehand", comment: ""))?.state = .on
  265. } else if self.listView.annotationType == .freeText {
  266. stypeMenu.item(withTitle: NSLocalizedString("Text Note", comment: ""))?.state = .on
  267. } else if self.listView.annotationType == .anchored {
  268. stypeMenu.item(withTitle: NSLocalizedString("Anchored Note", comment: ""))?.state = .on
  269. } else if self.listView.annotationType == .square {
  270. stypeMenu.item(withTitle: NSLocalizedString("Rectangle", comment: ""))?.state = .on
  271. } else if self.listView.annotationType == .circle {
  272. stypeMenu.item(withTitle: NSLocalizedString("Circle", comment: ""))?.state = .on
  273. } else if self.listView.annotationType == .arrow {
  274. stypeMenu.item(withTitle: NSLocalizedString("Arrow", comment: ""))?.state = .on
  275. } else if self.listView.annotationType == .line {
  276. stypeMenu.item(withTitle: NSLocalizedString("Line", comment: ""))?.state = .on
  277. } else if self.listView.annotationType == .link {
  278. stypeMenu.item(at: 7)?.state = .on
  279. } else if self.listView.annotationType == .stamp {
  280. stypeMenu.item(withTitle: NSLocalizedString("Stamp", comment: ""))?.state = .on
  281. } else if self.listView.annotationType == .signSignature {
  282. stypeMenu.item(withTitle: NSLocalizedString("Signature", comment: ""))?.state = .on
  283. }
  284. return stypItem
  285. }
  286. func setAnnotationToolStype() -> NSMenuItem {
  287. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  288. let stypeMenu = NSMenu()
  289. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.textToolMode.rawValue)
  290. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Scroll", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.moveToolMode.rawValue)
  291. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.magnifyToolMode.rawValue)
  292. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: CToolMode.selectToolMode.rawValue)
  293. stypeMenu.insertItem(NSMenuItem.separator(), at: 4)
  294. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Highlight", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.highlight.rawValue)
  295. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Underline", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.underline.rawValue)
  296. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Strikethrough", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.strikeOut.rawValue)
  297. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Squiggly", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.squiggly.rawValue)
  298. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.ink.rawValue)
  299. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Text Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.freeText.rawValue)
  300. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Anchored Note", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.anchored.rawValue)
  301. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.square.rawValue)
  302. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.circle.rawValue)
  303. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.arrow.rawValue)
  304. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.line.rawValue)
  305. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(changeAnnotationMode_itemAction), target: self, tag: CAnnotationType.link.rawValue)
  306. stypItem.submenu = stypeMenu
  307. return stypItem
  308. }
  309. func addReadModelStype() -> NSMenuItem {
  310. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openPDFReadMode), target: self)
  311. if viewManager.isPDFReadMode {
  312. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(exitPDFReadMode), target: self)
  313. }
  314. return stypItem
  315. }
  316. func addOutlineStype() -> NSMenuItem {
  317. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  318. return stypItem
  319. }
  320. func setTTSStype() -> NSMenuItem {
  321. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  322. return stypItem
  323. }
  324. func setShareStype() -> NSMenuItem {
  325. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  326. var string = ""
  327. if listView.activeAnnotation != nil {
  328. string = self.listView.activeAnnotation?.contents ?? ""
  329. }
  330. if string.count < 1{
  331. string = self.listView.currentSelection?.string() ?? ""
  332. }
  333. stypItem.submenu = NSSharingServicePicker.menu(forSharingItems: [string], subjectContext: "", withTarget: self, selector: #selector(shareFromService), serviceDelegate: nil)
  334. return stypItem
  335. }
  336. func numberOfChars(_ str: String) -> (num: Int, indexN: Int) {
  337. var number = 0
  338. var indexN = 0
  339. guard str.count > 0 else {return (0, 0)}
  340. for i in 0...str.count - 1 {
  341. let c: unichar = (str as NSString).character(at: i)
  342. if (c >= 0x4E00) {
  343. number += 2
  344. }else {
  345. number += 1
  346. }
  347. if number > 56{
  348. indexN = i
  349. number = 100
  350. break
  351. }
  352. }
  353. return (number, indexN)
  354. }
  355. func setLookUpStype() -> NSMenuItem {
  356. guard let str = listView.currentSelection?.string() else {
  357. return NSMenuItem.separator()
  358. }//String(format: "Look Up %@", listView.currentSelection?.string() ?? "")
  359. let dic = numberOfChars(str)
  360. var newStr = str
  361. if dic.num == 100{
  362. newStr = str.prefix(dic.indexN) + "..."
  363. }
  364. newStr = NSLocalizedString("Look Up ", comment: "") + "\"" + newStr + "\""
  365. let stypItem = NSMenuItem(title: newStr, action: #selector(lookUpAction), target: self)
  366. return stypItem
  367. }
  368. func setSearchBaiduStype() -> NSMenuItem {
  369. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  370. return stypItem
  371. }
  372. func setCutStype() -> NSMenuItem {
  373. let stypItem = NSMenuItem(title: NSLocalizedString("Cut", comment: ""), action: #selector(cutAction), target: self)
  374. return stypItem
  375. }
  376. func setDeleteStype() -> NSMenuItem {
  377. let stypItem = NSMenuItem(title: NSLocalizedString("Delete", comment: ""), action: #selector(deleteAction), target: self)
  378. return stypItem
  379. }
  380. func setColorsStype() -> NSMenuItem {
  381. let stypItem = NSMenuItem(title: NSLocalizedString("Colors", comment: ""), action: #selector(ColorsItemAction), target: self)
  382. return stypItem
  383. }
  384. func setLinesStype() -> NSMenuItem {
  385. let stypItem = NSMenuItem(title: NSLocalizedString("Lines", comment: ""), action: #selector(LinesItemAction), target: self)
  386. return stypItem
  387. }
  388. func setEditNoteStype() -> NSMenuItem {
  389. let stypItem = NSMenuItem(title: NSLocalizedString("Edit Note", comment: ""), action: #selector(EditNoteItemAction), target: self)
  390. return stypItem
  391. }
  392. func setRotateStype() -> NSMenuItem {
  393. let stypItem = NSMenuItem(title: NSLocalizedString("Rotate", comment: ""), action: nil, target: self)
  394. let stypeMenu = NSMenu()
  395. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Left", comment: ""), action: #selector(rotateLeftAction), target: self, tag: 0)
  396. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Rotate Right", comment: ""), action: #selector(rotateRightAction), target: self, tag: 1)
  397. stypItem.submenu = stypeMenu
  398. return stypItem
  399. }
  400. func setNextPageStype() -> NSMenuItem {
  401. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  402. stypItem.isEnabled = false
  403. if listView.canGoToNextPage() {
  404. stypItem.isEnabled = true
  405. }
  406. return stypItem
  407. }
  408. func setPreviousPageStype() -> NSMenuItem {
  409. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  410. stypItem.isEnabled = false
  411. if listView.canGoToPreviousPage() {
  412. stypItem.isEnabled = true
  413. }
  414. return stypItem
  415. }
  416. func setTranslateStype() -> NSMenuItem {
  417. let str = listView.currentSelection?.string() ?? ""//String(format: "Translate %@", listView.currentSelection?.string() ?? "")
  418. let dic = numberOfChars(str)
  419. var newStr = str
  420. if dic.num == 100{
  421. newStr = str.prefix(dic.indexN) + "..."
  422. }
  423. newStr = NSLocalizedString("Translate", comment: "") + " \"" + newStr + "\""
  424. let stypItem = NSMenuItem(title: newStr, action: #selector(TranslateItemAction), target: self)
  425. return stypItem
  426. }
  427. func setAutoScrollStype() -> NSMenuItem {
  428. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  429. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  430. return stypItem
  431. }
  432. func setSnapshotStype() -> NSMenuItem {
  433. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  434. let stypeMenu = NSMenu()
  435. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  436. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  437. stypItem.submenu = stypeMenu
  438. return stypItem
  439. }
  440. func setServicesStype() -> NSMenuItem {
  441. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  442. let stypeMenu = NSMenu()
  443. let item1 = stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  444. let item2 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  445. let item3 = stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  446. let item4 = stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  447. let item5 = stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  448. let item6 = stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  449. let item7 = stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  450. stypItem.submenu = stypeMenu
  451. return stypItem
  452. }
  453. func setCropStype() -> NSMenuItem {
  454. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  455. let stypeMenu = NSMenu()
  456. if NSIsEmptyRect(listView.selectionRect){
  457. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  458. _ = stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  459. }
  460. stypItem.submenu = stypeMenu
  461. return stypItem
  462. }
  463. func setAITranslateStype() -> NSMenuItem {
  464. let stypItem = NSMenuItem(title: NSLocalizedString("AI Translate", comment: ""), action: #selector(AITranslateItemAction), target: self)
  465. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  466. return stypItem
  467. }
  468. func setAIProofreadStype() -> NSMenuItem {
  469. let stypItem = NSMenuItem(title: NSLocalizedString("AI Proofread", comment: ""), action: #selector(AIProofreadItemAction), target: self)
  470. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  471. return stypItem
  472. }
  473. func setAIRewriteStype() -> NSMenuItem {
  474. let stypItem = NSMenuItem(title: NSLocalizedString("AI Rewrite", comment: ""), action: #selector(AIRewriteItemAction), target: self)
  475. stypItem.state = self.listView.isAutoFlow() ? .on : .off
  476. return stypItem
  477. }
  478. func addHighlightLinksStype() -> NSMenuItem {
  479. let highlightLink = KMPreferenceManager.shared.highlightLinks
  480. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  481. if highlightLink {
  482. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  483. }
  484. let highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  485. return highlightLinksItem
  486. }
  487. func addAnnotationForStyleMenu(_ item: NSMenuItem?) {
  488. if item == nil {
  489. return
  490. }
  491. let menu = NSMenu()
  492. item?.submenu = menu
  493. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  494. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  495. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  496. let wavyLine = NSMenuItem(title: NSLocalizedString("Squiggly", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  497. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  498. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  499. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  500. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  501. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  502. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  503. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  504. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  505. if listView.currentSelection.selectionType() != .image {
  506. menu.insertItem(height, at: menu.items.count)
  507. menu.insertItem(underline, at: menu.items.count)
  508. menu.insertItem(strickout, at: menu.items.count)
  509. menu.insertItem(wavyLine, at: menu.items.count)
  510. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  511. }
  512. if viewManager.isPDFReadMode {
  513. } else {
  514. if listView.currentSelection.selectionType() != .image &&
  515. listView.currentSelection.selectionType() != .text {
  516. menu.insertItem(text, at: menu.items.count)
  517. menu.insertItem(note, at: menu.items.count)
  518. }
  519. }
  520. if viewManager.isPDFReadMode {
  521. } else {
  522. if listView.currentSelection.selectionType() != .image {
  523. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  524. menu.insertItem(rectangle, at: menu.items.count)
  525. menu.insertItem(oval, at: menu.items.count)
  526. }
  527. }
  528. if viewManager.isPDFReadMode {
  529. } else {
  530. if listView.currentSelection.selectionType() != .image &&
  531. listView.currentSelection.selectionType() != .text {
  532. menu.insertItem(line, at: menu.items.count)
  533. }
  534. }
  535. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  536. if viewManager.isPDFReadMode {
  537. } else {
  538. menu.insertItem(link, at: menu.items.count)
  539. }
  540. if viewManager.isPDFReadMode {
  541. } else {
  542. if listView.currentSelection.selectionType() != .image {
  543. menu.insertItem(outline, at: menu.items.count)
  544. }
  545. }
  546. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  547. if viewManager.isPDFReadMode {
  548. } else {
  549. if (listView.currentSelection.selectionType() != .image) {
  550. }
  551. }
  552. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  553. }
  554. func addBookmarkMenu() -> NSMenuItem {
  555. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  556. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  557. return bookMarkItem
  558. } else {
  559. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  560. return bookMarkItem
  561. }
  562. }
  563. func findStringMenu() -> NSMenuItem {
  564. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  565. menuItem.keyEquivalent = "f"
  566. return menuItem
  567. }
  568. func printingMenu() -> NSMenuItem {
  569. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  570. return menuItem
  571. }
  572. func fontSizes()->NSArray {
  573. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  574. }
  575. func handleRightMouseDown(theEvent: NSEvent) -> Bool {
  576. if interactionMode == .presentation {
  577. listView.goToPreviousPage(nil)
  578. return true
  579. }
  580. return false
  581. }
  582. func useNativeFullScreen() -> Bool {
  583. var isFull = false
  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 forceSubwindowsOnTop(_ flag: Bool) {
  591. }
  592. //MARK: menuItem Action
  593. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  594. let color = listView.editingSelectionFontColor()
  595. let panel = NSColorPanel.shared
  596. panel.setTarget(self)
  597. panel.setAction(#selector(fontColorChangeAction))
  598. panel.orderFront(nil)
  599. panel.showsAlpha = false
  600. panel.color = color ?? NSColor.black
  601. }
  602. @objc func fontColorChangeAction(sender: NSColorPanel) {
  603. self.listView.setEditingSelectionFontColor(sender.color)
  604. }
  605. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  606. let fontSize = self.fontSizes().object(at: sender.tag)
  607. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  608. }
  609. @objc func addImageText(sender: NSMenuItem) {
  610. let event = NSApp.currentEvent
  611. let clickLocation = event?.locationInWindow
  612. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  613. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  614. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  615. point = point2
  616. if sender.tag == 0 {
  617. KMPrint("添加文字")
  618. } else if sender.tag == 1 {
  619. } else if sender.tag == 2 {
  620. KMPrint("粘贴")
  621. }
  622. }
  623. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  624. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  625. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  626. }
  627. }
  628. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  629. self.listView.exitCrop(with: self.listView.selectImageAreas)
  630. self.listView.cropAreas = nil
  631. self.listView.isEditImage = false
  632. }
  633. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  634. self.listView.resetCrop(with: self.listView.selectImageAreas)
  635. }
  636. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  637. }
  638. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  639. if self.listView.selectImageAreas == nil {
  640. return
  641. }
  642. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Replace"])
  643. let panel = NSOpenPanel()
  644. panel.allowsMultipleSelection = false
  645. panel.allowedFileTypes = ["png","jpg"]
  646. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  647. if response == .OK {
  648. let openPath = panel.url?.path
  649. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  650. if s {
  651. }
  652. }
  653. }
  654. }
  655. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  656. if self.listView.selectImageAreas == nil {
  657. return
  658. }
  659. let panel = NSSavePanel()
  660. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  661. panel.isExtensionHidden = true
  662. let response = panel.runModal()
  663. if response == .OK {
  664. let url = panel.url
  665. if FileManager.default.fileExists(atPath: url!.path) {
  666. try?FileManager.default.removeItem(atPath: url!.path)
  667. }
  668. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  669. if result {
  670. NSWorkspace.shared.activateFileViewerSelecting([url!])
  671. }
  672. }
  673. }
  674. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  675. }
  676. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  677. }
  678. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  679. }
  680. @objc func OpenItemAction(sender: NSMenuItem) {
  681. }
  682. @objc func customCropModel(sender: NSMenuItem) {
  683. }
  684. @objc func rotateRightAction(sender: NSMenuItem) {
  685. }
  686. @objc func rotateLeftAction(sender: NSMenuItem) {
  687. }
  688. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  689. self.listView.toolMode = .noteToolMode
  690. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  691. var model : KMToolbarViewType = .None
  692. switch sender.tag {
  693. case 0:
  694. identifier = KMDocumentAnnotationToolbarItemIdentifier
  695. model = .Annatiton
  696. case 1:
  697. identifier = KMToolbarMoveToolModeItemIdentifier
  698. model = .Move
  699. case 2:
  700. identifier = KMToolbarMagnifyToolModeItemIdentifier
  701. model = .Magnify
  702. case 3:
  703. identifier = KMToolbarSelectToolModeItemIdentifier
  704. model = .Select
  705. case 4:
  706. identifier = KMToolbarZoomToSelectionItemIdentifier
  707. model = .SelectZoom
  708. default:
  709. break
  710. }
  711. }
  712. @objc func changeAnnotationMode_itemAction(sender : NSMenuItem) {
  713. var itemId: String?
  714. if sender.tag == CAnnotationType.highlight.rawValue {
  715. itemId = KMToolbarHighlightAnnotationItemIdentifier
  716. } else if sender.tag == CAnnotationType.underline.rawValue {
  717. itemId = KMToolbarUnderlineAnnotationItemIdentifier
  718. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  719. itemId = KMToolbarStrikeOutAnnotationItemIdentifier
  720. } else if sender.tag == CAnnotationType.squiggly.rawValue {
  721. itemId = KMToolbarSquigglyAnnotationItemIdentifier
  722. } else if sender.tag == CAnnotationType.ink.rawValue {
  723. itemId = KMToolbarInkAnnotationItemIdentifier
  724. } else if sender.tag == CAnnotationType.freeText.rawValue {
  725. itemId = KMToolbarFreeTextAnnotationItemIdentifier
  726. } else if sender.tag == CAnnotationType.anchored.rawValue {
  727. itemId = KMToolbarAnchoredAnnotationItemIdentifier
  728. } else if sender.tag == CAnnotationType.square.rawValue {
  729. itemId = KMToolbarSquareAnnotationItemIdentifier
  730. } else if sender.tag == CAnnotationType.circle.rawValue {
  731. itemId = KMToolbarCircleAnnotationItemIdentifier
  732. } else if sender.tag == CAnnotationType.arrow.rawValue {
  733. itemId = KMToolbarArrowAnnotationItemIdentifier
  734. } else if sender.tag == CAnnotationType.line.rawValue {
  735. itemId = KMToolbarLineAnnotationItemIdentifier
  736. } else if sender.tag == CAnnotationType.link.rawValue {
  737. itemId = KMToolbarLinkAnnotationItemIdentifier
  738. }
  739. }
  740. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  741. var annotationType : CAnnotationType = .unkown
  742. switch sender.tag {
  743. case 0:
  744. annotationType = .highlight
  745. case 1:
  746. annotationType = .underline
  747. case 2:
  748. if sender.title == NSLocalizedString("Squiggly", comment: "") {
  749. annotationType = .squiggly
  750. } else {
  751. annotationType = .strikeOut
  752. }
  753. case 3:
  754. annotationType = .freeText
  755. case 4:
  756. annotationType = .anchored
  757. case 5:
  758. annotationType = .square
  759. case 6:
  760. annotationType = .circle
  761. case 7:
  762. annotationType = .line
  763. case 8:
  764. annotationType = .link
  765. case 9:
  766. if self.model.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  767. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  768. }
  769. return
  770. case 10:
  771. annotationType = .unkown
  772. default:
  773. break
  774. }
  775. if (annotationType != .link) {
  776. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  777. self.listView.currentSelection = nil;
  778. return
  779. }
  780. // link
  781. let selection = self.listView.currentSelection
  782. DispatchQueue.main.async {
  783. Task { @MainActor in
  784. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  785. self.listView.currentSelection = nil;
  786. if (annotation != nil) {
  787. self.listView.updateActiveAnnotations([annotation!])
  788. }
  789. }
  790. }
  791. }
  792. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  793. Task { @MainActor in
  794. let idx = sender.tag
  795. if idx == 10 {
  796. if IAPProductsManager.default().isAvailableAllFunction() == false {
  797. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  798. return
  799. }
  800. }
  801. var point = mouseRightMenuEvent?.locationInWindow
  802. if (point == nil) {
  803. point = NSZeroPoint
  804. }
  805. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  806. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  807. var pagePoint = self.listView.convert(currentPoint, to: currentPage)
  808. var annotation: CPDFAnnotation?
  809. if viewManager.isPDFReadMode {
  810. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  811. self.listView.toolMode = .noteToolMode
  812. }
  813. switch sender.tag {
  814. case 0:
  815. self.listView.annotationType = CAnnotationType.ink
  816. case 1:
  817. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  818. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  819. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  820. if ((annotation) != nil) {
  821. self.listView.updateActiveAnnotations([annotation!])
  822. self.listView.edit(annotation)
  823. }
  824. case 2:
  825. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  826. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  827. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  828. self.listView.edit(annotation)
  829. case 3:
  830. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  831. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  832. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  833. case 4:
  834. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  835. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  836. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  837. case 5:
  838. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  839. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  840. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  841. case 6:
  842. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  843. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  844. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  845. case 7:
  846. self.listView.annotationType = CAnnotationType.link
  847. toggleOpenRightSide()
  848. case 8:
  849. self.listView.annotationType = CAnnotationType.stamp
  850. toggleOpenRightSide()
  851. case 9:
  852. self.listView.annotationType = CAnnotationType.signSignature
  853. toggleOpenRightSide()
  854. default:
  855. break
  856. }
  857. } else {
  858. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  859. self.listView.toolMode = .noteToolMode
  860. }
  861. switch sender.tag {
  862. case 0:
  863. self.listView.toolMode = .noteToolMode
  864. self.listView.annotationType = CAnnotationType.ink
  865. case 1:
  866. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  867. if (pagePoint.x - defaultSize.width > 0){
  868. pagePoint.x -= defaultSize.width;
  869. }else{
  870. pagePoint.x = 0;
  871. }
  872. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  873. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  874. if ((annotation) != nil) {
  875. self.listView.edit(annotation)
  876. }
  877. case 2:
  878. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  879. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  880. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  881. self.listView.edit(annotation)
  882. case 3:
  883. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  884. if (pagePoint.x - defaultSize.width > 0){
  885. pagePoint.x -= defaultSize.width;
  886. }else{
  887. pagePoint.x = 0;
  888. }
  889. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  890. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  891. case 4:
  892. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  893. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  894. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  895. case 5:
  896. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  897. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  898. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  899. case 6:
  900. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  901. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  902. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  903. case 7:
  904. self.listView.annotationType = CAnnotationType.link
  905. toggleOpenRightSide()
  906. case 8:
  907. self.listView.annotationType = CAnnotationType.stamp
  908. toggleOpenRightSide()
  909. case 9:
  910. self.listView.annotationType = CAnnotationType.signSignature
  911. toggleOpenRightSide()
  912. case 10:
  913. self.addImgAnnotationToView(center: pagePoint)
  914. default:
  915. break
  916. }
  917. if annotation != nil{
  918. self.listView.activeAnnotations.removeAllObjects()
  919. var newAnnonations : [CPDFAnnotation] = []
  920. newAnnonations.append(annotation!)
  921. self.listView.updateActiveAnnotations(newAnnonations)
  922. }
  923. }
  924. }
  925. }
  926. func addImgAnnotationToView(center: NSPoint) {
  927. let accessoryCtr = KMImageAccessoryController()
  928. let openPanel = NSOpenPanel()
  929. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  930. openPanel.allowsMultipleSelection = false
  931. openPanel.accessoryView = accessoryCtr.view
  932. openPanel.isAccessoryViewDisclosed = true
  933. openPanel.beginSheetModal(for: self.view.window!) { result in
  934. if result == .OK {
  935. let fileURL = openPanel.urls.first
  936. let filePath = fileURL!.path
  937. if filePath.pathExtension == "pdf" {
  938. let pdf = CPDFDocument(url: fileURL)
  939. if pdf!.isEncrypted {
  940. NSSound.beep()
  941. return
  942. }
  943. }
  944. let img = NSImage(contentsOfFile: filePath)
  945. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  946. self.listView.addImageAnnotation(img, center: center, isRemoveBGColor: isRemoveBGColor)
  947. }
  948. }
  949. }
  950. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  951. if self.listView.document?.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  952. let index = self.listView.currentPageIndex
  953. self.listView.document?.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  954. self.listView.setNeedsDisplayForVisiblePages()
  955. } else {
  956. self.listView.document?.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  957. self.listView.setNeedsDisplayForVisiblePages()
  958. }
  959. self.setDocumentEditedState(window: self.view.window)
  960. if viewManager.isPDFReadMode {
  961. } else {
  962. self.leftSideViewController.showBookmarkTab()
  963. }
  964. }
  965. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  966. self.leftSideViewController.refreshMethodType(methodType: .Search)
  967. }
  968. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  969. let rect = listView.currentSelectionRect()
  970. let page = listView.currentPage()
  971. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  972. copyPage.setBounds(rect, for: .cropBox)
  973. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  974. // 执行右键操作后,需要取消框选区域
  975. if self.listView.toolMode == .selectToolMode {
  976. objc_sync_enter(self)
  977. self.listView.selectionRect = NSZeroRect
  978. self.listView.selectionPageIndex = UInt(NSNotFound)
  979. objc_sync_exit(self)
  980. }
  981. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  982. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  983. if (result == .cancel) {
  984. return
  985. }
  986. // 解除权限
  987. self?.model.isSaveKeyChain = false
  988. self?.listView.document.unlock(withPassword: password)
  989. // 隐藏提示
  990. self?.hiddenSecureLimitTip()
  991. // 去打印
  992. KMPrintWindowController.printImage(image: image)
  993. }
  994. return
  995. }
  996. KMPrintWindowController.printImage(image: image)
  997. }
  998. // MARK: - Measure
  999. @objc func menuItemActionMeasureProperty(sender: NSMenuItem) {
  1000. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1001. return
  1002. }
  1003. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  1004. distanceMeasureInfoWindowController?.hideFloatingWindow()
  1005. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  1006. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1007. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  1008. areaMeasureInfoWindowController?.hideFloatingWindow()
  1009. }
  1010. self.listView.updateActiveAnnotations([anno])
  1011. self.pdfListViewChangeatioActiveAnnotations(self.listView, forActiveAnnotations: [anno], isRightMenu: false)
  1012. self.listView.setNeedsDisplayForVisiblePages()
  1013. }
  1014. @objc func menuItemActionMeasureEditNote(sender: NSMenuItem) {
  1015. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1016. return
  1017. }
  1018. self.listView.edit(anno)
  1019. }
  1020. @objc func menuItemActionMeasureSetting(sender: NSMenuItem) {
  1021. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1022. return
  1023. }
  1024. self.listView.updateActiveAnnotations([anno])
  1025. self.listView.setNeedsDisplayForVisiblePages()
  1026. if let data = anno as? CPDFLineAnnotation, data.isMeasure {
  1027. self.showMeasureDistanceSettingWindow(measureInfo: data.measureInfo)
  1028. } else if let data = anno as? CPDFPolylineAnnotation {
  1029. self.showMeasurePerimeterSettingWindow(measureInfo: data.measureInfo)
  1030. } else if let data = anno as? CPDFPolygonAnnotation {
  1031. self.showMeasureAreaSettingWindow(measureInfo: data.measureInfo)
  1032. }
  1033. }
  1034. @objc func menuItemActionMeasureDelete(sender: NSMenuItem) {
  1035. guard let anno = sender.representedObject as? CPDFAnnotation else {
  1036. return
  1037. }
  1038. self.listView.remove(anno)
  1039. }
  1040. func showMeasureDistanceSettingWindow(measureInfo: CPDFDistanceMeasureInfo?, hideInfoWindow: Bool = true) {
  1041. guard let mInfo = measureInfo else {
  1042. return
  1043. }
  1044. let winC = CDistanceSettingWindowController(distanceMeasureInfo: mInfo)
  1045. if hideInfoWindow {
  1046. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  1047. }
  1048. winC.delegate = self
  1049. winC.startModal("")
  1050. }
  1051. func showMeasurePerimeterSettingWindow(measureInfo: CPDFPerimeterMeasureInfo?, hideInfoWindow: Bool = true) {
  1052. guard let mInfo = measureInfo else {
  1053. return
  1054. }
  1055. let winC = CDistanceSettingWindowController(perimeterMeasureInfo: mInfo)
  1056. if hideInfoWindow {
  1057. self.perimeterMeasureInfoWindowController?.hideFloatingWindow()
  1058. }
  1059. winC.delegate = self
  1060. winC.startModal("")
  1061. }
  1062. func showMeasureAreaSettingWindow(measureInfo: CPDFAreaMeasureInfo?, hideInfoWindow: Bool = true) {
  1063. guard let mInfo = measureInfo else {
  1064. return
  1065. }
  1066. let winC = CAreaSettingWindowController(measureInfo: mInfo)
  1067. if hideInfoWindow {
  1068. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  1069. }
  1070. winC.delegate = self
  1071. winC.startModal("")
  1072. }
  1073. func splitView(withTag tag: Int) {
  1074. if tag == 0 {
  1075. self.listView.viewSplitMode = KMPDFViewSplitMode.horizontal
  1076. self.singlePageScreen(isSinglePage: false, doublePagesScreen: false)
  1077. } else if tag == 1 {
  1078. self.listView.viewSplitMode = KMPDFViewSplitMode.vertical
  1079. self.singlePageScreen(isSinglePage: false, doublePagesScreen: true)
  1080. } else if tag == 2 {
  1081. self.listView.viewSplitMode = KMPDFViewSplitMode.disable
  1082. self.singlePageScreen(isSinglePage: true, doublePagesScreen: false)
  1083. }
  1084. self.listView.needsDisplay = true
  1085. }
  1086. // MARK: - 幻灯片
  1087. func fadeInFullScreenWindow(with backgroundColor: NSColor, level: Int) {
  1088. let view: NSView = self.view.window!.firstResponder as! NSView
  1089. if view.isDescendant(of: pdfSplitView){
  1090. self.view.window?.makeFirstResponder(nil)
  1091. }
  1092. self.mainWindow = self.view.window
  1093. let fullScreenWindow = KMFullScreenWindow(screen: (self.mainWindow?.screen ?? NSScreen.main)!, bgColor: backgroundColor, level: NSWindow.Level.popUpMenu.rawValue, isMain: true)
  1094. fullScreenWindow.interactionParent = self.view.window
  1095. self.mainWindow?.delegate = nil
  1096. fullScreenWindow.fadeInBlocking()
  1097. self.browserWindowController?.window = fullScreenWindow
  1098. fullScreenWindow.makeKey()
  1099. let sel = NSSelectorFromString("setAnimationBehavior:")
  1100. if self.mainWindow?.responds(to: sel) ?? false{
  1101. self.mainWindow?.animationBehavior = .none
  1102. }
  1103. self.mainWindow?.orderOut(nil)
  1104. if self.mainWindow?.responds(to: sel) ?? false{
  1105. self.mainWindow?.animationBehavior = .default
  1106. }
  1107. fullScreenWindow.level = NSWindow.Level(rawValue: level)
  1108. fullScreenWindow.orderFront(nil)
  1109. }
  1110. func fadeInFullScreenView(_ view: NSView, inset: CGFloat) {
  1111. guard let fullScreenWindow = self.browserWindowController?.window as? KMFullScreenWindow else {
  1112. return
  1113. }
  1114. let fadeWindow = KMFullScreenWindow(screen: fullScreenWindow.screen!, bgColor: fullScreenWindow.backgroundColor, level: fullScreenWindow.level.rawValue, isMain: false)
  1115. fadeWindow.order(.above, relativeTo: fullScreenWindow.windowNumber)
  1116. view.frame = NSInsetRect(fullScreenWindow.contentView?.bounds ?? .zero, inset, 0)
  1117. fullScreenWindow.contentView?.addSubview(view)
  1118. self.listView.layoutDocumentView()
  1119. self.listView.requiresDisplay()
  1120. fullScreenWindow.makeFirstResponder(self.listView)
  1121. fullScreenWindow.recalculateKeyViewLoop()
  1122. fullScreenWindow.delegate = self.browserWindowController
  1123. fullScreenWindow.display()
  1124. fadeWindow.fadeOut()
  1125. }
  1126. // MARK: Redact 【密文标记】
  1127. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  1128. self.listView.remove(self.listView.activeAnnotation)
  1129. }
  1130. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  1131. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  1132. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  1133. self.view.window?.beginSheet(windowController.window!)
  1134. self.currentWindowController = windowController
  1135. windowController.itemClick = { [weak self] index, value in
  1136. if (index == 1) { /// 取消
  1137. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1138. self?.currentWindowController = nil
  1139. return
  1140. }
  1141. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  1142. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  1143. annotaton.setBorderColor(windowController_redact.outsideColor)
  1144. annotaton.setInteriorColor(windowController_redact.fillColor)
  1145. if (windowController_redact.isOver) {
  1146. annotaton.setFontColor(windowController_redact.fontColor)
  1147. annotaton.setAlignment(windowController_redact.aligement)
  1148. annotaton.setFont(windowController_redact.font)
  1149. annotaton.setOverlayText(windowController_redact.overText)
  1150. }
  1151. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1152. self?.currentWindowController = nil
  1153. }
  1154. }
  1155. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  1156. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1157. return
  1158. }
  1159. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  1160. let model = CPDFAnnotationModel(annotationType: .redact)
  1161. model?.setColor(annotation.borderColor())
  1162. model?.setInteriorColor(annotation.interiorColor())
  1163. let overlayText: String = annotation.overlayText()
  1164. if (overlayText.isEmpty) {
  1165. model?.setIsOverlayText(false)
  1166. } else {
  1167. model?.setIsOverlayText(true)
  1168. model?.setOverlayText(overlayText)
  1169. model?.setFontColor(annotation.fontColor())
  1170. model?.setAlignment(annotation.alignment())
  1171. model?.setFontName(annotation.font().fontName)
  1172. model?.setFontSize(annotation.font().pointSize)
  1173. }
  1174. }
  1175. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  1176. let anno = self.listView.activeAnnotation
  1177. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1178. return
  1179. }
  1180. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  1181. windowController.pageCount = Int(self.listView.document?.pageCount ?? 0)
  1182. self.currentWindowController = windowController
  1183. self.view.window?.beginSheet(windowController.window!)
  1184. windowController.itemClick = { [weak self] index, value in
  1185. if (index == 1) {
  1186. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1187. self!.currentWindowController = nil
  1188. return
  1189. }
  1190. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  1191. let pageType = windowController_mutilPageFlag.pageType
  1192. let pageString = windowController_mutilPageFlag.pageString
  1193. if (pageType == 4) { /// 自定义页面
  1194. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  1195. if (array.count == 0) {
  1196. let alert = NSAlert()
  1197. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  1198. alert.runModal()
  1199. return
  1200. }
  1201. }
  1202. self!.view.window?.endSheet(self!.currentWindowController.window!)
  1203. self!.currentWindowController = nil
  1204. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  1205. if (indexs.count == 0) {
  1206. return
  1207. }
  1208. for i in indexs {
  1209. let page: CPDFPage = (self?.listView.document?.page(at: UInt(i)))!
  1210. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  1211. self?.listView.add(redactAnno, to: page)
  1212. }
  1213. }
  1214. }
  1215. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  1216. self.exeRedactConfirm(.redactOne) {}
  1217. }
  1218. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  1219. self.exeRedactConfirm(.eraserOne) {}
  1220. }
  1221. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  1222. }
  1223. @objc func exportStampImage(sender:NSMenuItem) {
  1224. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) || (self.listView.selectImageAreas != nil) {
  1225. var image : NSImage = NSImage()
  1226. if (listView.activeAnnotation is CPDFStampAnnotation) {
  1227. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  1228. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  1229. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  1230. } else {
  1231. image = self.listView.selectImageAreas.thumbnailImage(with: CGSize(width: 1920, height: 1920)) ?? NSImage()
  1232. }
  1233. let data = image.tiffRepresentation
  1234. if sender.tag == 0 {
  1235. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1236. imageRep.size = image.size
  1237. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1238. let savePanel = NSSavePanel()
  1239. savePanel.allowedFileTypes = ["png"]
  1240. savePanel.beginSheetModal(for: self.view.window!) { response in
  1241. if (response != .OK) {
  1242. return
  1243. }
  1244. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1245. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1246. }
  1247. }
  1248. } else {
  1249. let pdfdocument = CPDFDocument()
  1250. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1251. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1252. pdfdocument?.km_insertPage(image.size, withImage: signatureImagePath!, at: 0)
  1253. let savePanel = NSSavePanel()
  1254. savePanel.allowedFileTypes = ["pdf"]
  1255. savePanel.beginSheetModal(for: self.view.window!) { response in
  1256. if (response != .OK) {
  1257. return
  1258. }
  1259. if pdfdocument!.write(to: savePanel.url!) {
  1260. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1261. }
  1262. }
  1263. }
  1264. }
  1265. }
  1266. }
  1267. @objc func exportCorpImage(sender:NSMenuItem) {
  1268. let rect = NSIntegralRect(listView.currentSelectionRect())
  1269. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1270. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1271. page.setBounds(rect, for: .cropBox)
  1272. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1273. let data = image.tiffRepresentation
  1274. guard let data = data else { return }
  1275. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data) ?? NSBitmapImageRep()
  1276. imageRep.size = rect.size
  1277. let savePanel = NSSavePanel()
  1278. switch sender.tag {
  1279. case 0:
  1280. savePanel.allowedFileTypes = ["png"]
  1281. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1282. savePanel.beginSheetModal(for: self.view.window!) { response in
  1283. if (response != .OK) {
  1284. return
  1285. }
  1286. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1287. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1288. }
  1289. }
  1290. case 1:
  1291. savePanel.allowedFileTypes = ["jpg"]
  1292. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1293. savePanel.beginSheetModal(for: self.view.window!) { response in
  1294. if (response != .OK) {
  1295. return
  1296. }
  1297. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1298. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1299. }
  1300. }
  1301. case 2:
  1302. savePanel.allowedFileTypes = ["pdf"]
  1303. let pdfdocument = CPDFDocument()
  1304. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1305. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1306. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1307. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1308. savePanel.beginSheetModal(for: self.view.window!) { response in
  1309. if (response != .OK) {
  1310. return
  1311. }
  1312. if pdfdocument!.write(to: savePanel.url!) {
  1313. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1314. }
  1315. }
  1316. }
  1317. default:
  1318. break
  1319. }
  1320. // 执行右键操作后,需要取消框选区域
  1321. if self.listView.toolMode == .selectToolMode {
  1322. objc_sync_enter(self)
  1323. self.listView.selectionRect = NSZeroRect
  1324. self.listView.selectionPageIndex = UInt(NSNotFound)
  1325. objc_sync_exit(self)
  1326. }
  1327. }
  1328. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1329. let rect = listView.currentSelectionRect()
  1330. let page = listView.currentPage()
  1331. if NSIsEmptyRect(rect) == false && page != nil {
  1332. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1333. var bounds = listView.bounds
  1334. var scale = 1.0
  1335. if isLegacy {
  1336. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1337. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1338. }
  1339. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1340. scale = NSHeight(bounds) / NSHeight(rect)
  1341. } else {
  1342. scale = NSWidth(bounds) / NSWidth(rect)
  1343. }
  1344. listView.setScaleFactor(scale, animated: false)
  1345. let scrollView = listView.scroll()
  1346. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1347. if ((scrollView?.hasVerticalScroller) != nil) {
  1348. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1349. }
  1350. if ((scrollView?.hasHorizontalScroller) != nil) {
  1351. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1352. }
  1353. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1354. scale = NSHeight(bounds) / NSHeight(rect)
  1355. } else {
  1356. scale = NSWidth(bounds) / NSWidth(rect)
  1357. }
  1358. listView.setScaleFactor(scale, animated: false)
  1359. }
  1360. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1361. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1362. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1363. };
  1364. }
  1365. // 执行右键操作后,需要取消框选区域
  1366. if self.listView.toolMode == .selectToolMode {
  1367. objc_sync_enter(self)
  1368. self.listView.selectionRect = NSZeroRect
  1369. self.listView.selectionPageIndex = UInt(NSNotFound)
  1370. objc_sync_exit(self)
  1371. }
  1372. }
  1373. private func cropPagesToRects(rects:NSPointerArray) {
  1374. }
  1375. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1376. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1377. switch sender.tag {
  1378. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1379. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1380. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1381. var red: CGFloat = 0.0
  1382. var green: CGFloat = 0.0
  1383. var blue: CGFloat = 0.0
  1384. var alpha: CGFloat = 0.0
  1385. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1386. if sender.tag == CAnnotationType.highlight.rawValue {
  1387. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1388. } else if sender.tag == CAnnotationType.underline.rawValue {
  1389. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1390. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1391. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1392. }
  1393. case CAnnotationType.ink.rawValue:
  1394. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1395. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1396. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1397. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1398. var red: CGFloat = 0.0
  1399. var green: CGFloat = 0.0
  1400. var blue: CGFloat = 0.0
  1401. var alpha: CGFloat = 0.0
  1402. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1403. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1404. case CAnnotationType.freeText.rawValue:
  1405. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1406. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1407. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1408. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1409. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1410. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1411. var red: CGFloat = 0.0
  1412. var green: CGFloat = 0.0
  1413. var blue: CGFloat = 0.0
  1414. var alpha: CGFloat = 0.0
  1415. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1416. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1417. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1418. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1419. UserDefaults.standard.synchronize()
  1420. }
  1421. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1422. if (alignment == .left || alignment == .center || alignment == .right) {
  1423. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1424. UserDefaults.standard.synchronize()
  1425. }
  1426. case CAnnotationType.anchored.rawValue:
  1427. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1428. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1429. var red: CGFloat = 0.0
  1430. var green: CGFloat = 0.0
  1431. var blue: CGFloat = 0.0
  1432. var alpha: CGFloat = 0.0
  1433. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1434. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1435. case CAnnotationType.square.rawValue:
  1436. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1437. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1438. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1439. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1440. var red: CGFloat = 0.0
  1441. var green: CGFloat = 0.0
  1442. var blue: CGFloat = 0.0
  1443. var alpha: CGFloat = 0.0
  1444. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1445. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1446. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1447. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1448. case CAnnotationType.circle.rawValue:
  1449. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1450. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1451. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1452. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1453. var red: CGFloat = 0.0
  1454. var green: CGFloat = 0.0
  1455. var blue: CGFloat = 0.0
  1456. var alpha: CGFloat = 0.0
  1457. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1458. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1459. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1460. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1461. default:
  1462. break
  1463. }
  1464. }
  1465. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1466. self.showOrHideNotes()
  1467. }
  1468. //MARK: - action
  1469. // 开启/关闭左边栏
  1470. @objc func toggleLeftPane() -> Void {
  1471. self.model.leftPanelOpen = true
  1472. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1473. }
  1474. // 开启左边栏
  1475. @objc func openLeftPane() -> Void {
  1476. self.model.leftPanelOpen = true
  1477. applyLeftSideWidth(self.model.panelWidth+functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1478. }
  1479. // 关闭左边栏
  1480. @objc func closeLeftPane() -> Void {
  1481. self.model.leftPanelOpen = false
  1482. applyLeftSideWidth(functionWidth, rightSideWidth: self.model.lastRightPanWidth)
  1483. }
  1484. func rename(_ sender: NSNotification) -> Void {
  1485. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1486. return
  1487. }
  1488. let tabController = sender.object as? CTTabController
  1489. if tabController?.title == self.document?.documentURL.deletingPathExtension().lastPathComponent {
  1490. if let doc = self.myDocument, doc.isDocumentEdited {
  1491. Task {
  1492. let resp = await KMAlertTool.runModel(message: NSLocalizedString("File Updated", comment: ""), buttons: [NSLocalizedString("Save", comment: ""), NSLocalizedString("Cancel", comment: "")])
  1493. if resp != .alertFirstButtonReturn { // 取消
  1494. return
  1495. }
  1496. doc.updateChangeCount(.changeCleared)
  1497. self.document?.write(to: doc.fileURL)
  1498. Task { @MainActor in
  1499. self._renameForSavePanel(tabController)
  1500. }
  1501. }
  1502. return
  1503. }
  1504. self._renameForSavePanel(tabController)
  1505. }
  1506. }
  1507. func savePdfAlertView() {
  1508. if AutoSaveManager.manager.isSaving || AutoSaveManager.manager.isSaveNoti{
  1509. return
  1510. }
  1511. AutoSaveManager.manager.isSaveNoti = true
  1512. var num = 0
  1513. if self.listView.document != nil{
  1514. num = Int(self.listView.document.pageCount)
  1515. }
  1516. if Thread.current.isMainThread {
  1517. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1518. } else {
  1519. DispatchQueue.main.async {
  1520. self.beginProgressSheet(withMessage: NSLocalizedString("Saving PDF", comment: "") + "...", maxValue: UInt(num))
  1521. }
  1522. }
  1523. }
  1524. func savePdfFinishAlertView() {
  1525. if !AutoSaveManager.manager.isSaveNoti{
  1526. return
  1527. }
  1528. AutoSaveManager.manager.isSaveNoti = false
  1529. if Thread.current.isMainThread {
  1530. self.dismissProgressSheet()
  1531. } else {
  1532. DispatchQueue.main.async {
  1533. self.dismissProgressSheet()
  1534. }
  1535. }
  1536. }
  1537. private func _renameForSavePanel(_ tabC: CTTabController?) {
  1538. let outputSavePanel = NSSavePanel()
  1539. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1540. outputSavePanel.allowedFileTypes = ["pdf"]
  1541. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1542. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1543. let resp = outputSavePanel.runModal()
  1544. if resp == .OK {
  1545. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1546. let fileURL = pdfDocument?.documentURL
  1547. let fileManager = FileManager.default
  1548. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1549. var result = true
  1550. do {
  1551. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1552. } catch {
  1553. result = false
  1554. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1555. }
  1556. if (result) {
  1557. tabC?.title = outputSavePanel.url!.lastPathComponent
  1558. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1559. self.model.isSaveKeyChain = false
  1560. newPdfDocument.unlock(withPassword: self.document?.password)
  1561. if (newPdfDocument.pageCount > 0) {
  1562. self.setDocument = newPdfDocument
  1563. }
  1564. }
  1565. }
  1566. } else {
  1567. outputSavePanel.close()
  1568. }
  1569. }
  1570. func showInFinder(_ sender: Any) -> Void {
  1571. if sender is NSNotification {
  1572. let tabController = (sender as! NSNotification).object as? CTTabController
  1573. let path = self.document?.documentURL.deletingPathExtension().lastPathComponent
  1574. if tabController?.title == path {
  1575. if let file = self.myDocument?.fileURL {
  1576. if FileManager.default.fileExists(atPath: file.path) {
  1577. NSWorkspace.shared.activateFileViewerSelecting([file])
  1578. }
  1579. }
  1580. }
  1581. } else {
  1582. guard let url = self.myDocument?.fileURL else { return }
  1583. let file: URL = url
  1584. if FileManager.default.fileExists(atPath: file.path) {
  1585. NSWorkspace.shared.activateFileViewerSelecting([file])
  1586. }
  1587. }
  1588. }
  1589. func closeTab(_ sender: NSNotification) -> Void {
  1590. }
  1591. @IBAction func toggleSplitPDF(_ sender: Any) {
  1592. if let menuItem = sender as? NSMenuItem {
  1593. splitView(withTag: menuItem.tag)
  1594. }
  1595. }
  1596. func changeLineAttribute(_ sender: Any?) {
  1597. var inspector = sender as? KMLineInspector
  1598. if inspector == nil {
  1599. inspector = KMLineInspector.shared
  1600. }
  1601. let action = inspector?.currentLineChangeAction ?? .no
  1602. for annotation in self.listView.activeAnnotations {
  1603. guard let anno = annotation as? CPDFAnnotation else {
  1604. continue
  1605. }
  1606. if anno.hasBorder() {
  1607. switch (action) {
  1608. case .lineWidth:
  1609. anno.setLineWidth(inspector?.lineWidth ?? 0)
  1610. break
  1611. case .style:
  1612. anno.setBorderStyle(CPDFBorderStyle(rawValue: inspector?.style ?? 0) ?? .solid)
  1613. break
  1614. case .dashPattern:
  1615. anno.setDashPattern(inspector?.dashPattern ?? [])
  1616. break
  1617. case .startLineStyle:
  1618. if anno.isLine() {
  1619. (anno as? CPDFLineAnnotation)?.startLineStyle = CPDFLineStyle(rawValue: inspector?.startLineStyle ?? 0) ?? .none
  1620. }
  1621. break
  1622. case .endLineStyle:
  1623. if anno.isLine() {
  1624. (anno as? CPDFLineAnnotation)?.endLineStyle = CPDFLineStyle(rawValue: inspector?.endLineStyle ?? 0) ?? .none
  1625. }
  1626. break
  1627. case .no:
  1628. break
  1629. }
  1630. }
  1631. }
  1632. }
  1633. // MARK: -
  1634. // MARK: 显示窗口
  1635. // internal func showCompressWindow(url: URL? = nil) {
  1636. //
  1637. // self.compressWIndowControllerNew = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1638. // self.view.window?.beginSheet(self.compressWIndowControllerNew!.window!)
  1639. // self.compressWIndowControllerNew?.password = self.listView.document?.password ?? ""
  1640. //
  1641. // self.compressWIndowControllerNew?.documentURL = self.listView.document.documentURL
  1642. //
  1643. //
  1644. // self.compressWIndowControllerNew?.itemClick = { [unowned self] in
  1645. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1646. //
  1647. // }
  1648. //
  1649. // self.compressWIndowControllerNew?.batchAction = { [unowned self] view, filePaths in
  1650. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1651. //
  1652. //
  1653. // let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1654. // let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path, type: .Compress)
  1655. // batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1656. // batchWindowController.window?.makeKeyAndOrderFront("")
  1657. // }
  1658. //
  1659. // self.compressWIndowControllerNew?.resultCallback = { [unowned self] result, openDocument, fileURL, error in
  1660. // self.view.window?.endSheet((self.compressWIndowControllerNew?.window)!)
  1661. // if (result) {
  1662. //
  1663. // if (openDocument) {
  1664. // NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1665. // } else {
  1666. // NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1667. // }
  1668. // } else {
  1669. // let alert = NSAlert()
  1670. // alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1671. // alert.runModal()
  1672. // }
  1673. // }
  1674. // }
  1675. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1676. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1677. KMPrint("转档窗口已显示")
  1678. return
  1679. }
  1680. var convertT: KMConvertType = .Word
  1681. var windowController: KMConvertBaseWindowController?
  1682. if (type == .word) { /// Word
  1683. convertT = .Word
  1684. windowController = KMConvertWordWindowController()
  1685. } else if (type == .excel) {
  1686. convertT = .Excel
  1687. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1688. if (type == .ppt) {
  1689. convertT = .PPT
  1690. } else if (type == .rtf) {
  1691. convertT = .RTF
  1692. } else if (type == .html) {
  1693. convertT = .HTML
  1694. } else if (type == .conversion_text) {
  1695. convertT = .Text
  1696. }
  1697. } else if (type == .csv) {
  1698. convertT = .CSV
  1699. } else if (type == .conversion_image) {
  1700. windowController = KMConvertImageWindowController()
  1701. convertT = .JPEG
  1702. } else if type == .json {
  1703. convertT = .Json
  1704. }
  1705. var url: URL?
  1706. if (documentUrl != nil) {
  1707. url = documentUrl
  1708. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1709. } else {
  1710. url = self.listView.document.documentURL
  1711. }
  1712. let model = KMDocumentModel(url: url!)
  1713. windowController?.documentModel = model
  1714. self.km_safe_beginSheet(windowC: windowController)
  1715. }
  1716. //MARK: 转档 -
  1717. func showAllConvertWindow(convertT: KMConvertType) {
  1718. self.ConvertTrackEvent(type: convertT)
  1719. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1720. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1721. var type: KMConvertWithPDFType = .WordAdvance
  1722. switch convertT {
  1723. case .Word:
  1724. break
  1725. case .Excel:
  1726. type = .Excel
  1727. case .PPT:
  1728. type = .PowerPoint
  1729. case .RTF:
  1730. type = .RTF
  1731. case .CSV:
  1732. type = .CSV
  1733. case .HTML:
  1734. type = .HTML
  1735. case .Text:
  1736. type = .Text
  1737. case .JPEG:
  1738. type = .JPEG
  1739. case .PNG:
  1740. type = .PNG
  1741. case .GIF:
  1742. type = .GIF
  1743. case .JPG:
  1744. type = .JPG
  1745. case .TIFF:
  1746. type = .TIFF
  1747. case .TGA:
  1748. type = .TGA
  1749. case .BMP:
  1750. type = .BMP
  1751. case .JP2:
  1752. type = .JPEG2000
  1753. case .AdvancedWord:
  1754. break
  1755. case .Json:
  1756. type = .Json
  1757. break
  1758. default:
  1759. break
  1760. }
  1761. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1762. var needShowHint = false
  1763. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1764. needShowHint = true
  1765. } else {
  1766. var needContinue = false
  1767. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1768. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1769. let ss = self.document?.documentURL.path
  1770. if arr.contains(ss!) {
  1771. needContinue = false
  1772. }else {
  1773. needContinue = true
  1774. }
  1775. }else {
  1776. needContinue = true
  1777. }
  1778. if needContinue {
  1779. let ss = self.document?.documentURL.path
  1780. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1781. file.password = document?.password ?? ""
  1782. KMBatchOperateManager.defaultManager.files?.append(file)
  1783. }
  1784. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1785. batchWindowController.switchToConvertType(convertType: type)
  1786. }
  1787. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1788. if needShowHint {
  1789. batchWindowController.showIsConvertingHint()
  1790. } else {
  1791. }
  1792. }
  1793. }
  1794. self.km_beginSheet(windowC: convertWC)
  1795. }
  1796. func ConvertTrackEvent(type: KMConvertType) {
  1797. var eventStr: String = "Btn_SubTbr_Converter_ToWord"
  1798. switch type {
  1799. case .Word:
  1800. eventStr = "Btn_SubTbr_Converter_ToWord"
  1801. break
  1802. case .Excel:
  1803. eventStr = "Btn_SubTbr_Converter_ToExcel"
  1804. case .PPT:
  1805. eventStr = "Btn_SubTbr_Converter_ToPPT"
  1806. case .RTF:
  1807. eventStr = "Btn_SubTbr_Converter_ToRTF"
  1808. case .CSV:
  1809. eventStr = "Btn_SubTbr_Converter_ToCSV"
  1810. case .HTML:
  1811. eventStr = "Btn_SubTbr_Converter_ToHTML"
  1812. case .Text:
  1813. eventStr = "Btn_SubTbr_Converter_ToText"
  1814. case .JPEG:
  1815. eventStr = "Btn_SubTbr_Converter_ToImage"
  1816. case .PNG:
  1817. eventStr = "Btn_SubTbr_Converter_ToImage"
  1818. case .GIF:
  1819. eventStr = "Btn_SubTbr_Converter_ToImage"
  1820. case .JPG:
  1821. eventStr = "Btn_SubTbr_Converter_ToImage"
  1822. case .TIFF:
  1823. eventStr = "Btn_SubTbr_Converter_ToImage"
  1824. case .TGA:
  1825. eventStr = "Btn_SubTbr_Converter_ToImage"
  1826. case .BMP:
  1827. eventStr = "Btn_SubTbr_Converter_ToImage"
  1828. case .JP2:
  1829. eventStr = "Btn_SubTbr_Converter_ToImage"
  1830. case .AdvancedWord:
  1831. eventStr = "Btn_SubTbr_Converter_ToWord"
  1832. break
  1833. default:
  1834. break
  1835. }
  1836. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": eventStr])
  1837. }
  1838. //MARK: 转档 - OCR
  1839. func showOCRWindow() {
  1840. if !IAPProductsManager.default().isAvailableAllFunction(){
  1841. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1842. winC?.showWindow(nil)
  1843. return
  1844. }
  1845. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document?.password ?? "")
  1846. com.currentIndexPage = self.listView.currentPageIndex
  1847. self.km_beginSheet(windowC: com)
  1848. }
  1849. //MARK: 导出图片
  1850. func extractImageAction(num: Int) {
  1851. if !IAPProductsManager.default().isAvailableAllFunction(){
  1852. let winC = KMPurchaseCompareWindowController.sharedInstance()
  1853. winC?.kEventName = "Reading_ExtractImage_BuyNow"
  1854. winC?.showWindow(nil)
  1855. return
  1856. }
  1857. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1858. let alert = NSAlert()
  1859. alert.alertStyle = .critical
  1860. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1861. alert.runModal()
  1862. return
  1863. }
  1864. let document = self.listView.document
  1865. var fileURL = document?.documentURL
  1866. if num == 1 {
  1867. let pageCount = document?.pageCount ?? 0
  1868. let indeSet = NSMutableIndexSet()
  1869. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1870. if indeSet.count == 0 {
  1871. return
  1872. }
  1873. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  1874. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  1875. let outputSavePanel = NSSavePanel()
  1876. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  1877. outputSavePanel.allowsOtherFileTypes = true
  1878. outputSavePanel.isExtensionHidden = true
  1879. outputSavePanel.canCreateDirectories = true
  1880. outputSavePanel.nameFieldStringValue = tFileName
  1881. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  1882. if result == NSApplication.ModalResponse.OK {
  1883. DispatchQueue.main.async {
  1884. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  1885. let tDestFile = outputSavePanel.url!.path
  1886. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  1887. let pdfconverter = PDFConvertObject()
  1888. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  1889. self.dismissProgressSheet()
  1890. let fileManager = FileManager.default
  1891. if fileManager.fileExists(atPath: tDestFile) {
  1892. let workspace = NSWorkspace.shared
  1893. let url = URL(fileURLWithPath: tDestFile)
  1894. workspace.activateFileViewerSelecting([url])
  1895. }
  1896. }
  1897. }
  1898. })
  1899. return
  1900. }
  1901. if fileURL != nil {
  1902. self.myDocument?.save(nil)
  1903. } else {
  1904. let myDocument = self.myDocument
  1905. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  1906. let writeSuccess = document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1907. if writeSuccess {
  1908. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1909. fileURL = document?.documentURL
  1910. } else {
  1911. NSSound.beep()
  1912. return
  1913. }
  1914. }
  1915. extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  1916. extract?.docPath = fileURL?.path ?? ""
  1917. extract?.password = document?.password ?? ""
  1918. extract?.currentPage = self.listView.currentPageIndex
  1919. self.km_beginSheet(windowC: extract!)
  1920. extract?.selectCurrentPageBtn()
  1921. }
  1922. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  1923. let progress = SKProgressController()
  1924. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1925. progress.window?.contentView?.wantsLayer = true
  1926. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1927. progress.progressField.textColor = NSColor.white
  1928. progress.message = NSLocalizedString("Converting...", comment: "")
  1929. progressC = progress
  1930. progressC?.message = message
  1931. if maxValue > 0 {
  1932. progressC?.indeterminate = false
  1933. progressC?.maxValue = Double(maxValue)
  1934. progressC?.progressBar.doubleValue = 0.3
  1935. } else {
  1936. progressC?.indeterminate = true
  1937. }
  1938. self.view.km_beginSheet(windowC: progressC!)
  1939. }
  1940. func dismissProgressSheet() {
  1941. progressC?.stopAnimation()
  1942. self.view.km_endSheet()
  1943. progressC = nil
  1944. }
  1945. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  1946. let newArr = NSMutableArray()
  1947. for item in files {
  1948. newArr.add(item.filePath)
  1949. }
  1950. return newArr as! [String]
  1951. }
  1952. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  1953. self.saveDocument()
  1954. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  1955. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  1956. if (result == .cancel) {
  1957. return
  1958. }
  1959. // 解除权限
  1960. self?.listView.document.unlock(withPassword: password)
  1961. // 隐藏提示
  1962. self?.hiddenSecureLimitTip()
  1963. // 去打印
  1964. KMPrintWindowController.openDocument(inputDocument: self?.listView.document, inputPageRange: pageRange)
  1965. }
  1966. return
  1967. }
  1968. KMPrintWindowController.openDocument(inputDocument: self.listView.document, inputPageRange: pageRange)
  1969. }
  1970. // MARK: - 图片注释
  1971. @IBAction func imageAnnotation(_ sender: Any) {
  1972. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Image"])
  1973. changeAnnotationMode(sender)
  1974. guard IAPProductsManager.default().isAvailableAllFunction() else {
  1975. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1976. return
  1977. }
  1978. let accessoryCtr = KMImageAccessoryController()
  1979. let openPanel = NSOpenPanel()
  1980. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  1981. openPanel.allowsMultipleSelection = false
  1982. openPanel.accessoryView = accessoryCtr.view
  1983. openPanel.canSelectHiddenExtension = true
  1984. openPanel.beginSheetModal(for: NSApp.mainWindow!) { [self] (result) in
  1985. if result == .OK {
  1986. guard let url = openPanel.url else {
  1987. return
  1988. }
  1989. let filePath = url.path
  1990. if filePath.pathExtension.lowercased() == "pdf" {
  1991. if let pdf = PDFDocument(url: url), pdf.isEncrypted {
  1992. NSSound.beep()
  1993. return
  1994. }
  1995. }
  1996. guard let image = NSImage(contentsOfFile: url.path) else {
  1997. let alert = NSAlert()
  1998. alert.alertStyle = .critical
  1999. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2000. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2001. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2002. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2003. if response == .alertFirstButtonReturn {
  2004. // Handle cancel button clicked
  2005. }
  2006. }
  2007. return
  2008. }
  2009. let isDamageImage: Bool = self.isDamageImage(image, imagePath: url.path)
  2010. if isDamageImage {
  2011. let alert = NSAlert()
  2012. alert.alertStyle = .critical
  2013. alert.messageText = String(format: NSLocalizedString("The file \"%@\" could not be opened.", comment: ""), url.lastPathComponent)
  2014. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  2015. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2016. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  2017. if response == .alertFirstButtonReturn {
  2018. // Handle cancel button clicked
  2019. }
  2020. }
  2021. return
  2022. }
  2023. let isRemoveBGColor = accessoryCtr.selectedButton.state == .on
  2024. listView.addAnnotation(with: image, isRemoveBGColor: isRemoveBGColor)
  2025. if (self.listView.activeAnnotation != nil) && (self.listView.activeAnnotation.type == "Image") {
  2026. }
  2027. }
  2028. }
  2029. }
  2030. @IBAction func tableAnnotation(_ sender: Any) {
  2031. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Tools_Table"])
  2032. changeAnnotationMode(sender)
  2033. guard IAPProductsManager.default().isAvailableAllFunction() else {
  2034. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2035. winC?.kEventName = "Reading_Table_BuyNow"
  2036. winC?.showWindow(nil)
  2037. return
  2038. }
  2039. listView.addAnnotationWithTable()
  2040. toggleOpenRightSide()
  2041. }
  2042. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  2043. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!)
  2044. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  2045. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  2046. }
  2047. if let data = image.tiffRepresentation,
  2048. let imageRep = NSBitmapImageRep(data: data) {
  2049. imageRep.size = image.size
  2050. var imageData: Data?
  2051. if path.lowercased() == "png" {
  2052. imageData = imageRep.representation(using: .png, properties: [:])
  2053. } else {
  2054. imageData = imageRep.representation(using: .jpeg, properties: [:])
  2055. }
  2056. if let imageData = imageData {
  2057. let rPath = (addImageAnnotation as NSString).appendingPathComponent((self.tagString() as NSString).appendingPathExtension("png")!)
  2058. if !((try? imageData.write(to: URL(fileURLWithPath: rPath), options: .atomicWrite)) != nil) {
  2059. return true
  2060. } else {
  2061. return false
  2062. }
  2063. }
  2064. }
  2065. return false
  2066. }
  2067. func tagString() -> String {
  2068. let dateFormatter = DateFormatter()
  2069. dateFormatter.dateFormat = "yyMMddHHmmss"
  2070. return "\(dateFormatter.string(from: Date()))\(Int.random(in: 0..<10000))"
  2071. }
  2072. // MARK: - Split View
  2073. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2074. }
  2075. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2076. }
  2077. func updateBackAndForwardButtonState() {
  2078. }
  2079. }
  2080. extension KMMainViewController {
  2081. func changeModelAction(mode: CToolMode) {
  2082. self.listView.toolMode = mode
  2083. if mode == .editPDFToolMode {
  2084. }
  2085. }
  2086. func changePDFViewZoomInAction() {
  2087. }
  2088. func changePDFViewZoomOutAction() {
  2089. }
  2090. func changePDFViewGotoNextPageAction() {
  2091. self.listView.km_goBack(nil)
  2092. if (self.listView.canGoToNextPage()) {
  2093. self.listView.goToNextPage(nil)
  2094. }
  2095. }
  2096. func changePDFViewGoToPreviousPageAction() {
  2097. if (self.listView.canGoToPreviousPage()) {
  2098. self.listView.goToPreviousPage(nil)
  2099. }
  2100. }
  2101. func changePDFViewGotoBackAction() {
  2102. self.listView.km_goBack(nil)
  2103. self.updateBackAndForwardButtonState()
  2104. }
  2105. func changePDFViewGoToForwardAction() {
  2106. self.listView.km_goForward(nil)
  2107. self.updateBackAndForwardButtonState()
  2108. }
  2109. func aiTranslationPDFFileAction() {
  2110. self.trackEvent_aiTranslate()
  2111. self._aiTranslationPDFFileAction()
  2112. }
  2113. private func _aiTranslationPDFFileAction() {
  2114. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2115. if KMTools.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2116. let alert = NSAlert()
  2117. alert.alertStyle = .critical
  2118. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2119. alert.runModal()
  2120. return
  2121. } else if isExceedsLimit {
  2122. let alert = NSAlert()
  2123. alert.alertStyle = .critical
  2124. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2125. alert.runModal()
  2126. return
  2127. }
  2128. let alert = NSAlert()
  2129. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2130. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2131. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2132. alert.beginSheetModal(for: view.window!) { [weak self] result in
  2133. if (result == .alertFirstButtonReturn) {
  2134. } else if result == .alertSecondButtonReturn {
  2135. return
  2136. }
  2137. }
  2138. }
  2139. func clickChildTool(type: KMToolbarType, index: Int) {
  2140. if (type == .secure) {
  2141. if (index == 1) {
  2142. self.trackEvent_setPassword()
  2143. } else if (index == 2) {
  2144. self.trackEvent_removePassword()
  2145. }
  2146. } else {
  2147. self.trackEvent(toolBarType: type)
  2148. }
  2149. Task { @MainActor in
  2150. if (type == .compress) { /// 压缩
  2151. if !self.documentAllowsEdit() {
  2152. return
  2153. }
  2154. if (self.needSaveDocument()) {
  2155. self.saveDocumentWithProgressAlert { [unowned self] params in
  2156. // self.showCompressWindow()
  2157. }
  2158. return
  2159. }
  2160. // self.showCompressWindow()
  2161. return
  2162. }
  2163. if ((KMToolbarType.word.rawValue ... KMToolbarType.json.rawValue).contains(type.rawValue)) { /// 转档
  2164. if type == .conversion_imageToPDF {
  2165. Task {
  2166. let _ = await NSApplication.ShowImageToPDFWindow(urls: [])
  2167. }
  2168. return
  2169. }
  2170. var identifier: String?
  2171. if (type == .word) { /// Word
  2172. identifier = KMToolbarConversionWordItemIdentifier
  2173. } else if (type == .excel) {
  2174. identifier = KMToolbarConversionExcelItemIdentifier
  2175. } else if (type == .ppt) {
  2176. identifier = KMToolbarConversionPPTItemIdentifier
  2177. } else if (type == .rtf) {
  2178. identifier = KMToolbarConversionRTFItemIdentifier
  2179. } else if (type == .html) {
  2180. identifier = KMToolbarConversionHTMLItemIdentifier
  2181. } else if (type == .conversion_text) {
  2182. identifier = KMToolbarConversionTextItemIdentifier
  2183. } else if (type == .csv) {
  2184. identifier = KMToolbarConversionCSVItemIdentifier
  2185. } else if (type == .conversion_image) {
  2186. identifier = KMToolbarConversionImageItemIdentifier
  2187. }
  2188. if (self.needSaveDocument()) {
  2189. self.saveDocumentWithProgressAlert { [unowned self] params in
  2190. self.showConvertWindow(type: type, identifier: identifier)
  2191. }
  2192. return
  2193. }
  2194. self.showConvertWindow(type: type, identifier: identifier)
  2195. return
  2196. }
  2197. if (type == .merge) { /// 合并
  2198. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Merge"])
  2199. if !self.documentAllowsEdit() {
  2200. return
  2201. }
  2202. if (self.needSaveDocument()) {
  2203. self.saveDocumentWithProgressAlert { [unowned self] params in
  2204. self.showMergeWindow(self.listView.document.password)
  2205. }
  2206. return
  2207. }
  2208. self.showMergeWindow(self.listView.document.password)
  2209. return
  2210. }
  2211. if (type == .bates || type == .headerAndFooter) {
  2212. if !IAPProductsManager.default().isAvailableAllFunction(){
  2213. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2214. if type == .headerAndFooter {
  2215. if index == 1 {
  2216. winC?.kEventName = "Reading_AddHeaderFooter_BuyNow"
  2217. } else if index == 2 {
  2218. winC?.kEventName = "Reading_RemoveHeaderFooter_BuyNow"
  2219. }
  2220. } else if type == .bates {
  2221. if index == 1 {
  2222. winC?.kEventName = "Reading_AddBates_BuyNow"
  2223. } else if index == 2 {
  2224. winC?.kEventName = "Reading_RemoveBates_BuyNow"
  2225. }
  2226. }
  2227. winC?.showWindow(nil)
  2228. return
  2229. }
  2230. if !self.documentAllowsEdit() {
  2231. return
  2232. }
  2233. if (index == 1) {
  2234. var windowController: KMBaseWindowController = KMBaseWindowController()
  2235. if (type == .bates) {
  2236. } else if (type == .headerAndFooter) {
  2237. } else if (type == .background) {
  2238. } else if (type == .watermark) {
  2239. }
  2240. windowController.pdfDocument = self.listView.document
  2241. windowController.cancelAction = { [unowned self] controller in
  2242. self.view.window?.endSheet((self.currentWindowController.window)!)
  2243. self.currentWindowController = nil
  2244. }
  2245. self.currentWindowController = windowController
  2246. await self.view.window?.beginSheet(windowController.window!)
  2247. return
  2248. }
  2249. if (index == 1) { /// 取消
  2250. ///
  2251. toggleCloseRightSide()
  2252. return
  2253. } else if index == 3 {
  2254. let fpath = self.document?.documentURL?.path ?? ""
  2255. if type == .bates {
  2256. self.showBatchWindow(type: .AddBates, filepaths: [fpath])
  2257. } else {
  2258. self.showBatchWindow(type: .AddHeaderFooter, filepaths: [fpath])
  2259. }
  2260. } else if index == 4 {
  2261. let fpath = self.document?.documentURL?.path ?? ""
  2262. if type == .bates {
  2263. self.showBatchWindow(type: .RemoveBates, filepaths: [fpath])
  2264. } else {
  2265. self.showBatchWindow(type: .RemoveHeaderFooter, filepaths: [fpath])
  2266. }
  2267. } else if (index == 2) { //// 移除
  2268. if type == .headerAndFooter {
  2269. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2270. let savePanel = NSSavePanel()
  2271. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2272. savePanel.allowedFileTypes = ["pdf"]
  2273. savePanel.accessoryView = savePanelAccessoryViewController.view
  2274. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2275. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2276. }
  2277. }
  2278. } else if type == .bates {
  2279. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2280. let savePanel = NSSavePanel()
  2281. savePanel.nameFieldStringValue = self.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  2282. savePanel.allowedFileTypes = ["pdf"]
  2283. savePanel.accessoryView = savePanelAccessoryViewController.view
  2284. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { [unowned self] result in
  2285. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  2286. }
  2287. }
  2288. }
  2289. } else if (index == 2) { /// 应用
  2290. } else if index == 5 {
  2291. self.toggleOpenRightSide()
  2292. }
  2293. } else if (type == .redact) { /// 标记密文
  2294. if !IAPProductsManager.default().isAvailableAllFunction(){
  2295. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  2296. return
  2297. }
  2298. if (index == 1) { /// 取消
  2299. if (self.model.hasAddRedact) {
  2300. let alert = NSAlert()
  2301. 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: "")
  2302. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2303. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2304. let result = alert.runModal()
  2305. if (result == .alertFirstButtonReturn) {
  2306. self.listView.toolMode = .moveToolMode
  2307. }
  2308. return
  2309. }
  2310. self.listView.toolMode = .moveToolMode
  2311. return
  2312. }
  2313. if (index == 2) { /// 擦除
  2314. self.exeRedactConfirm(.eraserAll) {}
  2315. return
  2316. }
  2317. if (index == 3) { /// 应用
  2318. self.exeRedactConfirm(.redactAll) {}
  2319. return
  2320. }
  2321. if (index == 4) { /// 文本&图像
  2322. self.listView.toolMode = .redactToolMode
  2323. return
  2324. }
  2325. if (index == 5) { /// 页面
  2326. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2327. await self.view.window?.beginSheet(windowController.window!)
  2328. self.currentWindowController = windowController
  2329. windowController.itemClick = { [weak self] index, value in
  2330. if (index == 1) {
  2331. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2332. self?.currentWindowController = nil
  2333. return
  2334. }
  2335. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2336. let pageType = windowController_pageRange.pageType
  2337. let pageString = windowController_pageRange.pageString
  2338. if (pageType == 5) { /// 自定义页面
  2339. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document?.pageCount) ?? 0))
  2340. if (array.count == 0) {
  2341. let alert = NSAlert()
  2342. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2343. alert.runModal()
  2344. return
  2345. }
  2346. }
  2347. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2348. self!.currentWindowController = nil
  2349. var indexs: IndexSet = []
  2350. if (pageType == 1) { /// 当前页面
  2351. indexs.insert((self?.listView.currentPageIndex)!)
  2352. } else {
  2353. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document?.pageCount) ?? 0))
  2354. }
  2355. if (indexs.count == 0) {
  2356. return
  2357. }
  2358. for i in indexs {
  2359. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2360. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2361. redactAnno.bounds = page.bounds
  2362. self?.listView.add(redactAnno, to: page)
  2363. }
  2364. }
  2365. return
  2366. }
  2367. } else if (type == .secure) { /// 安全
  2368. if (index == 1) { /// 设置密码
  2369. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2370. if !self.documentAllowsEdit() {
  2371. return
  2372. }
  2373. }
  2374. self.showSecureWindow(self.listView.document.documentURL)
  2375. return
  2376. } else if index == 2 {
  2377. if !self.document!.allowsCopying || !self.document!.allowsPrinting {
  2378. let alert = NSAlert()
  2379. alert.alertStyle = .warning
  2380. alert.messageText = NSLocalizedString("Warning", comment: "")
  2381. alert.informativeText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2382. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  2383. alert.addButton(withTitle: NSLocalizedString("Remove Security", comment: ""))
  2384. alert.beginSheetModal(for: NSWindow.currentWindow()) { returnCode in
  2385. if returnCode == .alertSecondButtonReturn {
  2386. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  2387. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner) { [unowned self] success, resultPassword in
  2388. if success {
  2389. self.document?.unlock(withPassword: resultPassword)
  2390. self.clickChildTool(type: .secure, index: 2)
  2391. }
  2392. }
  2393. }
  2394. }
  2395. }
  2396. } else {
  2397. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2398. controller.pdfDocument = self.document
  2399. self.currentWindowController = controller
  2400. controller.batchAction = { [unowned self] controller, files in
  2401. self.view.window?.endSheet((self.currentWindowController.window)!)
  2402. self.currentWindowController = nil
  2403. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  2404. if #available(macOS 10.13, *) {
  2405. baseWindowController.window?.makeKeyAndOrderFront(nil)
  2406. } else {
  2407. baseWindowController.showWindow(nil)
  2408. }
  2409. let arr = NSMutableArray()
  2410. let file = KMBatchOperateFile(filePath: self.listView.document!.documentURL!.path, type: .RemovePassword)
  2411. file.password = document?.password ?? ""
  2412. arr.add(file)
  2413. baseWindowController.switchToOperateType(.RemovePassword, files: arr as! [KMBatchOperateFile])
  2414. }
  2415. controller.cancelAction = { [unowned self] controller in
  2416. self.view.window?.endSheet((self.currentWindowController.window)!)
  2417. self.currentWindowController = nil
  2418. }
  2419. controller.doneAction = { [unowned self] controller in
  2420. self.view.window?.endSheet((self.currentWindowController.window)!)
  2421. self.currentWindowController = nil
  2422. KMBaseWindowController.checkPassword(url: self.document!.documentURL!, type: .owner, password: self.document?.password ?? "") { [unowned self] success, resultPassword in
  2423. if success {
  2424. let savePanel = NSSavePanel()
  2425. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent + "_RemovePassword"
  2426. savePanel.allowedFileTypes = ["pdf"]
  2427. savePanel.beginSheetModal(for: NSApp.mainWindow!) {[unowned self] result in
  2428. guard result == .OK else { return }
  2429. /// 删除安全性设置
  2430. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2431. self.model.isSaveKeyChain = false
  2432. self.listView.document.unlock(withPassword: resultPassword)
  2433. }
  2434. let document = CPDFDocument.init(url: self.listView.document.documentURL)
  2435. guard let document = document else { return }
  2436. document.unlock(withPassword: resultPassword)
  2437. let success = document.writeDecrypt(to: savePanel.url)
  2438. if success {
  2439. self.hiddenSecureLimitTip()
  2440. let tip = KMRemovePasswordResultTipView()
  2441. tip.result = .success
  2442. tip.showInView(superView: (self.listView.superview)!)
  2443. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  2444. } else {
  2445. self.hiddenSecureLimitTip()
  2446. let tip = KMRemovePasswordResultTipView()
  2447. tip.result = .failure
  2448. tip.showInView(superView: (self.listView.superview)!)
  2449. }
  2450. }
  2451. }
  2452. }
  2453. }
  2454. await NSWindow.currentWindow().beginSheet(controller.window!)
  2455. }
  2456. return
  2457. }
  2458. } else if type == .comparison {
  2459. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compare"])
  2460. if !IAPProductsManager.default().isAvailableAllFunction(){
  2461. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2462. winC?.kEventName = "Reading_Compare_BuyNow"
  2463. winC?.showWindow(nil)
  2464. return
  2465. }
  2466. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2467. self.currentWindowController = controller
  2468. controller.password = self.document?.password ?? ""
  2469. controller.filePath = (self.document?.documentURL.path)!
  2470. controller.cancelAction = { [unowned self] controller in
  2471. self.view.window?.endSheet((self.currentWindowController.window)!)
  2472. self.currentWindowController = nil
  2473. }
  2474. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  2475. self.view.window?.endSheet((self.currentWindowController.window)!)
  2476. self.currentWindowController = nil
  2477. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  2478. }
  2479. controller.coveringComplete = { [unowned self] controller, document in
  2480. self.view.window?.endSheet((self.currentWindowController.window)!)
  2481. self.currentWindowController = nil
  2482. self.openCoveringCompareVC(with: document)
  2483. }
  2484. if index == 1 {
  2485. controller.fileType = .content
  2486. } else {
  2487. controller.fileType = .coverting
  2488. }
  2489. await NSWindow.currentWindow().beginSheet(controller.window!)
  2490. } else if type == .watermark {
  2491. if !IAPProductsManager.default().isAvailableAllFunction(){
  2492. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2493. if index == 1 {
  2494. winC?.kEventName = "Reading_AddWatermark_BuyNow"
  2495. } else if index == 2 {
  2496. winC?.kEventName = "Reading_RemoveWatermark_BuyNow"
  2497. }
  2498. winC?.showWindow(nil)
  2499. return
  2500. }
  2501. if !self.documentAllowsEdit() {
  2502. return
  2503. }
  2504. if index == 1 {
  2505. } else if index == 2 {
  2506. let watermarks = self.listView.document.watermarks()
  2507. if (watermarks == nil || watermarks!.count <= 0) {
  2508. let alert = NSAlert()
  2509. alert.alertStyle = .warning
  2510. alert.messageText = NSLocalizedString("Could not find a removable watermark in this document. If you see a watermark, it was not added with PDF Reader Pro and therefore cannot be detected.", comment: "")
  2511. alert.addButton(withTitle: NSLocalizedString("Confirm", comment: ""))
  2512. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2513. alert.runModal()
  2514. return
  2515. }
  2516. let alert = NSAlert()
  2517. alert.alertStyle = .warning
  2518. alert.messageText = NSLocalizedString("Are you sure you want to remove the watermark?", comment: "")
  2519. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  2520. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2521. let result = alert.runModal()
  2522. if (result != .alertFirstButtonReturn) {
  2523. return
  2524. }
  2525. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2526. let savePanel = NSSavePanel()
  2527. savePanel.nameFieldStringValue = self.listView.document.documentURL.deletingPathExtension().lastPathComponent
  2528. savePanel.allowedFileTypes = ["pdf"]
  2529. savePanel.accessoryView = savePanelAccessoryViewController.view
  2530. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2531. guard result == .OK else { return }
  2532. }
  2533. } else if index == 3 {
  2534. let fpath = self.document?.documentURL?.path ?? ""
  2535. self.showBatchWindow(type: .AddWatermark, filepaths: [fpath])
  2536. } else if index == 4 {
  2537. let fpath = self.document?.documentURL?.path ?? ""
  2538. self.showBatchWindow(type: .RemoveWatermark, filepaths: [fpath])
  2539. } else if index == 5 {
  2540. toggleOpenRightSide()
  2541. return
  2542. }
  2543. } else if type == .background {
  2544. if !IAPProductsManager.default().isAvailableAllFunction(){
  2545. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2546. if index == 1 {
  2547. winC?.kEventName = "Reading_AddBackground_BuyNow"
  2548. } else if index == 2 {
  2549. winC?.kEventName = "Reading_RemoveBackground_BuyNow"
  2550. }
  2551. winC?.showWindow(nil)
  2552. return
  2553. }
  2554. if !self.documentAllowsEdit() {
  2555. return
  2556. }
  2557. if index == 1 {
  2558. } else if index == 2 {
  2559. guard let document = self.document else { return }
  2560. if !document.allowsPrinting || !document.allowsCopying {
  2561. let alert = NSAlert()
  2562. alert.alertStyle = .critical
  2563. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  2564. alert.runModal()
  2565. return
  2566. }
  2567. guard let documentURL = document.documentURL else { return }
  2568. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  2569. let savePanel = NSSavePanel()
  2570. savePanel.nameFieldStringValue = documentURL.deletingPathExtension().lastPathComponent
  2571. savePanel.allowedFileTypes = ["pdf"]
  2572. savePanel.accessoryView = savePanelAccessoryViewController.view
  2573. savePanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  2574. guard result == .OK else { return }
  2575. }
  2576. } else if index == 3 {
  2577. let fpath = self.document?.documentURL?.path ?? ""
  2578. self.showBatchWindow(type: .AddBackground, filepaths: [fpath])
  2579. } else if index == 4 {
  2580. let fpath = self.document?.documentURL?.path ?? ""
  2581. self.showBatchWindow(type: .RemoveBackground, filepaths: [fpath])
  2582. } else if index == 5 {
  2583. toggleOpenRightSide()
  2584. return
  2585. }
  2586. } else if type == .measure {
  2587. if !IAPProductsManager.default().isAvailableAllFunction(){
  2588. let winC = KMPurchaseCompareWindowController.sharedInstance()
  2589. winC?.kEventName = "Reading_Measure_BuyNow"
  2590. winC?.showWindow(nil)
  2591. return
  2592. }
  2593. if !self.documentAllowsEdit() {
  2594. return
  2595. }
  2596. self.listView.toolMode = .measureToolMode
  2597. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  2598. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2599. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  2600. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2601. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  2602. areaMeasureInfoWindowController?.hideFloatingWindow()
  2603. }
  2604. if distanceMeasureInfoWindowController == nil {
  2605. let measureInfo = CPDFDistanceMeasureInfo()
  2606. distanceMeasureInfoWindowController = CDistanceMeasureInfoWindowController()
  2607. distanceMeasureInfoWindowController?.measureInfo = measureInfo
  2608. distanceMeasureInfoWindowController?.delegate = self
  2609. }
  2610. if perimeterMeasureInfoWindowController == nil {
  2611. let measureInfo = CPDFPerimeterMeasureInfo()
  2612. perimeterMeasureInfoWindowController = CPerimeterMeasureInfoWindowController()
  2613. perimeterMeasureInfoWindowController?.measureInfo = measureInfo
  2614. perimeterMeasureInfoWindowController?.delegate = self
  2615. }
  2616. if areaMeasureInfoWindowController == nil {
  2617. let measureInfo = CPDFAreaMeasureInfo()
  2618. areaMeasureInfoWindowController = CAreaMeasureInfoWindowController()
  2619. areaMeasureInfoWindowController?.measureInfo = measureInfo
  2620. areaMeasureInfoWindowController?.delegate = self
  2621. }
  2622. if index == 1 {
  2623. self.listView.annotationType = .line
  2624. let winW: CGFloat = 300
  2625. let rightW: CGFloat = 270
  2626. var winFrame = self.view.window?.frame ?? .zero
  2627. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2628. distanceMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2629. distanceMeasureInfoWindowController?.showWindow(nil)
  2630. distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2631. distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2632. distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2633. distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2634. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2635. self.trackEvent(toolMode: .measureToolMode)
  2636. } else if index == 2 {
  2637. self.listView.annotationType = .polyLine
  2638. let winW: CGFloat = 300
  2639. let rightW: CGFloat = 270
  2640. var winFrame = self.view.window?.frame ?? .zero
  2641. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2642. perimeterMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2643. perimeterMeasureInfoWindowController?.showWindow(nil)
  2644. perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2645. perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2646. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2647. self.trackEvent(toolMode: .measureToolMode)
  2648. } else if index == 3 {
  2649. self.listView.annotationType = .polyGon
  2650. let winW: CGFloat = 300
  2651. let rightW: CGFloat = 270
  2652. var winFrame = self.view.window?.frame ?? .zero
  2653. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2654. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2655. areaMeasureInfoWindowController?.showWindow(nil)
  2656. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2657. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2658. _ = CustomAlertView.alertView(message: "Double-click to finish drawing. Press ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2659. self.trackEvent(toolMode: .measureToolMode)
  2660. } else if index == 4 {
  2661. self.listView.annotationType = .square
  2662. let winW: CGFloat = 300
  2663. let rightW: CGFloat = 270
  2664. var winFrame = self.view.window?.frame ?? .zero
  2665. winFrame.origin.x += (winFrame.size.width-winW-rightW)
  2666. areaMeasureInfoWindowController?.window?.setFrameOrigin(winFrame.origin)
  2667. areaMeasureInfoWindowController?.showWindow(nil)
  2668. areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2669. areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2670. _ = CustomAlertView.alertView(message: "ESC to exit continuous measuring mode.", fromView: self.view, withStyle: .black)
  2671. self.trackEvent(toolMode: .measureToolMode)
  2672. } else {
  2673. if let isVisible = distanceMeasureInfoWindowController!.window?.isVisible, isVisible {
  2674. distanceMeasureInfoWindowController?.hideFloatingWindow()
  2675. } else if let isVisible = perimeterMeasureInfoWindowController!.window?.isVisible, isVisible {
  2676. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  2677. } else if let isVisible = areaMeasureInfoWindowController!.window?.isVisible, isVisible {
  2678. areaMeasureInfoWindowController?.hideFloatingWindow()
  2679. }
  2680. }
  2681. toggleOpenRightSide()
  2682. }
  2683. }
  2684. }
  2685. func showBatchWindow(type: KMBatchOperationType, filepaths: [String]?) {
  2686. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2687. var array: [KMBatchOperateFile] = []
  2688. for fpath in filepaths ?? [] {
  2689. let batchOperateFile = KMBatchOperateFile(filePath: fpath, type: type)
  2690. array.append(batchOperateFile)
  2691. }
  2692. batchWindowController.switchToOperateType(type, files: array)
  2693. batchWindowController.window?.makeKeyAndOrderFront("")
  2694. }
  2695. func openNewWindowAlertWindow() {
  2696. var needShowChooseWindow = false
  2697. //#if VERSION_FREE
  2698. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  2699. needShowChooseWindow = true
  2700. }
  2701. //#endif
  2702. if needShowChooseWindow {
  2703. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  2704. if preferenceNoteShow {
  2705. menuItemAction_newTagPageToNewWindow("")
  2706. } else {
  2707. if !KMDataManager.default.isTabbingWin{
  2708. KMDataManager.default.isTabbingWin = true
  2709. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  2710. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  2711. KMDataManager.default.isTabbingWin = false
  2712. if continueOrNot {
  2713. self?.reopenDocument(forPaths: [])
  2714. } else {
  2715. }
  2716. }
  2717. self.km_beginSheet(windowC: tabbingWin)
  2718. }
  2719. }
  2720. }else{
  2721. handleTabbingLogic()
  2722. }
  2723. }
  2724. func reopenDocument(forPaths paths: [String]) -> Void {
  2725. let browser = KMBrowser.init() as KMBrowser
  2726. browser.windowController = KMBrowserWindowController.init(browser: browser)
  2727. browser.addHomeTabContents()
  2728. browser.windowController.showWindow(self)
  2729. }
  2730. func handleTabbingLogic() {
  2731. self.browserWindowController?.browser?.selectTabContents(at: 0, userGesture: true)
  2732. }
  2733. func showTTSWindow() {
  2734. var lastPDFView: CPDFView?
  2735. let ttsView = KMTTSWindowController.share
  2736. if (ttsView.window?.isVisible ?? false) {
  2737. lastPDFView = ttsView.pdfView
  2738. if lastPDFView?.document?.documentURL?.path == self.listView.document?.documentURL?.path {
  2739. lastPDFView = nil
  2740. ttsView.window?.orderOut(nil)
  2741. } else {
  2742. ttsView.pdfView = self.listView
  2743. ttsView.showWindow(nil)
  2744. }
  2745. } else {
  2746. ttsView.pdfView = self.listView
  2747. ttsView.showWindow(nil)
  2748. }
  2749. ttsView.closeWindowCallback = { (isCloseWindow: Bool) in
  2750. if isCloseWindow {
  2751. }
  2752. }
  2753. if let currentSelection = self.listView.currentSelection {
  2754. if let data = currentSelection.selectionsByLine, data.isEmpty == false {
  2755. ttsView.startSpeakingPDFSelection(currentSelection)
  2756. }
  2757. }
  2758. if let lastPDFView = lastPDFView {
  2759. lastPDFView.setHighlightedSelections([])
  2760. ttsView.stopSpeaking()
  2761. }
  2762. }
  2763. func convertToImg(index: Int) {
  2764. var convertT: KMConvertType = .JPEG
  2765. switch index {
  2766. case 7:
  2767. convertT = .JPEG
  2768. case 8:
  2769. convertT = .JPG
  2770. case 9:
  2771. convertT = .PNG
  2772. case 10:
  2773. convertT = .GIF
  2774. case 11:
  2775. convertT = .TIFF
  2776. case 12:
  2777. convertT = .TGA
  2778. case 13:
  2779. convertT = .BMP
  2780. default:
  2781. convertT = .JPEG
  2782. }
  2783. showAllConvertWindow(convertT: convertT)
  2784. }
  2785. }
  2786. // MARK: CDistanceMeasureInfoWindowControllerDelegate
  2787. extension KMMainViewController : CDistanceMeasureInfoWindowControllerDelegate {
  2788. func distanceMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2789. let distanceSettingWC = CDistanceSettingWindowController(distanceMeasureInfo: self.distanceMeasureInfoWindowController!.measureInfo)
  2790. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2791. distanceSettingWC.delegate = self
  2792. distanceSettingWC.startModal("")
  2793. }
  2794. func cancelMeasureInfoWindowControllerSetting(_ distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController) {
  2795. }
  2796. }
  2797. // MARK: CPerimeterMeasureInfoWindowControllerDelegate
  2798. extension KMMainViewController : CPerimeterMeasureInfoWindowControllerDelegate {
  2799. func perimeterMeasureInfoWindowControllerSetting(_ perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController) {
  2800. let distanceSettingWC = CDistanceSettingWindowController(perimeterMeasureInfo: self.perimeterMeasureInfoWindowController!.measureInfo)
  2801. self.distanceMeasureInfoWindowController?.hideFloatingWindow()
  2802. distanceSettingWC.delegate = self
  2803. distanceSettingWC.startModal("")
  2804. }
  2805. }
  2806. // MARK: CAreaMeasureInfoWindowControllerDelegate
  2807. extension KMMainViewController : CAreaMeasureInfoWindowControllerDelegate {
  2808. func areaMeasureInfoWindowControllerSetting(_ areaMeasureInfoWindowController: CAreaMeasureInfoWindowController) {
  2809. let areaSettingWC = CAreaSettingWindowController(measureInfo: self.areaMeasureInfoWindowController!.measureInfo)
  2810. self.areaMeasureInfoWindowController?.hideFloatingWindow()
  2811. areaSettingWC.delegate = self
  2812. areaSettingWC.startModal("")
  2813. }
  2814. }
  2815. // MARK: CDistanceSettingWindowControllerDelegate
  2816. extension KMMainViewController : CDistanceSettingWindowControllerDelegate {
  2817. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, distanceMeasureInfo: CPDFDistanceMeasureInfo?) {
  2818. if distanceMeasureInfo != nil {
  2819. if self.listView.activeAnnotations.count > 0 {
  2820. if self.listView.activeAnnotation.isKind(of: CPDFLineAnnotation.self) {
  2821. (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo = distanceMeasureInfo
  2822. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2823. }
  2824. self.distanceMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFLineAnnotation).measureInfo!)
  2825. } else {
  2826. distanceMeasureInfo?.leadLength = 0
  2827. self.listView.distanceMeasureInfo = distanceMeasureInfo
  2828. self.distanceMeasureInfoWindowController?.reloadData(with: self.listView.distanceMeasureInfo)
  2829. self.distanceMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2830. self.distanceMeasureInfoWindowController?.angleLabel.stringValue = ""
  2831. self.distanceMeasureInfoWindowController?.xLabel.stringValue = ""
  2832. self.distanceMeasureInfoWindowController?.yLabel.stringValue = ""
  2833. }
  2834. if let data = self.listView.activeAnnotation {
  2835. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2836. }
  2837. }
  2838. self.distanceMeasureInfoWindowController?.showWindow(self)
  2839. }
  2840. func distanceSettingWindowController(_ distanceSettingWindowController: CDistanceSettingWindowController, perimeterMeasureInfo: CPDFPerimeterMeasureInfo?) {
  2841. if perimeterMeasureInfo != nil {
  2842. if self.listView.activeAnnotations.count > 0 {
  2843. if self.listView.activeAnnotation.isKind(of: CPDFPolylineAnnotation.self) {
  2844. (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo = perimeterMeasureInfo
  2845. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2846. }
  2847. self.perimeterMeasureInfoWindowController?.reloadData(with: (self.listView.activeAnnotation as! CPDFPolylineAnnotation).measureInfo!)
  2848. } else {
  2849. self.listView.perimeterMeasureInfo = perimeterMeasureInfo
  2850. self.perimeterMeasureInfoWindowController?.reloadData(with: self.listView.perimeterMeasureInfo)
  2851. self.perimeterMeasureInfoWindowController?.lengthLabel.stringValue = ""
  2852. self.perimeterMeasureInfoWindowController?.angleLabel.stringValue = ""
  2853. }
  2854. if let data = self.listView.activeAnnotation {
  2855. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2856. }
  2857. }
  2858. self.perimeterMeasureInfoWindowController?.showWindow(self)
  2859. }
  2860. }
  2861. // MARK: CAreaSettingWindowControllerDelegate
  2862. extension KMMainViewController : CAreaSettingWindowControllerDelegate {
  2863. func areaSettingWindowController(_ areaSettingWindowController: CAreaSettingWindowController, measureInfo: CPDFAreaMeasureInfo?) {
  2864. if self.listView.annotationType == .square && self.listView.toolMode == .measureToolMode {
  2865. if measureInfo != nil {
  2866. if self.listView.activeAnnotations.count > 0 {
  2867. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2868. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2869. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2870. }
  2871. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2872. } else {
  2873. self.listView.squareAreaMeasureInfo = measureInfo
  2874. self.areaMeasureInfoWindowController?.reloadData(self.listView.squareAreaMeasureInfo)
  2875. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2876. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2877. }
  2878. }
  2879. self.areaMeasureInfoWindowController?.showWindow(self)
  2880. } else if self.listView.annotationType == .polyGon && self.listView.toolMode == .measureToolMode {
  2881. if measureInfo != nil {
  2882. if self.listView.activeAnnotations.count > 0 {
  2883. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2884. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2885. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2886. }
  2887. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2888. } else {
  2889. self.listView.polygonAreaMeasureInfo = measureInfo
  2890. self.areaMeasureInfoWindowController?.reloadData(self.listView.polygonAreaMeasureInfo)
  2891. self.areaMeasureInfoWindowController?.areaLabel.stringValue = ""
  2892. self.areaMeasureInfoWindowController?.angleLabel.stringValue = ""
  2893. }
  2894. }
  2895. self.areaMeasureInfoWindowController?.showWindow(self)
  2896. } else {
  2897. if measureInfo != nil {
  2898. if self.listView.activeAnnotations.count > 0 {
  2899. if self.listView.activeAnnotation.isKind(of: CPDFPolygonAnnotation.self) {
  2900. (self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo = measureInfo
  2901. self.listView.setNeedsDisplayAnnotationViewFor(self.listView.activeAnnotation.page)
  2902. }
  2903. self.areaMeasureInfoWindowController?.reloadData((self.listView.activeAnnotation as! CPDFPolygonAnnotation).measureInfo!)
  2904. }
  2905. }
  2906. self.areaMeasureInfoWindowController?.showWindow(self)
  2907. }
  2908. if measureInfo != nil {
  2909. if let data = self.listView.activeAnnotation {
  2910. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(data, attributes: nil)
  2911. }
  2912. }
  2913. }
  2914. }
  2915. //MARK: LeftSideViewController
  2916. extension KMMainViewController {
  2917. func leftSideViewCancelSelect() {
  2918. if self.listView.isEditing() == true {
  2919. if self.listView.editingAreas() != nil &&
  2920. self.listView.editingAreas().count != 0 {
  2921. let areas = self.listView.editingAreas().first
  2922. if areas is CPDFEditTextArea {
  2923. self.listView.clearEditingSelectCharItem()
  2924. self.listView.updateEditing([])
  2925. KMPrint("取消选中")
  2926. }
  2927. }
  2928. }
  2929. }
  2930. }
  2931. // MARK: - Analytics (埋点)
  2932. extension KMMainViewController {
  2933. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  2934. if (type == .Annatiton) {
  2935. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_Tools"])
  2936. } else if (type == .editPDF) {
  2937. } else if (type == .Page) {
  2938. FMTrackEventManager.defaultManager.trackEvent(event: "Tbr", withProperties: ["Tbr_Btn" : "Btn_Tbr_PageEdit"])
  2939. } else if (type == .Conversion) {
  2940. } else if (type == .Tool) {
  2941. }
  2942. }
  2943. func trackEvent_aiTranslate() -> Void {
  2944. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  2945. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2946. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2947. }
  2948. func trackEvent_print() -> Void {
  2949. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  2950. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2951. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2952. }
  2953. func trackEvent_share() -> Void {
  2954. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  2955. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2956. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2957. }
  2958. func trackEvent_upgrade() -> Void {
  2959. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  2960. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  2961. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  2962. }
  2963. func trackEvent(annotationType type: CAnnotationType) -> Void {
  2964. if (type == .highlight) {
  2965. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Highlight"])
  2966. } else if (type == .underline) {
  2967. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Underline"])
  2968. } else if (type == .strikeOut) {
  2969. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Strikethrough"])
  2970. } else if (type == .ink) {
  2971. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Freehand"])
  2972. } else if (type == .freeText) {
  2973. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_TextBox"])
  2974. } else if (type == .anchored) {
  2975. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_AnchoredNote"])
  2976. } else if (type == .square) {
  2977. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Rectangle"])
  2978. } else if (type == .link) {
  2979. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Link"])
  2980. } else if (type == .stamp) {
  2981. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Stamp"])
  2982. } else if (type == .signSignature) {
  2983. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Signature"])
  2984. } else if (type == .circle) {
  2985. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Oval"])
  2986. } else if (type == .arrow) {
  2987. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Arrow"])
  2988. } else if (type == .line) {
  2989. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Line"])
  2990. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .text) {
  2991. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  2992. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  2993. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  2994. } else if (self.listView.isEditing() && self.listView.shouAddEditAreaType() == .image) {
  2995. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Image"])
  2996. } else if (type == .textField) {
  2997. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_TextField"])
  2998. } else if (type == .checkBox) {
  2999. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_CheckBox"])
  3000. } else if (type == .radioButton) {
  3001. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_RadioButton"])
  3002. } else if (type == .listMenu) {
  3003. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ListBox"])
  3004. } else if (type == .comboBox) {
  3005. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_ComboBox"])
  3006. } else if (type == .actionButton) {
  3007. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  3008. } else if (type == .actionButton) {
  3009. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Button"])
  3010. } else if (type == .signature) {
  3011. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Form", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Form_Signature"])
  3012. } else if (type == .squiggly) {
  3013. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Squiglly"])
  3014. } else if (type == .eraser) {
  3015. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Tools", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Tools_Erasder"])
  3016. }
  3017. }
  3018. func trackEvent(toolMode mode: CToolMode) -> Void {
  3019. if (mode == .selectToolMode) {
  3020. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3021. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3022. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3023. } else if (mode == .moveToolMode) {
  3024. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3025. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3026. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3027. } else if mode == .measureToolMode {
  3028. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_Editor_Measure"])
  3029. }
  3030. }
  3031. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3032. if (type == .word) {
  3033. } else if (type == .excel) {
  3034. } else if (type == .ppt) {
  3035. } else if (type == .rtf) {
  3036. } else if (type == .csv) {
  3037. } else if (type == .html) {
  3038. } else if (type == .conversion_text) {
  3039. } else if (type == .conversion_image) {
  3040. } else if (type == .compress) {
  3041. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Editor", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Editor_Compress"])
  3042. } else if (type == .merge) {
  3043. } else if (type == .secure) {
  3044. } else if (type == .crop) {
  3045. } else if type == .json {
  3046. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_Converter", withProperties: ["SubTbr_Btn": "Btn_SubTbr_Converter_ToOthers_ToJson"])
  3047. }
  3048. }
  3049. func trackEvent_setPassword() -> Void {
  3050. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3051. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3052. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3053. }
  3054. func trackEvent_removePassword() -> Void {
  3055. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3056. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3057. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3058. }
  3059. func trackEvent_replace() -> Void {
  3060. self.trackEvent(eventName: "Tbr", params: ["Tbr_Btn" : "Btn_Tbr_ReplaceText"], platform: .AppCenter)
  3061. }
  3062. }
  3063. extension KMMainViewController {
  3064. //文件对比
  3065. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3066. self.isCompareModel = true
  3067. let compareContentView = KMCompareContentView()
  3068. compareContentView.oldDocument = oldDocument
  3069. compareContentView.document = document
  3070. compareContentView.compareResults = results
  3071. compareContentView.saveHandle = { [unowned self] view in
  3072. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  3073. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3074. self.currentWindowController = saveController
  3075. saveController.cancelHandle = { [unowned self] controller in
  3076. self.view.window!.endSheet(controller.window!)
  3077. self.currentWindowController = nil
  3078. }
  3079. saveController.saveHandle = { [unowned self] controller, saveType in
  3080. let folderPath = controller.fileSaveFolderPath
  3081. if folderPath != nil {
  3082. if !FileManager.default.fileExists(atPath: folderPath) {
  3083. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3084. }
  3085. #if VERSION_DMG
  3086. #else
  3087. let url = URL(fileURLWithPath: folderPath)
  3088. let fileAccess = AppSandboxFileAccess()
  3089. fileAccess?.persistPermissionURL(url)
  3090. if let bookmarkData = try?url.bookmarkData(options: [.withSecurityScope]) {
  3091. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: url)
  3092. let urlString = url.path
  3093. let _url = URL(fileURLWithPath: urlString)
  3094. fileAccess?.bookmarkPersistanceDelegate.setBookmarkData(bookmarkData, for: _url)
  3095. }
  3096. #endif
  3097. var savePath: String
  3098. switch saveType {
  3099. case 0:
  3100. let filePath = oldDocument.documentURL.path
  3101. let fileName = filePath.deletingPathExtension.lastPathComponent
  3102. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3103. savePath = self.getValidFilePath(savePath)
  3104. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3105. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3106. case 1:
  3107. let filePath = document.documentURL.path
  3108. let fileName = filePath.deletingPathExtension.lastPathComponent
  3109. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  3110. savePath = self.getValidFilePath(savePath)
  3111. document.write(to: URL(fileURLWithPath: savePath))
  3112. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3113. case 2:
  3114. let filePath = oldDocument.documentURL.path
  3115. let fileName = filePath.deletingPathExtension.lastPathComponent
  3116. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  3117. savePath = self.getValidFilePath(savePath)
  3118. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  3119. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3120. default:
  3121. break
  3122. }
  3123. }
  3124. self.view.window!.endSheet(controller.window!)
  3125. self.currentWindowController = nil
  3126. }
  3127. NSWindow.currentWindow().beginSheet(saveController.window!)
  3128. }
  3129. }
  3130. compareContentView.closeHandle = { [unowned self] view in
  3131. self.isCompareModel = false
  3132. view.removeFromSuperview()
  3133. }
  3134. compareContentView.autoresizingMask = [.width,.height]
  3135. }
  3136. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3137. self.isCompareModel = true
  3138. let coveringView = KMCompareCoveringView()
  3139. coveringView.pdfDocument = pdfDocument
  3140. coveringView.closeHandle = { [unowned self] view in
  3141. self.isCompareModel = false
  3142. view.removeFromSuperview()
  3143. }
  3144. coveringView.saveHandle = { [unowned self] view in
  3145. let savePanel = NSSavePanel()
  3146. savePanel.nameFieldStringValue = "untitled"
  3147. savePanel.allowedFileTypes = ["pdf"]
  3148. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  3149. if result == .OK {
  3150. pdfDocument.write(to: savePanel.url!)
  3151. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3152. }
  3153. }
  3154. }
  3155. coveringView.autoresizingMask = [.width,.height]
  3156. }
  3157. func getValidFilePath(_ oldPath: String) -> String {
  3158. let fileManager = FileManager.default
  3159. do {
  3160. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3161. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3162. return oldPath
  3163. }
  3164. var i = 1
  3165. var newPath = oldPath
  3166. while fileManager.fileExists(atPath: newPath) {
  3167. if fileType == FileAttributeType.typeDirectory.rawValue {
  3168. newPath = oldPath + "(\(i))"
  3169. } else {
  3170. let fileExtension = (oldPath as NSString).pathExtension
  3171. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3172. }
  3173. i += 1
  3174. }
  3175. return newPath
  3176. } catch {
  3177. print("Error getting file attributes: \(error)")
  3178. return oldPath
  3179. }
  3180. }
  3181. }
  3182. extension KMMainViewController {
  3183. func documentAllowsEdit() -> Bool {
  3184. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  3185. let alert = NSAlert()
  3186. alert.alertStyle = .critical
  3187. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  3188. alert.runModal()
  3189. return false
  3190. } else {
  3191. return true
  3192. }
  3193. }
  3194. func changeFont(_ sender: NSFontManager) {
  3195. KMPrint("changeFont ...")
  3196. if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
  3197. let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
  3198. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  3199. font = sender.convert(font!)
  3200. annotation.fontSize = font?.pointSize ?? 12
  3201. self.listView.commitEditAnnotationFreeText(annotation)
  3202. self.listView.setNeedsDisplay(annotation)
  3203. }
  3204. }
  3205. func currentSetup() -> [String: Any] {
  3206. var setup: [String: Any] = [:]
  3207. var point = NSZeroPoint
  3208. if listView == nil {
  3209. return setup
  3210. }
  3211. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  3212. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  3213. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  3214. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  3215. setup[KMMainModel.Key.pageIndex] = pageIndex
  3216. return setup
  3217. }
  3218. // MARK: - Recommond活动
  3219. func loadRecommondPopWindow() {
  3220. if IAPProductsManager.default().isAvailableAllFunction() {
  3221. return
  3222. }
  3223. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  3224. if recommondPopWindowVC == nil {
  3225. recommondPopWindowVC = KMRecommondPopWindow.default()
  3226. }
  3227. recommondPopWindowVC?.recommondInfo = info
  3228. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  3229. return
  3230. }
  3231. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  3232. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  3233. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  3234. recommondPopWindowVC?.window?.orderFront((Any).self)
  3235. recommondPopWindowVC?.window?.becomeMain()
  3236. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  3237. UserDefaults.standard.synchronize()
  3238. }
  3239. }
  3240. @objc func didAddContentViewNotification(_ sender: Notification) {
  3241. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  3242. return
  3243. }
  3244. if self.interactionMode == .presentation {
  3245. }
  3246. }
  3247. @objc func purchaseStateUpdateNoti() {
  3248. if IAPProductsManager.default().isAvailableAllFunction() {
  3249. }
  3250. }
  3251. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  3252. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  3253. guard let anno = sender.object as? CPDFAnnotation else {
  3254. return
  3255. }
  3256. if anno.page?.document != self.listView.document {
  3257. return
  3258. }
  3259. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  3260. }
  3261. // MARK: Split View
  3262. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  3263. let openPanel = NSOpenPanel()
  3264. openPanel.allowedFileTypes = ["pdf", "PDF"]
  3265. openPanel.allowsMultipleSelection = false
  3266. guard let mainWindow = NSApp.mainWindow else {
  3267. return
  3268. }
  3269. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  3270. if response == NSApplication.ModalResponse.OK {
  3271. guard let url = openPanel.url else {
  3272. return
  3273. }
  3274. if let document = CPDFDocument(url: url) {
  3275. replaceBlock(document.documentURL?.path ?? "")
  3276. } else {
  3277. let alert = NSAlert()
  3278. alert.alertStyle = .critical
  3279. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  3280. alert.runModal()
  3281. }
  3282. }
  3283. }
  3284. }
  3285. }