forked from laullon/gitx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPBWebController.m
247 lines (201 loc) · 7.63 KB
/
PBWebController.m
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//
// PBWebController.m
// GitX
//
// Created by Pieter de Bie on 08-10-08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "PBWebController.h"
#import "PBGitRepository.h"
#import "PBGitXProtocol.h"
#import "PBGitDefaults.h"
#include <SystemConfiguration/SCNetworkReachability.h>
@interface PBWebController()
- (void)preferencesChangedWithNotification:(NSNotification *)theNotification;
@end
@implementation PBWebController
@synthesize startFile, repository;
- (void) awakeFromNib
{
callbacks = [NSMapTable mapTableWithKeyOptions:(NSPointerFunctionsObjectPointerPersonality|NSPointerFunctionsStrongMemory) valueOptions:(NSPointerFunctionsObjectPointerPersonality|NSPointerFunctionsStrongMemory)];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(preferencesChangedWithNotification:)
name:NSUserDefaultsDidChangeNotification
object:nil];
finishedLoading = NO;
[view setUIDelegate:self];
[view setFrameLoadDelegate:self];
[view setResourceLoadDelegate:self];
NSURL *resourceURL = [[[NSBundle mainBundle] resourceURL] URLByStandardizingPath];
NSURL *baseURL = [[resourceURL URLByAppendingPathComponent:@"html/views"] URLByAppendingPathComponent:startFile];
NSURL *fileURL = [baseURL URLByAppendingPathComponent:@"index.html"];
[[view mainFrame] loadRequest:[NSURLRequest requestWithURL:fileURL]];
}
- (WebScriptObject *) script
{
return [view windowScriptObject];
}
- (void)closeView
{
if (view) {
[[self script] setValue:nil forKey:@"Controller"];
[view close];
}
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
# pragma mark Delegate methods
- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowObject forFrame:(WebFrame *)frame
{
id script = [view windowScriptObject];
[script setValue: self forKey:@"Controller"];
}
- (void) webView:(id) v didFinishLoadForFrame:(id) frame
{
finishedLoading = YES;
if ([self respondsToSelector:@selector(didLoad)])
[self performSelector:@selector(didLoad)];
}
- (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)dictionary
{
DLog(@"Error from webkit: %@", dictionary);
}
- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame
{
DLog(@"Message from webkit: %@", message);
}
- (NSURLRequest *)webView:(WebView *)sender
resource:(id)identifier
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
fromDataSource:(WebDataSource *)dataSource
{
if (!self.repository)
return request;
// TODO: Change this to canInitWithRequest
NSString *scheme = [[[request URL] scheme] lowercaseString];
if ([scheme isEqualToString:@"gitx"]) {
NSMutableURLRequest *newRequest = [request mutableCopy];
[newRequest setRepository:self.repository];
return newRequest;
}
return request;
}
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector
{
return NO;
}
+ (BOOL)isKeyExcludedFromWebScript:(const char *)name {
return NO;
}
#pragma mark Functions to be used from JavaScript
- (void) log: (NSString*) logMessage
{
DLog(@"%@", logMessage);
}
- (BOOL) isReachable:(NSString *)hostname
{
SCNetworkReachabilityRef target;
SCNetworkConnectionFlags flags = 0;
Boolean reachable;
target = SCNetworkReachabilityCreateWithName(NULL, [hostname cStringUsingEncoding:NSASCIIStringEncoding]);
reachable = SCNetworkReachabilityGetFlags(target, &flags);
CFRelease(target);
if (!reachable)
return FALSE;
// If a connection is required, then it's not reachable
if (flags & (kSCNetworkFlagsConnectionRequired | kSCNetworkFlagsConnectionAutomatic | kSCNetworkFlagsInterventionRequired))
return FALSE;
return flags > 0;
}
- (BOOL) isFeatureEnabled:(NSString *)feature
{
if([feature isEqualToString:@"gravatar"])
return [PBGitDefaults isGravatarEnabled];
else if([feature isEqualToString:@"gist"])
return [PBGitDefaults isGistEnabled];
else if([feature isEqualToString:@"confirmGist"])
return [PBGitDefaults confirmPublicGists];
else if([feature isEqualToString:@"publicGist"])
return [PBGitDefaults isGistPublic];
else
return YES;
}
- (void) openGitHub:(NSString*)sha;
{
NSLog(@"PBWebController::openGitHub()");
// assuming "origin" here
if (![repository hasRemotes]) {
NSLog(@"Repository has no remotes");
return;
}
NSString* remote = [repository URLsForRemote:@"origin"][0];
NSLog(@"Remote URL: %@", remote);
// TODO: should also support http:// github urls
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[email protected]:(.+)\\.git" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:remote options:0 range:NSMakeRange(0, [remote length])];
NSString* path = [remote substringWithRange:[match rangeAtIndex:1]];
if (![path length]) {
NSLog(@"Origin does not seem to be a github repo?");
return;
}
NSString* fullurl = [NSString stringWithFormat:@"https://github.com/%@/commit/%@", path, sha];
NSLog(@"Full repo URL: %@", fullurl);
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:fullurl]];
}
#pragma mark Using async function from JS
- (void) runCommand:(WebScriptObject *)arguments inRepository:(PBGitRepository *)repo callBack:(WebScriptObject *)callBack
{
// The JS bridge does not handle JS Arrays, even though the docs say it does. So, we convert it ourselves.
int length = [[arguments valueForKey:@"length"] intValue];
NSMutableArray *realArguments = [NSMutableArray arrayWithCapacity:length];
int i = 0;
for (i = 0; i < length; i++)
[realArguments addObject:[arguments webScriptValueAtIndex:i]];
NSFileHandle *handle = [repo handleInWorkDirForArguments:realArguments];
[callbacks setObject:callBack forKey:handle];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(JSRunCommandDone:) name:NSFileHandleReadToEndOfFileCompletionNotification object:handle];
[handle readToEndOfFileInBackgroundAndNotify];
}
- (void) callSelector:(NSString *)selectorString onObject:(id)object callBack:(WebScriptObject *)callBack
{
NSArray *arguments = [NSArray arrayWithObjects:selectorString, object, nil];
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(runInThread:) object:arguments];
[callbacks setObject:callBack forKey:thread];
[thread start];
}
- (void) runInThread:(NSArray *)arguments
{
SEL selector = NSSelectorFromString([arguments objectAtIndex:0]);
id object = [arguments objectAtIndex:1];
id ret = [object performSelector:selector];
NSArray *returnArray = [NSArray arrayWithObjects:[NSThread currentThread], ret, nil];
[self performSelectorOnMainThread:@selector(threadFinished:) withObject:returnArray waitUntilDone:NO];
}
- (void) returnCallBackForObject:(id)object withData:(id)data
{
WebScriptObject *a = [callbacks objectForKey: object];
if (!a) {
DLog(@"Could not find a callback for object: %@", object);
return;
}
[callbacks removeObjectForKey:object];
[a callWebScriptMethod:@"call" withArguments:[NSArray arrayWithObjects:@"", data, nil]];
}
- (void) threadFinished:(NSArray *)arguments
{
[self returnCallBackForObject:[arguments objectAtIndex:0] withData:[arguments objectAtIndex:1]];
}
- (void) JSRunCommandDone:(NSNotification *)notification
{
NSString *data = [[NSString alloc] initWithData:[[notification userInfo] valueForKey:NSFileHandleNotificationDataItem] encoding:NSUTF8StringEncoding];
[self returnCallBackForObject:[notification object] withData:data];
}
- (void) preferencesChanged
{
}
- (void)preferencesChangedWithNotification:(NSNotification *)theNotification
{
[self preferencesChanged];
}
@end