Эх сурвалжийг харах

Mac app: export buffer, export selection; Library: API to expose contents as Data; Update localhost testing address

Miguel de Icaza 4 жил өмнө
parent
commit
1ed974b5c6

+ 3 - 3
Sources/SwiftTerm/Buffer.swift

@@ -118,9 +118,9 @@ class Buffer {
     var savedOriginMode : Bool = false
     var savedOriginMode : Bool = false
     /// Saved state for the origin mode
     /// Saved state for the origin mode
     var savedMarginMode: Bool = false
     var savedMarginMode: Bool = false
-    
+    /// Saved state for the wrap around mode
     var savedWraparound : Bool = false
     var savedWraparound : Bool = false
-
+    /// Saved state for the reverse wrap around mode
     var savedReverseWraparound: Bool = false
     var savedReverseWraparound: Bool = false
 
 
     /**
     /**
@@ -969,5 +969,5 @@ class Buffer {
         
         
             print ("[\(istr):\(cstr)]\(flag)\(yb) \(debugBuffer._lines.array [y].debugDescription)")
             print ("[\(istr):\(cstr)]\(flag)\(yb) \(debugBuffer._lines.array [y].debugDescription)")
         }
         }
-    }
+    }    
 }
 }

+ 16 - 0
Sources/SwiftTerm/Mac/MacTerminalView.swift

@@ -751,6 +751,22 @@ open class TerminalView: NSView, NSTextInputClient, NSUserInterfaceValidations {
         clipboard.setString(str, forType: .string)
         clipboard.setString(str, forType: .string)
     }
     }
     
     
+    /// Set to true if the selection is active, false otherwise
+    public var selectionActive: Bool {
+        get {
+            selection.active
+        }
+    }
+    
+    
+    /// Returns the contents of the selection, if active, or nil otherwise
+    public func getSelection () -> String?
+    {
+        if selection.active {
+            return selection.getSelectedText()
+        }
+        return nil
+    }
     public override func selectAll(_ sender: Any?)
     public override func selectAll(_ sender: Any?)
     {
     {
         selection.selectAll()
         selection.selectAll()

+ 42 - 0
Sources/SwiftTerm/Terminal.swift

@@ -4492,6 +4492,48 @@ open class Terminal {
         }
         }
         return l
         return l
     }
     }
+    
+    /// Specified the kind of buffer is being requested from the terminal
+    public enum BufferKind {
+        /// The currently active buffer (can be either normal or alt)
+        case active
+        /// The normal buffer, regardless of which buffer is active
+        case normal
+        /// The alternate buffer, regardless of which buffer is active
+        case alt
+    }
+    
+    func bufferFromKind (kind: BufferKind) -> Buffer
+    {
+        switch kind {
+        case .active:
+            return buffers.active
+        case .normal:
+            return buffers.normal
+        case .alt:
+            return buffers.alt
+        }
+    }
+    
+    /// Returns the contents of the specified terminal buffer encoded as UTF8 in the provided Data buffer
+    /// - Parameter kind: which buffer to retrive the data for
+    /// - Parameter encoding: which encoding to use for the returned value, defaults to utf8
+    public func getBufferAsData (kind: BufferKind = .active, encoding: String.Encoding = .utf8) -> Data
+    {
+        var result = Data()
+        
+        let b = bufferFromKind(kind: kind)
+        let newLine = Data([10])
+        for row in 0..<b.lines.count {
+            let bufferLine = b.lines [row]
+            let str = bufferLine.translateToString(trimRight: true)
+            if let encoded = str.data(using: encoding) {
+                result.append (encoded)
+                result.append (newLine)
+            }
+        }
+        return result
+    }    
 }
 }
 
 
 // Default implementations
 // Default implementations

+ 9 - 3
TerminalApp/MacTerminal/Base.lproj/Main.storyboard

@@ -1,7 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
+<document type="com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB" version="3.0" toolsVersion="17506" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES">
     <dependencies>
     <dependencies>
-        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="16097"/>
+        <deployment identifier="macosx"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="17506"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
     </dependencies>
     <scenes>
     <scenes>
@@ -95,7 +96,12 @@
                                         </menuItem>
                                         </menuItem>
                                         <menuItem title="Export Text As..." keyEquivalent="s" id="pxx-59-PXV">
                                         <menuItem title="Export Text As..." keyEquivalent="s" id="pxx-59-PXV">
                                             <connections>
                                             <connections>
-                                                <action selector="saveDocument:" target="Ady-hI-5gd" id="teZ-XB-qJY"/>
+                                                <action selector="exportBuffer:" target="Ady-hI-5gd" id="RuH-bk-JQe"/>
+                                            </connections>
+                                        </menuItem>
+                                        <menuItem title="Export Selected Text As..." keyEquivalent="S" id="NIO-el-3Fl">
+                                            <connections>
+                                                <action selector="exportSelection:" target="Ady-hI-5gd" id="Qfi-Yz-gBE"/>
                                             </connections>
                                             </connections>
                                         </menuItem>
                                         </menuItem>
                                         <menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
                                         <menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>

+ 10 - 2
TerminalApp/MacTerminal/Document.swift

@@ -26,10 +26,18 @@ class Document: NSDocument {
         self.addWindowController(windowController)
         self.addWindowController(windowController)
     }
     }
 
 
-   override func data(ofType typeName: String) throws -> Data {
+    override func data(ofType typeName: String) throws -> Data {
+        throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
+        
        // Insert code here to write your document to data of the specified type, throwing an error in case of failure.
        // Insert code here to write your document to data of the specified type, throwing an error in case of failure.
        // Alternatively, you could remove this method and override fileWrapper(ofType:), write(to:ofType:), or write(to:ofType:for:originalContentsURL:) instead.
        // Alternatively, you could remove this method and override fileWrapper(ofType:), write(to:ofType:), or write(to:ofType:for:originalContentsURL:) instead.
-       throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
+        guard let wc = windowControllers.first else {
+            throw NSError(domain: NSOSStatusErrorDomain, code: controlErr, userInfo: nil)
+        }
+        guard let vc = wc.contentViewController as? ViewController else {
+            
+        }
+        return vc.terminal.getTerminal().getBufferAsData ()
    }
    }
 
 
    //override func read(from data: Data, ofType typeName: String) throws {
    //override func read(from data: Data, ofType typeName: String) throws {

+ 2 - 0
TerminalApp/MacTerminal/Info.plist

@@ -41,6 +41,8 @@
 	<string>1.0</string>
 	<string>1.0</string>
 	<key>CFBundleVersion</key>
 	<key>CFBundleVersion</key>
 	<string>1</string>
 	<string>1</string>
+	<key>LSApplicationCategoryType</key>
+	<string>public.app-category.utilities</string>
 	<key>LSMinimumSystemVersion</key>
 	<key>LSMinimumSystemVersion</key>
 	<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
 	<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
 	<key>NSHumanReadableCopyright</key>
 	<key>NSHumanReadableCopyright</key>

+ 50 - 0
TerminalApp/MacTerminal/ViewController.swift

@@ -74,6 +74,11 @@ class ViewController: NSViewController, LocalProcessTerminalViewDelegate, NSUser
 
 
     static var lastTerminal: LocalProcessTerminalView!
     static var lastTerminal: LocalProcessTerminalView!
     
     
+    func getBufferAsData () -> Data
+    {
+        return terminal.getTerminal().getBufferAsData ()
+    }
+    
     func updateLogging ()
     func updateLogging ()
     {
     {
         let path = logging ? "/Users/miguel/Downloads/Logs" : nil
         let path = logging ? "/Users/miguel/Downloads/Logs" : nil
@@ -193,6 +198,46 @@ class ViewController: NSViewController, LocalProcessTerminalViewDelegate, NSUser
         terminal.allowMouseReporting.toggle ()
         terminal.allowMouseReporting.toggle ()
     }
     }
     
     
+    @objc @IBAction
+    func exportBuffer (_ source: AnyObject)
+    {
+        saveData { self.terminal.getTerminal().getBufferAsData () }
+    }
+
+    @objc @IBAction
+    func exportSelection (_ source: AnyObject)
+    {
+        saveData {
+            if let str = self.terminal.getSelection () {
+                return str.data (using: .utf8) ?? Data ()
+            }
+            return Data ()
+        }
+    }
+
+    func saveData (_ getData: @escaping () -> Data)
+    {
+        let savePanel = NSSavePanel ()
+        savePanel.canCreateDirectories = true
+        savePanel.allowedFileTypes = ["txt"]
+        savePanel.title = "Export Buffer Contents As Text"
+        savePanel.nameFieldStringValue = "TerminalCapture"
+        
+        savePanel.begin { (result) in
+            if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
+                let data = getData ()
+                if let url = savePanel.url {
+                    do {
+                        try data.write(to: url)
+                    } catch let error as NSError {
+                        let alert = NSAlert (error: error)
+                        alert.runModal()
+                    }
+                }
+            }
+        }
+    }
+    
     @objc @IBAction
     @objc @IBAction
     func softReset (_ source: AnyObject)
     func softReset (_ source: AnyObject)
     {
     {
@@ -297,6 +342,11 @@ class ViewController: NSViewController, LocalProcessTerminalViewDelegate, NSUser
                 m.state = terminal.optionAsMetaKey ? NSControl.StateValue.on : NSControl.StateValue.off
                 m.state = terminal.optionAsMetaKey ? NSControl.StateValue.on : NSControl.StateValue.off
             }
             }
         }
         }
+        
+        // Only enable "Export selection" if we have a selection
+        if item.action == #selector(exportSelection(_:)) {
+            return terminal.selectionActive
+        }
         return true
         return true
     }
     }
     
     

+ 1 - 1
TerminalApp/iOSTerminal/UIKitSshTerminalView.swift

@@ -27,7 +27,7 @@ public class SshTerminalView: TerminalView, TerminalViewDelegate {
             
             
             authenticationChallenge = .byPassword(username: "miguel", password: try String (contentsOfFile: "/Users/miguel/password"))
             authenticationChallenge = .byPassword(username: "miguel", password: try String (contentsOfFile: "/Users/miguel/password"))
             shell = try? SSHShell(sshLibrary: Libssh2.self,
             shell = try? SSHShell(sshLibrary: Libssh2.self,
-                                  host: "192.168.86.77",
+                                  host: "192.168.86.74",
                                   port: 22,
                                   port: 22,
                                   environment: [Environment(name: "LANG", variable: "en_US.UTF-8")],
                                   environment: [Environment(name: "LANG", variable: "en_US.UTF-8")],
                                   terminal: "xterm-256color")
                                   terminal: "xterm-256color")