Skip to content

Commit

Permalink
Merge branch 'enableterm'
Browse files Browse the repository at this point in the history
  • Loading branch information
terrychou committed Mar 3, 2020
2 parents db58d0f + 6b13ed5 commit 8a160df
Show file tree
Hide file tree
Showing 164 changed files with 23,817 additions and 374 deletions.
247 changes: 233 additions & 14 deletions iVim.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion iVim/ExtendedKeyboardConfigNodes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,11 @@ extension EKSubitems {

private extension Dictionary where Key: StringProtocol {
func anyValue<T>(for key: Key) -> T? {
return self[key] as? T
// Any could be some(nil)
// so "self[key] as? T" is not enough
let value = self[key]

return value != nil ? value as? T : nil
}
}

Expand Down
7 changes: 7 additions & 0 deletions iVim/GlobalConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,12 @@
// Copyright © 2017 Boogaloo. All rights reserved.
//

import Foundation


let gSchemeName = "ivimeditor"
let gAppGroup = "group.com.terrychou.ivim"

extension UserDefaults {
static let appGroup = UserDefaults(suiteName: gAppGroup)!
}
2 changes: 2 additions & 0 deletions iVim/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
<key>UIAppFonts</key>
<array>
<string>SourceCodePro-Regular.ttf</string>
<string>SourceCodePro-Bold.ttf</string>
<string>SourceCodePro-It.ttf</string>
</array>
<key>UIFileSharingEnabled</key>
<true/>
Expand Down
2 changes: 1 addition & 1 deletion iVim/OptionalButton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ extension OptionalButton {
}

private func restore() {
DispatchQueue.main.async {
Thread.runOnMainThread {
self.layer.backgroundColor = UIColor.normalBackground.cgColor
self.reset()
}
Expand Down
12 changes: 11 additions & 1 deletion iVim/Settings.bundle/Root.plist
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<key>Title</key>
<string>Hardware Keyboard</string>
<key>FooterText</key>
<string>Mapping caps lock has caveats. See &quot;:h ios-external-keyboard&quot;. Mapping [alt] enables iVim take over alt- keystrokes.</string>
<string>Mapping caps lock has caveats. See &quot;:h ios-external-keyboard&quot;. Mapping [alt] enables iVim take over alt- keystrokes. Key Repeating repeats the held key for English keyboards.</string>
</dict>
<dict>
<key>Type</key>
Expand Down Expand Up @@ -98,6 +98,16 @@
<key>DefaultValue</key>
<false/>
</dict>
<dict>
<key>Type</key>
<string>PSToggleSwitchSpecifier</string>
<key>Title</key>
<string>Key Repeating</string>
<key>Key</key>
<string>kUDKeyRepeating</string>
<key>DefaultValue</key>
<true/>
</dict>
<dict>
<key>Type</key>
<string>PSGroupSpecifier</string>
Expand Down
Binary file added iVim/SourceCodePro-Bold.ttf
Binary file not shown.
Binary file added iVim/SourceCodePro-It.ttf
Binary file not shown.
32 changes: 10 additions & 22 deletions iVim/URLSchemeWorker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ struct URLSchemeWorker {
}

enum URLCommand: String {
case newtab
case shareextension

init?(url: URL) {
guard let host = url.host else { return nil }
Expand All @@ -41,32 +41,20 @@ extension URLCommand {
func invoke(with url: URL, info: Any?) {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
switch self {
case .newtab: self.doNewtab(components)
case .shareextension: self.doShareExtension(components)
}
}

private func text(of file: String) -> String? {
guard let c = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: gAppGroup) else { return nil }
let url = c.appendingPathComponent(file)
do {
let text = try String(contentsOf: url, encoding: .utf8)
try FileManager.default.removeItem(at: url)
return text
} catch {
NSLog("Failed to read temp file: \(error)")
return nil
private func doShareExtension(_ components: URLComponents) {
guard let name = components.firstQueryValue(for: "action") else { return }
if let textAction = ShareTextAction(name: name) {
textAction.run()
} else if let fileAction = ShareFileAction(name: name) {
fileAction.run()
} else {
NSLog("invalid share extension action name '\(name)'")
}
}

private func doNewtab(_ components: URLComponents) {
guard let fn = components.firstQueryValue(for: "file"),
let t = self.text(of: fn) else { return }
if !is_current_buf_new() {
do_cmdline_cmd("tabnew")
}
do_cmdline_cmd("normal! i\(t)")
gEnsureSuccessfulOpen()
}
}

extension URLComponents {
Expand Down
75 changes: 67 additions & 8 deletions iVim/VimAppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//

import UIKit
import ios_system

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
Expand All @@ -17,7 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// self.logToFile()
self.registerUserDefaultsValues()
//Start Vim!
// Start Vim!
self.performSelector(
onMainThread: #selector(self.VimStarter),
with: nil,
Expand Down Expand Up @@ -51,6 +52,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
gPIM.didEnterBackground()
}

func applicationDidBecomeActive(_ application: UIApplication) {
// resume focus
gui_mch_flush()
}

// private func logToFile() {
// let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
// let file = path + "/NSLog.log"
Expand All @@ -65,16 +71,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

private func registerUserDefaultsValues() {
register_auto_restore_enabled()
VimViewController.registerExternalKeyboardUserDefaults()
}

@objc func VimStarter() {
guard let vimPath = Bundle.main.resourcePath else { return }
let runtimePath = vimPath + "/runtime"
vim_setenv("VIM", vimPath)
vim_setenv("VIMRUNTIME", runtimePath)
let workingDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
vim_setenv("HOME", workingDir)
FileManager.default.changeCurrentDirectoryPath(workingDir)
guard self.customizeEnv() else { return }
var args = ["vim"]
if !scenes_keeper_restore_prepare() {
gSVO.showError("failed to auto-restore")
Expand All @@ -89,3 +90,61 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
argv.forEach { free($0) }
}
}

extension AppDelegate { // env setup
private func appendToEnvPath(_ path: String) {
var old = String(cString: getenv("PATH"))
old.append(":" + path)
vim_setenv("PATH", old)
}

private func customizeEnv() -> Bool {
guard let resPath = Bundle.main.resourcePath else { return false }
// for ios_system
initializeEnvironment()

// setup vim
let runtimePath = resPath + "/runtime"
vim_setenv("VIM", resPath)
vim_setenv("VIMRUNTIME", runtimePath)
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true)[0]
vim_setenv("HOME", docDir)
FileManager.default.changeCurrentDirectoryPath(docDir)

// setup shell
self.setupShell(homePath: docDir, resPath: resPath)

// setup python
self.setupPython(withResourcePath: resPath)

return true
}

private func setupPython(withResourcePath resPath: String) {
numPythonInterpreters = 2
let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
.userDomainMask,
true)[0]
let libHome = libPath + "/python"
let pythonHome = resPath + "/python"
let siteSubpath = "/lib/python3.7/site-packages"
vim_setenv("PYTHONHOME", pythonHome)
vim_setenv("PYTHONPATH", libHome + siteSubpath)
let pipBin = pythonHome + siteSubpath + "/bin"
let libBin = libHome + "/bin"
self.appendToEnvPath(pipBin + ":" + libBin)
vim_setenv("PYTHONIOENCODING", "utf-8")
// setup pip: install into the writable one
vim_setenv("PIP_PREFIX", libHome)
vim_setenv("PIP_DISABLE_PIP_VERSION_CHECK", "yes")
// vim_setenv("PIP_NO_COLOR", "yes")
}

private func setupShell(homePath: String, resPath: String) {
vim_setenv("IVISH_CMD_DB", resPath + "/commandPersonalities.plist")
// history file path
vim_setenv("IVISH_HISTORY_FILE", homePath + "/.ivish_history")
}
}
69 changes: 53 additions & 16 deletions iVim/VimFontsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,12 @@ extension VimFontsManager {
}

private func uncacheUserFont(with name: String) {
guard let font = self.cache[name]?.cgFont else { return }
if !CTFontManagerUnregisterGraphicsFont(font, nil) {
NSLog("Failed to unregistered font \(name)")
guard let url = self.cache[name]?.url else { return }
var err: Unmanaged<CFError>?
if !CTFontManagerUnregisterFontsForURL(url, .none, &err) {
let e = err?.nsError
NSLog("failed to unregister font '\(name)': " +
"\(e?.localizedDescription ?? "unknown reason")")
}
self.cache[name] = nil
}
Expand Down Expand Up @@ -225,16 +228,37 @@ extension VimFontsManager {
}

private func prepareUserFont(with name: String) -> String? {
guard let path = userFontsURL?.appendingPathComponent(name),
let dp = CGDataProvider(url: path as CFURL)
else { return nil }
_ = UIFont() //to overcome the CGFontCreate hanging bug: http://stackoverflow.com/a/40256390/723851
let font = CGFont(dp)
guard let psName = font?.postScriptName as String?,
CTFontManagerRegisterGraphicsFont(font!, nil) else { return nil }
self.cache[name] = FontCache(postScriptName: psName, cgFont: font)
guard let fontURL = userFontsURL?.appendingPathComponent(name) else { return nil }
let url = fontURL as CFURL
// to overcome the CGFontCreate hanging bug:
// http://stackoverflow.com/a/40256390/723851
_ = UIFont()
var err: Unmanaged<CFError>?
if !CTFontManagerRegisterFontsForURL(url, .none, &err) {
let e = err?.nsError
if e?.isCTFontManagerError(.alreadyRegistered) != true {
NSLog("failed to register font '\(name)': " +
"\(e?.localizedDescription ?? "unknown reason")")
return nil
}
}
var ret: String?
if let ds = CTFontManagerCreateFontDescriptorsFromURL(url) as? [CTFontDescriptor] {
for d in ds {
if let n = CTFontDescriptorCopyAttribute(d, kCTFontNameAttribute) as? String {
ret = n
if n.hasSuffix("Regular") {
break
}
}
}
}
if let psName = ret {
self.cache[name] = FontCache(postScriptName: psName,
url: url)
}

return psName
return ret
}

private func postScriptName(for name: String) -> String? {
Expand Down Expand Up @@ -270,6 +294,19 @@ extension VimFontsManager {
}
}

private extension Unmanaged where Instance == CFError {
var nsError: NSError? {
return (self.takeRetainedValue() as Error) as NSError
}
}

private extension NSError {
func isCTFontManagerError(_ err: CTFontManagerError) -> Bool {
return (self.domain == kCTFontManagerErrorDomain as String) &&
self.code == err.rawValue
}
}

extension VimFontsManager {
func importFont(from url: URL?, isMoving: Bool, removeOriginIfFailed: Bool) -> Bool {
guard let src = url, let fontsDir = userFontsURL else { return false }
Expand Down Expand Up @@ -338,11 +375,11 @@ func ==(lfi: FontInfo, rfi: FontInfo) -> Bool {

struct FontCache {
let postScriptName: String
let cgFont: CGFont?
let url: CFURL?

init(postScriptName: String, cgFont: CGFont? = nil) {
init(postScriptName: String, url: CFURL? = nil) {
self.postScriptName = postScriptName
self.cgFont = cgFont
self.url = url
}
}

Expand All @@ -363,7 +400,7 @@ extension String {
extension URL {
var isSupportedFont: Bool {
switch self.pathExtension {
case "ttf", "otf": return true
case "ttf", "otf", "ttc": return true
default: return false
}
}
Expand Down
2 changes: 1 addition & 1 deletion iVim/VimFunctions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ final class SafeVimOperations {
let isNewBuf = is_current_buf_new()
let openCmd = isNewBuf ? "edit" : "tabedit"
// let path = path_relative_to_cwd(url.path).spaceEscaped
let path = url.path.spaceEscaped
let path = ivim_escaping_filepath(url.path)
do_cmdline_cmd("\(openCmd) \(path)")
gEnsureSuccessfulOpen()
// if url.isDirectory {
Expand Down
48 changes: 48 additions & 0 deletions iVim/VimShareActions+Host.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//
// VimShareAction+Host.swift
// iVim
//
// Created by Terry Chou on 12/26/19.
// Copyright © 2019 Boogaloo. All rights reserved.
//

import Foundation


extension ShareAction {
func removeData() {
guard let key = self.userDefaultsKey else { return }
UserDefaults.appGroup.removeObject(forKey: key)
}

func newWithText() {
guard let text: String = self.getData() else {
NSLog("failed to get text for \(self.name)")
return
}
if !is_current_buf_new() {
do_cmdline_cmd("tabnew")
}
do_cmdline_cmd("normal! i\(text)")
gEnsureSuccessfulOpen()
self.removeData()
}
}

extension ShareTextAction {
func run() {
switch self {
case .text:
self.newWithText()
}
}
}

extension ShareFileAction {
func run() {
switch self {
case .content:
self.newWithText()
}
}
}
Loading

0 comments on commit 8a160df

Please sign in to comment.