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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
|
/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import "ClientController.h"
#import "EDTCPSocket.h"
#import "Preferences.h"
#import "RendezvousUtils.h"
@implementation ClientController
idAccessor(socket, setSocket)
idAccessor(netConnection, setNetConnection)
idAccessor(rendezvousBrowser, setRendezvousBrowser)
-(id)init {
[super init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(readPropertyList:)
name:@"NetConnectionReadPropertyListNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(gotNetworkConnection:)
name:@"NetConnectionEstablishedNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkConnectionTerminated:)
name:@"NetConnectionTerminatedNotification"
object:nil];
rendezvousServers = [[NSMutableArray alloc] init];
return self;
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self setSocket:nil];
[self setNetConnection:nil];
[rendezvousServers release];
[super dealloc];
}
idAccessor(gameConfiguration, setGameConfiguration)
-(void)awakeFromNib {
isWindowExpanded = YES;
windowHeightDelta = [windowSizerField frame].origin.y * [window userSpaceScaleFactor_];
[self setUseRendezvousServer:NO];
[self setRendezvousEnabled:NO];
[rendezvousHostsPopup removeAllItems];
// kick off rendezvous discovery...
[self setupRendezvousDiscovery];
[connectionStatusField setStringValue:@"Not connected"];
[usernameField setStringValue:[[Preferences sharedInstance] networkUsername]];
[self showWindow];
}
-(void)showWindow {
[self setWindowExpanded:NO display:NO];
[connectionStatusField setStringValue:@""];
[windowSizerField setStringValue:@""];
[window makeKeyAndOrderFront:nil];
}
-(void)setupRendezvousDiscovery {
if (isRendezvousAvailable_()) {
id browser = [[[nsNetServiceBrowserClass_() alloc] init] autorelease];
[self setRendezvousBrowser:browser];
[browser setDelegate:self];
[browser searchForServicesOfType:@"_gridlock._tcp" inDomain:@""];
}
}
-(void)setUseRendezvousServer:(BOOL)value {
[rendezvousCheckbox setState:(value) ? NSOnState : NSOffState];
[hostnameCheckbox setState:(!value) ? NSOnState : NSOffState];
}
-(BOOL)useRendezvousServer {
return [rendezvousCheckbox state]==NSOnState;
}
-(void)setRendezvousEnabled:(BOOL)value {
[rendezvousCheckbox setEnabled:value];
[rendezvousHostsPopup setEnabled:value];
if (!value) {
[self setUseRendezvousServer:NO];
}
}
-(void)setWindowExpanded:(BOOL)isExp display:(BOOL)disp {
if (isExp && !isWindowExpanded) {
// expand
NSRect frame = [window frame];
[window setFrame:NSMakeRect(frame.origin.x, frame.origin.y-windowHeightDelta,
frame.size.width, frame.size.height+windowHeightDelta)
display:disp
animate:YES];
}
else if (!isExp && isWindowExpanded) {
// collapse
NSRect frame = [window frame];
[window setFrame:NSMakeRect(frame.origin.x, frame.origin.y+windowHeightDelta,
frame.size.width, frame.size.height-windowHeightDelta)
display:disp
animate:YES];
}
isWindowExpanded = isExp;
}
-(BOOL)hasExistingConnection {
// not very nice...
return ([[[[[NSApp delegate] gameController] gameState] allNetConnections] count]>0);
}
-(int)nextConnectionID {
return ++connectionIDCounter;
}
-(NSFileHandle *)connectToHostname:(NSString *)hostname port:(int)port {
EDTCPSocket *sock = [EDTCPSocket socket];
NS_DURING
[sock connectToHost:[NSHost hostWithName:hostname] port:port];
NSLog(@"Got connection");
NS_HANDLER
sock = nil;
NS_ENDHANDLER
return sock;
}
-(void)connectInNewThread:(NSDictionary *)dict {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
NSFileHandle *sock = [self connectToHostname:[dict objectForKey:@"hostname"]
port:[[dict objectForKey:@"port"] intValue]];
[resultDict setObject:[dict objectForKey:@"connectionID"] forKey:@"connectionID"];
if (sock) [resultDict setObject:sock forKey:@"socket"];
[self performSelectorOnMainThread:@selector(connectionCallback:)
withObject:resultDict
waitUntilDone:YES];
[pool release];
}
-(void)connectionCallback:(NSDictionary *)resultDict {
// ignore if we weren't waiting for this connection or if we already have one
if ([[resultDict objectForKey:@"connectionID"] intValue]!=waitingForConnectionID) return;
if ([self hasExistingConnection]) return;
if ([resultDict objectForKey:@"socket"]) {
[self setSocket:[resultDict objectForKey:@"socket"]];
[self setNetConnection:[NetConnection connectionWithSocket:[self socket]]];
[self sendConnectMessage];
}
else {
[self setSocket:nil];
[self setNetConnection:nil];
[connectionStatusField setStringValue:@"Unable to connect"];
}
}
-(void)cancelConnect:(id)sender {
if (waitingForConnectionID>0) {
waitingForConnectionID = 0;
[connectionStatusField setStringValue:@"Connect cancelled"];
}
}
- (IBAction)connect:(id)sender {
NSString *hostname = nil;
int port = 0;
[self updateUsername:nil];
if ([self hasExistingConnection]) {
[connectionStatusField setStringValue:@"Already connected"];
return;
}
if ([rendezvousCheckbox state]==NSOnState) {
id rendezvousService = [[rendezvousHostsPopup selectedItem] representedObject];
getHostAndPortForNetService_(rendezvousService, &hostname, &port);
NSLog(@"Using server info from Rendezvous: %@:%d", hostname, port);
}
else {
hostname = [hostField stringValue];
port = [portField intValue];
}
if ([hostname length] && port) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:hostname forKey:@"hostname"];
[dict setObject:[NSNumber numberWithInt:port] forKey:@"port"];
[dict setObject:[NSNumber numberWithInt:(waitingForConnectionID=[self nextConnectionID])] forKey:@"connectionID"];
[connectionStatusField setStringValue:@"Connecting..."];
[NSThread detachNewThreadSelector:@selector(connectInNewThread:) toTarget:self withObject:dict];
}
}
- (IBAction)connectMethodChanged:(id)sender {
if (sender==rendezvousCheckbox) {
[hostnameCheckbox setState:NSOffState];
}
else {
[rendezvousCheckbox setState:NSOffState];
}
}
- (IBAction)disconnect:(id)sender {
[[self socket] closeFile];
[self setSocket:nil];
[self setNetConnection:nil];
[connectionStatusField setStringValue:@"Not connected"];
//[self setWindowExpanded:NO display:YES];
}
- (IBAction)rendezvousHostSelected:(id)sender
{
}
-(void)sendConnectMessage {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"" forKey:@"connect"];
if ([passwordField stringValue]) [dict setObject:[passwordField stringValue] forKey:@"password"];
[dict setObject:[[Preferences sharedInstance] networkUsername] forKey:@"username"];
[netConnection transmitPropertyList:dict];
}
- (IBAction)startGame:(id)sender {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[self gameConfiguration], @"configuration",
[self netConnection], @"connection",
[NSNumber numberWithInt:1], @"playerNumber",
nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NetConnectionEstablishedNotification"
object:self userInfo:dict];
}
-(void)readPropertyList:(NSNotification *)notification {
if ([self netConnection]==[notification object]) {
id plist = [[notification userInfo] objectForKey:@"plist"];
if ([plist objectForKey:@"start"]) {
id configPlist = [plist objectForKey:@"configuration"];
NSString *username = [plist objectForKey:@"username"];
[[self netConnection] setRemoteUsername:username];
[self setGameConfiguration:[[[GameConfiguration alloc] initFromPropertyList:configPlist] autorelease]];
if ([self gameConfiguration]) {
[self startGame:nil];
}
else {
[self disconnect:nil];
[connectionStatusField setStringValue:@"Connection Error"];
}
}
else if ([plist objectForKey:@"refused"]) {
[self setSocket:nil];
[connectionStatusField setStringValue:@"Connection refused"];
//[self setWindowExpanded:NO display:YES];
}
}
}
-(IBAction)updateUsername:(id)sender {
[[Preferences sharedInstance] setNetworkUsername:[usernameField stringValue]];
}
// called when a connection is established (could be from connecting by this window or from server)
-(void)gotNetworkConnection:(NSNotification *)notification {
[self setSocket:nil];
[self setNetConnection:nil];
[window orderOut:nil];
waitingForConnectionID = 0;
}
-(void)networkConnectionTerminated:(NSNotification *)notification {
}
-(void)windowWillClose:(NSNotification *)notification {
if (window==[notification object]) {
[self cancelConnect:nil];
}
}
// Rendezvous delegate methods
-(void)netServiceBrowserWillSearch:(id)browser {
}
-(void)netServiceBrowser:(id)browser didFindService:(id)service moreComing:(BOOL)moreComing {
[service setDelegate:self];
[service resolve];
if (!moreComing) {
}
}
-(void)netServiceBrowser:(id)browser didRemoveService:(id)service moreComing:(BOOL)moreComing {
int index = [rendezvousHostsPopup indexOfItemWithRepresentedObject:service];
[rendezvousServers removeObject:service];
if (index>=0) [rendezvousHostsPopup removeItemAtIndex:index];
if ([rendezvousHostsPopup numberOfItems]==0) {
[self setRendezvousEnabled:NO];
}
}
-(void)netServiceBrowserDidStopSearch:(id)browser {
}
-(NSString *)displayNameForNetServiceName:(NSString *)serviceName {
// the name should have 4 fields separated by ':'
NSArray *fields = [serviceName componentsSeparatedByString:@":"];
if ([fields count]<4) return nil;
else {
NSString *game = [fields objectAtIndex:0];
NSString *variation = [fields objectAtIndex:1];
NSString *username = [fields objectAtIndex:2];
NSString *rendezvousID = [fields objectAtIndex:3];
if ([game length]==0 || [username length]==0 || [rendezvousID length]==0) return nil;
// if rendezvousID is the same as ours, it's our own server and we don't want to show it
if ([rendezvousID isEqual:rendezvousIdentifier_()]) return nil;
if ([variation length]>0) {
return [NSString stringWithFormat:@"%@ (%@) - %@", game, variation, username];
}
else {
return [NSString stringWithFormat:@"%@ - %@", game, username];
}
}
}
-(void)netServiceDidResolveAddress:(id)service {
NSString *displayName = [self displayNameForNetServiceName:[service name]];
NSString *ipaddr = nil;
int port = 0;
getHostAndPortForNetService_(service, &ipaddr, &port);
NSLog(@"Resolved service address:%@ port:%d", ipaddr, port);
if (displayName) {
[rendezvousServers addObject:service];
[rendezvousHostsPopup addItemWithTitle:displayName];
[[rendezvousHostsPopup lastItem] setRepresentedObject:service];
[self setRendezvousEnabled:YES];
}
}
@end
|