File: MConnectionPanel.m

package info (click to toggle)
mysql-query-browser 1.1.6-1sarge0
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 36,320 kB
  • ctags: 24,680
  • sloc: pascal: 203,479; xml: 136,561; ansic: 47,502; cpp: 28,926; sh: 12,433; objc: 4,823; java: 1,849; php: 1,485; python: 1,225; sql: 1,128; makefile: 872
file content (675 lines) | stat: -rw-r--r-- 17,611 bytes parent folder | download
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
#import "MConnectionPanel.h"
#import "MDialogs.h"
#import "MPreferences.h"
#include "myxutil.h"
#import "MPreferenceEditor.h"

#include <mysqld_error.h>


@interface MConnectionPanel(Private)
- (void)setEnabled: (BOOL)flag;
- (void)controlTextDidChange:(NSNotification *)aNotification;

- (void)showConnectionError: (MYSQL*)mysql
                       info: (MYX_USER_CONNECTION*)info;


- (void)connectionFinished: (id)result;

- (void)checkConnectOK;
- (MYX_USER_CONNECTION*)getDisplayedConnection;
- (void)displayConnection:(MYX_USER_CONNECTION*)info;
- (void)fillConnectionPopUp:(BOOL)selectLast;
- (void)startConnection: (MYX_USER_CONNECTION*)connectionInfo;

- (void)showConnectionEditor:(id)sender;
- (void)saveConnection:(id)sender;

- (void)finish;
@end


@implementation MConnectionPanel(Private)

- (void)finish
{
  int rc;
  MYX_USER_CONNECTION *info= NULL;

  if (_mysql && myx_mysql_errno(_mysql)==0)
  {
    MYX_USER_CONNECTION *conn= [self getDisplayedConnection];
    
    info= myx_copy_user_connection(conn);
    rc= 1;
    
    // save
    if (conn && !conn->connection_name)
    {
      int i;
      // look for connection with same contents
      for (i= 0; i < _connections->user_connections_num; i++)
      {
        if (!_connections->user_connections[i].connection_name)
        {
          if (myx_same_user_connections(conn, _connections->user_connections+i))
          {
            _connections->last_connection= i;
            break;
          }
        }
      }
      if (i == _connections->user_connections_num)
        _connections->last_connection= myx_add_user_connection(&_connections, conn);
    }
    else
    {
      _connections->last_connection= myx_add_user_connection(&_connections, conn);
    }
    //XXX check return value
    myx_store_user_connections(_connections,[MPreferences preferences]->passwordStorageType,
                               [_connectionsFile fileSystemRepresentation]);
  }
  else if (_mysql)
  {
    NSLog(@"connected with errno %i", myx_mysql_errno(_mysql));
    myx_mysql_close(_mysql);
    _mysql= NULL;
    rc= -1;
  }
  else
    rc= 0;
  [[self window] close];

  if (rc > 0)
    [_delegate connectionPanel:self finished:_mysql info:info];
  else
    [_delegate connectionPanel:self aborted:(rc<0?YES:NO)];
}


- (void)setEnabled: (BOOL)flag
{
  [connectButton setEnabled: flag];
  [detailsButton setEnabled: flag];
  
  [hostname setEnabled: flag];
  [password setEnabled: flag];
  [username setEnabled: flag];
  [port setEnabled: flag];
  [portSpin setEnabled: flag];
}


- (void)connectionFinished: (id)result
{  
  int err;
  
  _connecting= NO;

  [progressIndicator stopAnimation: self];
  [self setEnabled: YES];
  
  if (_mysql)
    myx_mysql_close(_mysql);
  _mysql= [[result valueForKey:@"mysql"] pointerValue];
  
  if (!_mysql)
  {
    NSRunAlertPanelRelativeToWindow(@"Error",
                                    @"Could not initialize MySQL connection.",
                                    @"OK", nil, nil, [self window]);
  }
  else if ((err= myx_mysql_errno(_mysql))!=0)
  {
    [self showConnectionError: _mysql
                         info: [[result valueForKey:@"info"] pointerValue]];
    if (_mysql)
      myx_mysql_close(_mysql);
    _mysql= NULL;
    
    switch (err)
    {
      case ER_ACCESS_DENIED_ERROR:
        [[self window] makeFirstResponder:password];
        break;
    }
  }
  else
  {
    [self finish];
  }
  [result release];
}


- (void)connectThread: (id)info
{
  MYSQL *mysql;
  NSDictionary *result;
  BOOL ok= YES;
  id tmp;
  
  mysql= myx_mysql_init();

  if (myx_connect_to_instance([info pointerValue], mysql) < 0)
    ok= NO;
  
  tmp= [[NSValue alloc] initWithBytes:&mysql objCType:@encode(void *)];
  result= [[NSDictionary alloc] initWithObjectsAndKeys:
    tmp, @"mysql", info, @"info", 0];

  [self performSelectorOnMainThread:@selector(connectionFinished:)
                          withObject:result
                       waitUntilDone:NO];
}


- (void)startConnection: (MYX_USER_CONNECTION*)connectionInfo
{
  if (!_connecting)
  {
    [NSThread detachNewThreadSelector: @selector(connectThread:)
                             toTarget: self
                           withObject: [NSValue valueWithPointer:connectionInfo]];
  }
}


- (MYX_USER_CONNECTION*)getDisplayedConnection
{
  id item= [connectionPopUp selectedItem];

  if (item && [item representedObject])
  {
    MYX_USER_CONNECTION *conn= [[item representedObject] pointerValue];

    if (conn)
    {
      g_free(conn->password);
      conn->password= g_strdup([[password stringValue] UTF8String]);
    }
    return conn;
  }
  else
  { 
    unsigned int i;
    
    g_free(_new_connection.username);
    _new_connection.username= g_strdup([[username stringValue] UTF8String]);
    g_free(_new_connection.password);
    _new_connection.password= g_strdup([[password stringValue] UTF8String]);
    g_free(_new_connection.hostname);
    _new_connection.hostname= g_strdup([[hostname stringValue] UTF8String]);
    _new_connection.port= [port intValue];
    _new_connection.storage_type= MYX_HISTORY_USER_CONNECTION;

    for (i= 0; i < _new_connection.advanced_options_num; i++)
      g_free(_new_connection.advanced_options[i]);
    
    if (_new_connection.advanced_options)
      g_free(_new_connection.advanced_options);
    
    _new_connection.advanced_options= g_new0(char*, 1);
    
    i= 0;
    if ([[socketText stringValue] length] > 0)
      _new_connection.advanced_options[i++]= g_strdup_printf("SOCKET_PATH=%s", 
                                                             [[socketText stringValue] UTF8String]);
    _new_connection.advanced_options_num= i;
    
    return &_new_connection;
  }
}

- (void)displayConnection:(MYX_USER_CONNECTION*)info
{
  if (info)
  {
    [username setStringValue: [NSString stringWithUTF8String: info->username?:""]];
    [password setStringValue: [NSString stringWithUTF8String: info->password?:""]];
    [hostname setStringValue: [NSString stringWithUTF8String: info->hostname?:""]];
    [port setIntValue: info->port];
    
    [socketText setStringValue: 
      [NSString stringWithUTF8String: 
        myx_get_option_value((const char**)info->advanced_options,
                             info->advanced_options_num,
                             "SOCKET_PATH") ? : ""]];
  }
}

- (void)fillConnectionPopUp:(BOOL)selectLast
{
  unsigned int i;
  id selectItem= nil;
  id item;
  
  [connectionPopUp removeAllItems];
  [connectionPopUp addItemWithTitle:@""];
  
  for (i= 0; i < _connections->user_connections_num; i++)
  {
    MYX_USER_CONNECTION *conn= _connections->user_connections+i;
    if (conn->connection_name && conn->storage_type == MYX_FAVORITE_USER_CONNECTION)
    {
      NSString *name= [NSString stringWithUTF8String: conn->connection_name];
      // dont add duplicated items
      if ([connectionPopUp itemWithTitle:name]!=nil)
      {
        if (i== _connections->last_connection)
          selectItem= [connectionPopUp itemWithTitle:name];
        continue;
      }
      
      [connectionPopUp addItemWithTitle: name];
      
      [[connectionPopUp lastItem] setRepresentedObject: [NSValue valueWithPointer: conn]];
      if (i == _connections->last_connection)
      {
        selectItem= [connectionPopUp lastItem];
      }
    } 
    else
    {
      if (i == _connections->last_connection)
      {
        [connectionPopUp insertItemWithTitle:@"(last connection)"
                                     atIndex:1];
        [(selectItem= [connectionPopUp itemAtIndex: 1]) setRepresentedObject:
          [NSValue valueWithPointer: conn]];
      }
    }
  }
  
  [[connectionPopUp menu] addItem: [NSMenuItem separatorItem]];

  [connectionPopUp addItemWithTitle: @"Save Connection..."];
  item= [connectionPopUp lastItem];
  [item setTarget: self];
  [item setAction: @selector(saveConnection:)];

  [connectionPopUp addItemWithTitle: @"Open Connection Editor..."];
  item = [connectionPopUp lastItem];
  [item setAction: @selector(showConnectionEditor:)];
  [item setTarget: self];

  if (selectItem && selectLast)
  {
    [connectionPopUp selectItem:selectItem];
    [self connectionChanged:self];
  }
}


- (void)controlTextDidChange:(NSNotification *)aNotification
{
  NSString *old= [[aNotification object] stringValue];
  
  [self checkConnectOK];
  [connectionPopUp selectItemAtIndex:0];

  [[aNotification object] setStringValue:old];
}

- (void)checkConnectOK
{
  if ([[username stringValue] length] > 0
      && [[hostname stringValue] length] > 0)
    [connectButton setEnabled: YES];
  else
    [connectButton setEnabled: NO];
}

- (void)showConnectionError: (MYSQL*)mysql
                       info: (MYX_USER_CONNECTION*)info
{
  NSRect f= [errorPanel frame];
  f.size= [errorPanel minSize];
  
  [pingTextContainer setHidden: YES];
  
  [errorText setStringValue: 
    [NSString stringWithFormat: @"Could not connect to MySQL instance at %s.\nError: %s (code %i)",
      info->hostname, myx_mysql_error(mysql), myx_mysql_errno(mysql)]];

  [errorPanel setFrame: f
               display: YES];
  
  [NSApp runModalForWindow: errorPanel];
}


- (void)showConnectionEditor:(id)sender
{
  MPreferenceEditor *editor= [[MPreferenceEditor alloc] initForConnectionsFile:_connectionsFile];
  MYX_USER_CONNECTIONS *conns;
  MYX_LIB_ERROR error;
  
  [editor runConnectionEditor];
  
  conns= myx_load_user_connections([_connectionsFile cString], &error);
  if (conns)
  {
    myx_free_user_connections(_connections);
    _connections= conns;
  }

  [connectionPopUp selectItemAtIndex:_lastSelectedConnection];
  [self fillConnectionPopUp:YES];
  
  [editor release];
}


- (void)saveConnection:(id)sender
{
  MStringRequestSheet *sheet= [MStringRequestSheet sheetWithTitle:@"Save this connection for later use."
														   labels:[NSArray arrayWithObject:@"Connection Name:"]];
  NSArray *name;

  [connectionPopUp selectItemAtIndex:0];
  
  name= [sheet runModal:[self window]];
  
  if (name && [(NSString*)[name objectAtIndex:0] length]>0)
  {
    unsigned int i;
    const char *sname= [[name objectAtIndex:0] UTF8String];
    for (i= 0; i < _connections->user_connections_num; i++)
    {
      if (strcmp2(sname, _connections->user_connections[i].connection_name)==0)
        break;
    }
    if (_connections->user_connections_num != i)
    {
      NSRunAlertPanel(@"Error", @"The given name is already used by another connection.",
                      nil, nil, nil);
    }
    else
    {
      MYX_USER_CONNECTION *conn= [self getDisplayedConnection];
      
      if (conn->connection_name)
        g_free(conn->connection_name);
      conn->connection_name= g_strdup([[name objectAtIndex:0] UTF8String]);
      conn->storage_type= MYX_FAVORITE_USER_CONNECTION;

      myx_add_user_connection(&_connections, conn);
      
      myx_store_user_connections(_connections, [MPreferences preferences]->passwordStorageType,
                                 [_connectionsFile fileSystemRepresentation]);
      
      [self fillConnectionPopUp:NO];

      [connectionPopUp selectItemWithTitle:[NSString stringWithUTF8String:conn->connection_name]];
    }
  }  
}

@end

//==========================================================================

@implementation MConnectionPanel

+ (NSString*)representationForConnection:(MYX_USER_CONNECTION*)conn
{
  if (conn->connection_name)
    return [NSString stringWithUTF8String:conn->connection_name];
  else
    return [NSString stringWithFormat:@"%s@%s", conn->username, conn->hostname];
}


- (id)initWithConnectionsFile:(NSString*)file
{
  MYX_LIB_ERROR error;

  self= [super initWithWindowNibName: @"ConnectPanel"];
  
  _connectionsFile= [file retain];
  _connections= myx_load_user_connections([file cString], &error);
  if (!_connections)
  {
    if (error != MYX_ERROR_CANT_OPEN_FILE)
      NSLog(@"Could not load user connections file");
    _connections= g_malloc0(sizeof(MYX_USER_CONNECTIONS));
  }
  
  _connecting= NO;
  _mysql= NULL;
  memset(&_new_connection, 0, sizeof(MYX_USER_CONNECTION));
  
  return self;
}

- (void)awakeFromNib
{
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(errorPanelWillClose:)
                                               name:NSWindowWillCloseNotification
                                             object:errorPanel];
}

- (void)dealloc
{
  [_connectionsFile release];
  if (_connections)
    myx_free_user_connections(_connections);
  myx_free_user_connection_content(&_new_connection);
  [[NSNotificationCenter defaultCenter] removeObserver: self];
  
  if (pingPipe) [pingPipe release];
  if (pingTask) 
  {
    [pingTask terminate]; 
    [pingTask release];
  }
  if (pingPipeHandle) [pingPipeHandle release];
  
  [super dealloc];
}

- (IBAction)cancel:(id)sender
{
  if (!_connecting)
  {
    [self finish];
  }
}


- (IBAction)connect:(id)sender
{
  MYX_USER_CONNECTION *conn;
  
  // typing a password and then clicking on Connect doesnt work
  // unless we call this here...
  [password stringValue];
  
  [progressIndicator startAnimation: self];

  [self setEnabled: NO];

  conn= [self getDisplayedConnection];

  if (conn)
    [self startConnection: conn];
}

- (IBAction)connectionChanged:(id)sender
{
  id pitem= [connectionPopUp selectedItem];
  id item= [pitem representedObject];
  MYX_USER_CONNECTION *conn= [item pointerValue];
  
  if (conn)
    [self displayConnection:conn];
  [self checkConnectOK];
  
  _lastSelectedConnection= [connectionPopUp indexOfItem:pitem];
}

- (IBAction)toggleDetails:(id)sender
{
  NSRect frame= [[self window] frame];
  NSSize newSize;
  BOOL flag;
  
  if ([detailsButton state])
  {
    flag= NO;
    newSize= [[self window] maxSize];
  }
  else
  {
    flag= YES;
    newSize= [[self window] minSize];
  }
  
  frame.origin.y += (frame.size.height - newSize.height);
  frame.size= newSize;

  if (flag)
    [[self window] setFrame:frame display:YES animate:YES];
  [extraView setHidden:flag];
  if (!flag)
    [[self window] setFrame:frame display:YES animate:YES];
}

- (void)windowDidLoad
{
  // fill list of saved connections
  [self fillConnectionPopUp:YES];

  [self checkConnectOK];
}

- (void)show
{ 
  [self showWindow: self];  
}


- (void)showAndConnectTo:(NSString*)connection
{
  unsigned int i;
  
  for (i= 0; i < _connections->user_connections_num; i++)
  {
    if (_connections->user_connections[i].connection_name &&
        strcmp([connection UTF8String], _connections->user_connections[i].connection_name)==0)
    {
      [connectionPopUp selectItem:[connectionPopUp itemWithTitle:connection]];
      break;
    }
    if (!_connections->user_connections[i].connection_name &&
        [connection isEqualTo:[NSString stringWithFormat:@"%s@%s",
          _connections->user_connections[i].username,
          _connections->user_connections[i].hostname]])
    {
      [connectionPopUp selectItemAtIndex:0];
      [self displayConnection:_connections->user_connections+i];
      break;
    }
  }
  
  [self show];
  
  if (i < _connections->user_connections_num)
  {
    [self connect:nil];
  }
}

- (void)setDelegate:(id)deleg
{
  _delegate= deleg;
}

- (void)setHeaderImage:(NSImage*)image
{
  [topImage setImage: image];
}

// --------------------------

- (void)handlePingData:(NSNotification*)notif
{
  NSDictionary *userInfo= [notif userInfo];
  NSString *str= [[NSString alloc] initWithData:[userInfo objectForKey:@"NSFileHandleNotificationDataItem"]
                                       encoding: NSUTF8StringEncoding];

  [[pingText textStorage] appendAttributedString:[[[NSAttributedString alloc] initWithString: str] autorelease]];
  
  [pingText scrollPageDown:nil];
  [str release];
  
  [pingPipeHandle readInBackgroundAndNotifyForModes:[NSArray arrayWithObject:NSModalPanelRunLoopMode]];
}


- (IBAction)pingHost:(id)sender
{
  if (!pingTask)
  {
    NSRect f= [errorPanel frame];
    f.origin.y+= (f.size.height - [errorPanel maxSize].height);
    f.size= [errorPanel maxSize];
    
    [pingTextContainer setHidden: NO];
  
    [errorPanel setFrame: f
                 display: YES
                 animate: YES];
    
    pingPipe= [[NSPipe alloc] init];
    pingPipeHandle= [[pingPipe fileHandleForReading] retain];
    
    pingTask= [[NSTask alloc] init];
    [pingTask setLaunchPath:@"/sbin/ping"];
    [pingTask setArguments:[NSArray arrayWithObjects:[hostname stringValue], nil]];
    [pingTask setStandardOutput:pingPipe];
    [pingTask setStandardError:pingPipe];

    [pingTask launch];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handlePingData:)
                                                 name:NSFileHandleReadCompletionNotification
                                               object:pingPipeHandle];
    
    [pingPipeHandle readInBackgroundAndNotifyForModes:[NSArray arrayWithObject: NSModalPanelRunLoopMode]];
  }
}


- (IBAction)closeErrorPanel:(id)sender
{
  [pingTask terminate];
  [pingTask release];
  pingTask= nil;
  [pingPipe release];
  pingPipe= nil;
  [pingPipeHandle release];
  pingPipeHandle= nil;

  [[NSNotificationCenter defaultCenter] removeObserver:self
                                                  name:NSFileHandleReadCompletionNotification
                                                object:pingPipeHandle];

  [NSApp stopModal];
  if (sender != nil) // ie, not being called from the notif. observer
    [errorPanel close];
}


- (void)errorPanelWillClose:(NSNotification*)notif
{
  [self closeErrorPanel:nil];
}


@end