KMMainViewController+Action.swift 156 KB

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