-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppDelegate.swift
103 lines (82 loc) · 3.49 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// AppDelegate.swift
// ApkDropZone
//
// Created by dstd on 12.05.15.
// Copyright (c) 2015 stdlabs. All rights reserved.
//
import Cocoa
func rangeForString(string: String) -> NSRange {
return NSMakeRange(0, count(string))
}
extension String {
func substringWithRange(range: NSRange) -> String {
return (self as NSString).substringWithRange(range);
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var outputLog: NSTextField!
var launchPath: String!
func applicationDidFinishLaunching(aNotification: NSNotification) {
launchPath = "~/Library/Android/sdk/platform-tools/adb".stringByExpandingTildeInPath;
if !NSFileManager.defaultManager().fileExistsAtPath(launchPath!) {
launchPath = "adb"
}
}
func applicationWillTerminate(aNotification: NSNotification) {
}
func writeLog(string: String) {
self.outputLog.stringValue = self.outputLog.stringValue + string + "\n"
}
func installApk(filename: String) {
writeLog("Installing \(filename)")
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
var outputTotal = String()
let outputPipe = NSPipe()
let outputStream = outputPipe.fileHandleForReading;
var task = NSTask()
task.launchPath = self.launchPath
task.arguments = ["install", "-r", filename];
task.standardOutput = outputPipe;
let exception = Exceptions.try
{ () -> Void in
task.launch()
while task.running {
let ouputData = outputStream.availableData
let ouputString = NSString(data: ouputData, encoding: NSUTF8StringEncoding) as! String
outputTotal += ouputString
}
}
if exception != nil {
self.writeLog("Failed to start ADB. Check PATH or move to ~/Library/Android/sdk/platform-tools/adb")
return;
}
dispatch_async(dispatch_get_main_queue()) {
if let regex = NSRegularExpression(pattern: "Failure \\[(.*)\\]", options: NSRegularExpressionOptions(0), error: nil) {
let lines = outputTotal.componentsSeparatedByString("\n")
let errors = lines.filter { regex.firstMatchInString($0, options: NSMatchingOptions(0), range: rangeForString($0)) != nil }
if errors.count > 0 {
let errorLine = errors[0];
let error: String
if let errorItem = regex.firstMatchInString(errorLine, options: NSMatchingOptions(0), range: rangeForString(errorLine)) {
error = errorLine.substringWithRange(errorItem.rangeAtIndex(1))
}
else {
error = "UNKNOWN ERROR"
}
self.writeLog("Failed: \(error)")
}
else {
self.writeLog("Done")
}
}
}
}
}
func application(sender: NSApplication, openFile filename: String) -> Bool {
installApk(filename);
return true;
}
}