KMMainViewController+Action.swift 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. func search(searchString: String, isCase: Bool) {
  10. let document = self.listView.document
  11. if ((document?.isFinding) != nil) {
  12. document?.cancelFindString()
  13. }
  14. if searchString == "" {
  15. self.searchResults = []
  16. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  17. self.leftSideViewController.searchResults = self.searchResults
  18. // self.leftSideViewController.searchViewController.reloadData()
  19. } else {
  20. mwcFlags.wholeWordSearch = isCase == true ? 1 : 0
  21. var findArray : [[CPDFSelection]]
  22. if isCase {
  23. findArray = self.listView.document.findString(searchString) ?? []
  24. } else {
  25. findArray = self.listView.document.findString(searchString, with: .caseSensitive) ?? []
  26. }
  27. self.searchResults.removeAll()
  28. for selections in findArray {
  29. for selection in selections {
  30. let mode : KMSearchMode = KMSearchMode()
  31. mode.selection = selection
  32. mode.attributedString = KMOCToolClass.getAttributedString(selection: selection, keyword: searchString)
  33. mode.selectionPageIndex = self.listView.document.index(for: selection.page)
  34. self.searchResults.insert(mode, at: self.searchResults.count)
  35. }
  36. }
  37. // self.leftSideViewController.searchViewController.searchResults = self.searchResults
  38. // self.leftSideViewController.searchViewController.reloadData()
  39. self.leftSideViewController.searchResults = self.searchResults
  40. }
  41. if self.leftSideViewController.findPaneState == .singular {
  42. self.leftSideViewController.displayFindViewAnimating(true)
  43. } else {
  44. self.leftSideViewController.displayGroupedFindViewAnimating(true)
  45. }
  46. }
  47. func removeSignatures(signatures:[CPDFSignature]) {
  48. for signature in signatures {
  49. self.listView.document.removeSignature(signature)
  50. }
  51. for i in 0..<self.listView.document.pageCount {
  52. let page : CPDFPage = self.listView.document.page(at: i)
  53. let annotations : [CPDFAnnotation] = page.annotations
  54. for j in 0..<annotations.count {
  55. let annotation = annotations[j]
  56. if annotation is CPDFSignatureWidgetAnnotation {
  57. (annotation as! CPDFSignatureWidgetAnnotation).updateAppearanceStream()
  58. }
  59. }
  60. }
  61. self.listView.setNeedsDisplayForVisiblePages()
  62. let tSignatures : [CPDFSignature] = self.listView.document.signatures()
  63. var mSignatures : [CPDFSignature] = []
  64. for sign in tSignatures {
  65. if sign.signers.count > 0 {
  66. mSignatures.append(sign)
  67. }
  68. }
  69. // self.leftSideViewController.signatureViewController.signatures = signatures
  70. // self.leftSideViewController.signatureViewController.reloadData()
  71. }
  72. //MARK: menu菜单
  73. func fontColorMenuItem()->NSMenuItem {
  74. let fontColorItem = NSMenuItem(title: NSLocalizedString("Text Color", comment: ""), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  75. return fontColorItem;
  76. }
  77. func fontSizeMenuItem()->NSMenuItem {
  78. let currentFontSize = self.listView.editingTextFontSize()
  79. let fontSizes = self.fontSizes()
  80. let submenu = NSMenu(title: "")
  81. for i in 0 ... fontSizes.count - 1 {
  82. let fontSize : String = fontSizes.object(at: i) as! String
  83. let item = NSMenuItem(title:fontSize as! String, action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  84. item.target = self
  85. item.tag = i
  86. submenu.addItem(item)
  87. if (Int(currentFontSize) == Int(fontSize)) {
  88. item.state = .on
  89. }
  90. }
  91. let fontSizeItem = NSMenuItem(title: NSLocalizedString("Font Size", comment: ""), action:nil, keyEquivalent: "")
  92. fontSizeItem.submenu = submenu
  93. return fontSizeItem;
  94. }
  95. func corpImageMenuItem()->NSMenuItem {
  96. var corpImageItem = NSMenuItem(title: NSLocalizedString("Confirm Crop", comment: ""), action: #selector(menuItemEditingClick_CropImage), target: self)
  97. return corpImageItem
  98. }
  99. func cancelCorpImageMenuItem()->NSMenuItem {
  100. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Cancel Crop", comment: ""), action: #selector(menuItemEditingClick_CancelCrop), target: self)
  101. return cancelCorpImageItem
  102. }
  103. func restoreCorpImageMenuItem()->NSMenuItem {
  104. let cancelCorpImageItem = NSMenuItem(title: NSLocalizedString("Restore Crop", comment: ""), action: #selector(menuItemEditingClick_RestoreCrop), target: self)
  105. return cancelCorpImageItem
  106. }
  107. func cutImageArea()->NSMenuItem {
  108. let deleteItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: #selector(menuItemEditingClick_CutImage), target: self)
  109. return deleteItem
  110. }
  111. func editAddBlanMenu(menu:NSMenu){
  112. menu.insertItem(withTitle: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, at: 0)
  113. menu.insertItem(withTitle: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, at: 1)
  114. }
  115. func addText() -> NSMenuItem {
  116. var addTextItem = NSMenuItem(title: NSLocalizedString("Add Text", comment: ""), action: #selector(addImageText), target: self, tag: 0)
  117. return addTextItem
  118. }
  119. func addImage() -> NSMenuItem {
  120. var addImageItem = NSMenuItem(title: NSLocalizedString("Add Image", comment: ""), action: #selector(addImageText), target: self, tag: 1)
  121. return addImageItem
  122. }
  123. func replaceImageArea()->NSMenuItem {
  124. let replaceItem = NSMenuItem(title: NSLocalizedString("Replace", comment: ""), action: #selector(menuItemEditingClick_ReplaceImage), target: self)
  125. return replaceItem
  126. }
  127. func exportImageArea()->NSMenuItem {
  128. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  129. return exportItem
  130. }
  131. func exportImageStampItem()->NSMenuItem {
  132. let exportItem = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: #selector(menuItemEditingClick_ExportImage), target: self)
  133. let menu = NSMenu()
  134. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportStampImage), target: self, tag:0, at: 0)
  135. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportStampImage), target: self, tag:2, at: 1)
  136. exportItem.submenu = menu
  137. return exportItem
  138. }
  139. func exportMenu() -> NSMenu {
  140. let menu = NSMenu()
  141. menu.insertItem(withTitle: NSLocalizedString("PNG", comment: ""), action:#selector(exportCorpImage), target: self, tag:0, at: 0)
  142. menu.insertItem(withTitle: NSLocalizedString("JPG", comment: ""), action:#selector(exportCorpImage), target: self, tag:1, at: 1)
  143. menu.insertItem(withTitle: NSLocalizedString("PDF", comment: ""), action:#selector(exportCorpImage), target: self, tag:2, at: 2)
  144. return menu
  145. }
  146. func cropMenu() -> NSMenu {
  147. let menu = NSMenu()
  148. menu.insertItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action:#selector(cropCurrentPage), target: self, at: 0)
  149. menu.insertItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action:#selector(cropAllPage), target: self, at: 1)
  150. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  151. menu.insertItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action:#selector(autoCropAll), target: self, at: 2)
  152. return menu
  153. }
  154. func zoomSelectionMenuItem() -> NSMenuItem {
  155. let item = NSMenuItem(title: NSLocalizedString("Zoom To Selection", comment: ""), action: #selector(doZoomToAutoSelection), target: self)
  156. return item
  157. }
  158. func setDefaultAnnotationPorpert(type:CAnnotationType) -> NSMenuItem {
  159. let item = NSMenuItem(title: NSLocalizedString("Set as Default", comment: ""), action: #selector(defaultAnnotationPorpert), target: self, tag: type.rawValue)
  160. return item
  161. }
  162. func enterAnnotationStype() -> NSMenuItem {
  163. let stypItem = NSMenuItem(title: NSLocalizedString("Annotation", comment: ""), action: nil, target: self)
  164. let stypeMenu = NSMenu()
  165. stypeMenu.addItem(withTitle: NSLocalizedString("Freehand", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 0)
  166. stypeMenu.addItem(withTitle: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 1)
  167. stypeMenu.addItem(withTitle: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 2)
  168. stypeMenu.addItem(withTitle: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 3)
  169. stypeMenu.addItem(withTitle: NSLocalizedString("Circle", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 4)
  170. stypeMenu.addItem(withTitle: NSLocalizedString("Arrow", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 5)
  171. stypeMenu.addItem(withTitle: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 6)
  172. if self.isReadMode {
  173. } else {
  174. stypeMenu.addItem(withTitle: NSLocalizedString("Link", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 7)
  175. stypeMenu.addItem(withTitle: NSLocalizedString("Stamp", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 8)
  176. stypeMenu.addItem(withTitle: NSLocalizedString("Signature", comment: ""), action: #selector(menuItemAnnotationClick_addStype), target: self, tag: 9)
  177. }
  178. stypItem.submenu = stypeMenu
  179. if self.listView.annotationType == .ink {
  180. stypeMenu.item(at: 0)?.state = .on
  181. } else if self.listView.annotationType == .freeText {
  182. stypeMenu.item(at: 1)?.state = .on
  183. } else if self.listView.annotationType == .anchored {
  184. stypeMenu.item(at: 2)?.state = .on
  185. } else if self.listView.annotationType == .square {
  186. stypeMenu.item(at: 3)?.state = .on
  187. } else if self.listView.annotationType == .circle {
  188. stypeMenu.item(at: 4)?.state = .on
  189. } else if self.listView.annotationType == .arrow {
  190. stypeMenu.item(at: 5)?.state = .on
  191. } else if self.listView.annotationType == .line {
  192. stypeMenu.item(at: 6)?.state = .on
  193. } else if self.listView.annotationType == .link {
  194. stypeMenu.item(at: 7)?.state = .on
  195. } else if self.listView.annotationType == .stamp {
  196. stypeMenu.item(at: 8)?.state = .on
  197. } else if self.listView.annotationType == .signSignature {
  198. stypeMenu.item(at: 9)?.state = .on
  199. }
  200. return stypItem
  201. }
  202. func setAnnotationToolStype() -> NSMenuItem {
  203. let stypItem = NSMenuItem(title: NSLocalizedString("Tool Mode", comment: ""), action: nil, target: self)
  204. let stypeMenu = NSMenu()
  205. stypeMenu.addItem(withTitle: NSLocalizedString("Default Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 0)
  206. stypeMenu.addItem(withTitle: NSLocalizedString("Scroll Tool", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 1)
  207. stypeMenu.addItem(withTitle: NSLocalizedString("Magnify", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 2)
  208. stypeMenu.addItem(withTitle: NSLocalizedString("Select", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 3)
  209. stypeMenu.addItem(withTitle: NSLocalizedString("Zoom to Selected Area", comment: ""), action: #selector(menuItemAnnotationClick_toolModel), target: self, tag: 4)
  210. stypItem.submenu = stypeMenu
  211. if self.toolbarController.toolbarType == .Annatiton {
  212. stypeMenu.item(at: 0)?.state = .on
  213. } else if self.toolbarController.toolbarType == .Move {
  214. stypeMenu.item(at: 1)?.state = .on
  215. } else if self.toolbarController.toolbarType == .Magnify {
  216. stypeMenu.item(at: 2)?.state = .on
  217. } else if self.toolbarController.toolbarType == .Select {
  218. stypeMenu.item(at: 3)?.state = .on
  219. } else if self.toolbarController.toolbarType == .SelectZoom {
  220. stypeMenu.item(at: 4)?.state = .on
  221. }
  222. return stypItem
  223. }
  224. func addReadModelStype() -> NSMenuItem {
  225. var stypItem = NSMenuItem(title: NSLocalizedString("Read Mode On", comment: ""), action: #selector(openReadModel), target: self)
  226. if self.isReadMode {
  227. stypItem = NSMenuItem(title: NSLocalizedString("Read Mode Off", comment: ""), action: #selector(closeReadModel), target: self)
  228. }
  229. return stypItem
  230. }
  231. func addOutlineStype() -> NSMenuItem {
  232. let stypItem = NSMenuItem(title: NSLocalizedString("Add Outline Item", comment: ""), action: #selector(addOutLineItemAction), target: self)
  233. return stypItem
  234. }
  235. func setTTSStype() -> NSMenuItem {
  236. let stypItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(showTTSView), target: self)
  237. return stypItem
  238. }
  239. func setShareStype() -> NSMenuItem {
  240. let stypItem = NSMenuItem(title: NSLocalizedString("Share", comment: ""), action: #selector(showShareAction), target: self)
  241. return stypItem
  242. }
  243. func setLookUpStype() -> NSMenuItem {
  244. let str = String(format: "Look Up %@", listView.currentSelection.string())
  245. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(lookUpAction), target: self)
  246. return stypItem
  247. }
  248. func setSearchBaiduStype() -> NSMenuItem {
  249. let stypItem = NSMenuItem(title: NSLocalizedString("Search with Baidu", comment: ""), action: #selector(searchBaiduAction), target: self)
  250. return stypItem
  251. }
  252. func setNextPageStype() -> NSMenuItem {
  253. let stypItem = NSMenuItem(title: NSLocalizedString("Next Page", comment: ""), action: #selector(NextPageAction), target: self)
  254. return stypItem
  255. }
  256. func setPreviousPageStype() -> NSMenuItem {
  257. let stypItem = NSMenuItem(title: NSLocalizedString("Previous Page", comment: ""), action: #selector(PreviousPageAction), target: self)
  258. return stypItem
  259. }
  260. func setTranslateStype() -> NSMenuItem {
  261. let str = String(format: "Translate %@", listView.currentSelection.string())
  262. let stypItem = NSMenuItem(title: NSLocalizedString(str, comment: ""), action: #selector(TranslateItemAction), target: self)
  263. return stypItem
  264. }
  265. func setAutoScrollStype() -> NSMenuItem {
  266. let stypItem = NSMenuItem(title: NSLocalizedString("Auto Scroll", comment: ""), action: #selector(AutoScrollItemAction), target: self)
  267. return stypItem
  268. }
  269. func setSnapshotStype() -> NSMenuItem {
  270. let stypItem = NSMenuItem(title: NSLocalizedString("Snapshot", comment: ""), action: nil, target: self)
  271. let stypeMenu = NSMenu()
  272. stypeMenu.addItem(withTitle: NSLocalizedString("Auto", comment: ""), action: #selector(takeSnapshot), target: self, tag: 0)
  273. stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(takeSnapshotSelectContent), target: self, tag: 1)
  274. stypItem.submenu = stypeMenu
  275. // if self.toolbarController.toolbarType == .Annatiton {
  276. // stypeMenu.item(at: 0)?.state = .on
  277. // } else if self.toolbarController.toolbarType == .Move {
  278. // stypeMenu.item(at: 1)?.state = .on
  279. // }
  280. return stypItem
  281. }
  282. func setServicesStype() -> NSMenuItem {
  283. let stypItem = NSMenuItem(title: NSLocalizedString("Services", comment: ""), action: nil, target: self)
  284. let stypeMenu = NSMenu()
  285. stypeMenu.addItem(withTitle: NSLocalizedString("Add to Music as a Spoken Track", comment: ""), action: #selector(AddtoMusicasASpokenTrack), target: self, tag: 0)
  286. stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Simplified Chinese", comment: ""), action: #selector(ConvertTextToSimplifiedChinese), target: self, tag: 1)
  287. stypeMenu.addItem(withTitle: NSLocalizedString("Convert Text to Traditional Chinese", comment: ""), action: #selector(ConvertTextToTraditionalChinese), target: self, tag: 2)
  288. stypeMenu.addItem(withTitle: NSLocalizedString("Open", comment: ""), action: #selector(OpenItemAction), target: self, tag: 3)
  289. stypeMenu.addItem(withTitle: NSLocalizedString("Search With Baidu", comment: ""), action: #selector(searchBaiduAction), target: self, tag: 4)
  290. stypeMenu.addItem(withTitle: NSLocalizedString("Show in Finder", comment: ""), action: #selector(showInFinder), target: self, tag: 4)
  291. stypeMenu.addItem(withTitle: NSLocalizedString("Show Info in Finder", comment: ""), action: #selector(showInfoInFinder), target: self, tag: 5)
  292. stypItem.submenu = stypeMenu
  293. // if self.toolbarController.toolbarType == .Annatiton {
  294. // stypeMenu.item(at: 0)?.state = .on
  295. // } else if self.toolbarController.toolbarType == .Move {
  296. // stypeMenu.item(at: 1)?.state = .on
  297. // }
  298. return stypItem
  299. }
  300. func setCropStype() -> NSMenuItem {
  301. let stypItem = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action: nil, target: self)
  302. let stypeMenu = NSMenu()
  303. stypeMenu.addItem(withTitle: NSLocalizedString("Crop All Pages", comment: ""), action: #selector(cropAllPageItem), target: self, tag: 0)
  304. stypeMenu.addItem(withTitle: NSLocalizedString("Crop Current Page", comment: ""), action: #selector(cropCurrentPageItem), target: self, tag: 1)
  305. stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Separate", comment: ""), action: #selector(autoCropAllItem), target: self, tag: 2)
  306. stypeMenu.addItem(withTitle: NSLocalizedString("Auto Crop – Combined", comment: ""), action: #selector(smartAutoCropAllItem), target: self, tag: 3)
  307. // if(NSIsEmptyRect(selectionRect)) {
  308. stypeMenu.addItem(withTitle: NSLocalizedString("Select Area", comment: ""), action: #selector(selectToolModel), target: self, tag: 4)
  309. stypeMenu.addItem(withTitle: NSLocalizedString("Crop Options...", comment: ""), action: #selector(customCropModel), target: self, tag: 5)
  310. //
  311. // }
  312. stypItem.submenu = stypeMenu
  313. // if self.toolbarController.toolbarType == .Annatiton {
  314. // stypeMenu.item(at: 0)?.state = .on
  315. // } else if self.toolbarController.toolbarType == .Move {
  316. // stypeMenu.item(at: 1)?.state = .on
  317. // } else if self.toolbarController.toolbarType == .Magnify {
  318. // stypeMenu.item(at: 2)?.state = .on
  319. // } else if self.toolbarController.toolbarType == .Select {
  320. // stypeMenu.item(at: 3)?.state = .on
  321. // } else if self.toolbarController.toolbarType == .SelectZoom {
  322. // stypeMenu.item(at: 4)?.state = .on
  323. // }
  324. return stypItem
  325. }
  326. func addHighlightLinksStype() -> NSMenuItem {
  327. let highlightLink = KMPreferenceManager.shared.highlightLinks
  328. var highlightLinkTitle = NSLocalizedString("Highlight Links", comment: "")
  329. if highlightLink {
  330. highlightLinkTitle = NSLocalizedString("Disable Highlight Links", comment: "")
  331. }
  332. var highlightLinksItem = NSMenuItem(title: highlightLinkTitle, action: #selector(highlightLinks), target: self)
  333. return highlightLinksItem
  334. }
  335. func addAnnotationForStyleMenu(menu:NSMenu) {
  336. if menu == nil {
  337. return
  338. }
  339. let height = NSMenuItem(title: NSLocalizedString("Highlight", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 0)
  340. let underline = NSMenuItem(title: NSLocalizedString("Underline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 1)
  341. let strickout = NSMenuItem(title: NSLocalizedString("Strikethrough", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 2)
  342. let text = NSMenuItem(title: NSLocalizedString("Text", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 3)
  343. let note = NSMenuItem(title: NSLocalizedString("Note", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 4)
  344. let rectangle = NSMenuItem(title: NSLocalizedString("Rectangle", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 5)
  345. let oval = NSMenuItem(title: NSLocalizedString("Oval", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 6)
  346. let line = NSMenuItem(title: NSLocalizedString("Line", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 7)
  347. let link = NSMenuItem(title: NSLocalizedString("Add Link", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 8)
  348. let outline = NSMenuItem(title: NSLocalizedString("Add Outline", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 9)
  349. let aiTranslation = NSMenuItem(title: NSLocalizedString("AI Translation", comment: ""), action: #selector(aiTranslationAction), target: self)
  350. // let tts = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action: #selector(menuItemAnnotationClick_add), target: self, tag: 10)!
  351. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  352. if listView.currentSelection.selectionType() != .image {
  353. menu.insertItem(height, at: menu.items.count)
  354. menu.insertItem(underline, at: menu.items.count)
  355. menu.insertItem(strickout, at: menu.items.count)
  356. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  357. }
  358. if self.isReadMode {
  359. } else {
  360. if listView.currentSelection.selectionType() != .image &&
  361. listView.currentSelection.selectionType() != .text {
  362. menu.insertItem(text, at: menu.items.count)
  363. menu.insertItem(note, at: menu.items.count)
  364. }
  365. }
  366. if self.isReadMode {
  367. } else {
  368. if listView.currentSelection.selectionType() != .image {
  369. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  370. menu.insertItem(rectangle, at: menu.items.count)
  371. menu.insertItem(oval, at: menu.items.count)
  372. }
  373. }
  374. if self.isReadMode {
  375. } else {
  376. if listView.currentSelection.selectionType() != .image &&
  377. listView.currentSelection.selectionType() != .text {
  378. menu.insertItem(line, at: menu.items.count)
  379. }
  380. }
  381. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  382. if self.isReadMode {
  383. } else {
  384. menu.insertItem(link, at: menu.items.count)
  385. }
  386. if self.isReadMode {
  387. } else {
  388. if listView.currentSelection.selectionType() != .image {
  389. menu.insertItem(outline, at: menu.items.count)
  390. }
  391. }
  392. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  393. if self.isReadMode {
  394. } else {
  395. if (listView.currentSelection.selectionType() != .image) {
  396. menu.insertItem(aiTranslation, at: menu.items.count)
  397. }
  398. }
  399. menu.insertItem(NSMenuItem.separator(), at: menu.items.count)
  400. }
  401. func addBookmarkMenu() -> NSMenuItem {
  402. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  403. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Add Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  404. return bookMarkItem
  405. } else {
  406. let bookMarkItem = NSMenuItem(title: NSLocalizedString("Remove Bookmark", comment: ""), action: #selector(menuItemBookMarkClick_add), target: self)
  407. return bookMarkItem
  408. }
  409. }
  410. func findStringMenu() -> NSMenuItem {
  411. let menuItem = NSMenuItem(title: NSLocalizedString("Find", comment: ""), action: #selector(menuItemAnnotationClick_FindString), target: self)
  412. menuItem.keyEquivalent = "f"
  413. return menuItem
  414. }
  415. func printingMenu() -> NSMenuItem {
  416. let menuItem = NSMenuItem(title: NSLocalizedString("Print", comment: ""), action: #selector(menuItemAnnotationClick_Print), keyEquivalent: "p")
  417. return menuItem
  418. }
  419. func fontSizes()->NSArray {
  420. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  421. }
  422. //MARK: menuItem Action
  423. @objc func menuItemEditingClick_FontColor(sender: NSMenuItem) {
  424. let color = listView.editingSelectionFontColor()
  425. let panel = NSColorPanel.shared
  426. panel.setTarget(self)
  427. panel.setAction(#selector(fontColorChangeAction))
  428. panel.orderFront(nil)
  429. panel.showsAlpha = false
  430. panel.color = color ?? NSColor.black
  431. }
  432. @objc func fontColorChangeAction(sender: NSColorPanel) {
  433. self.listView.setEditingSelectionFontColor(sender.color)
  434. }
  435. @objc func menuItemEditingClick_FontSize(sender: NSMenuItem) {
  436. let fontSize = self.fontSizes().object(at: sender.tag)
  437. self.listView.setEditingSelectionFontSize(CGFloat(Int(fontSize as! String)!))
  438. }
  439. @objc func addImageText(sender: NSMenuItem) {
  440. let event = NSApp.currentEvent
  441. let clickLocation = event?.locationInWindow
  442. var point = self.listView.convert(clickLocation!, from: NSApp.mainWindow?.contentView)
  443. var point2 = self.listView.convert(point, to: self.listView.currentPage())
  444. point2 = CGPoint(x: self.listView.bounds.width - point2.x, y: self.listView.bounds.height - point2.y)
  445. point = point2
  446. if sender.tag == 0 {
  447. KMPrint("添加文字")
  448. let isSelect = self.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)?.isSelected ?? false
  449. if !isSelect {
  450. self.toolbarController.selectItem(KMToolbarAddTextEditPDFItemIdentifier)
  451. }
  452. // self.pdfViewEditingAddTextArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  453. } else if sender.tag == 1 {
  454. KMPrint("添加图片")
  455. let isSelect = self.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)?.isSelected ?? false
  456. if !isSelect {
  457. self.toolbarController.selectItem(KMToolbarAddImageEditPDFItemIdentifier)
  458. }
  459. // self.pdfViewEditingAddImageArea(self.listView, add: CGRectMake(point.x, point.y, 0, 0))
  460. } else if sender.tag == 2 {
  461. KMPrint("粘贴")
  462. }
  463. }
  464. @objc func menuItemEditingClick_CropImage(sender: NSMenuItem) {
  465. if self.rightSideViewController.eidtPDFImageProperty != nil {
  466. self.rightSideViewController.eidtPDFImageProperty.confirmVCImageAction((Any).self)
  467. } else {
  468. if self.listView.cropAreas != nil && self.listView.selectImageAreas != nil{
  469. self.listView.cropEditImageArea(self.listView.selectImageAreas, withBounds: self.listView.cropAreas.cropRect)
  470. }
  471. }
  472. }
  473. @objc func menuItemEditingClick_CancelCrop(sender: NSMenuItem) {
  474. if self.rightSideViewController.eidtPDFImageProperty != nil {
  475. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  476. } else {
  477. self.listView.exitCrop(with: self.listView.selectImageAreas)
  478. self.listView.cropAreas = nil
  479. self.listView.isEditImage = false
  480. }
  481. }
  482. @objc func menuItemEditingClick_RestoreCrop(sender: NSMenuItem) {
  483. if self.rightSideViewController.eidtPDFImageProperty != nil {
  484. self.rightSideViewController.eidtPDFImageProperty?.restoreCutImageAction("")
  485. } else {
  486. self.listView.resetCrop(with: self.listView.selectImageAreas)
  487. }
  488. }
  489. @objc func menuItemEditingClick_CutImage(sender: NSMenuItem) {
  490. if self.listView.selectImageAreas != nil {
  491. self.listView.isEditImage = true
  492. self.listView.enterCrop(with: self.listView.selectImageAreas)
  493. self.rightSideViewController.eidtPDFImageProperty.updateButtonState(hidden: false)
  494. }
  495. }
  496. @objc func menuItemEditingClick_ReplaceImage(sender: NSMenuItem) {
  497. if self.listView.selectImageAreas == nil {
  498. return
  499. }
  500. let panel = NSOpenPanel()
  501. panel.allowsMultipleSelection = false
  502. panel.allowedFileTypes = ["png","jpg"]
  503. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  504. if response == .OK {
  505. let openPath = panel.url?.path
  506. let s = self.listView.replace(self.listView.selectImageAreas, imagePath: openPath!)
  507. if s {
  508. }
  509. }
  510. }
  511. }
  512. @objc func menuItemEditingClick_ExportImage(sender: NSMenuItem) {
  513. if self.listView.selectImageAreas == nil {
  514. return
  515. }
  516. let panel = NSSavePanel()
  517. // panel.nameFieldStringValue = "[新文件].png"
  518. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  519. // let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  520. // button.state = .on
  521. // panel.accessoryView = button
  522. panel.isExtensionHidden = true
  523. let response = panel.runModal()
  524. if response == .OK {
  525. let url = panel.url
  526. if FileManager.default.fileExists(atPath: url!.path) {
  527. try?FileManager.default.removeItem(atPath: url!.path)
  528. }
  529. let result = self.listView.extractImage(with: self.listView.selectImageAreas, toImagePath: url!.path)
  530. if result {
  531. NSWorkspace.shared.activateFileViewerSelecting([url!])
  532. // if button.state == .on { /// 开启文档
  533. // NSWorkspace.shared.openFile(url!.path)
  534. // } else {
  535. //
  536. // }
  537. }
  538. }
  539. }
  540. @objc func AddtoMusicasASpokenTrack(sender: NSMenuItem) {
  541. }
  542. @objc func ConvertTextToSimplifiedChinese(sender: NSMenuItem) {
  543. }
  544. @objc func ConvertTextToTraditionalChinese(sender: NSMenuItem) {
  545. }
  546. @objc func OpenItemAction(sender: NSMenuItem) {
  547. }
  548. @objc func takeSnapshot(sender: NSMenuItem) {
  549. }
  550. @objc func takeSnapshotSelectContent(sender: NSMenuItem) {
  551. }
  552. @objc func cropAllPageItem(sender: NSMenuItem) {
  553. }
  554. @objc func cropCurrentPageItem(sender: NSMenuItem) {
  555. }
  556. @objc func autoCropAllItem(sender: NSMenuItem) {
  557. }
  558. @objc func smartAutoCropAllItem(sender: NSMenuItem) {
  559. }
  560. @objc func selectToolModel(sender: NSMenuItem) {
  561. }
  562. @objc func customCropModel(sender: NSMenuItem) {
  563. }
  564. @objc func menuItemAnnotationClick_toolModel(sender: NSMenuItem) {
  565. self.listView.toolMode = .noteToolMode
  566. var identifier = KMDocumentAnnotationToolbarItemIdentifier
  567. var model : KMToolbarViewType = .None
  568. switch sender.tag {
  569. case 0:
  570. identifier = KMDocumentAnnotationToolbarItemIdentifier
  571. model = .Annatiton
  572. case 1:
  573. identifier = KMToolbarMoveToolModeItemIdentifier
  574. model = .Move
  575. case 2:
  576. identifier = KMToolbarMagnifyToolModeItemIdentifier
  577. model = .Magnify
  578. case 3:
  579. identifier = KMToolbarSelectToolModeItemIdentifier
  580. model = .Select
  581. case 4:
  582. identifier = KMToolbarZoomToSelectionItemIdentifier
  583. model = .SelectZoom
  584. default:
  585. break
  586. }
  587. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: identifier))!
  588. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode:model, toolbar: item, [])
  589. }
  590. @objc func menuItemAnnotationClick_add(sender : NSMenuItem) {
  591. var annotationType : CAnnotationType = .unkown
  592. switch sender.tag {
  593. case 0:
  594. annotationType = .highlight
  595. case 1:
  596. annotationType = .underline
  597. case 2:
  598. annotationType = .strikeOut
  599. case 3:
  600. annotationType = .freeText
  601. case 4:
  602. annotationType = .anchored
  603. case 5:
  604. annotationType = .square
  605. case 6:
  606. annotationType = .circle
  607. case 7:
  608. annotationType = .line
  609. case 8:
  610. annotationType = .link
  611. case 9:
  612. // var newOutline : CPDFOutline = CPDFOutline()
  613. // newOutline.label = "11111111"
  614. // let des = self.listView.currentDestination
  615. // if "\(des?.point.x ?? 0)" != "nan" {
  616. // newOutline.destination = self.listView.currentDestination
  617. // } else {
  618. // let destination : CPDFDestination = CPDFDestination(document: self.listView.document, pageIndex: self.listView.currentPageIndex, at: CGPoint(x: 0, y: 0), zoom: self.listView.scaleFactor)
  619. // newOutline.destination = destination
  620. // }
  621. // let current = self.listView.document.outlineRoot().insertChild(at: 0) ?? CPDFOutline()
  622. // let parent = current.parent ?? CPDFOutline()
  623. // let index = current.index + 1
  624. // parent.insertChild(newOutline, at: index)
  625. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .Outline {
  626. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  627. }
  628. // self.leftSideViewController.outlineViewController.addItemAction()
  629. return
  630. case 10:
  631. annotationType = .unkown
  632. default:
  633. break
  634. }
  635. if (annotationType != .link) {
  636. self.listView.addAnnotation(with: annotationType, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  637. self.listView.currentSelection = nil;
  638. return
  639. }
  640. // link
  641. let selection = self.listView.currentSelection
  642. self.toolbarController.selectItem(KMToolbarLinkAnnotationItemIdentifier)
  643. DispatchQueue.main.async {
  644. Task { @MainActor in
  645. #if VERSION_DMG
  646. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  647. return
  648. }
  649. #endif
  650. let annotation = self.listView.addAnnotation(with: annotationType, selection: selection, page: selection?.page, bounds: selection!.bounds)
  651. self.listView.currentSelection = nil;
  652. if (annotation != nil) {
  653. self.listView.updateActiveAnnotations([annotation!])
  654. }
  655. }
  656. }
  657. }
  658. @objc func aiTranslationAction(sender: NSMenuItem) {
  659. let content = self.listView.currentSelection.string() as? String ?? ""
  660. let origin = self.listView.currentSelection.bounds.origin
  661. self.aiTranslationWindow = KMAITranslationWindowController.init(windowNibName: "KMAITranslationWindowController")
  662. self.aiTranslationWindow?.content = content
  663. self.view.window!.addChildWindow(self.aiTranslationWindow!.window!, ordered: NSWindow.OrderingMode.above)
  664. self.aiTranslationWindow!.window?.center()
  665. }
  666. @objc func menuItemAnnotationClick_addStype(sender: NSMenuItem) {
  667. Task { @MainActor in
  668. #if VERSION_DMG
  669. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) {
  670. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  671. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  672. return
  673. }
  674. }
  675. #endif
  676. var point = mouseRightMenuEvent?.locationInWindow
  677. if (point == nil) {
  678. point = NSZeroPoint
  679. }
  680. let currentPoint: NSPoint = self.listView.convert(point!, from: self.listView.superview)
  681. let currentPage = self.listView.page(for: currentPoint, nearest: true)
  682. let pagePoint = self.listView.convert(currentPoint, to: currentPage)
  683. var annotation: CPDFAnnotation?
  684. if self.isReadMode {
  685. if (sender.tag == 0 || sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  686. self.listView.toolMode = .noteToolMode
  687. }
  688. switch sender.tag {
  689. case 0:
  690. self.listView.annotationType = CAnnotationType.ink
  691. case 1:
  692. // self.listView.annotationType = CAnnotationType.freeText
  693. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  694. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  695. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  696. if ((annotation) != nil) {
  697. self.listView.updateActiveAnnotations([annotation!])
  698. self.listView.edit(annotation)
  699. }
  700. case 2:
  701. // self.listView.annotationType = CAnnotationType.anchored
  702. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  703. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  704. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  705. self.listView.edit(annotation)
  706. case 3:
  707. // self.listView.annotationType = CAnnotationType.square
  708. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  709. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  710. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  711. case 4:
  712. // self.listView.annotationType = CAnnotationType.circle
  713. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  714. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  715. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  716. case 5:
  717. // self.listView.annotationType = CAnnotationType.arrow
  718. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  719. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  720. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  721. case 6:
  722. // self.listView.annotationType = CAnnotationType.line
  723. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  724. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  725. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  726. case 7:
  727. self.listView.annotationType = CAnnotationType.link
  728. self.openRightPane()
  729. case 8:
  730. self.listView.annotationType = CAnnotationType.stamp
  731. self.openRightPane()
  732. case 9:
  733. self.listView.annotationType = CAnnotationType.signSignature
  734. self.openRightPane()
  735. default:
  736. break
  737. }
  738. self.rightSideViewController.isHidden = true
  739. self.rightSideViewController.subViewType = .AnnotationProperts
  740. } else {
  741. if (sender.tag == 7 || sender.tag == 8 || sender.tag == 9) { // Ink & Link & stamp & sign
  742. if(self.toolbarController.toolbarType == .None) {
  743. self.toolbarController.toolbarType = .Annatiton
  744. }
  745. self.listView.toolMode = .noteToolMode
  746. }
  747. switch sender.tag {
  748. case 0:
  749. self.toolbarController.ignoreCurrentAnnotationTypeChange = true
  750. self.rightMouseEventing = true
  751. if(self.toolbarController.toolbarType == .None) {
  752. self.toolbarController.toolbarType = .Annatiton
  753. }
  754. self.listView.toolMode = .noteToolMode
  755. self.listView.annotationType = CAnnotationType.ink
  756. case 1:
  757. // self.listView.annotationType = CAnnotationType.freeText
  758. let defaultSize = self.listView.defaultSize(with: .freeText, in: currentPage)
  759. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  760. annotation = self.listView.addAnnotation(with: .freeText, selection: nil, page: currentPage, bounds: bounds)
  761. // self.view.window?.makeFirstResponder()
  762. if ((annotation) != nil) {
  763. // self.listView.updateActiveAnnotations([annotation!])
  764. self.listView.edit(annotation)
  765. }
  766. case 2:
  767. // self.listView.annotationType = CAnnotationType.anchored
  768. let defaultSize = self.listView.defaultSize(with: .anchored, in: currentPage)
  769. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  770. annotation = self.listView.addAnnotation(with: .anchored, selection: nil, page: currentPage, bounds: bounds)
  771. self.listView.edit(annotation)
  772. case 3:
  773. // self.listView.annotationType = CAnnotationType.square
  774. let defaultSize = self.listView.defaultSize(with: .square, in: currentPage)
  775. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  776. annotation = self.listView.addAnnotation(with: .square, selection: nil, page: currentPage, bounds: bounds)
  777. case 4:
  778. // self.listView.annotationType = CAnnotationType.circle
  779. let defaultSize = self.listView.defaultSize(with: .circle, in: currentPage)
  780. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  781. annotation = self.listView.addAnnotation(with: .circle, selection: nil, page: currentPage, bounds: bounds)
  782. case 5:
  783. // self.listView.annotationType = CAnnotationType.arrow
  784. let defaultSize = self.listView.defaultSize(with: .arrow, in: currentPage)
  785. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  786. annotation = self.listView.addAnnotation(with: .arrow, selection: nil, page: currentPage, bounds: bounds)
  787. case 6:
  788. // self.listView.annotationType = CAnnotationType.line
  789. let defaultSize = self.listView.defaultSize(with: .line, in: currentPage)
  790. let bounds = CPDFListViewRectFromCenterAndSize(CPDFListViewIntegralPoint(pagePoint), defaultSize)
  791. annotation = self.listView.addAnnotation(with: .line, selection: nil, page: currentPage, bounds: bounds)
  792. case 7:
  793. self.listView.annotationType = CAnnotationType.link
  794. self.openRightPane()
  795. case 8:
  796. self.listView.annotationType = CAnnotationType.stamp
  797. self.openRightPane()
  798. case 9:
  799. self.listView.annotationType = CAnnotationType.signSignature
  800. self.openRightPane()
  801. default:
  802. break
  803. }
  804. // self.rightSideViewController.view.isHidden = false
  805. self.rightSideViewController.isHidden = false
  806. // self.openRightPane()
  807. self.rightSideViewController.subViewType = .AnnotationProperts
  808. }
  809. if (annotation != nil) {
  810. self.listView.updateIsRightActiveAnnotations([annotation!])
  811. }
  812. }
  813. }
  814. @objc func menuItemBookMarkClick_add(sender:NSMenuItem) {
  815. if self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex)) == nil {
  816. let index = self.listView.currentPageIndex
  817. self.listView.document.addBookmark("\(NSLocalizedString("Page", comment: "")) \(index+1)", forPageIndex: UInt(index))
  818. self.listView.setNeedsDisplayForVisiblePages()
  819. } else {
  820. self.listView.document.removeBookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  821. self.listView.setNeedsDisplayForVisiblePages()
  822. }
  823. if self.isReadMode {
  824. } else {
  825. if self.leftPanelOpen == false || self.leftSideViewController.type.methodType != .BookMark {
  826. self.leftSideViewController.refreshMethodType(methodType: .BookMark)
  827. }
  828. let bookMark = self.listView.document.bookmark(forPageIndex: UInt(self.listView.currentPageIndex))
  829. if bookMark != nil {
  830. let item = KMBookMarkItem()
  831. item.bookMark = bookMark!
  832. item.label = (bookMark?.label)!
  833. item.index = UInt(bookMark!.pageIndex)
  834. self.leftSideViewController.bookViewController.reloadData()
  835. self.leftSideViewController.bookViewController.addBookMarkAndEdit(newBookMark: item)
  836. } else {
  837. self.leftSideViewController.bookViewController.reloadData()
  838. }
  839. }
  840. }
  841. @objc func menuItemAnnotationClick_FindString(sender:NSMenuItem) {
  842. self.leftSideViewController.refreshMethodType(methodType: .Search)
  843. }
  844. @objc func menuItemAnnotationClick_Print(sender:NSMenuItem) {
  845. let rect = listView.currentSelectionRect()
  846. let page = listView.currentPage()
  847. let copyPage : CPDFPage = page!.copy() as! CPDFPage
  848. copyPage.setBounds(rect, for: .cropBox)
  849. let image : NSImage = copyPage.thumbnail(of:(copyPage.bounds(for: .cropBox)).size)
  850. // let pdfDocument : PDFDocument = PDFDocument()
  851. // let newpage : PDFPage = PDFPage(image: image)!
  852. // pdfDocument.insert(newpage, at: 0)
  853. // 执行右键操作后,需要取消框选区域
  854. if self.listView.toolMode == .selectToolMode {
  855. objc_sync_enter(self)
  856. self.listView.selectionRect = NSZeroRect
  857. self.listView.selectionPageIndex = UInt(NSNotFound)
  858. objc_sync_exit(self)
  859. }
  860. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  861. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  862. if (result == .cancel) {
  863. return
  864. }
  865. // 解除权限
  866. self?.isSaveKeyChain = false
  867. self?.listView.document.unlock(withPassword: password)
  868. // 隐藏提示
  869. self?.hiddenSecureLimitTip()
  870. // 去打印
  871. KMPrintWindowController.printImage(image: image)
  872. }
  873. return
  874. }
  875. KMPrintWindowController.printImage(image: image)
  876. }
  877. // MARK: Redact 【密文标记】
  878. @objc func redact_menuItemClick_delete(sender: NSMenuItem?) {
  879. self.listView.remove(self.listView.activeAnnotation)
  880. }
  881. @objc func redact_menuItemClick_setProperty(sender: NSMenuItem?) {
  882. let windowController = KMRedactPropertyWindowController(windowNibName: "KMRedactBaseWindowController")
  883. windowController.annotation = (self.listView.activeAnnotation as! CPDFRedactAnnotation)
  884. self.view.window?.beginSheet(windowController.window!)
  885. self.currentWindowController = windowController
  886. windowController.itemClick = { [weak self] index, value in
  887. if (index == 1) { /// 取消
  888. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  889. self?.currentWindowController = nil
  890. return
  891. }
  892. let windowController_redact = self?.currentWindowController as! KMRedactPropertyWindowController
  893. let annotaton: CPDFRedactAnnotation = self?.listView.activeAnnotation as! CPDFRedactAnnotation
  894. annotaton.setBorderColor(windowController_redact.outsideColor)
  895. annotaton.setInteriorColor(windowController_redact.fillColor)
  896. if (windowController_redact.isOver) {
  897. annotaton.setFontColor(windowController_redact.fontColor)
  898. annotaton.setAlignment(windowController_redact.aligement)
  899. annotaton.setFont(windowController_redact.font)
  900. annotaton.setOverlayText(windowController_redact.overText)
  901. }
  902. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  903. self?.currentWindowController = nil
  904. }
  905. }
  906. @objc func redact_menuItemClick_setCurrentPropertyToDefaultValue(sender: NSMenuItem?) {
  907. if (self.listView.activeAnnotation == nil || (self.listView.activeAnnotation.isKind(of: CPDFRedactAnnotation.self)) == false) {
  908. return
  909. }
  910. let annotation: CPDFRedactAnnotation = self.listView.activeAnnotation as! CPDFRedactAnnotation
  911. let model = CPDFAnnotationModel(annotationType: .redact)
  912. model?.setColor(annotation.borderColor())
  913. model?.setInteriorColor(annotation.interiorColor())
  914. let overlayText: String = annotation.overlayText()
  915. if (overlayText.isEmpty) {
  916. model?.setIsOverlayText(false)
  917. } else {
  918. model?.setIsOverlayText(true)
  919. model?.setOverlayText(overlayText)
  920. model?.setFontColor(annotation.fontColor())
  921. model?.setAlignment(annotation.alignment())
  922. model?.setFontName(annotation.font().fontName)
  923. model?.setFontSize(annotation.font().pointSize)
  924. }
  925. }
  926. @objc func redact_menuItemClick_MultiPageFlag(sender: NSMenuItem?) {
  927. let anno = self.listView.activeAnnotation
  928. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  929. return
  930. }
  931. let windowController = KMRedactMutilPageFlagWindowController(windowNibName: "KMRedactBaseWindowController")
  932. windowController.pageCount = Int(self.listView.document.pageCount)
  933. self.currentWindowController = windowController
  934. self.view.window?.beginSheet(windowController.window!)
  935. windowController.itemClick = { [weak self] index, value in
  936. if (index == 1) {
  937. self!.view.window?.endSheet(self!.currentWindowController.window!)
  938. self!.currentWindowController = nil
  939. return
  940. }
  941. let windowController_mutilPageFlag = self?.currentWindowController as! KMRedactMutilPageFlagWindowController
  942. let pageType = windowController_mutilPageFlag.pageType
  943. let pageString = windowController_mutilPageFlag.pageString
  944. if (pageType == 4) { /// 自定义页面
  945. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  946. if (array.count == 0) {
  947. let alert = NSAlert()
  948. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  949. alert.runModal()
  950. return
  951. }
  952. }
  953. self!.view.window?.endSheet(self!.currentWindowController.window!)
  954. self!.currentWindowController = nil
  955. let indexs = KMRedactTools.getPageIndexs(pageType, string: pageString, Int((self?.listView.document.pageCount)!))
  956. if (indexs.count == 0) {
  957. return
  958. }
  959. for i in indexs {
  960. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  961. let redactAnno = KMRedactTools.createRedactAnnotation((self?.listView.document)!, anno as! CPDFRedactAnnotation)
  962. self?.listView.add(redactAnno, to: page)
  963. }
  964. }
  965. }
  966. @objc func redact_menuItemClick_apply(sender: NSMenuItem?) {
  967. self.exeRedactConfirm(.redactOne) {}
  968. }
  969. @objc func redact_menuItemClick_clear(sender: NSMenuItem?) {
  970. self.exeRedactConfirm(.eraserOne) {}
  971. }
  972. @objc func redact_menuItemClick_paste(sender: NSMenuItem?) {
  973. }
  974. @objc func exportStampImage(sender:NSMenuItem) {
  975. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  976. var image : NSImage = NSImage()
  977. if (listView.activeAnnotation is CPDFStampAnnotation) {
  978. image = (listView.activeAnnotation as! CPDFStampAnnotation).stampImage()
  979. } else if (listView.activeAnnotation is CPDFSignatureAnnotation) {
  980. image = (listView.activeAnnotation as! CPDFSignatureAnnotation).signImage
  981. }
  982. let data = image.tiffRepresentation
  983. if sender.tag == 0 {
  984. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  985. imageRep.size = image.size
  986. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  987. let savePanel = NSSavePanel()
  988. savePanel.allowedFileTypes = ["png"]
  989. savePanel.beginSheetModal(for: self.view.window!) { response in
  990. if (response != .OK) {
  991. return
  992. }
  993. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  994. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  995. }
  996. }
  997. } else {
  998. let pdfdocument = CPDFDocument()
  999. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1000. if NSData(data: data!).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1001. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1002. let savePanel = NSSavePanel()
  1003. savePanel.allowedFileTypes = ["pdf"]
  1004. savePanel.beginSheetModal(for: self.view.window!) { response in
  1005. if (response != .OK) {
  1006. return
  1007. }
  1008. if pdfdocument!.write(to: savePanel.url!) {
  1009. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. @objc func exportCorpImage(sender:NSMenuItem) {
  1017. let rect = NSIntegralRect(listView.currentSelectionRect())
  1018. let orgPage : CPDFPage = listView.currentSelectionPage() ?? listView.currentPage()
  1019. let page : CPDFPage = orgPage.copy() as! CPDFPage
  1020. page.setBounds(rect, for: .cropBox)
  1021. let image = page.thumbnail(of: rect.size) ?? NSImage()
  1022. let data = image.tiffRepresentation
  1023. let imageRep : NSBitmapImageRep = NSBitmapImageRep(data: data!) ?? NSBitmapImageRep()
  1024. imageRep.size = rect.size
  1025. let savePanel = NSSavePanel()
  1026. switch sender.tag {
  1027. case 0:
  1028. savePanel.allowedFileTypes = ["png"]
  1029. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
  1030. savePanel.beginSheetModal(for: self.view.window!) { response in
  1031. if (response != .OK) {
  1032. return
  1033. }
  1034. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1035. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1036. }
  1037. }
  1038. case 1:
  1039. savePanel.allowedFileTypes = ["jpg"]
  1040. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1041. savePanel.beginSheetModal(for: self.view.window!) { response in
  1042. if (response != .OK) {
  1043. return
  1044. }
  1045. if NSData(data: imageData).write(to: savePanel.url!, atomically: true) {
  1046. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1047. }
  1048. }
  1049. case 2:
  1050. savePanel.allowedFileTypes = ["pdf"]
  1051. let pdfdocument = CPDFDocument()
  1052. let signatureImagePath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first?.stringByAppendingPathComponent("signatureImage.png")
  1053. let imageData : Data = imageRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
  1054. if NSData(data: imageData).write(to: URL(fileURLWithPath: signatureImagePath!), atomically: true) {
  1055. pdfdocument?.insertPage(image.size, withImage: signatureImagePath, at: 0)
  1056. savePanel.beginSheetModal(for: self.view.window!) { response in
  1057. if (response != .OK) {
  1058. return
  1059. }
  1060. if pdfdocument!.write(to: savePanel.url!) {
  1061. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "");
  1062. }
  1063. }
  1064. }
  1065. default:
  1066. break
  1067. }
  1068. // 执行右键操作后,需要取消框选区域
  1069. if self.listView.toolMode == .selectToolMode {
  1070. objc_sync_enter(self)
  1071. self.listView.selectionRect = NSZeroRect
  1072. self.listView.selectionPageIndex = UInt(NSNotFound)
  1073. objc_sync_exit(self)
  1074. }
  1075. }
  1076. @IBAction func doZoomToAutoSelection(sender:NSMenuItem) {
  1077. let rect = listView.currentSelectionRect()
  1078. let page = listView.currentPage()
  1079. if NSIsEmptyRect(rect) == false && page != nil {
  1080. let isLegacy = NSScroller.responds(to: NSSelectorFromString("preferredScrollerStyle")) == false || NSScroller.preferredScrollerStyle == .legacy
  1081. var bounds = listView.bounds
  1082. var scale = 1.0
  1083. if isLegacy {
  1084. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1085. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1086. }
  1087. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1088. scale = NSHeight(bounds) / NSHeight(rect)
  1089. } else {
  1090. scale = NSWidth(bounds) / NSWidth(rect)
  1091. }
  1092. listView.setScaleFactor(scale, animated: false)
  1093. let scrollView = listView.scroll()
  1094. if isLegacy && scrollView?.hasHorizontalScroller == false || scrollView?.hasVerticalScroller == false {
  1095. if ((scrollView?.hasVerticalScroller) != nil) {
  1096. bounds.size.width -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1097. }
  1098. if ((scrollView?.hasHorizontalScroller) != nil) {
  1099. bounds.size.height -= NSScroller.scrollerWidth(for: .regular, scrollerStyle: listView.documentView().scrollerStyle)
  1100. }
  1101. if NSWidth(bounds) * NSHeight(rect) > NSWidth(rect) * NSHeight(bounds) {
  1102. scale = NSHeight(bounds) / NSHeight(rect)
  1103. } else {
  1104. scale = NSWidth(bounds) / NSWidth(rect)
  1105. }
  1106. listView.setScaleFactor(scale, animated: false)
  1107. }
  1108. DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { [self] in
  1109. let pagePoint = CGPoint(x: rect.origin.x, y: (rect.origin.y + rect.size.height))
  1110. listView.go(toTargetPoint: pagePoint, on: page, at: .top)
  1111. };
  1112. }
  1113. // 执行右键操作后,需要取消框选区域
  1114. if self.listView.toolMode == .selectToolMode {
  1115. objc_sync_enter(self)
  1116. self.listView.selectionRect = NSZeroRect
  1117. self.listView.selectionPageIndex = UInt(NSNotFound)
  1118. objc_sync_exit(self)
  1119. }
  1120. }
  1121. @IBAction func autoCropAll(sender:NSMenuItem) {
  1122. }
  1123. private func cropPagesToRects(rects:NSPointerArray) {
  1124. }
  1125. @IBAction func defaultAnnotationPorpert(sender:NSMenuItem) {
  1126. let model : CPDFAnnotationModel = CPDFAnnotationModel(annotationType: CAnnotationType(rawValue: sender.tag)!)!
  1127. switch sender.tag {
  1128. case CAnnotationType.highlight.rawValue,CAnnotationType.underline.rawValue,CAnnotationType.strikeOut.rawValue:
  1129. model.setColor((listView.activeAnnotation as! CPDFMarkupAnnotation).color)
  1130. model.setOpacity((listView.activeAnnotation as! CPDFMarkupAnnotation).opacity)
  1131. var red: CGFloat = 0.0
  1132. var green: CGFloat = 0.0
  1133. var blue: CGFloat = 0.0
  1134. var alpha: CGFloat = 0.0
  1135. (listView.activeAnnotation as! CPDFMarkupAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1136. if sender.tag == CAnnotationType.highlight.rawValue {
  1137. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorHighlightKey)
  1138. } else if sender.tag == CAnnotationType.underline.rawValue {
  1139. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorUnderlineKey)
  1140. } else if sender.tag == CAnnotationType.strikeOut.rawValue {
  1141. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFMarkupAnnotation).opacity], forKey: KMPreference.markupColorStrikthroughKey)
  1142. }
  1143. case CAnnotationType.ink.rawValue:
  1144. model.setColor((listView.activeAnnotation as! CPDFInkAnnotation).color)
  1145. model.setOpacity((listView.activeAnnotation as! CPDFInkAnnotation).opacity)
  1146. model.setLineWidth((listView.activeAnnotation as! CPDFInkAnnotation).lineWidth())
  1147. model.setStyle((listView.activeAnnotation as! CPDFInkAnnotation).borderStyle())
  1148. var red: CGFloat = 0.0
  1149. var green: CGFloat = 0.0
  1150. var blue: CGFloat = 0.0
  1151. var alpha: CGFloat = 0.0
  1152. (listView.activeAnnotation as! CPDFInkAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1153. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFInkAnnotation).opacity], forKey: KMPreference.markupColorPenKey)
  1154. case CAnnotationType.freeText.rawValue:
  1155. model.setColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).color)
  1156. model.setOpacity((listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity)
  1157. model.setFontColor((listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor)
  1158. model.setFontName((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)
  1159. model.setFontSize((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.pointSize)
  1160. model.setAlignment((listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment)
  1161. var red: CGFloat = 0.0
  1162. var green: CGFloat = 0.0
  1163. var blue: CGFloat = 0.0
  1164. var alpha: CGFloat = 0.0
  1165. (listView.activeAnnotation as! CPDFFreeTextAnnotation).fontColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1166. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFFreeTextAnnotation).opacity], forKey: KMPreference.markupColorTextKey)
  1167. if (KMPreferenceManager.supportFonts.contains((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName)) {
  1168. UserDefaults.standard.set((listView.activeAnnotation as! CPDFFreeTextAnnotation).font.fontName, forKey: KMPreference.markupFontTextStringKey)
  1169. UserDefaults.standard.synchronize()
  1170. }
  1171. let alignment = (listView.activeAnnotation as! CPDFFreeTextAnnotation).alignment
  1172. if (alignment == .left || alignment == .center || alignment == .right) {
  1173. UserDefaults.standard.set(alignment.rawValue, forKey: KMPreference.markupFontTextAligmentKey)
  1174. UserDefaults.standard.synchronize()
  1175. }
  1176. case CAnnotationType.anchored.rawValue:
  1177. model.setColor((listView.activeAnnotation as! CPDFTextAnnotation).color)
  1178. model.setAnchoredIconType((listView.activeAnnotation as! CPDFTextAnnotation).iconType())
  1179. var red: CGFloat = 0.0
  1180. var green: CGFloat = 0.0
  1181. var blue: CGFloat = 0.0
  1182. var alpha: CGFloat = 0.0
  1183. (listView.activeAnnotation as! CPDFTextAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1184. KMPreferenceManager.shared.setData(data: [red, green, blue, alpha], forKey: KMPreference.markupColorNoteKey)
  1185. case CAnnotationType.square.rawValue:
  1186. model.setInteriorColor((listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor)
  1187. model.setColor((listView.activeAnnotation as! CPDFSquareAnnotation).color)
  1188. model.setOpacity((listView.activeAnnotation as! CPDFSquareAnnotation).opacity)
  1189. model.setLineWidth((listView.activeAnnotation as! CPDFSquareAnnotation).lineWidth())
  1190. var red: CGFloat = 0.0
  1191. var green: CGFloat = 0.0
  1192. var blue: CGFloat = 0.0
  1193. var alpha: CGFloat = 0.0
  1194. (listView.activeAnnotation as! CPDFSquareAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1195. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).interiorOpacity], forKey: KMPreference.markupColorRectangleFillKey)
  1196. (listView.activeAnnotation as! CPDFSquareAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1197. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFSquareAnnotation).opacity], forKey: KMPreference.markupColorRectangleBorderKey)
  1198. case CAnnotationType.circle.rawValue:
  1199. model.setInteriorColor((listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor)
  1200. model.setColor((listView.activeAnnotation as! CPDFCircleAnnotation).color)
  1201. model.setOpacity((listView.activeAnnotation as! CPDFCircleAnnotation).opacity)
  1202. model.setLineWidth((listView.activeAnnotation as! CPDFCircleAnnotation).lineWidth())
  1203. var red: CGFloat = 0.0
  1204. var green: CGFloat = 0.0
  1205. var blue: CGFloat = 0.0
  1206. var alpha: CGFloat = 0.0
  1207. (listView.activeAnnotation as! CPDFCircleAnnotation).interiorColor.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1208. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).interiorOpacity], forKey: KMPreference.markupColorCircleFillKey)
  1209. (listView.activeAnnotation as! CPDFCircleAnnotation).color.usingColorSpaceName(.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
  1210. KMPreferenceManager.shared.setData(data: [red, green, blue, (listView.activeAnnotation as! CPDFCircleAnnotation).opacity], forKey: KMPreference.markupColorCircleBorderKey)
  1211. default:
  1212. break
  1213. }
  1214. }
  1215. @objc internal func menuItemClick_HidenorShowNote(sender: NSMenuItem?) {
  1216. self.showOrHideNotes()
  1217. }
  1218. //MARK: action
  1219. @objc func cropCurrentPage() {
  1220. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1221. var page: CPDFPage?
  1222. if ((self.listView.currentSelectionPage()) != nil) {
  1223. page = self.listView.currentSelectionPage()
  1224. } else {
  1225. page = self.listView.currentPage()
  1226. }
  1227. if (NSIsEmptyRect(rect)) {
  1228. rect = KMCropTools.getPageForegroundBox(page!)
  1229. }
  1230. let index: UInt = (page?.pageIndex())!
  1231. cropPage(at: index, in: rect)
  1232. // 执行右键操作后,需要取消框选区域
  1233. if self.listView.toolMode == .selectToolMode {
  1234. objc_sync_enter(self)
  1235. self.listView.selectionRect = NSZeroRect
  1236. self.listView.selectionPageIndex = UInt(NSNotFound)
  1237. objc_sync_exit(self)
  1238. }
  1239. }
  1240. func cropPage(at index: UInt, in rect: NSRect) {
  1241. let oldRect = self.listView.document.page(at: index)?.bounds(for: .cropBox)
  1242. let undoManager = self.listView.undoManager
  1243. (undoManager?.prepare(withInvocationTarget: self) as? AnyObject)!.cropPage(at: index, in: oldRect!)
  1244. let page = self.listView.document.page(at: index)
  1245. let newRect = NSIntersectionRect(rect, (page?.bounds(for: .mediaBox))!)
  1246. page?.setBounds(newRect, for: .cropBox)
  1247. /// 刷新预览视图
  1248. self.listView.layoutDocumentView()
  1249. self.listView.displayBox = .cropBox
  1250. }
  1251. @objc private func cropAllPage() {
  1252. var size = NSZeroSize
  1253. for i in 0 ..< self.listView.document.pageCount {
  1254. let page = self.listView.document.page(at: i)
  1255. var rect = KMCropTools.getPageForegroundBox(page!)
  1256. size.width = fmax(size.width, NSWidth(rect))
  1257. size.height = fmax(size.height, NSHeight(rect))
  1258. }
  1259. var rectArray: Array<NSRect> = []
  1260. for i in 0 ..< self.listView.document.pageCount {
  1261. let page = self.listView.document.page(at: i)
  1262. var rect = KMCropTools.getPageForegroundBox(page!)
  1263. var bounds: NSRect = (page?.bounds(for: .mediaBox))!
  1264. if (rect.minX - bounds.minX > bounds.maxX-rect.maxX) {
  1265. rect.origin.x = rect.maxX-size.width
  1266. }
  1267. rect.origin.y = rect.maxY-size.height
  1268. rect.size = size
  1269. if (NSWidth(rect) > NSWidth(bounds)) {
  1270. rect.size.width = NSWidth(bounds)
  1271. }
  1272. if (NSHeight(rect) > NSHeight(bounds)) {
  1273. rect.size.height = NSHeight(bounds)
  1274. }
  1275. if (NSMinX(rect) < NSMinX(bounds)) {
  1276. rect.origin.x = NSMinX(bounds)
  1277. } else if (NSMaxX(rect) > NSMaxX(bounds)) {
  1278. rect.origin.x = NSMaxX(bounds) - NSWidth(rect)
  1279. }
  1280. if (NSMinY(rect) < NSMinY(bounds)) {
  1281. rect.origin.y = NSMinY(bounds)
  1282. } else if (NSMaxY(rect) > NSMaxY(bounds)) {
  1283. rect.origin.y = NSMaxY(bounds) - NSHeight(rect)
  1284. }
  1285. rectArray.append(rect)
  1286. }
  1287. cropPages(to: rectArray)
  1288. }
  1289. func cropPages(to rects: Array<NSRect>) {
  1290. let currentPage = self.listView.currentPage()
  1291. let visibleRect: NSRect = self.listView.convert(self.listView.convert(self.listView.documentView().visibleRect, from: self.listView.documentView()), to: self.listView.currentPage())
  1292. var oldRectArray: Array<NSRect> = []
  1293. for i in 0 ..< self.listView.document.pageCount {
  1294. let page = self.listView.document.page(at: i)
  1295. var rect = NSIntersectionRect(rects[Int(i)], (page?.bounds(for: .mediaBox))!)
  1296. let oldRect = page?.bounds(for: .cropBox)
  1297. oldRectArray.append(oldRect!)
  1298. page?.setBounds(rect, for: .cropBox)
  1299. }
  1300. let undoManager = self.listView.undoManager
  1301. (undoManager?.prepare(withInvocationTarget: self) as AnyObject).cropPages(to: oldRectArray)
  1302. /// 刷新预览视图
  1303. self.listView.layoutDocumentView()
  1304. self.listView.displayBox = .cropBox
  1305. self.listView.go(to: currentPage)
  1306. self.listView.go(to: visibleRect, on: currentPage)
  1307. }
  1308. private func cropCustomArea() {
  1309. self.listView.toolMode = .selectToolMode
  1310. self.listView.autoScales = true
  1311. self.listView.autoScales = false
  1312. var pageHeight: CGFloat = NSHeight(self.listView.currentPage().bounds(for: self.listView.displayBox))
  1313. if (self.listView.displaysPageBreaks) {
  1314. pageHeight += 8
  1315. }
  1316. var scaleFactor: CGFloat = fmax(self.listView.minimumScaleFactor, NSHeight(self.listView.frame)/pageHeight)
  1317. // if (scaleFactor < self.preView.scaleFactor) {
  1318. self.listView.scaleFactor = scaleFactor
  1319. // }
  1320. let tipView = KMCropTipView()
  1321. tipView.setString(string: "请框选裁剪区域")
  1322. tipView.frame = self.topTipBox.contentView!.frame
  1323. tipView.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
  1324. self.addTopTip(tipView)
  1325. tipView.enterAction = {
  1326. () in
  1327. var rect = NSIntegralRect(self.listView.currentSelectionRect())
  1328. if (NSIsEmptyRect(rect)) {
  1329. return
  1330. }
  1331. let window = KMCropSettingWindowController(windowNibName: "KMCropSettingWindowController")
  1332. self.view.window?.beginSheet(window.window!)
  1333. self.cropSettingWindowController = window
  1334. window.itemClick = { [self]
  1335. (index: Int) in
  1336. if (index == 1) { /// 取消
  1337. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1338. self.cropSettingWindowController = nil
  1339. return
  1340. }
  1341. let pageRangeType = self.cropSettingWindowController.pageRangeIndex
  1342. let pageCount: Int = Int(self.listView.document.pageCount)
  1343. var pages: Array<Int> = []
  1344. if (pageRangeType == 0) { /// 当前页面
  1345. pages.append(self.listView.currentPageIndex)
  1346. } else if (pageRangeType == 1) { /// 全部页面
  1347. for i in 0 ..< pageCount {
  1348. pages.append(i)
  1349. }
  1350. } else if (pageRangeType == 2) { /// 奇数页面
  1351. var string: String = ""
  1352. for i in 0 ..< pageCount {
  1353. if (i % 2 == 1) {
  1354. continue
  1355. }
  1356. pages.append(i)
  1357. }
  1358. } else if (pageRangeType == 3) { /// 偶数页面
  1359. var string: String = ""
  1360. for i in 0 ..< pageCount {
  1361. if (i % 2 == 0) {
  1362. continue
  1363. }
  1364. pages.append(i)
  1365. }
  1366. } else { /// 自定义
  1367. for i in self.cropSettingWindowController.pageRangePages {
  1368. pages.append(i)
  1369. }
  1370. }
  1371. if (pages.count < 0) {
  1372. let alert = NSAlert()
  1373. alert.messageText = "请选择页面"
  1374. alert.runModal()
  1375. return
  1376. }
  1377. var pageSize: NSSize = NSZeroSize
  1378. if (self.cropSettingWindowController.pageSize == "None") {
  1379. } else {
  1380. pageSize = KMCropTools.getPageSizeValue(self.cropSettingWindowController.pageSize)
  1381. }
  1382. for i in pages {
  1383. var page: CPDFPage = self.listView.document.page(at: UInt(i))
  1384. var rect = NSIntegralRect(self.listView.selectionRect)
  1385. if (NSIsEmptyRect(rect)) {
  1386. rect = KMCropTools.getPageForegroundBox(page)
  1387. }
  1388. var newRect = NSIntersectionRect(rect, (page.bounds(for: .mediaBox)))
  1389. page.setBounds(newRect, for: .cropBox)
  1390. if (pageSize.width == 0 && pageSize.height == 0) {
  1391. } else {
  1392. // let tiffData = page.pdfListViewTIFFData(for: rect)
  1393. let index: UInt = (page.pageIndex())
  1394. // let newPage: CPDFPage = nil
  1395. // self.listView.document.removePage(at: index)
  1396. // newPage.setBounds(NSMakeRect(0, 0, pageSize.width, pageSize.height), for: .cropBox)
  1397. // let result = self.preView.document.insertPageObject(newPage, at: index)
  1398. let result = self.listView.document.insertPage(pageSize, at: index)
  1399. }
  1400. }
  1401. /// 保存到临时路径
  1402. let toPath: String = self.listView.document.documentURL.path
  1403. let documentPath = NSTemporaryDirectory()
  1404. let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
  1405. if (FileManager.default.fileExists(atPath: tempPath)) {
  1406. try?FileManager.default.removeItem(atPath: tempPath)
  1407. }
  1408. let result = self.listView.document.write(to: URL(fileURLWithPath: tempPath))
  1409. if (result) {
  1410. if (FileManager.default.fileExists(atPath: toPath)) {
  1411. try?FileManager.default.removeItem(atPath: toPath)
  1412. }
  1413. try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
  1414. } else {
  1415. try?FileManager.default.removeItem(atPath: tempPath)
  1416. }
  1417. DispatchQueue.main.async {
  1418. self.listView.toolMode = .textToolMode
  1419. /// 刷新预览视图
  1420. self.listView.layoutDocumentView()
  1421. self.listView.displayBox = .cropBox
  1422. }
  1423. self.view.window?.endSheet((self.cropSettingWindowController?.window)!)
  1424. self.cropSettingWindowController = nil
  1425. self.addTopTip(nil)
  1426. }
  1427. }
  1428. }
  1429. @objc private func shareDocument(sender:KMToolbarViewController, limit: Bool = false) {
  1430. if (limit) {
  1431. var doucumentURL : URL = self.listView.document.documentURL
  1432. if doucumentURL != nil {
  1433. let docDir = NSTemporaryDirectory()
  1434. let documentName : String = doucumentURL.path.lastPathComponent
  1435. let path = docDir.stringByAppendingPathComponent(documentName)
  1436. // let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1437. let data = KMTools.saveWatermarkDocument(document: self.listView.document, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1438. let writeSuccess = data != nil
  1439. if writeSuccess == false {
  1440. __NSBeep()
  1441. return;
  1442. }
  1443. doucumentURL = URL(fileURLWithPath: path)
  1444. }
  1445. let array = [doucumentURL]
  1446. let picker = NSSharingServicePicker.init(items: array)
  1447. if sender.shareButton.window != nil {
  1448. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1449. } else {
  1450. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1451. }
  1452. return
  1453. }
  1454. var doucumentURL : URL = self.listView.document.documentURL
  1455. if doucumentURL != nil {
  1456. let docDir = NSTemporaryDirectory()
  1457. let documentName : String = doucumentURL.path.lastPathComponent
  1458. let path = docDir.stringByAppendingPathComponent(documentName)
  1459. let writeSuccess = self.listView.document.write(to: URL(fileURLWithPath: path))
  1460. if writeSuccess == false {
  1461. __NSBeep()
  1462. return;
  1463. }
  1464. doucumentURL = URL(fileURLWithPath: path)
  1465. }
  1466. let array = [doucumentURL]
  1467. let picker = NSSharingServicePicker.init(items: array)
  1468. if sender.shareButton.window != nil {
  1469. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1470. } else {
  1471. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1472. }
  1473. }
  1474. @objc private func shareFlatten(sender:KMToolbarViewController, limit: Bool = false) {
  1475. if (limit) {
  1476. let document = self.listView.document ?? CPDFDocument()
  1477. var path = document!.documentURL.path
  1478. if path != nil {
  1479. let docDir = NSTemporaryDirectory()
  1480. let documentName : String = path.lastPathComponent
  1481. path = docDir.stringByAppendingPathComponent(documentName)
  1482. }
  1483. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1484. var tfileName = path.deletingPathExtension.lastPathComponent
  1485. let tStdFileSuffix = "_flatten"
  1486. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1487. path = pathFolder + "/" + tfileName
  1488. let data = KMTools.saveWatermarkDocumentForFlatten(document: document!, to: URL(fileURLWithPath: path))
  1489. let success = data != nil
  1490. if success {
  1491. let url = URL(fileURLWithPath: path)
  1492. let picker = NSSharingServicePicker.init(items: [url])
  1493. if sender.shareButton.window != nil {
  1494. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1495. } else {
  1496. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1497. }
  1498. }
  1499. return
  1500. }
  1501. let document = self.listView.document ?? CPDFDocument()
  1502. var path = document!.documentURL.path
  1503. if path != nil {
  1504. let docDir = NSTemporaryDirectory()
  1505. let documentName : String = path.lastPathComponent
  1506. path = docDir.stringByAppendingPathComponent(documentName)
  1507. }
  1508. let pathFolder = path.fileURL.deletingLastPathComponent().path
  1509. var tfileName = path.deletingPathExtension.lastPathComponent
  1510. let tStdFileSuffix = "_flatten"
  1511. tfileName = tfileName + tStdFileSuffix + ".pdf"
  1512. path = pathFolder + "/" + tfileName
  1513. let success : Bool = document!.writeFlatten(to: URL(fileURLWithPath: path))
  1514. if success {
  1515. let url = URL(fileURLWithPath: path)
  1516. let picker = NSSharingServicePicker.init(items: [url])
  1517. if sender.shareButton.window != nil {
  1518. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1519. } else {
  1520. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1521. }
  1522. }
  1523. }
  1524. @objc private func shareOriginalPDF(sender:KMToolbarViewController, limit: Bool = false) {
  1525. if (limit) {
  1526. let document = self.listView.document ?? CPDFDocument()
  1527. var path = document!.documentURL.path
  1528. if path != nil {
  1529. let docDir = NSTemporaryDirectory()
  1530. let documentName : String = path.lastPathComponent
  1531. path = docDir.stringByAppendingPathComponent(documentName)
  1532. }
  1533. // var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1534. let data = KMTools.saveWatermarkDocument(document: document!, to: URL(fileURLWithPath: path), secureOptions: self.secureOptions, removePWD: self.removeSecureFlag)
  1535. var writeSuccess = data != nil
  1536. if writeSuccess == false {
  1537. __NSBeep()
  1538. return;
  1539. }
  1540. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1541. for i in 0 ... newDocument.pageCount-1 {
  1542. let page = newDocument.page(at: i)
  1543. var annotations : [CPDFAnnotation] = []
  1544. for annotation in page!.annotations {
  1545. annotations.append(annotation)
  1546. }
  1547. for annotation in annotations {
  1548. annotation.page.removeAnnotation(annotation)
  1549. }
  1550. }
  1551. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1552. if writeSuccess {
  1553. let url = URL(fileURLWithPath: path)
  1554. let picker = NSSharingServicePicker.init(items: [url])
  1555. if sender.shareButton.window != nil {
  1556. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1557. } else {
  1558. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1559. }
  1560. }
  1561. return
  1562. }
  1563. let document = self.listView.document ?? CPDFDocument()
  1564. var path = document!.documentURL.path
  1565. if path != nil {
  1566. let docDir = NSTemporaryDirectory()
  1567. let documentName : String = path.lastPathComponent
  1568. path = docDir.stringByAppendingPathComponent(documentName)
  1569. }
  1570. var writeSuccess = document!.write(to: URL(fileURLWithPath: path))
  1571. if writeSuccess == false {
  1572. __NSBeep()
  1573. return;
  1574. }
  1575. let newDocument = CPDFDocument(url: URL(fileURLWithPath: path))!
  1576. for i in 0 ... newDocument.pageCount-1 {
  1577. let page = newDocument.page(at: i)
  1578. var annotations : [CPDFAnnotation] = []
  1579. for annotation in page!.annotations {
  1580. annotations.append(annotation)
  1581. }
  1582. for annotation in annotations {
  1583. annotation.page.removeAnnotation(annotation)
  1584. }
  1585. }
  1586. writeSuccess = newDocument.write(to:URL(fileURLWithPath: path))
  1587. if writeSuccess {
  1588. let url = URL(fileURLWithPath: path)
  1589. let picker = NSSharingServicePicker.init(items: [url])
  1590. if sender.shareButton.window != nil {
  1591. picker.show(relativeTo: sender.shareButton.bounds, of: sender.shareButton, preferredEdge: NSRectEdge.minY)
  1592. } else {
  1593. picker.show(relativeTo: NSRect(x: (self.view.window?.contentView?.frame.size.width)!, y: (self.view.window?.contentView?.frame.size.height ?? 0)-8, width: 0, height: 0), of: self.view.window?.contentView ?? NSView(), preferredEdge: NSRectEdge.minY)
  1594. }
  1595. }
  1596. }
  1597. // 开启/关闭左边栏
  1598. @objc func toggleLeftPane() -> Void {
  1599. // if lastLeftPanWidth >= functionWidth {
  1600. leftPanelOpen = true
  1601. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1602. // } else {
  1603. // leftPanelOpen = false
  1604. // applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1605. // }
  1606. }
  1607. // 开启左边栏
  1608. @objc func openLeftPane() -> Void {
  1609. leftPanelOpen = true
  1610. applyLeftSideWidth(panelWidth+functionWidth, rightSideWidth: lastRightPanWidth)
  1611. }
  1612. // 关闭左边栏
  1613. @objc func closeLeftPane() -> Void {
  1614. leftPanelOpen = false
  1615. applyLeftSideWidth(functionWidth, rightSideWidth: lastRightPanWidth)
  1616. }
  1617. // 开启/关闭右边栏
  1618. @objc func toggleRightPane() -> Void {
  1619. if lastRightPanWidth > 5 {
  1620. self.rightPanelIsOpen = false
  1621. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1622. } else {
  1623. self.rightPanelIsOpen = true
  1624. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1625. }
  1626. }
  1627. @objc func openRightPane() -> Void {
  1628. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1629. if self.rightPanelIsOpen {
  1630. return
  1631. }
  1632. self.rightPanelIsOpen = true
  1633. self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  1634. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: defaultRightWidth)
  1635. }
  1636. }
  1637. @objc func closeRightPane() -> Void {
  1638. if (KMPreferenceManager.shared.autoExpandPropertyPanel) {
  1639. self.rightPanelIsOpen = false
  1640. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  1641. applyLeftSideWidth(lastLeftPanWidth, rightSideWidth: 0)
  1642. }
  1643. }
  1644. func rename(_ sender: NSNotification) -> Void {
  1645. if (self.view.window == nil || self.view.window!.isVisible == false) {
  1646. return
  1647. }
  1648. let tabController = sender.object as? CTTabController
  1649. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1650. let outputSavePanel = NSSavePanel()
  1651. outputSavePanel.title = NSLocalizedString("Rename", comment: "")
  1652. outputSavePanel.allowedFileTypes = ["pdf"]
  1653. outputSavePanel.nameFieldStringValue = (self.document?.documentURL.lastPathComponent)!
  1654. outputSavePanel.directoryURL = self.document?.documentURL.deletingLastPathComponent()
  1655. let result = outputSavePanel.runModal()
  1656. if result == .OK {
  1657. let pdfDocument = CPDFDocument(url: self.document?.documentURL)
  1658. let fileURL = pdfDocument?.documentURL
  1659. let fileManager = FileManager.default
  1660. let newFileURL = fileURL!.deletingLastPathComponent().appendingPathComponent(outputSavePanel.url!.lastPathComponent)
  1661. var result = true
  1662. do {
  1663. try fileManager.moveItem(at: fileURL!, to: newFileURL)
  1664. } catch {
  1665. result = false
  1666. KMPrint("Error renaming file! Threw: \(error.localizedDescription)")
  1667. }
  1668. if (result) {
  1669. tabController?.title = outputSavePanel.url!.lastPathComponent
  1670. if let newPdfDocument = CPDFDocument(url: newFileURL) {
  1671. self.isSaveKeyChain = false
  1672. newPdfDocument.unlock(withPassword: self.document?.password)
  1673. if (newPdfDocument.pageCount > 0) {
  1674. self.setDocument = newPdfDocument
  1675. }
  1676. }
  1677. }
  1678. } else {
  1679. outputSavePanel.close()
  1680. }
  1681. }
  1682. }
  1683. func showInFinder(_ sender: Any) -> Void {
  1684. if sender is NSNotification {
  1685. let tabController = (sender as! NSNotification).object as? CTTabController
  1686. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1687. let file: URL = (self.myDocument?.fileURL)!
  1688. if FileManager.default.fileExists(atPath: file.path) {
  1689. NSWorkspace.shared.activateFileViewerSelecting([file])
  1690. }
  1691. }
  1692. } else {
  1693. let file: URL = (self.myDocument?.fileURL)!
  1694. if FileManager.default.fileExists(atPath: file.path) {
  1695. NSWorkspace.shared.activateFileViewerSelecting([file])
  1696. }
  1697. }
  1698. }
  1699. func showOrHideNotes() {
  1700. self.listView.hideNotes = !self.listView.hideNotes
  1701. self.toolbarController.isShowAllAnnotations = !self.listView.hideNotes
  1702. //BOTA 注释列表显示隐藏
  1703. self.leftSideViewController.annotationViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1704. // self.leftSideViewController.thumbnailViewController.annotationShowState = self.listView.hideNotes ? .hidden : .none
  1705. }
  1706. func closeTab(_ sender: NSNotification) -> Void {
  1707. let tabController = sender.object as? CTTabController
  1708. if tabController?.title == self.document?.documentURL.lastPathComponent {
  1709. print("closeTab")
  1710. self.leftSideViewController.clearAnnotationFilterData()
  1711. self.leftSideViewController.clearNotification()
  1712. }
  1713. }
  1714. // MARK: -
  1715. // MARK: 显示窗口
  1716. internal func showCompressWindow(url: URL? = nil) {
  1717. if let wc = self.currentWindowController as? KMCompressWindowController, let _ = wc.window?.isSheet {
  1718. KMPrint("压缩窗口已显示")
  1719. return
  1720. }
  1721. let windowController = KMCompressWIndowControllerNew(windowNibName: "KMCompressWIndowControllerNew")
  1722. self.view.window?.beginSheet(windowController.window!)
  1723. self.currentWindowController = windowController
  1724. if let _url = url {
  1725. windowController.documentURL = _url
  1726. windowController.oriDocumentUrl = self.listView.document.documentURL
  1727. } else {
  1728. windowController.documentURL = self.listView.document.documentURL
  1729. }
  1730. windowController.password = self.listView.document.password
  1731. windowController.itemClick = { [weak self] in
  1732. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1733. self?.currentWindowController = nil
  1734. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1735. }
  1736. windowController.batchAction = { [weak self] view, filePaths in
  1737. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1738. self?.currentWindowController = nil
  1739. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1740. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1741. batchWindowController.window?.makeKeyAndOrderFront("")
  1742. let batchOperateFile = KMBatchOperateFile(filePath: filePaths.first!.path)
  1743. batchWindowController.switchToOperateType(KMBatchOperationType.Compress, files: [batchOperateFile])
  1744. batchWindowController.window?.makeKeyAndOrderFront("")
  1745. }
  1746. windowController.resultCallback = { [weak self] result, openDocument, fileURL, error in
  1747. if (result) {
  1748. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1749. self?.currentWindowController = nil
  1750. self?.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1751. if (openDocument) {
  1752. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  1753. } else {
  1754. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1755. }
  1756. } else {
  1757. let alert = NSAlert()
  1758. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1759. alert.runModal()
  1760. }
  1761. }
  1762. }
  1763. internal func showConvertWindow(type: KMToolbarType, documentUrl: URL? = nil, identifier: String?) {
  1764. if let wc = self.currentWindowController as? KMConvertBaseWindowController, let _ = wc.window?.isSheet {
  1765. KMPrint("转档窗口已显示")
  1766. return
  1767. }
  1768. var convertT: KMConvertType = .Word
  1769. var windowController: KMConvertBaseWindowController?
  1770. if (type == .word) { /// Word
  1771. convertT = .Word
  1772. } else if (type == .excel) {
  1773. convertT = .Excel
  1774. } else if (type == .ppt || type == .rtf || type == .html || type == .conversion_text) {
  1775. if (type == .ppt) {
  1776. convertT = .PPT
  1777. } else if (type == .rtf) {
  1778. convertT = .RTF
  1779. } else if (type == .html) {
  1780. convertT = .HTML
  1781. } else if (type == .conversion_text) {
  1782. convertT = .Text
  1783. }
  1784. } else if (type == .csv) {
  1785. convertT = .CSV
  1786. } else if (type == .conversion_image) {
  1787. windowController = KMConvertImageWindowController()
  1788. }
  1789. windowController?.subscribeWaterMarkType = type.toSubscribeWaterMarkType()
  1790. var url: URL?
  1791. if (documentUrl != nil) {
  1792. url = documentUrl
  1793. windowController?.oriDocumentUrl = self.listView.document.documentURL
  1794. } else {
  1795. url = self.listView.document.documentURL
  1796. }
  1797. self.showAllConvertWindow(convertT: convertT)
  1798. // let model = KMDocumentModel(url: url!)
  1799. // if (self.listView.document.password != nil) {
  1800. // let _ = model.unlock(self.listView.document.password)
  1801. // }
  1802. // model.currentIndex = self.listView.currentPageIndex
  1803. // windowController?.documentModel = model
  1804. //
  1805. // windowController?.itemClick = { [weak self] index in
  1806. // if (identifier != nil) {
  1807. // self?.toolbarController.cancelSelected(identifier!)
  1808. // }
  1809. //
  1810. // if (self?.currentWindowController == nil) {
  1811. // return
  1812. // }
  1813. // self?.view.window?.endSheet(self!.currentWindowController.window!)
  1814. // self?.currentWindowController = nil
  1815. // }
  1816. //
  1817. // self.view.window?.beginSheet((windowController?.window)!)
  1818. // self.currentWindowController = windowController
  1819. }
  1820. //MARK: 转档 -
  1821. func showAllConvertWindow(convertT: KMConvertType) {
  1822. let convertWC = KMConvertWindowController(documemtV: self.document!, currentPage: self.listView.currentPage(), convertT: convertT) {
  1823. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [self] in
  1824. var type: KMConvertWithPDFType = .WordAdvance
  1825. switch convertT {
  1826. case .Word:
  1827. break
  1828. case .Excel:
  1829. type = .Excel
  1830. case .PPT:
  1831. type = .PowerPoint
  1832. case .RTF:
  1833. type = .RTF
  1834. case .CSV:
  1835. type = .CSV
  1836. case .HTML:
  1837. type = .HTML
  1838. case .Text:
  1839. type = .Text
  1840. case .JPEG:
  1841. type = .JPEG
  1842. case .PNG:
  1843. type = .PNG
  1844. case .GIF:
  1845. type = .GIF
  1846. case .JPG:
  1847. type = .JPG
  1848. case .TIFF:
  1849. type = .TIFF
  1850. case .TGA:
  1851. type = .TGA
  1852. case .BMP:
  1853. type = .BMP
  1854. case .JP2:
  1855. type = .JPEG2000
  1856. case .AdvancedWord:
  1857. break
  1858. default:
  1859. break
  1860. }
  1861. // let document = self.document
  1862. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1863. var needShowHint = false
  1864. if KMConvertOperationQueue.sharedQueue.operations.count > 0 {
  1865. needShowHint = true
  1866. } else {
  1867. var needContinue = false
  1868. if KMBatchOperateManager.defaultManager.files?.count ?? 0 > 0 {
  1869. let arr: [String] = converFilesToPath(files: KMBatchOperateManager.defaultManager.files!)
  1870. let ss = self.document?.documentURL.path
  1871. if arr.contains(ss!) {
  1872. needContinue = false
  1873. }else {
  1874. needContinue = true
  1875. }
  1876. }else {
  1877. needContinue = true
  1878. }
  1879. if needContinue {
  1880. let ss = self.document?.documentURL.path
  1881. let file = KMBatchOperateFile(filePath: ss!, type: .Convert)
  1882. file.password = document?.password ?? ""
  1883. KMBatchOperateManager.defaultManager.files?.append(file)
  1884. }
  1885. batchWindowController.switchToOperateType(.Convert, files: KMBatchOperateManager.defaultManager.files!)
  1886. batchWindowController.switchToConvertType(convertType: type)
  1887. }
  1888. batchWindowController.window?.makeKeyAndOrderFront(nil)
  1889. if needShowHint {
  1890. batchWindowController.showIsConvertingHint()
  1891. } else {
  1892. }
  1893. }
  1894. }
  1895. self.km_beginSheet(windowC: convertWC)
  1896. }
  1897. //MARK: 转档 - OCR
  1898. func showOCRWindow() {
  1899. let com = KMOCRPDFWindowController(cpdfDocument: self.listView.document!, pwd: self.listView.document.password)
  1900. self.km_beginSheet(windowC: com)
  1901. }
  1902. //MARK: 导出图片
  1903. func extractImageAction(num: Int) {
  1904. if !(self.listView.document.allowsPrinting || self.listView.document.allowsCopying) {
  1905. let alert = NSAlert()
  1906. alert.alertStyle = .critical
  1907. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1908. alert.runModal()
  1909. return
  1910. }
  1911. // if sender is KMToolbarItem {
  1912. // (sender as! KMToolbarItem).isSelected = false
  1913. // }
  1914. // if !IAPProductsManager.defaultManager.isAvailableAllFunction {
  1915. // KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  1916. // return
  1917. // }
  1918. let document = self.listView.document
  1919. var fileURL = document?.documentURL
  1920. if num == 1 {
  1921. let pageCount = self.document?.pageCount ?? 0
  1922. var indeSet = NSMutableIndexSet()
  1923. indeSet.add(in: NSRange(location: 0, length: Int(pageCount)))
  1924. if indeSet.count == 0 {
  1925. return
  1926. }
  1927. let lastPathName = fileURL?.deletingPathExtension().lastPathComponent ?? ""
  1928. let tFileName = (String(format: "%@_Extract Images", lastPathName))
  1929. let outputSavePanel = NSSavePanel()
  1930. outputSavePanel.title = NSLocalizedString("Save as PDF", comment: "")
  1931. outputSavePanel.allowsOtherFileTypes = true
  1932. outputSavePanel.isExtensionHidden = true
  1933. outputSavePanel.canCreateDirectories = true
  1934. outputSavePanel.nameFieldStringValue = tFileName
  1935. outputSavePanel.beginSheetModal(for: self.view.window!, completionHandler: { (result) in
  1936. if result == NSApplication.ModalResponse.OK {
  1937. DispatchQueue.main.async {
  1938. self.beginProgressSheet(withMessage: NSLocalizedString("Extracting all pictures...", comment: "") + "...", maxValue: 0)
  1939. let tDestFile = outputSavePanel.url!.path
  1940. let uniquePath = KMExtractImageWindowController.createDestFolder(path: tDestFile, isUnique: false)
  1941. let pdfconverter = PDFConvertObject()
  1942. pdfconverter.extractResourcesFromPDF(at: fileURL?.path ?? "", pdfPassword: document?.password, selectIndexSet: indeSet as IndexSet, destDocPath: uniquePath, moreOptions: nil)
  1943. self.dismissProgressSheet()
  1944. let fileManager = FileManager.default
  1945. if fileManager.fileExists(atPath: tDestFile) {
  1946. let workspace = NSWorkspace.shared
  1947. let url = URL(fileURLWithPath: tDestFile)
  1948. workspace.activateFileViewerSelecting([url])
  1949. }
  1950. }
  1951. }
  1952. })
  1953. return
  1954. }
  1955. if fileURL != nil {
  1956. self.myDocument?.save(nil)
  1957. } else {
  1958. let myDocument = self.myDocument
  1959. let str = String(format: "%@.pdf", myDocument?.displayName ?? "")
  1960. let writeSuccess = self.document!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1961. if writeSuccess {
  1962. var documentTemp = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  1963. fileURL = self.document?.documentURL
  1964. } else {
  1965. NSSound.beep()
  1966. return
  1967. }
  1968. }
  1969. let extract = KMExtractImageWindowController(windowNibName: "KMExtractImageWindowController")
  1970. extract.docPath = fileURL?.path ?? ""
  1971. extract.password = document?.password ?? ""
  1972. extract.currentPage = self.listView.currentPageIndex - 1
  1973. // extract.beginSheetModal(for: NSApp.mainWindow!, completionHandler: nil)
  1974. self.km_beginSheet(windowC: extract)
  1975. extract.selectCurrentPageBtn()
  1976. // self.showCreateStamp()
  1977. // self.showAddSignature()
  1978. }
  1979. //MARK: 创建文字图章示例实际上不会在这里使用
  1980. func showCreateStamp() {
  1981. let stampCreaterWindowController = KMStampCreaterWindowController()
  1982. stampCreaterWindowController.window?.backgroundColor = .clear
  1983. self.km_beginSheet(windowC: stampCreaterWindowController)
  1984. stampCreaterWindowController.closeCallBack = { result in
  1985. if result == 1 {
  1986. }
  1987. }
  1988. }
  1989. //MARK: 添加签名示例实际上不会在这里使用
  1990. func showAddSignature() {
  1991. var signatureWindowController = KMSignatureWindowController(windowNibName: "KMSignatureWindowController")//[[KMSignatureWindowController alloc] initWithWindowNibName:@"KMSignatureWindowController"];
  1992. // signatureWindowController.window?.backgroundColor = .clear
  1993. signatureWindowController.beginSheetModal(for: self.view.window) { signature in
  1994. }
  1995. }
  1996. func beginProgressSheet(withMessage message: String, maxValue: UInt) {
  1997. // if progressController == nil {
  1998. // progressController = SKProgressController(windowNibName: "ProgressSheet")
  1999. // }
  2000. let progress = SKProgressController()
  2001. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  2002. progress.window?.contentView?.wantsLayer = true
  2003. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  2004. progress.progressField.textColor = NSColor.white
  2005. progress.message = NSLocalizedString("Converting...", comment: "")
  2006. progressController = progress
  2007. progressController?.message = message
  2008. if maxValue > 0 {
  2009. progressController?.indeterminate = false
  2010. progressController?.maxValue = Double(maxValue)
  2011. } else {
  2012. progressController?.indeterminate = true
  2013. }
  2014. self.km_beginSheet(windowC: progressController!)
  2015. }
  2016. func dismissProgressSheet() {
  2017. progressController?.stopAnimation()
  2018. self.km_endSheet()
  2019. progressController = nil
  2020. }
  2021. func converFilesToPath(files: Array<KMBatchOperateFile>) -> [String] {
  2022. let newArr = NSMutableArray()
  2023. for item in files {
  2024. newArr.add(item.filePath)
  2025. }
  2026. return newArr as! [String]
  2027. }
  2028. internal func showPrintWindow(pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [])) {
  2029. if (self.listView.document != nil && !self.listView.document.allowsPrinting) { // 有打印限制
  2030. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result ,password in
  2031. if (result == .cancel) {
  2032. return
  2033. }
  2034. // 解除权限
  2035. self?.listView.document.unlock(withPassword: password)
  2036. // 隐藏提示
  2037. self?.hiddenSecureLimitTip()
  2038. // 去打印
  2039. if let data = self?.saveWatermarkFlag, !data {
  2040. KMPrintWindowController.openDocument(inputDocument: self!.listView?.document, inputPageRange: pageRange)
  2041. return
  2042. }
  2043. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self!.listView.document, secureOptions: self!.secureOptions, removePWD: self!.removeSecureFlag) {
  2044. _ = CPDFDocument(url: _url)
  2045. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self?.listView.document, inputPageRange: pageRange)
  2046. } else {
  2047. KMPrintWindowController.openDocument(inputDocument: self?.listView?.document, inputPageRange: pageRange)
  2048. }
  2049. }
  2050. return
  2051. }
  2052. if (!self.saveWatermarkFlag) {
  2053. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2054. return
  2055. }
  2056. if let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) {
  2057. let _document = CPDFDocument(url: _url)
  2058. KMPrintWindowController.showPrintWindowControll(inputData: _url, inputDocument: self.listView.document, inputPageRange: pageRange)
  2059. } else {
  2060. KMPrintWindowController.openDocument(inputDocument: self.listView?.document, inputPageRange: pageRange)
  2061. }
  2062. }
  2063. // MARK: - Split View
  2064. @IBAction func secondaryViewOpenFile(_ sender: NSButton) -> Void {
  2065. }
  2066. func singlePageScreen(isSinglePage: Bool, doublePagesScreen isHorizontal: Bool) -> Void {
  2067. if !isSinglePage && isHorizontal {
  2068. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 208)
  2069. }
  2070. if (!isSinglePage && !isHorizontal) {
  2071. self.openSecondaryPdfView?.changeBenefit(ofContrastLabelWidth: 300)
  2072. }
  2073. self.displaySinglePageScreen(isSinglePage: isSinglePage, doublePageScreen: isHorizontal)
  2074. }
  2075. func displaySinglePageScreen(isSinglePage: Bool, doublePageScreen isHorizontal: Bool) -> Void {
  2076. if isSinglePage {
  2077. pdfSplitView.dividerStyle = .thin
  2078. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  2079. } else {
  2080. pdfSplitView.dividerStyle = .paneSplitter
  2081. pdfSplitView.isVertical = !isHorizontal
  2082. pdfSplitView.setPosition(500, ofDividerAt: 0, animate: true)
  2083. if secondaryPdfView.document != nil {
  2084. // secondaryPdfView.frame = pdfSplitSecondView.frame
  2085. // pdfSplitSecondView.contentView = secondaryPdfView
  2086. } else {
  2087. openSecondaryPdfView = KMSecondaryViewController.init()
  2088. openSecondaryPdfView?.view.frame = pdfSplitSecondView.frame
  2089. pdfSplitSecondView.contentView = openSecondaryPdfView?.view
  2090. openSecondaryPdfView?.delegate = self
  2091. }
  2092. }
  2093. }
  2094. func lastSplitPDFHeightFloat(_ rect: NSRect) -> Float {
  2095. if (pdfSplitView.isVertical) {
  2096. return Float(NSWidth(rect))
  2097. } else {
  2098. return Float(NSHeight(rect))
  2099. }
  2100. }
  2101. func displaySecondaryPDFView(withUrl url: URL) -> Bool {
  2102. let document = CPDFDocument.init(url: url)
  2103. if document != nil {
  2104. secondaryPdfView.frame = pdfSplitSecondView.frame
  2105. pdfSplitSecondView.contentView = secondaryPdfView
  2106. secondaryPdfView.document = nil
  2107. secondaryPdfView.document = document
  2108. return true
  2109. } else {
  2110. return false
  2111. }
  2112. }
  2113. func updateNextAndPreViousButtonState() {
  2114. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2115. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2116. if self.listView.canGoToNextPage() {
  2117. item?.unEnabled = false
  2118. } else {
  2119. item?.unEnabled = true
  2120. }
  2121. if self.listView.canGoToPreviousPage() {
  2122. toItem?.unEnabled = false
  2123. } else {
  2124. toItem?.unEnabled = true
  2125. }
  2126. }
  2127. func updateBackAndForwardButtonState() {
  2128. let item = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentNextPageToolbarItemIdentifier)
  2129. let toItem = self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPreviousPageToolbarItemIdentifier)
  2130. if self.listView.km_canGoBack() {
  2131. item?.unEnabled = false
  2132. } else {
  2133. item?.unEnabled = true
  2134. }
  2135. if self.listView.km_canGoForward() {
  2136. toItem?.unEnabled = false
  2137. } else {
  2138. toItem?.unEnabled = true
  2139. }
  2140. }
  2141. func updateZoomInOutButtonState() {
  2142. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomOutToolbarItemIdentifier)) ?? KMToolbarItemView()
  2143. let toItem : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentZoomToolbarItemIdentifier)) ?? KMToolbarItemView()
  2144. if self.listView.canZoomIn {
  2145. item.unEnabled = false
  2146. } else {
  2147. item.unEnabled = true
  2148. }
  2149. if self.listView.canZoomOut {
  2150. toItem.unEnabled = false
  2151. } else {
  2152. toItem.unEnabled = true
  2153. }
  2154. }
  2155. }
  2156. // MARK: -
  2157. // MARK: - KMSecondaryViewControllerDelegate
  2158. extension KMMainViewController: KMSecondaryViewControllerDelegate {
  2159. func receivedFileUrl(_ url: URL!) {
  2160. let state = self.displaySecondaryPDFView(withUrl: url)
  2161. if !state {
  2162. let alert = NSAlert()
  2163. alert.alertStyle = .critical
  2164. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2165. alert.runModal()
  2166. return
  2167. }
  2168. }
  2169. }
  2170. // MARK: -
  2171. // MARK: - KMMainToolbarControllerDelegate
  2172. extension KMMainViewController : KMMainToolbarControllerDelegate {
  2173. func changeModelAction(mode: CToolMode) {
  2174. self.listView.toolMode = mode
  2175. if mode == .editPDFToolMode {
  2176. self.childToolbarController.updateType(newType: .editPDF)
  2177. }
  2178. }
  2179. func toolbarViewController(_ viewController:KMToolbarViewController, zoomModel selectedTag:Int) {
  2180. switch selectedTag {
  2181. case 2:
  2182. if self.listView.scaleFactor != 1.0 {
  2183. self.listView.scaleFactor = 1.0
  2184. self.listView.autoScales = false
  2185. }
  2186. break
  2187. case 1:
  2188. let pageHeight = self.listView.currentPage()!.size.height
  2189. let pdfviewHeight = self.listView.bounds.size.height
  2190. self.listView.scaleFactor = pdfviewHeight/pageHeight
  2191. self.listView.autoScales = false
  2192. break
  2193. case 0:
  2194. // self.listView.autoScales = !self.listView.autoScales
  2195. self.listView.autoScales = true
  2196. break
  2197. case 3:
  2198. self.listView.scaleFactor = 0.1
  2199. break
  2200. case 4:
  2201. self.listView.scaleFactor = 0.25
  2202. break
  2203. case 5:
  2204. self.listView.scaleFactor = 0.5
  2205. break
  2206. case 6:
  2207. self.listView.scaleFactor = 0.75
  2208. break
  2209. case 7:
  2210. self.listView.scaleFactor = 1.0
  2211. break
  2212. case 8:
  2213. self.listView.scaleFactor = 1.5
  2214. break
  2215. case 9:
  2216. self.listView.scaleFactor = 2.0
  2217. break
  2218. case 10:
  2219. self.listView.scaleFactor = 4.0
  2220. break
  2221. case 11:
  2222. self.listView.scaleFactor = 8.0
  2223. break
  2224. case 12:
  2225. self.listView.scaleFactor = 10.0
  2226. break
  2227. default:
  2228. break
  2229. }
  2230. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2231. }
  2232. func toolbarViewController(_ viewController: KMToolbarViewController, zoomSting: String) {
  2233. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2234. if scale > 100 {
  2235. scale = 100
  2236. }
  2237. if (scale <= 0.101) {
  2238. self.listView.scaleFactor = self.listView.minScaleFactor()
  2239. } else {
  2240. self.listView.scaleFactor = scale
  2241. }
  2242. viewController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  2243. DispatchQueue.main.async {
  2244. self.updateZoomInOutButtonState()
  2245. }
  2246. }
  2247. func changePDFViewZoomInAction() {
  2248. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2249. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2250. switch scale {
  2251. case 0...0.25:
  2252. scale += 0.25
  2253. case 0.25...3:
  2254. scale += 0.25
  2255. case 3.1...10:
  2256. scale += 0.4
  2257. case 10.1...100:
  2258. scale += 1
  2259. default:
  2260. scale += 1
  2261. }
  2262. self.listView.scaleFactor = scale
  2263. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2264. // self.listView.zoomIn(nil)
  2265. }
  2266. func changePDFViewZoomOutAction() {
  2267. let zoomSting = self.toolbarController.mainToolBarView?.zoomTextField.stringValue ?? "10"
  2268. var scale = CGFloat((NSString(string: zoomSting)).floatValue / 100.0)
  2269. switch scale {
  2270. case 0...0.25:
  2271. scale = 0
  2272. case 0.25...3:
  2273. scale -= 0.25
  2274. case 3.1...10:
  2275. scale -= 0.4
  2276. case 10.1...100:
  2277. scale -= 1
  2278. default:
  2279. scale -= 1
  2280. }
  2281. self.listView.scaleFactor = scale
  2282. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(nearbyint(self.listView.scaleFactor*100))%"
  2283. // self.listView.zoomOut(nil)
  2284. // self.updateZoomInOutButtonState()
  2285. }
  2286. func changePDFViewGotoNextPageAction() {
  2287. self.listView.km_goBack(nil)
  2288. if (self.listView.canGoToNextPage()) {
  2289. self.listView.goToNextPage(nil)
  2290. }
  2291. self.updateNextAndPreViousButtonState()
  2292. }
  2293. func changePDFViewGoToPreviousPageAction() {
  2294. if (self.listView.canGoToPreviousPage()) {
  2295. self.listView.goToPreviousPage(nil)
  2296. }
  2297. self.updateNextAndPreViousButtonState()
  2298. }
  2299. func changePDFViewGotoBackAction() {
  2300. self.listView.km_goBack(nil)
  2301. self.updateBackAndForwardButtonState()
  2302. }
  2303. func changePDFViewGoToForwardAction() {
  2304. self.listView.km_goForward(nil)
  2305. self.updateBackAndForwardButtonState()
  2306. }
  2307. func aiTranslationPDFFileAction() {
  2308. #if VERSION_DMG
  2309. #else
  2310. if !KMLightMemberManager.manager.isLogin() && NSApp.mainWindow != nil {
  2311. KMLoginWindowController.show(window: NSApp.mainWindow!)
  2312. return
  2313. }
  2314. #endif
  2315. self.trackEvent_aiTranslate()
  2316. self._aiTranslationPDFFileAction()
  2317. // Task { @MainActor in
  2318. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2319. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  2320. // if (isClose) {
  2321. // return
  2322. // }
  2323. // if (isSub) {
  2324. // self._aiTranslationPDFFileAction()
  2325. // return
  2326. // }
  2327. // }
  2328. // return
  2329. // }
  2330. //
  2331. // self._aiTranslationPDFFileAction()
  2332. // }
  2333. }
  2334. private func _aiTranslationPDFFileAction() {
  2335. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: (self.document?.documentURL.path)!)
  2336. if self.isFileGreaterThan10MB(atPath: (self.document?.documentURL.path)!) {
  2337. let alert = NSAlert()
  2338. alert.alertStyle = .critical
  2339. alert.messageText = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  2340. alert.runModal()
  2341. return
  2342. } else if isExceedsLimit {
  2343. let alert = NSAlert()
  2344. alert.alertStyle = .critical
  2345. alert.messageText = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  2346. alert.runModal()
  2347. return
  2348. }
  2349. let alert = NSAlert()
  2350. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  2351. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  2352. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2353. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  2354. if (result == .alertFirstButtonReturn) {
  2355. self.aiTranslationConfirWC = KMAITranslationConfirmWindowController.init(windowNibName: NSNib.Name("KMAITranslationConfirmWindowController"))
  2356. self.aiTranslationConfirWC!.filePath = (self.document?.documentURL.path)!
  2357. self.view.window?.beginSheet(self.aiTranslationConfirWC!.window!)
  2358. } else if result == .alertSecondButtonReturn {
  2359. return
  2360. }
  2361. }
  2362. }
  2363. func toolbarViewController(_ viewController: KMToolbarViewController, shareAction toolbarItem: KMToolbarItemView) {
  2364. self.trackEvent_share()
  2365. }
  2366. func toolbarViewController(_ viewController: KMToolbarViewController, shareDocument item: NSMenuItem) {
  2367. if (!self.saveWatermarkFlag) {
  2368. self.shareDocument(sender: viewController)
  2369. return
  2370. }
  2371. Task { @MainActor in
  2372. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2373. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2374. if (isClose) {
  2375. return
  2376. }
  2377. if (isSubscribeSuccess) {
  2378. self.shareDocument(sender: viewController)
  2379. return
  2380. }
  2381. if (isWaterMarkExport) {
  2382. self.shareDocument(sender: viewController, limit: true)
  2383. return
  2384. }
  2385. }
  2386. return
  2387. }
  2388. self.shareDocument(sender: viewController)
  2389. }
  2390. }
  2391. func toolbarViewController(_ viewController: KMToolbarViewController, shareFlatten item: NSMenuItem) {
  2392. // if (!self.saveWatermarkFlag) {
  2393. // self.shareFlatten(sender: viewController)
  2394. // return
  2395. // }
  2396. Task { @MainActor in
  2397. #if VERSION_DMG
  2398. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2399. let _ = KMComparativeTableViewController.show(window: self.view.window!, .shareFlatten)
  2400. return
  2401. }
  2402. #endif
  2403. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2404. KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2405. if (isClose) {
  2406. return
  2407. }
  2408. if (isSubscribeSuccess) {
  2409. self.shareFlatten(sender: viewController)
  2410. return
  2411. }
  2412. if (isWaterMarkExport) {
  2413. self.shareFlatten(sender: viewController, limit: true)
  2414. return
  2415. }
  2416. }
  2417. return
  2418. }
  2419. self.shareFlatten(sender: viewController)
  2420. }
  2421. }
  2422. func toolbarViewController(_ viewController: KMToolbarViewController, shareOriginalPDF item: NSMenuItem) {
  2423. if (!self.saveWatermarkFlag) {
  2424. self.shareOriginalPDF(sender: viewController)
  2425. return
  2426. }
  2427. Task { @MainActor in
  2428. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2429. let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true) { isSubscribeSuccess, isWaterMarkExport, isClose in
  2430. if (isClose) {
  2431. return
  2432. }
  2433. if (isSubscribeSuccess) {
  2434. self.shareOriginalPDF(sender: viewController)
  2435. return
  2436. }
  2437. if (isWaterMarkExport) {
  2438. self.shareOriginalPDF(sender: viewController, limit: true)
  2439. return
  2440. }
  2441. }
  2442. return
  2443. }
  2444. self.shareOriginalPDF(sender: viewController)
  2445. }
  2446. }
  2447. func toolbarViewController(_ viewController: KMToolbarViewController, scanOCRModel selectedTag: Int) {
  2448. if(0 == selectedTag) {
  2449. // self.documentAIViewController?.enteredIncreaseAllPage()
  2450. // self.documentAIViewController?.updateToolState(false)
  2451. } else {
  2452. // self.documentAIViewController?.recognitionPageString("1", with: .english)
  2453. // self.documentAIViewController?.recognitionPartModel(with: .english)
  2454. // self.documentAIViewController?.updateToolState(true)
  2455. }
  2456. // 0 : Scan 1:OCR Text
  2457. }
  2458. func mainToolDidClicked(_ toolController: KMToolbarController, _ beforeType: KMToolbarViewType, _ type: KMToolbarViewType, _ item: KMToolbarItemView , _ pages: [Int]) {
  2459. if beforeType == .editPDF {
  2460. // self.asyncSaveDocument { params in
  2461. //
  2462. // }
  2463. }
  2464. // 埋点
  2465. self.trackEvent(toolType: type)
  2466. if(type != .Page) {
  2467. if (hasEnterPageEdit()) {
  2468. self.exitPageEdit()
  2469. }
  2470. }
  2471. if(type != .ScanOCR) {
  2472. // if ((self.documentAIViewController?.view.superview) != nil) {
  2473. // self.listView.isHidden = false
  2474. // self.documentAIViewController?.creatRecognitionDocument()
  2475. // self.documentAIViewController?.view .removeFromSuperview()
  2476. // self.documentAIViewController = nil;
  2477. // self.listView.layoutDocumentView()
  2478. // }
  2479. }
  2480. if (type == .Page) {
  2481. if (hasEnterPageEdit()) {
  2482. self.exitPageEdit()
  2483. } else {
  2484. self.enterPageEdit(pages)
  2485. }
  2486. } else if(type == .ScanOCR) {
  2487. // if((self.documentAIViewController?.view.superview) != nil) {
  2488. // let alert = NSAlert()
  2489. // alert.messageText = NSLocalizedString("If you need to edit again after exit, you need to re-execute OCR recognition, sure you want to exit?", comment: "")
  2490. // alert.addButton(withTitle: "YES")
  2491. // alert.addButton(withTitle: "NO")
  2492. // let result = alert.runModal()
  2493. // if (result == .alertFirstButtonReturn) { /// 取消
  2494. // self.listView.isHidden = false
  2495. // self.documentAIViewController?.creatRecognitionDocument()
  2496. // self.documentAIViewController?.view .removeFromSuperview()
  2497. // self.documentAIViewController = nil;
  2498. // self.listView.layoutDocumentView()
  2499. // } else {
  2500. // self.toolbarController.toolbarType = .ScanOCR
  2501. // }
  2502. // } else {
  2503. // self.documentAIViewController = KMDocumentAIViewController(pdfView: self.listView)
  2504. // self.PDFContendView.addSubview(self.documentAIViewController?.view ?? KMDocumentAIViewController().view);
  2505. // self.documentAIViewController?.view.frame = self.PDFContendView.bounds
  2506. // self.documentAIViewController?.view.autoresizingMask = NSView.AutoresizingMask([.width,.height])
  2507. // self.listView.isHidden = true //不影藏的话会出现鼠标事件的崩溃
  2508. // }
  2509. } else if type == .editPDF {
  2510. self.listView.annotationType = .editTextImage
  2511. } else if type == .Annatiton {
  2512. self.rightSideViewController.subViewType = .AnnotationProperts
  2513. }
  2514. }
  2515. func clickChildTool(type: KMToolbarType, index: Int) {
  2516. if (type == .secure) {
  2517. if (index == 1) {
  2518. self.trackEvent_setPassword()
  2519. } else if (index == 2) {
  2520. self.trackEvent_removePassword()
  2521. }
  2522. } else {
  2523. self.trackEvent(toolBarType: type)
  2524. }
  2525. Task { @MainActor in
  2526. if (type == .compress) { /// 压缩
  2527. // #if VERSION_DMG
  2528. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2529. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .compress)
  2530. // self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2531. // return
  2532. // }
  2533. // #endif
  2534. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2535. // self.view.window?.contentView?.superview?.beginLoading()
  2536. let document = self.listView.document
  2537. let secureOptions = self.secureOptions
  2538. let removeSecureFlag = self.removeSecureFlag
  2539. // DispatchQueue.global().async { [unowned self] in
  2540. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: document!, secureOptions: secureOptions, removePWD: removeSecureFlag) else {
  2541. // DispatchQueue.main.async {
  2542. // self.view.window?.contentView?.superview?.endLoading()
  2543. // }
  2544. return
  2545. }
  2546. // DispatchQueue.main.async {
  2547. // self.view.window?.contentView?.superview?.endLoading()
  2548. self.showCompressWindow(url: _url)
  2549. // }
  2550. // }
  2551. return
  2552. }
  2553. if (self.needSaveDocument()) {
  2554. self.saveDocumentWithProgressAlert { [unowned self] params in
  2555. self.showCompressWindow()
  2556. }
  2557. return
  2558. }
  2559. self.showCompressWindow()
  2560. return
  2561. }
  2562. if ((KMToolbarType.word.rawValue ... KMToolbarType.conversion_image.rawValue).contains(type.rawValue)) { /// 转档
  2563. var identifier: String?
  2564. if (type == .word) { /// Word
  2565. identifier = KMToolbarConversionWordItemIdentifier
  2566. } else if (type == .excel) {
  2567. identifier = KMToolbarConversionExcelItemIdentifier
  2568. } else if (type == .ppt) {
  2569. identifier = KMToolbarConversionPPTItemIdentifier
  2570. } else if (type == .rtf) {
  2571. identifier = KMToolbarConversionRTFItemIdentifier
  2572. } else if (type == .html) {
  2573. identifier = KMToolbarConversionHTMLItemIdentifier
  2574. } else if (type == .conversion_text) {
  2575. identifier = KMToolbarConversionTextItemIdentifier
  2576. } else if (type == .csv) {
  2577. identifier = KMToolbarConversionCSVItemIdentifier
  2578. } else if (type == .conversion_image) {
  2579. identifier = KMToolbarConversionImageItemIdentifier
  2580. }
  2581. #if VERSION_DMG
  2582. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2583. // if (identifier != nil) {
  2584. // self.toolbarController.cancelSelected(identifier!)
  2585. // }
  2586. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .convert)
  2587. // return
  2588. // }
  2589. #endif
  2590. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2591. // guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2592. // return
  2593. // }
  2594. // self.showConvertWindow(type: type, documentUrl: _url, identifier: identifier)
  2595. // return
  2596. // }
  2597. if (self.needSaveDocument()) {
  2598. self.saveDocumentWithProgressAlert { [unowned self] params in
  2599. self.showConvertWindow(type: type, identifier: identifier)
  2600. }
  2601. return
  2602. }
  2603. self.showConvertWindow(type: type, identifier: identifier)
  2604. return
  2605. }
  2606. if (type == .merge) { /// 合并
  2607. // #if VERSION_DMG
  2608. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2609. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  2610. //
  2611. // self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  2612. // return
  2613. // }
  2614. // #endif
  2615. if (self.listView.document.allowsCopying == false || self.listView.document.allowsPrinting == false) {
  2616. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2617. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2618. if (result == .cancel) {
  2619. return
  2620. }
  2621. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2622. return
  2623. }
  2624. self.showMergeWindow(url: _url, password)
  2625. }
  2626. return
  2627. }
  2628. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [unowned self] result , password in
  2629. if (result == .cancel) {
  2630. return
  2631. }
  2632. if (self.needSaveDocument()) {
  2633. self.saveDocumentWithProgressAlert { [unowned self] params in
  2634. self.showMergeWindow(password)
  2635. }
  2636. return
  2637. }
  2638. self.showMergeWindow(password)
  2639. }
  2640. return
  2641. }
  2642. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  2643. guard let _url = KMTools.saveWatermarkDocumentToTemp(document: self.listView.document, secureOptions: self.secureOptions, removePWD: self.removeSecureFlag) else {
  2644. return
  2645. }
  2646. self.showMergeWindow(url: _url, password)
  2647. return
  2648. }
  2649. if (self.needSaveDocument()) {
  2650. self.saveDocumentWithProgressAlert { [unowned self] params in
  2651. self.showMergeWindow(self.listView.document.password)
  2652. }
  2653. return
  2654. }
  2655. self.showMergeWindow(self.listView.document.password)
  2656. return
  2657. }
  2658. if (type == .crop) {
  2659. #if VERSION_DMG
  2660. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2661. let _ = KMComparativeTableViewController.show(window: self.view.window!, .crop)
  2662. return
  2663. }
  2664. #endif
  2665. self.recordSaveWatermarkFlag(type: .crop)
  2666. if (index == 1) {
  2667. self.cropCurrentPage()
  2668. return
  2669. }
  2670. if (index == 2) {
  2671. self.cropAllPage()
  2672. return
  2673. }
  2674. //// 自定义裁剪区域
  2675. // self.cropCustomArea()
  2676. } else if (type == .bates || type == .headerAndFooter) {
  2677. if (index == 0) {
  2678. var controller: KMWatermarkAdjectivePreViewBaseController!
  2679. if (type == .bates) {
  2680. controller = KMBatesPreviewController()
  2681. } else if (type == .headerAndFooter) {
  2682. controller = KMHeaderFooterPreviewController()
  2683. } else if (type == .background) {
  2684. controller = KMBackgroundController()
  2685. } else if (type == .watermark) {
  2686. controller = KMWatermarkViewController()
  2687. }
  2688. controller.applyDocument = self.listView.document
  2689. controller.view.frame = self.view.bounds
  2690. controller.view.autoresizingMask = [.width, .height]
  2691. controller.documentURL = self.listView.document.documentURL
  2692. self.view.addSubview(controller.view)
  2693. self.addChild(controller)
  2694. controller.itemClick = { [weak self] index, param in
  2695. if (index == 0 || index == 1) { /// 取消 和 应用
  2696. var controller_watermarkAdjective_preView: KMWatermarkAdjectivePreViewBaseController?
  2697. for i in 0 ..< self!.children.count {
  2698. let vc: NSViewController = self!.children[self!.children.count-1-i]
  2699. if (vc.isKind(of: KMWatermarkAdjectivePreViewBaseController.self) == true) {
  2700. controller_watermarkAdjective_preView = vc as! KMWatermarkAdjectivePreViewBaseController
  2701. break
  2702. }
  2703. }
  2704. if (controller_watermarkAdjective_preView == nil) {
  2705. return
  2706. }
  2707. controller_watermarkAdjective_preView!.view.removeFromSuperview()
  2708. controller_watermarkAdjective_preView?.removeFromParent()
  2709. // if (index == 1) {
  2710. self?.listView.document = CPDFDocument(url: self?.listView.document.documentURL)
  2711. self?.listView.layoutDocumentView()
  2712. self?.listView.setNeedsDisplayForVisiblePages()
  2713. // }
  2714. return
  2715. }
  2716. }
  2717. return
  2718. }
  2719. if (index == 1) { /// 取消
  2720. self.toolbarController.exitWatermarkAdjective()
  2721. // self.rightSideViewController.view.isHidden = true
  2722. self.rightSideViewController.isHidden = true
  2723. self.rightSideViewController.subViewType = .None
  2724. self.closeRightPane()
  2725. return
  2726. }
  2727. if (index == 5) { /// 批量
  2728. return
  2729. }
  2730. if (index == 4) { //// 移除
  2731. if (type == .watermark) {
  2732. let watermarks = self.listView.document.watermarks()
  2733. if (watermarks == nil || watermarks!.count <= 0) {
  2734. let alert = NSAlert()
  2735. alert.alertStyle = .warning
  2736. alert.messageText = NSLocalizedString("无法在本文件中找到可删除的水印。如果您看到水印,其不是使用PDF Master添加的,因此无法被检测到。", comment: "")
  2737. alert.addButton(withTitle: NSLocalizedString("确认", comment: ""))
  2738. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2739. alert.runModal()
  2740. return
  2741. }
  2742. let alert = NSAlert()
  2743. alert.alertStyle = .warning
  2744. alert.messageText = NSLocalizedString("确定要删除文件水印吗?", comment: "")
  2745. alert.addButton(withTitle: NSLocalizedString("删除", comment: ""))
  2746. alert.addButton(withTitle: NSLocalizedString("取消", comment: ""))
  2747. let result = alert.runModal()
  2748. if (result != .alertFirstButtonReturn) {
  2749. return
  2750. }
  2751. }
  2752. let oType: KMWatermarkAdjectiveType = KMWatermarkAdjectiveTools.KMWatermarkAdjectiveType(from: type)
  2753. KMWatermarkAdjectiveTools.delete(oType, self.listView, self.listView.document.documentURL.path) {
  2754. result in
  2755. DispatchQueue.main.async {
  2756. self.listView.layoutDocumentView()
  2757. self.listView.setNeedsDisplayForVisiblePages()
  2758. }
  2759. if (result) {
  2760. let alert = NSAlert()
  2761. alert.alertStyle = .warning
  2762. alert.messageText = "成功"
  2763. alert.runModal()
  2764. } else {
  2765. let alert = NSAlert()
  2766. alert.alertStyle = .critical
  2767. alert.messageText = "失败"
  2768. alert.runModal()
  2769. }
  2770. }
  2771. return
  2772. }
  2773. if (index == 2) { /// 应用
  2774. let model = self.rightSideViewController.model
  2775. if (type == .bates || type == .headerAndFooter) {
  2776. if (model == nil || (model?.isKind(of: KMBatesModel.self) == false)) {
  2777. let alert = NSAlert()
  2778. alert.alertStyle = .critical
  2779. alert.messageText = "没有找到模型"
  2780. alert.runModal()
  2781. return
  2782. }
  2783. if ((model as! KMBatesModel).hasVaild == false) {
  2784. let alert = NSAlert()
  2785. alert.alertStyle = .critical
  2786. alert.messageText = "没有找到内容"
  2787. alert.runModal()
  2788. return
  2789. }
  2790. }
  2791. KMWatermarkAdjectiveTools.apply(model!, self.listView, self.listView.document.documentURL.path) {
  2792. result in
  2793. DispatchQueue.main.async {
  2794. self.listView.layoutDocumentView()
  2795. self.listView.setNeedsDisplayForVisiblePages()
  2796. }
  2797. if (result) {
  2798. let alert = NSAlert()
  2799. alert.alertStyle = .warning
  2800. alert.messageText = "成功"
  2801. alert.runModal()
  2802. } else {
  2803. let alert = NSAlert()
  2804. alert.alertStyle = .critical
  2805. alert.messageText = "失败"
  2806. alert.runModal()
  2807. }
  2808. }
  2809. return
  2810. }
  2811. /// 新增
  2812. // self.rightSideViewController.view.isHidden = false
  2813. self.rightSideViewController.isHidden = false
  2814. self.rightSideViewController.subViewType = KMWatermarkAdjectiveTools.KMToolBarTypeToRightSubViewType(type)
  2815. self.openRightPane()
  2816. } else if (type == .redact) { /// 标记密文
  2817. if (index == 1) { /// 取消
  2818. if (self.hasAddRedact) {
  2819. let alert = NSAlert()
  2820. 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: "")
  2821. alert.addButton(withTitle: NSLocalizedString("Don’t Save", comment: ""))
  2822. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  2823. let result = alert.runModal()
  2824. if (result == .alertFirstButtonReturn) {
  2825. self.listView.toolMode = .moveToolMode
  2826. self.toolbarController.exitRedact()
  2827. }
  2828. return
  2829. }
  2830. self.listView.toolMode = .moveToolMode
  2831. self.toolbarController.exitRedact()
  2832. return
  2833. }
  2834. if (index == 2) { /// 擦除
  2835. self.exeRedactConfirm(.eraserAll) {}
  2836. return
  2837. }
  2838. if (index == 3) { /// 应用
  2839. self.exeRedactConfirm(.redactAll) {}
  2840. return
  2841. }
  2842. if (index == 4) { /// 文本&图像
  2843. self.listView.toolMode = .redactToolMode
  2844. return
  2845. }
  2846. if (index == 5) { /// 页面
  2847. let windowController = KMRedactPageRangeWindowController(windowNibName: "KMRedactBaseWindowController")
  2848. await self.view.window?.beginSheet(windowController.window!)
  2849. self.currentWindowController = windowController
  2850. windowController.itemClick = { [weak self] index, value in
  2851. if (index == 1) {
  2852. let topBarView = self?.toolbarController.fetchTopBarView()
  2853. if (topBarView == nil || topBarView?.isKind(of: KMRedactTopToolBar.self) == false) {
  2854. return
  2855. }
  2856. (topBarView as! KMRedactTopToolBar).selectItem(0)
  2857. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  2858. self?.currentWindowController = nil
  2859. return
  2860. }
  2861. let windowController_pageRange = self?.currentWindowController as! KMRedactPageRangeWindowController
  2862. let pageType = windowController_pageRange.pageType
  2863. let pageString = windowController_pageRange.pageString
  2864. if (pageType == 5) { /// 自定义页面
  2865. let array = KMPageRangeTools.findSelectPage(pageRangeString: pageString, pageCount: Int((self?.listView.document.pageCount)!))
  2866. if (array.count == 0) {
  2867. let alert = NSAlert()
  2868. alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
  2869. alert.runModal()
  2870. return
  2871. }
  2872. }
  2873. self!.view.window?.endSheet(self!.currentWindowController.window!)
  2874. self!.currentWindowController = nil
  2875. var indexs: IndexSet = []
  2876. if (pageType == 1) { /// 当前页面
  2877. indexs.insert((self?.listView.currentPageIndex)!)
  2878. } else {
  2879. indexs = KMRedactTools.getPageIndexs(pageType-1, string: pageString, Int((self?.listView.document.pageCount)!))
  2880. }
  2881. if (indexs.count == 0) {
  2882. return
  2883. }
  2884. for i in indexs {
  2885. let page: CPDFPage = (self?.listView.document.page(at: UInt(i)))!
  2886. let redactAnno = CPDFRedactAnnotation(PDFListViewNoteWith: (self?.listView.document)!)
  2887. redactAnno.bounds = page.bounds
  2888. self?.listView.add(redactAnno, to: page)
  2889. }
  2890. }
  2891. return
  2892. }
  2893. } else if (type == .secure) { /// 安全
  2894. #if VERSION_DMG
  2895. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  2896. let _ = KMComparativeTableViewController.show(window: self.view.window!, .secure)
  2897. return
  2898. }
  2899. #endif
  2900. if (index == 1) { /// 设置密码
  2901. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2902. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  2903. if (result == .cancel) {
  2904. return
  2905. }
  2906. self?.isSaveKeyChain = false
  2907. self?.listView.document.unlock(withPassword: password)
  2908. self?.hiddenSecureLimitTip()
  2909. self?.showSecureWindow((self?.listView.document.documentURL)!)
  2910. }
  2911. return
  2912. }
  2913. self.showSecureWindow(self.listView.document.documentURL)
  2914. return
  2915. } else if index == 2 {
  2916. let controller = KMRemovePasswordWindowController(windowNibName: "KMRemovePasswordWindowController")
  2917. self.currentWindowController = controller
  2918. controller.batchAction = { [unowned self] controller, files in
  2919. self.view.window?.endSheet((self.currentWindowController.window)!)
  2920. self.currentWindowController = nil
  2921. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  2922. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  2923. batchWindowController.window?.makeKeyAndOrderFront("")
  2924. let batchOperateFile = KMBatchOperateFile(filePath: files.first?.filePath ?? "")
  2925. batchWindowController.switchToOperateType(.RemovePassword, files: [batchOperateFile])
  2926. batchWindowController.window?.makeKeyAndOrderFront("")
  2927. }
  2928. controller.cancelAction = { [unowned self] controller in
  2929. self.view.window?.endSheet((self.currentWindowController.window)!)
  2930. self.currentWindowController = nil
  2931. }
  2932. controller.doneAction = { [unowned self] controller in
  2933. self.view.window?.endSheet((self.currentWindowController.window)!)
  2934. self.currentWindowController = nil
  2935. KMBaseWindowController.checkPassword(url: self.document!.documentURL!) { [unowned self] success, resultPassword in
  2936. if success {
  2937. /// 删除安全性设置
  2938. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  2939. self.isSaveKeyChain = false
  2940. self.listView.document.unlock(withPassword: password)
  2941. self.hiddenSecureLimitTip()
  2942. self.recordRemoveSecureFlag()
  2943. self.recordSaveWatermarkFlag(type: .removePassword)
  2944. let tip = KMRemovePasswordResultTipView()
  2945. tip.result = .success
  2946. tip.showInView(superView: (self.listView.superview)!)
  2947. } else {
  2948. self.recordRemoveSecureFlag()
  2949. self.recordSaveWatermarkFlag(type: .removePassword)
  2950. let tip = KMRemovePasswordResultTipView()
  2951. tip.result = .success
  2952. self.hiddenSecureLimitTip()
  2953. tip.showInView(superView: self.listView.superview!)
  2954. }
  2955. }
  2956. }
  2957. }
  2958. await NSWindow.currentWindow().beginSheet(controller.window!)
  2959. return
  2960. }
  2961. } else if type == .comparison {
  2962. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  2963. self.currentWindowController = controller
  2964. controller.filePath = (self.document?.documentURL.path)!
  2965. controller.cancelAction = { [unowned self] controller in
  2966. self.view.window?.endSheet((self.currentWindowController.window)!)
  2967. self.currentWindowController = nil
  2968. }
  2969. controller.contentComplete = { [unowned self] controller, result, oldDocument, document in
  2970. self.openContentCompareVC(with: controller.pdfCompareContent!, results: result, oldDocument: oldDocument, document: document)
  2971. }
  2972. controller.coveringComplete = { [unowned self] controller, document in
  2973. self.openCoveringCompareVC(with: document)
  2974. }
  2975. if index == 1 {
  2976. controller.fileType = .content
  2977. } else {
  2978. controller.fileType = .coverting
  2979. }
  2980. await NSWindow.currentWindow().beginSheet(controller.window!)
  2981. } else if type == .watermark {
  2982. let controller = KMWatermarkWindowController(windowNibName: "KMWatermarkWindowController")
  2983. self.currentWindowController = controller
  2984. controller.pdfDocument = self.document
  2985. controller.cancelAction = { [unowned self] controller in
  2986. self.view.window?.endSheet((self.currentWindowController.window)!)
  2987. self.currentWindowController = nil
  2988. }
  2989. if index == 1 {
  2990. } else {
  2991. }
  2992. await NSWindow.currentWindow().beginSheet(controller.window!)
  2993. } else if type == .background {
  2994. let controller = KMBackgroundWindowController(windowNibName: "KMBackgroundWindowController")
  2995. self.currentWindowController = controller
  2996. controller.pdfDocument = self.document
  2997. controller.cancelAction = { [unowned self] controller in
  2998. self.view.window?.endSheet((self.currentWindowController.window)!)
  2999. self.currentWindowController = nil
  3000. }
  3001. if index == 1 {
  3002. } else {
  3003. }
  3004. await NSWindow.currentWindow().beginSheet(controller.window!)
  3005. }
  3006. }
  3007. }
  3008. func toolbarViewController(_ viewController: KMToolbarViewController, itemDidClick toolbarItem: KMToolbarItemView) {
  3009. if let itemID = toolbarItem.itemIdentifier {
  3010. if isMainToolItem(itemID) {
  3011. if toolbarItem.itemIdentifier == KMDocumentHomeToolbarItemIdentifier {
  3012. Swift.debugPrint("KMDocumentHomeToolbarItemIdentifier ...")
  3013. } else if toolbarItem.itemIdentifier == KMDocumentPreviousPageToolbarItemIdentifier {
  3014. self.changePDFViewGoToPreviousPageAction()
  3015. } else if toolbarItem.itemIdentifier == KMDocumentNextPageToolbarItemIdentifier {
  3016. self.changePDFViewGotoNextPageAction()
  3017. } else if toolbarItem.itemIdentifier == KMDocumentViewDisplayToolbarItemIdentifier {
  3018. Swift.debugPrint("KMDocumentViewDisplayToolbarItemIdentifier ...")
  3019. } else if toolbarItem.itemIdentifier == KMLeftControlToolbarItemIdentifier {
  3020. toolbarItem.isSelected = !toolbarItem.isSelected
  3021. self.toggleLeftPane()
  3022. self.leftSideViewController.showPanelView(show: toolbarItem.isSelected)
  3023. } else if toolbarItem.itemIdentifier == KMRightControlToolbarItemIdentifier {
  3024. toolbarItem.isSelected = !toolbarItem.isSelected
  3025. self.toggleRightPane()
  3026. } else if itemID == KMDocumentRedactToolbarItemIdentifier {
  3027. Swift.debugPrint("KMDocumentRedactToolbarItemIdentifier ...")
  3028. } else if itemID == KMDocumentScanOCRToolbarItemIdentifier {
  3029. Swift.debugPrint("KMDocumentScanOCRToolbarItemIdentifier ...")
  3030. showOCRWindow()
  3031. }
  3032. } else {
  3033. if toolbarItem.itemIdentifier == KMToolbarAnnotationSettingItemIdentifier {
  3034. let windowC = KMToolbarCustomWindowController()
  3035. windowC.toolbar = self.toolbarController.childToolBarView?.toolbar
  3036. self.km_beginSheet(windowC: windowC)
  3037. } else if toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier {
  3038. Swift.debugPrint("KMToolbarComparisonItemIdentifier ...")
  3039. } else if toolbarItem.itemIdentifier == KMDocumentPrintToolbarItemIdentifier {
  3040. self.trackEvent_print()
  3041. self.showPrintWindow()
  3042. } else if toolbarItem.itemIdentifier == KMToolbarToolProfileIdentifier {
  3043. Swift.debugPrint("KMToolbarToolProfileIdentifier ...")
  3044. let windowC = KMProfileInfoWindowController(windowNibName: "KMProfileInfoWindowController")
  3045. windowC.callBack = { [weak self] string in
  3046. // if (string.length > 0) {
  3047. // [blockSelf.pdfView addTextFieldWithSubType:KMSelfSignAnnotationFreeTextSubType_Profile string:string];
  3048. // }
  3049. self?.km_endSheet()
  3050. }
  3051. self.km_beginSheet(windowC: windowC)
  3052. } else if toolbarItem.itemIdentifier == KMToolbarViewSettingIdentifier {
  3053. Swift.debugPrint("KMToolbarViewSettingIdentifier ...")
  3054. } else if toolbarItem.itemIdentifier == KMToolbarSnapshotIdentifier {
  3055. Swift.debugPrint("KMToolbarSnapshotIdentifier ...")
  3056. } else if toolbarItem.itemIdentifier == KMToolbarTTSIdentifier {
  3057. Swift.debugPrint("KMToolbarTTSIdentifier ...")
  3058. }
  3059. }
  3060. }
  3061. }
  3062. func toolbarViewController(_ viewController: KMToolbarViewController, menuItemDidClick toolbarItem: KMToolbarItemView, index: Int, info: Any?) {
  3063. if (toolbarItem.itemIdentifier == KMToolbarToolWatermarkItemIdentifier) {
  3064. KMPrint("KMToolbarToolWatermarkItemIdentifier \(index)")
  3065. self.clickChildTool(type: .watermark, index: index)
  3066. } else if (toolbarItem.itemIdentifier == KMToolbarToolBackgroundItemIdentifier) {
  3067. KMPrint("KMToolbarToolBackgroundItemIdentifier \(index)")
  3068. self.clickChildTool(type: .background, index: index)
  3069. } else if (toolbarItem.itemIdentifier == KMToolbarToolHeaderFooterItemIdentifier) {
  3070. KMPrint("KMToolbarToolHeaderFooterItemIdentifier \(index)")
  3071. self.clickChildTool(type: .headerAndFooter, index: index)
  3072. } else if (toolbarItem.itemIdentifier == KMToolbarToolBatesItemIdentifier) {
  3073. KMPrint("KMToolbarToolBatesItemIdentifier \(index)")
  3074. self.clickChildTool(type: .bates, index: index)
  3075. } else if (toolbarItem.itemIdentifier == KMToolbarComparisonItemIdentifier) {
  3076. KMPrint("KMToolbarComparisonItemIdentifier \(index)")
  3077. self.clickChildTool(type: .comparison, index: index)
  3078. } else if (toolbarItem.itemIdentifier == KMToolbarToolFormAlignIdentifier) {
  3079. KMPrint("KMToolbarToolFormAlignIdentifier \(index)")
  3080. } else if (toolbarItem.itemIdentifier == KMToolbarConversionImageItemIdentifier) {
  3081. KMPrint("KMToolbarConversionImageItemIdentifier \(index)")
  3082. convertToImg(index: index)
  3083. } else if (toolbarItem.itemIdentifier == KMToolbarConversionExportImageItemIdentifier) {
  3084. KMPrint("KMToolbarConversionExportImageItemIdentifier \(index)")
  3085. extractImageAction(num: index)
  3086. } else if (toolbarItem.itemIdentifier == KMToolbarConversionCreatePDFItemIdentifier) {
  3087. KMPrint("KMToolbarConversionCreatePDFItemIdentifier \(index)")
  3088. self.createPdf(index: index)
  3089. } else if (toolbarItem.itemIdentifier == KMToolbarCropIdentifier) {
  3090. KMPrint("KMToolbarCropIdentifier \(index)")
  3091. } else if (toolbarItem.itemIdentifier == KMToolbarToolSecureItemIdentifier) {
  3092. KMPrint("KMToolbarToolSecureItemIdentifier \(index)")
  3093. self.clickChildTool(type: .secure, index: index)
  3094. }
  3095. }
  3096. func convertToImg(index: Int) {
  3097. var convertT: KMConvertType = .JPEG
  3098. switch index {
  3099. case 7:
  3100. convertT = .JPEG
  3101. case 8:
  3102. convertT = .JPG
  3103. case 9:
  3104. convertT = .PNG
  3105. case 10:
  3106. convertT = .GIF
  3107. case 11:
  3108. convertT = .TIFF
  3109. case 12:
  3110. convertT = .TGA
  3111. case 13:
  3112. convertT = .BMP
  3113. default:
  3114. convertT = .JPEG
  3115. }
  3116. showAllConvertWindow(convertT: convertT)
  3117. }
  3118. func toolbarViewController(_ viewController: KMToolbarViewController, searchAction searchString: String) {
  3119. Swift.debugPrint("Search Result " + searchString)
  3120. }
  3121. }
  3122. // MARK: -
  3123. // MARK: - Mouse
  3124. extension KMMainViewController {
  3125. override func mouseDown(with event: NSEvent) {
  3126. super.mouseDown(with: event)
  3127. KMPrint("KMMainViewController mouseDown")
  3128. self.leftSideViewCancelSelect()
  3129. self.pageNumberDisplayView.isEdit = false
  3130. }
  3131. }
  3132. //MARK: LeftSideViewController
  3133. extension KMMainViewController {
  3134. func leftSideViewCancelSelect() {
  3135. // switch self.leftSideViewController.type.methodType {
  3136. // case .Thumbnail:
  3137. //// self.leftSideViewController.thumbnailViewController.cancelSelect()
  3138. // break
  3139. // case .Outline:
  3140. //// self.leftSideViewController.outlineViewController.cancelSelect()
  3141. // break
  3142. // case .BookMark:
  3143. //// self.leftSideViewController.bookViewController.cancelSelect()
  3144. // break
  3145. // case .Search:
  3146. //// self.leftSideViewController.searchViewController.cancelSelect()
  3147. // break
  3148. // case .Annotation:
  3149. //// self.leftSideViewController.annotationViewController.cancelSelect()
  3150. // break
  3151. // default:
  3152. if self.listView.isEditing() {
  3153. if self.listView.editingAreas() != nil &&
  3154. self.listView.editingAreas().count != 0 {
  3155. let areas = self.listView.editingAreas().first
  3156. if areas is CPDFEditTextArea {
  3157. self.listView.clearEditingSelectCharItem()
  3158. self.listView.updateEditing([])
  3159. KMPrint("取消选中")
  3160. }
  3161. }
  3162. }
  3163. KMPrint("其他")
  3164. // }
  3165. }
  3166. }
  3167. extension KMMainViewController: KMReadModelViewDelegate {
  3168. func firstPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3169. self.listView.goToFirstPage(nil)
  3170. }
  3171. func beforePageButtonDidChange(view: KMReadModelView, sender: Any) {
  3172. self.listView.goToPreviousPage(nil)
  3173. }
  3174. func afterPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3175. self.listView.goToNextPage(nil)
  3176. }
  3177. func lastPageButtonDidChange(view: KMReadModelView, sender: Any) {
  3178. self.listView.goToLastPage(nil)
  3179. }
  3180. func currentPageButtonDidChange(view: KMReadModelView, sender: Any, pageIndex: Int) {
  3181. self.listView.go(toPageIndex: max(pageIndex - 1, 0), animated: true)
  3182. }
  3183. func scaleDidChange(view: KMReadModelView, sender: Any, type: KMReadModelViewScaleType) {
  3184. var scale: Double = 1.0
  3185. switch type {
  3186. case .fitWidth:
  3187. self.listView.autoScales = !self.listView.autoScales
  3188. scale = self.listView.scaleFactor
  3189. break
  3190. case .actualSize:
  3191. if self.listView.scaleFactor != 1.0 {
  3192. self.listView.scaleFactor = 1.0
  3193. self.listView.autoScales = false
  3194. }
  3195. scale = self.listView.scaleFactor
  3196. break
  3197. case .autoSize:
  3198. self.listView.autoScales = true
  3199. self.listView.autoScales = false
  3200. scale = self.listView.scaleFactor
  3201. break
  3202. case ._10:
  3203. scale = 0.1
  3204. break
  3205. case ._25:
  3206. scale = 0.25
  3207. break
  3208. case ._50:
  3209. scale = 0.5
  3210. break
  3211. case ._100:
  3212. scale = 1.0
  3213. break
  3214. case ._150:
  3215. scale = 1.5
  3216. break
  3217. case ._200:
  3218. scale = 2.0
  3219. break
  3220. case ._400:
  3221. scale = 4.0
  3222. break
  3223. case ._800:
  3224. scale = 8.0
  3225. break
  3226. default:
  3227. break
  3228. }
  3229. self.listView.scaleFactor = scale
  3230. self.toolbarController.mainViewController?.childToolbarController.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor*100))%"
  3231. }
  3232. func cancelReadModel(view: KMReadModelView, sender: Any) {
  3233. if self.isReadMode {
  3234. self.closeReadModel()
  3235. }
  3236. }
  3237. func readModelViewWidthChange(view: KMReadModelView, width: CGFloat) {
  3238. // if self.readModelViewWidthConstraint.constant != width {
  3239. self.readModelViewWidthConstraint.constant = width
  3240. // }
  3241. }
  3242. }
  3243. extension KMMainViewController: KMPageNumberDisplayViewDelegate {
  3244. func gotoPageIndex(view: KMPageNumberDisplayView, pageIndex: Int) {
  3245. self.listView.go(toPageIndex: pageIndex, animated: true)
  3246. }
  3247. func updateWidth(view: KMPageNumberDisplayView, width: CGFloat) {
  3248. if self.tipCurrentPageBoxWidthConstraint.constant != width {
  3249. self.tipCurrentPageBoxWidthConstraint.constant = width
  3250. }
  3251. }
  3252. func commitEditingIfNeed() {
  3253. let isEdited = self.listView?.isEdited() ?? false
  3254. if isEdited || self.isPDFTextImageEdited {
  3255. self.listView.commitEditing()
  3256. }
  3257. }
  3258. }
  3259. // MARK: - Analytics (埋点)
  3260. extension KMMainViewController {
  3261. func trackEvent(toolType type: KMToolbarViewType) -> Void {
  3262. if (type == .Annatiton) {
  3263. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Annotation", parameters: [
  3264. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3265. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3266. } else if (type == .editPDF) {
  3267. KMAnalytics.trackEvent(eventName: "Btn_Tbr_EditPDF", parameters: [
  3268. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3269. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3270. } else if (type == .Page) {
  3271. KMAnalytics.trackEvent(eventName: "Btn_Tbr_PageEdit", parameters: [
  3272. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3273. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3274. } else if (type == .Conversion) {
  3275. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Converter", parameters: [
  3276. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3277. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3278. } else if (type == .Tool) {
  3279. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Tools", parameters: [
  3280. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3281. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3282. }
  3283. }
  3284. func trackEvent_aiTranslate() -> Void {
  3285. KMAnalytics.trackEvent(eventName: "Btn_Tbr_AITranslate", parameters: [
  3286. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3287. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3288. }
  3289. func trackEvent_print() -> Void {
  3290. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Print", parameters: [
  3291. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3292. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3293. }
  3294. func trackEvent_share() -> Void {
  3295. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Share", parameters: [
  3296. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3297. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3298. }
  3299. func trackEvent_upgrade() -> Void {
  3300. KMAnalytics.trackEvent(eventName: "Btn_Tbr_Upgrade", parameters: [
  3301. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.tbr,
  3302. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.tbr_Btn], platform: .AppCenter, appTarget: .all)
  3303. }
  3304. func trackEvent(annotationType type: CAnnotationType) -> Void {
  3305. if (type == .highlight) {
  3306. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Highlight", parameters: [
  3307. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3308. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3309. } else if (type == .underline) {
  3310. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Underline", parameters: [
  3311. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3312. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3313. } else if (type == .strikeOut) {
  3314. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Strikethrough", parameters: [
  3315. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3316. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3317. } else if (type == .ink) {
  3318. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Draw", parameters: [
  3319. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3320. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3321. } else if (type == .freeText) {
  3322. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Text", parameters: [
  3323. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3324. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3325. } else if (type == .anchored) {
  3326. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Note", parameters: [
  3327. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3328. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3329. } else if (type == .square) {
  3330. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Shape", parameters: [
  3331. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3332. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3333. } else if (type == .link) {
  3334. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Link", parameters: [
  3335. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3336. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3337. } else if (type == .stamp) {
  3338. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Stamp", parameters: [
  3339. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3340. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3341. } else if (type == .signSignature) {
  3342. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Sign", parameters: [
  3343. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3344. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3345. } else if (type == .addText) {
  3346. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddText", parameters: [
  3347. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3348. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3349. } else if (type == .addImage) {
  3350. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_AddImage", parameters: [
  3351. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_editPDF,
  3352. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3353. } else {
  3354. }
  3355. }
  3356. func trackEvent(toolMode mode: CToolMode) -> Void {
  3357. if (mode == .selectToolMode) {
  3358. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_ContentSelection", parameters: [
  3359. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3360. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3361. } else if (mode == .moveToolMode) {
  3362. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Scroll", parameters: [
  3363. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_annotation,
  3364. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3365. }
  3366. }
  3367. func trackEvent(toolBarType type: KMToolbarType) -> Void {
  3368. if (type == .word) {
  3369. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toWord", parameters: [
  3370. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3371. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3372. } else if (type == .excel) {
  3373. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toExcel", parameters: [
  3374. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3375. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3376. } else if (type == .ppt) {
  3377. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toPPT", parameters: [
  3378. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3379. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3380. } else if (type == .rtf) {
  3381. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toRTF", parameters: [
  3382. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3383. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3384. } else if (type == .csv) {
  3385. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toCSV", parameters: [
  3386. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3387. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3388. } else if (type == .html) {
  3389. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toHTML", parameters: [
  3390. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3391. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3392. } else if (type == .conversion_text) {
  3393. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toText", parameters: [
  3394. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3395. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3396. } else if (type == .conversion_image) {
  3397. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_toImage", parameters: [
  3398. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Converter,
  3399. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3400. } else if (type == .compress) {
  3401. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Compress", parameters: [
  3402. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3403. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3404. } else if (type == .merge) {
  3405. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Merge", parameters: [
  3406. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3407. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3408. } else if (type == .secure) {
  3409. } else if (type == .crop) {
  3410. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Crop", parameters: [
  3411. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3412. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3413. }
  3414. }
  3415. func trackEvent_setPassword() -> Void {
  3416. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_SetPassword", parameters: [
  3417. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3418. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3419. }
  3420. func trackEvent_removePassword() -> Void {
  3421. KMAnalytics.trackEvent(eventName: "Btn_SubTbr_RemovePassword", parameters: [
  3422. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_Tools,
  3423. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all)
  3424. }
  3425. }
  3426. extension KMMainViewController {
  3427. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  3428. let contentController: KMCompareContentWindowController = KMCompareContentWindowController.init(document: document, oldDocument: oldDocument, results: results)
  3429. contentController.hideCloseInfo = true
  3430. contentController.saveHandle = { [unowned self] controller in
  3431. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  3432. saveController.cancelHandle = { [unowned self] controller in
  3433. NSWindow.currentWindow().endSheet(controller.window!)
  3434. }
  3435. saveController.saveHandle = { [unowned self] controller, saveType in
  3436. let folderPath = controller.fileSaveFolderPath
  3437. //#if VERSION_DMG
  3438. //
  3439. //#else
  3440. // if let url = URL(string: folderPath) {
  3441. // AppSandboxFileAccess.fileAccess().persistPermissionURL(url)
  3442. // if let bookmarkData = try? url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) {
  3443. // AppSandboxFileAccess.fileAccess().bookmarkPersistanceDelegate?.setBookmarkData(bookmarkData, forURL: url)
  3444. // AppSandboxFileAccess.fileAccess().bookmarkPersistanceDelegate?.setBookmarkData(bookmarkData, forURL: URL(fileURLWithPath: url.path))
  3445. // }
  3446. // }
  3447. //#endif
  3448. if folderPath != nil {
  3449. if !FileManager.default.fileExists(atPath: folderPath) {
  3450. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  3451. }
  3452. var savePath: String
  3453. switch saveType {
  3454. case 0:
  3455. savePath = "\(folderPath)/\(oldDocument.documentURL.path.lastPathComponent.deletingPathExtension)_compare.\(oldDocument.documentURL.path.extension)"
  3456. savePath = self.getValidFilePath(savePath)
  3457. oldDocument.write(to: URL(fileURLWithPath: savePath))
  3458. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3459. case 1:
  3460. savePath = "\(folderPath)/\(document.documentURL.path.lastPathComponent.deletingPathExtension)_compare.\(document.documentURL.path.extension)"
  3461. savePath = self.getValidFilePath(savePath)
  3462. document.write(to: URL(fileURLWithPath: savePath))
  3463. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3464. case 2:
  3465. savePath = "\(folderPath)/MergedCompareFile.\(oldDocument.documentURL.path.extension)"
  3466. savePath = self.getValidFilePath(savePath)
  3467. pdfCompareContent.saveAsComparisonDocument(withFilePath: savePath)
  3468. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  3469. default:
  3470. break
  3471. }
  3472. }
  3473. NSWindow.currentWindow().endSheet(controller.window!)
  3474. }
  3475. }
  3476. contentController.closeHandle = { [unowned self] controller in
  3477. contentController.close()
  3478. }
  3479. NSWindow.currentWindow().km_beginSheet(windowC: contentController)
  3480. }
  3481. func getValidFilePath(_ oldPath: String) -> String {
  3482. let fileManager = FileManager.default
  3483. do {
  3484. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  3485. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  3486. return oldPath
  3487. }
  3488. var i = 1
  3489. var newPath = oldPath
  3490. while fileManager.fileExists(atPath: newPath) {
  3491. if fileType == FileAttributeType.typeDirectory.rawValue {
  3492. newPath = oldPath + "(\(i))"
  3493. } else {
  3494. let fileExtension = (oldPath as NSString).pathExtension
  3495. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  3496. }
  3497. i += 1
  3498. }
  3499. return newPath
  3500. } catch {
  3501. print("Error getting file attributes: \(error)")
  3502. return oldPath
  3503. }
  3504. }
  3505. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  3506. var coveringController: KMCompareCoveringWindowController = KMCompareCoveringWindowController.init(document: pdfDocument)
  3507. coveringController.hideCloseInfo = true
  3508. coveringController.saveHandle = { [unowned self] controller in
  3509. let savePanel = NSSavePanel()
  3510. savePanel.nameFieldStringValue = "untitled"
  3511. savePanel.allowedFileTypes = ["pdf"]
  3512. savePanel.beginSheetModal(for: controller.window!) { result in
  3513. if result == .OK {
  3514. pdfDocument.write(to: savePanel.url!)
  3515. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  3516. }
  3517. }
  3518. }
  3519. coveringController.closeHandle = { [unowned self] controller in
  3520. NSWindow.currentWindow().endSheet(controller.window!)
  3521. }
  3522. NSWindow.currentWindow().km_beginSheet(windowC: coveringController)
  3523. }
  3524. }