bb456efbab89d9df0bd7427527de770ea35a8a8c
[ovirt-viewer.git] / main.c
1 /* ovirt viewer console application
2  * Copyright (C) 2008 Red Hat Inc.
3  * Written by Richard W.M. Jones <rjones@redhat.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25
26 #include <glib.h>
27 #include <gtk/gtk.h>
28 #include <vncdisplay.h>
29
30 #ifdef HAVE_NETDB_H
31 #include <netdb.h>
32 #endif
33
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
40 #endif
41
42 #ifdef HAVE_SYS_UN_H
43 #include <sys/un.h>
44 #endif
45
46 #ifdef HAVE_WINDOWS_H
47 #include <windows.h>
48 #endif
49
50 #include "internal.h"
51
52 /*#define HTTPS "https"*/
53 #define HTTPS "http"
54
55 gboolean debug = 0;
56
57 /* Usually /etc/pki/tls/certs/ca-bundle.crt unless overridden during
58  * configure or on the command line.
59  */
60 const char *cainfo = CAINFO;
61 gboolean check_cert = FALSE; // do we want this enabled by default ?
62                       // would require a CA by default (self-signed wont work)
63                       // (don't set to true, change var/flag to no_check_cert)
64
65 /* Private functions. */
66 static void start_ui (void);
67 static GtkWidget *menu_item_new (int which_menu);
68 static void refresh_menu_vm_list (GtkWidget *, gpointer);
69 static void connect_to_wui_on_enter (GtkWidget *, gpointer);
70 static void connect_to_wui (GtkWidget *, gpointer);
71 static void login_to_wui_on_enter (GtkWidget *, gpointer);
72 static void login_to_wui (GtkWidget *, gpointer);
73 static gboolean delete_event (GtkWidget *widget, GdkEvent *event, gpointer data);
74 static void destroy (GtkWidget *widget, gpointer data);
75 static void clear_connectmenu (void);
76 static void help_about (GtkWidget *menu);
77 static void viewer_shutdown (GtkWidget *src, void *dummy, GtkWidget *vnc);
78 #if 0
79 static void viewer_quit (GtkWidget *src, GtkWidget *vnc);
80 #endif
81 static void viewer_connected (GtkWidget *vnc);
82 static void viewer_initialized (GtkWidget *vnc, GtkWidget *data);
83 static void viewer_disconnected (GtkWidget *vnc);
84 static void viewer_credential (GtkWidget *vnc, GValueArray *credList);
85 static int viewer_open_vnc_socket (const char *vnchost, int vncport);
86
87 /* For any widgets accessed from multiple functions. */
88 static GtkWidget *window;
89 static GtkWidget *connectitem;
90 static GtkWidget *connectmenu;
91 static GtkWidget *no_connections;
92 static GtkWidget *refresh_vmlist;
93 static GtkWidget *refresh_vmlist_separator;
94 static GtkWidget *connection_area;
95 static GtkWidget *ca_hostname;
96 static GtkWidget *ca_button;
97 static GtkWidget *ca_error;
98 static GtkWidget *login_area;
99 static GtkWidget *la_username;
100 static GtkWidget *la_password;
101 static GtkWidget *la_button;
102 static GtkWidget *la_error;
103 static GtkWidget *notebook;
104 static GtkWidget *statusbar;
105 static guint statusbar_ctx;
106 static GdkCursor *busy_cursor;
107
108 /* Menus. */
109 enum menuNums {
110   CONNECT_MENU,
111   VIEW_MENU,
112   SEND_KEY_MENU,
113   WINDOW_MENU,
114   HELP_MENU,
115 };
116
117 struct menuItem {
118   guint menu;
119   GtkWidget *label;
120   const char *ungrabbed_text;
121   const char *grabbed_text;
122 };
123
124 static struct menuItem menuItems[] = {
125   { CONNECT_MENU, NULL, "_Connect", "Connect" },
126   { VIEW_MENU, NULL, "_View", "View" },
127   { SEND_KEY_MENU, NULL, "_Send Key", "Send Key" },
128   { WINDOW_MENU, NULL, "_Window", "Window" },
129   { HELP_MENU, NULL, "_Help", "Help" }
130 };
131
132 /* Window title. */
133 static const char *title = "oVirt Viewer";
134
135 // when running vm
136 // 47 chars
137 static const char *title_vm =
138    "oVirt Viewer: (ctrl+alt to grab/release mouse) ";
139
140 /* Gtk widget styles.  Avoid installation hassles by keeping this
141  * inside the binary.  It can still be overridden by the user (who
142  * will do that?)
143  */
144 static const char *styles =
145   "style \"ovirt-viewer-yellow-box\"\n"
146   "{\n"
147   "  bg[NORMAL] = shade (1.5, \"yellow\")\n"
148   "}\n"
149   "widget \"*.ovirt-viewer-connection-area\" style \"ovirt-viewer-yellow-box\"\n"
150   ;
151
152 /* Command-line arguments. */
153 static int print_version = 0;
154
155 static const char *help_msg =
156   "Use '" PACKAGE " --help' to see a list of available command line options";
157
158 static const GOptionEntry options[] = {
159   { "cainfo", 0, 0, G_OPTION_ARG_STRING, &cainfo,
160     "set the path of the CA certificate bundle", NULL },
161   { "check-certificate", 0, 0, G_OPTION_ARG_NONE, &check_cert,
162     "check the SSL certificate of the server", NULL },
163   { "debug", 'd', 0, G_OPTION_ARG_NONE, &debug,
164     "turn on debugging messages", NULL },
165   { "version", 'V', 0, G_OPTION_ARG_NONE, &print_version,
166     "display version and exit", NULL },
167   { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
168 };
169
170 int
171 main (int argc, char *argv[])
172 {
173   GOptionContext *context;
174   GError *error = NULL;
175
176   /* Initialize GLib threads before anything else.
177    *
178    * There is one main thread, which is used for all Gtk interactions
179    * and to keep the UI responsive, and one WUI thread.  The WUI
180    * thread is used to connect to the WUI, log in, and maintain the list
181    * of virtual machines.  The WUI thread is the only thread allowed
182    * to use the CURL library.
183    *
184    * The main thread sends instructions to the WUI thread (like "connect",
185    * "disconnect", etc.) using a simple message-passing protocol and
186    * a GAsyncQueue.
187    *
188    * The WUI thread keeps the UI updated by adding idle events which are
189    * processed in the main thread - see:
190    * http://mail.gnome.org/archives/gtk-app-devel-list/2007-March/msg00232.html
191    *
192    * Note that under Win32 you must confine all Gtk/Gdk interactions
193    * to a single thread - see:
194    * http://developer.gimp.org/api/2.0/gdk/gdk-Threads.html
195    */
196   if (!g_thread_supported ()) {
197     g_thread_init (NULL);
198 #ifndef WIN32
199     gdk_threads_init ();
200 #endif
201   } else {
202     fprintf (stderr, "GLib threads not supported or not working.");
203     exit (1);
204   }
205
206   gtk_init (&argc, &argv);
207
208   /* Parse command-line options. */
209   context = g_option_context_new ("oVirt viewer");
210   g_option_context_add_main_entries (context, options, NULL);
211   g_option_context_add_group (context, gtk_get_option_group (TRUE));
212   g_option_context_add_group (context, vnc_display_get_option_group ());
213   g_option_context_parse (context, &argc, &argv, &error);
214
215   if (error) {
216     g_print ("%s\n%s\n", error->message, help_msg);
217     g_error_free (error);
218     exit (1);
219   }
220
221   if (print_version) {
222     printf ("%s %s\n", PACKAGE, VERSION);
223     exit (0);
224   }
225
226   start_wui_thread ();
227   start_ui ();
228
229   DEBUG ("entering the Gtk main loop");
230
231   gtk_main ();
232
233   stop_wui_thread ();
234
235   exit (0);
236 }
237
238 /* Create the viewer window, menus. */
239 static void
240 start_ui (void)
241 {
242   GtkWidget *vbox;
243   GtkWidget *menubar;
244   GtkWidget *view;
245   GtkWidget *viewmenu;
246   GtkWidget *sendkey;
247   GtkWidget *sendkeymenu;
248   GtkWidget *wind;
249   GtkWidget *windmenu;
250   GtkWidget *help;
251   GtkWidget *helpmenu;
252   GtkWidget *about;
253   GtkWidget *ca_vbox;
254   GtkWidget *ca_hbox;
255   GtkWidget *ca_label;
256   GtkWidget *la_vbox;
257   GtkWidget *la_hbox;
258   GtkWidget *la_label;
259
260   DEBUG ("creating viewer windows and menus");
261
262   /* Parse styles. */
263   gtk_rc_parse_string (styles);
264
265   /* Busy cursor, used by main_busy() function.
266    * XXX This cursor is crap - how can we use the Bluecurve/theme cursor?
267    */
268   busy_cursor = gdk_cursor_new (GDK_WATCH);
269
270   /* Window. */
271   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
272   gtk_window_set_default_size (GTK_WINDOW (window), 800, 600);
273   gtk_window_set_resizable (GTK_WINDOW (window), TRUE);
274   gtk_window_set_title (GTK_WINDOW (window), title);
275
276   g_signal_connect (G_OBJECT (window), "delete_event",
277                     G_CALLBACK (delete_event), NULL);
278   g_signal_connect (G_OBJECT (window), "destroy",
279                     G_CALLBACK (destroy), NULL);
280
281   /* VBox for layout within the window. */
282   vbox = gtk_vbox_new (FALSE, 0);
283
284   /* Menubar. */
285   menubar = gtk_menu_bar_new ();
286   connectitem = menu_item_new (CONNECT_MENU);
287   connectmenu = gtk_menu_new ();
288   gtk_menu_item_set_submenu (GTK_MENU_ITEM (connectitem), connectmenu);
289
290   no_connections = gtk_menu_item_new_with_label ("Not connected");
291   gtk_menu_append (GTK_MENU (connectmenu), no_connections);
292   gtk_widget_set_sensitive (no_connections, FALSE);
293
294   /* This is not added to the menu yet, but will be when we are
295    * connected.
296    */
297   refresh_vmlist =
298     gtk_menu_item_new_with_label ("Refresh list of virtual machines");
299   g_object_ref (refresh_vmlist);
300   refresh_vmlist_separator = gtk_separator_menu_item_new ();
301   g_object_ref (refresh_vmlist_separator);
302
303   g_signal_connect (G_OBJECT (refresh_vmlist), "activate",
304                     G_CALLBACK (refresh_menu_vm_list), NULL);
305
306 #if 0
307   screenshot = gtk_menu_item_new_with_mnemonic ("_Screenshot");
308   gtk_menu_append (GTK_MENU (filemenu), screenshot);
309   g_signal_connect (screenshot, "activate",
310                     GTK_SIGNAL_FUNC (take_screenshot), NULL);
311 #endif
312
313   view = menu_item_new (VIEW_MENU);
314   viewmenu = gtk_menu_new ();
315   gtk_menu_item_set_submenu (GTK_MENU_ITEM (view), viewmenu);
316
317   sendkey = menu_item_new (SEND_KEY_MENU);
318   sendkeymenu = gtk_menu_new ();
319   gtk_menu_item_set_submenu (GTK_MENU_ITEM (sendkey), sendkeymenu);
320
321   wind = menu_item_new (WINDOW_MENU);
322   windmenu = gtk_menu_new ();
323   gtk_menu_item_set_submenu (GTK_MENU_ITEM (wind), windmenu);
324
325   help = menu_item_new (HELP_MENU);
326   helpmenu = gtk_menu_new ();
327   gtk_menu_item_set_submenu (GTK_MENU_ITEM (help), helpmenu);
328
329   about = gtk_image_menu_item_new_from_stock(GTK_STOCK_ABOUT, NULL);
330   gtk_menu_append(GTK_MENU(helpmenu), about);
331   g_signal_connect(about, "activate", GTK_SIGNAL_FUNC (help_about), NULL);
332
333   gtk_menu_bar_append (GTK_MENU_BAR (menubar), connectitem);
334   gtk_menu_bar_append (GTK_MENU_BAR (menubar), view);
335   gtk_menu_bar_append (GTK_MENU_BAR (menubar), sendkey);
336   gtk_menu_bar_append (GTK_MENU_BAR (menubar), wind);
337   gtk_menu_bar_append (GTK_MENU_BAR (menubar), help);
338
339   /* For login dialogs, etc., usually invisible. */
340   connection_area = gtk_event_box_new ();
341   ca_vbox = gtk_vbox_new (FALSE, 0);
342   ca_label = gtk_label_new ("Give the name of the oVirt management server:");
343   ca_hbox = gtk_hbox_new (FALSE, 0);
344   ca_hostname = gtk_entry_new ();
345   gtk_entry_set_width_chars (GTK_ENTRY (ca_hostname), 24);
346   ca_button = gtk_button_new_with_label ("Connect");
347   ca_error = gtk_label_new (NULL);
348   gtk_box_pack_start (GTK_BOX (ca_hbox), ca_hostname, FALSE, FALSE, 0);
349   gtk_box_pack_start (GTK_BOX (ca_hbox), ca_button,   FALSE, FALSE, 0);
350   gtk_box_pack_start (GTK_BOX (ca_vbox), ca_label,    FALSE, FALSE, 4);
351   gtk_box_pack_start (GTK_BOX (ca_vbox), ca_hbox,     TRUE,  FALSE, 4);
352   gtk_box_pack_start (GTK_BOX (ca_vbox), ca_error,    TRUE,  FALSE, 4);
353   gtk_container_add (GTK_CONTAINER (connection_area), ca_vbox);
354
355   gtk_widget_set_name (connection_area, "ovirt-viewer-connection-area");
356
357   g_signal_connect (G_OBJECT (ca_hostname), "key-release-event",
358                     G_CALLBACK (connect_to_wui_on_enter), NULL);
359   g_signal_connect (G_OBJECT (ca_button), "clicked",
360                     G_CALLBACK (connect_to_wui), NULL);
361
362   login_area = gtk_event_box_new ();
363   la_vbox = gtk_vbox_new (FALSE, 0);
364   la_hbox = gtk_hbox_new (FALSE, 0);
365   la_label = gtk_label_new ("Username / password:");
366   la_username = gtk_entry_new ();
367   gtk_entry_set_width_chars (GTK_ENTRY (la_username), 12);
368   la_password = gtk_entry_new ();
369   gtk_entry_set_width_chars (GTK_ENTRY (la_password), 12);
370   gtk_entry_set_visibility (GTK_ENTRY (la_password), FALSE);
371   la_button = gtk_button_new_with_label ("Login");
372   la_error = gtk_label_new (NULL);
373   gtk_container_add (GTK_CONTAINER (la_hbox), la_username);
374   gtk_container_add (GTK_CONTAINER (la_hbox), la_password);
375   gtk_container_add (GTK_CONTAINER (la_hbox), la_button);
376   gtk_box_pack_start (GTK_BOX (la_vbox), la_label,     TRUE,  FALSE, 4);
377   gtk_box_pack_start (GTK_BOX (la_vbox), la_hbox,     TRUE,  FALSE, 4);
378   gtk_box_pack_start (GTK_BOX (la_vbox), la_error,    TRUE,  FALSE, 4);
379   gtk_container_add (GTK_CONTAINER (login_area), la_vbox);
380
381   gtk_widget_set_name (login_area, "ovirt-viewer-login-area");
382
383   g_signal_connect (G_OBJECT (la_username), "key-release-event",
384                     G_CALLBACK (login_to_wui_on_enter), NULL);
385   g_signal_connect (G_OBJECT (la_password), "key-release-event",
386                     G_CALLBACK (login_to_wui_on_enter), NULL);
387   g_signal_connect (G_OBJECT (la_button), "clicked",
388                     G_CALLBACK (login_to_wui), NULL);
389
390   /* Tabbed notebook. */
391   notebook = gtk_notebook_new ();
392   /*gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_LEFT);*/
393   gtk_notebook_set_show_tabs (GTK_NOTEBOOK (notebook), TRUE);
394   gtk_notebook_set_scrollable (GTK_NOTEBOOK (notebook), TRUE);
395
396   /* Status bar. */
397   statusbar = gtk_statusbar_new ();
398   statusbar_ctx = gtk_statusbar_get_context_id (GTK_STATUSBAR (statusbar),
399                                                 "context");
400   gtk_statusbar_push (GTK_STATUSBAR (statusbar), statusbar_ctx, "");
401
402   /* Packing. */
403   gtk_container_add (GTK_CONTAINER (window), vbox);
404   gtk_container_add_with_properties (GTK_CONTAINER (vbox), menubar,
405                                      "expand", FALSE, NULL);
406   gtk_container_add_with_properties (GTK_CONTAINER (vbox), connection_area,
407                                      "expand", FALSE, "fill", TRUE, NULL);
408   gtk_container_add_with_properties (GTK_CONTAINER (vbox), login_area,
409                                      "expand", FALSE, "fill", TRUE, NULL);
410   gtk_container_add_with_properties (GTK_CONTAINER (vbox), notebook,
411                                      "expand", TRUE, NULL);
412   gtk_container_add_with_properties (GTK_CONTAINER (vbox), statusbar,
413                                      "expand", FALSE, NULL);
414
415   /* Show widgets. */
416   gtk_widget_show_all (window);
417
418   if (wui_thread_is_connected ())
419     gtk_widget_hide (connection_area);
420   if (!wui_thread_is_connected () || wui_thread_is_logged_in ())
421     gtk_widget_hide (login_area);
422 }
423
424 static GtkWidget *
425 menu_item_new (int which_menu)
426 {
427   GtkWidget *widget;
428   GtkWidget *label;
429   const char *text;
430
431   text = menuItems[which_menu].ungrabbed_text;
432
433   widget = gtk_menu_item_new ();
434   label = g_object_new (GTK_TYPE_ACCEL_LABEL, NULL);
435   gtk_label_set_text_with_mnemonic (GTK_LABEL (label), text);
436   gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
437
438   gtk_container_add (GTK_CONTAINER (widget), label);
439   gtk_accel_label_set_accel_widget (GTK_ACCEL_LABEL (label), widget);
440   gtk_widget_show (label);
441
442   menuItems[which_menu].label = label;
443
444   return widget;
445 }
446
447 static gboolean
448 delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
449 {
450   DEBUG ("delete_event");
451   return FALSE;
452 }
453
454 static void
455 destroy (GtkWidget *widget, gpointer data)
456 {
457   DEBUG ("destroy");
458   gtk_main_quit ();
459 }
460
461 static void
462 help_about (GtkWidget *menu)
463 {
464   GtkWidget *about;
465   const char *authors[] = {
466     "Richard W.M. Jones <rjones@redhat.com>",
467     "Daniel P. Berrange <berrange@redhat.com>",
468     NULL
469   };
470
471   about = gtk_about_dialog_new();
472
473   gtk_about_dialog_set_name(GTK_ABOUT_DIALOG(about), "oVirt Viewer");
474   gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(about), VERSION);
475   gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(about), "http://ovirt.org/");
476   gtk_about_dialog_set_website_label(GTK_ABOUT_DIALOG(about), "oVirt website");
477   gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG(about), authors);
478   gtk_about_dialog_set_license(GTK_ABOUT_DIALOG(about), 
479  "This program is free software; you can redistribute it and/or modify\n" \
480  "it under the terms of the GNU General Public License as published by\n" \
481  "the Free Software Foundation; either version 2 of the License, or\n" \
482  "(at your option) any later version.\n" \
483  "\n" \
484  "This program is distributed in the hope that it will be useful,\n" \
485  "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" \
486  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" \
487  "GNU General Public License for more details.\n" \
488  "\n" \
489  "You should have received a copy of the GNU General Public License\n" \
490  "along with this program; if not, write to the Free Software\n" \
491  "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n");
492
493   gtk_dialog_run(GTK_DIALOG(about));
494   gtk_widget_destroy(about);
495 }
496
497 static void
498 refresh_menu_vm_list(GtkWidget *widget, gpointer data)
499 {
500    wui_thread_send_refresh_vm_list();
501 }
502
503 static void
504 connect_to_wui_on_enter (GtkWidget *widget, gpointer data)
505 {
506   // if key released was not 'enter' key
507   if(((GdkEventKey *)data)->type == GDK_KEY_RELEASE && (((GdkEventKey *)data)->keyval & 0xFF) != 13 ) return;
508
509   connect_to_wui(widget, data);
510 }
511
512 static void
513 connect_to_wui (GtkWidget *widget, gpointer data)
514 {
515   const char *hostname;
516   char *uri;
517   int len;
518
519   hostname = gtk_entry_get_text (GTK_ENTRY (ca_hostname));
520   if (STREQ (hostname, "")) return;
521
522   /* https:// + hostname + /ovirt + \0 */
523   len = 8 + strlen (hostname) + 6 + 1;
524   uri = g_alloca (len);
525   snprintf (uri, len, HTTPS "://%s/ovirt", hostname);
526
527   wui_thread_send_connect (uri);
528 }
529
530 static void
531 login_to_wui_on_enter (GtkWidget *widget, gpointer data)
532 {
533   // if key released was not 'enter' key
534   if(((GdkEventKey *)data)->type == GDK_KEY_RELEASE && (((GdkEventKey *)data)->keyval & 0xFF) != 13 ) return;
535
536   login_to_wui(widget, data);
537 }
538
539 static void
540 login_to_wui (GtkWidget *widget, gpointer data)
541 {
542   const char *username, *password;
543
544   username = gtk_entry_get_text (GTK_ENTRY (la_username));
545   if (STREQ (username, "")) return;
546   password = gtk_entry_get_text (GTK_ENTRY (la_password));
547
548   wui_thread_send_login (username, password);
549 }
550
551 /* Connect to a virtual machine.  This callback is called from the
552  * connect menu.  It searches the notebook of gtk-vnc widgets to see
553  * if we have already connected to this machine, and if not it
554  * makes a new connection.
555  */
556 static void
557 connect_to_vm (GtkWidget *widget, gpointer _vm)
558 {
559   struct vm *vm = (struct vm *) _vm;
560   int n = gtk_notebook_get_n_pages (GTK_NOTEBOOK (notebook));
561   int i, uuidlen, len, fd;
562   GtkWidget *child;
563   const char *label;
564   const char* hostname;
565   char *label2;
566   char new_title[97]; // 47 chars for title + 50 for vm name
567
568   DEBUG ("searching tabs for uuid %s", vm->uuid);
569
570   uuidlen = strlen (vm->uuid);
571
572   /* Search the tabs for this UUID, and if found, switch to it and return. */
573   for (i = 0; i < n; ++i) {
574     child = gtk_notebook_get_nth_page (GTK_NOTEBOOK (notebook), i);
575     label = gtk_notebook_get_tab_label_text (GTK_NOTEBOOK (notebook), child);
576     len = strlen (label);
577     if (len >= uuidlen &&
578         STREQ (label + len - uuidlen, vm->uuid)) {
579       DEBUG ("found on tab %d", i);
580       gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), i);
581       return;
582     }
583   }
584
585   DEBUG ("not found, creating new tab");
586
587   // before we open vnc connection, make sure vm is running
588   gboolean vm_running = main_vmlist_has_running_vm(vm);
589
590   if(!vm_running){
591     main_status_error (g_strdup ("VM not running"));
592     return;
593   }
594
595   /* This VM isn't in the notebook already, so create a new console. */
596   hostname = gtk_entry_get_text (GTK_ENTRY (ca_hostname));
597   fd = viewer_open_vnc_socket(hostname, vm->forward_vnc_port);
598   if (fd == -1) return;         /* We've already given an error. */
599
600   child = vnc_display_new ();
601   if (! vnc_display_open_fd (VNC_DISPLAY (child), fd)) {
602     main_status_error (g_strdup ("internal error in Gtk-VNC widget"));
603     return;
604   }
605
606   main_status_error(g_strdup(""));
607
608   for(i = 0; i < 47; ++i) new_title[i] = title_vm[i];
609   for(i = 0; i < 50; ++i){
610      if(vm->description[i] == '\0') break;
611      new_title[47 + i] = vm->description[i];
612   }
613   new_title[i < 50 ? i+47 : 96] = '\0';
614   gtk_window_set_title (GTK_WINDOW (window), new_title);
615
616   /*
617   gtk_signal_connect(GTK_OBJECT(child), "vnc-pointer-grab",
618                      GTK_SIGNAL_FUNC(viewer_grab), window);
619   gtk_signal_connect(GTK_OBJECT(child), "vnc-pointer-ungrab",
620                      GTK_SIGNAL_FUNC(viewer_ungrab), window);
621   */
622
623   gtk_signal_connect(GTK_OBJECT(child), "delete-event",
624                      GTK_SIGNAL_FUNC(viewer_shutdown), child);
625
626   gtk_signal_connect(GTK_OBJECT(child), "vnc-connected",
627                      GTK_SIGNAL_FUNC(viewer_connected), NULL);
628   gtk_signal_connect(GTK_OBJECT(child), "vnc-initialized",
629                      GTK_SIGNAL_FUNC(viewer_initialized), NULL);
630   gtk_signal_connect(GTK_OBJECT(child), "vnc-disconnected",
631                      GTK_SIGNAL_FUNC(viewer_disconnected), NULL);
632
633   g_signal_connect(GTK_OBJECT(child), "vnc-auth-credential",
634                    GTK_SIGNAL_FUNC(viewer_credential), NULL);
635
636   /* NB. We have to do this before adding it to the notebook. */
637   gtk_widget_show (child);
638
639   /* Choose a tab label, which MUST end with the uuid string, since
640    * we use the tab label to store uuid.
641    */
642   len = strlen (vm->description) + 1 + strlen (vm->uuid) + 1;
643   label2 = g_alloca (len);
644   snprintf (label2, len, "%s %s", vm->description, vm->uuid);
645
646   i = gtk_notebook_append_page (GTK_NOTEBOOK (notebook), child, NULL);
647   gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (notebook), child, label2);
648   gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), i);
649
650   DEBUG ("finished creating new tab");
651 }
652
653 /*
654 static void viewer_grab(GtkWidget *vnc, GtkWidget *window)
655 {
656         int i;
657
658         viewer_set_title(VNC_DISPLAY(vnc), window, TRUE);
659
660         for (i = 0 ; i < LAST_MENU; i++) {
661                 gtk_label_set_text_with_mnemonic(GTK_LABEL(menuItems[i].label), menuItems[i].grabbed_text);
662         }
663 }
664
665 static void viewer_ungrab(GtkWidget *vnc, GtkWidget *window)
666 {
667         int i;
668
669         viewer_set_title(VNC_DISPLAY(vnc), window, FALSE);
670
671         for (i = 0 ; i < LAST_MENU; i++) {
672                 gtk_label_set_text_with_mnemonic(GTK_LABEL(menuItems[i].label), menuItems[i].ungrabbed_text);
673         }
674 }
675 */
676
677 static void
678 viewer_shutdown (GtkWidget *src, void *dummy, GtkWidget *vnc)
679 {
680   vnc_display_close (VNC_DISPLAY(vnc));
681
682   /* Just close the notebook tab for now. XXX */
683   gtk_notebook_remove_page (GTK_NOTEBOOK (notebook),
684                             gtk_notebook_page_num (GTK_NOTEBOOK (notebook),
685                                                    vnc));
686 }
687
688 #if 0
689 static void
690 viewer_quit (GtkWidget *src, GtkWidget *vnc)
691 {
692   viewer_shutdown (src, NULL, vnc);
693 }
694 #endif
695
696 static void
697 viewer_connected (GtkWidget *vnc)
698 {
699   DEBUG ("Connected to server");
700 }
701
702 static void
703 viewer_initialized (GtkWidget *vnc, GtkWidget *data)
704 {
705   DEBUG ("Connection initialized");
706 }
707
708 static void
709 viewer_disconnected (GtkWidget *vnc)
710 {
711   DEBUG ("Disconnected from server");
712 }
713
714 static void
715 viewer_credential (GtkWidget *vnc, GValueArray *credList)
716 {
717         GtkWidget *dialog = NULL;
718         int response;
719         unsigned int i, prompt = 0;
720         const char **data;
721
722         DEBUG ("Got credential request for %d credential(s)",
723                credList->n_values);
724
725         data = g_new0(const char *, credList->n_values);
726
727         for (i = 0 ; i < credList->n_values ; i++) {
728                 GValue *cred = g_value_array_get_nth(credList, i);
729                 switch (g_value_get_enum(cred)) {
730                 case VNC_DISPLAY_CREDENTIAL_USERNAME:
731                 case VNC_DISPLAY_CREDENTIAL_PASSWORD:
732                         prompt++;
733                         break;
734                 case VNC_DISPLAY_CREDENTIAL_CLIENTNAME:
735                         data[i] = "libvirt";
736                 default:
737                         break;
738                 }
739         }
740
741         if (prompt) {
742                 GtkWidget **label, **entry, *box, *vbox;
743                 int row;
744                 dialog = gtk_dialog_new_with_buttons("Authentication required",
745                                                      NULL,
746                                                      0,
747                                                      GTK_STOCK_CANCEL,
748                                                      GTK_RESPONSE_CANCEL,
749                                                      GTK_STOCK_OK,
750                                                      GTK_RESPONSE_OK,
751                                                      NULL);
752                 gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
753
754                 box = gtk_table_new(credList->n_values, 2, FALSE);
755                 label = g_new(GtkWidget *, prompt);
756                 entry = g_new(GtkWidget *, prompt);
757
758                 for (i = 0, row =0 ; i < credList->n_values ; i++) {
759                         GValue *cred = g_value_array_get_nth(credList, i);
760                         switch (g_value_get_enum(cred)) {
761                         case VNC_DISPLAY_CREDENTIAL_USERNAME:
762                                 label[row] = gtk_label_new("Username:");
763                                 break;
764                         case VNC_DISPLAY_CREDENTIAL_PASSWORD:
765                                 label[row] = gtk_label_new("Password:");
766                                 break;
767                         default:
768                                 continue;
769                         }
770                         entry[row] = gtk_entry_new();
771                         if (g_value_get_enum(cred) == VNC_DISPLAY_CREDENTIAL_PASSWORD)
772                                 gtk_entry_set_visibility(GTK_ENTRY(entry[row]), FALSE);
773
774                         gtk_table_attach(GTK_TABLE(box), label[i], 0, 1, row, row+1, GTK_SHRINK, GTK_SHRINK, 3, 3);
775                         gtk_table_attach(GTK_TABLE(box), entry[i], 1, 2, row, row+1, GTK_SHRINK, GTK_SHRINK, 3, 3);
776                         row++;
777                 }
778
779                 vbox = gtk_bin_get_child(GTK_BIN(dialog));
780                 gtk_container_add(GTK_CONTAINER(vbox), box);
781
782                 gtk_widget_show_all(dialog);
783                 response = gtk_dialog_run(GTK_DIALOG(dialog));
784                 gtk_widget_hide(GTK_WIDGET(dialog));
785
786                 if (response == GTK_RESPONSE_OK) {
787                         for (i = 0, row = 0 ; i < credList->n_values ; i++) {
788                                 GValue *cred = g_value_array_get_nth(credList, i);
789                                 switch (g_value_get_enum(cred)) {
790                                 case VNC_DISPLAY_CREDENTIAL_USERNAME:
791                                 case VNC_DISPLAY_CREDENTIAL_PASSWORD:
792                                         data[i] = gtk_entry_get_text(GTK_ENTRY(entry[row]));
793                                         break;
794                                 }
795                         }
796                 }
797         }
798
799         for (i = 0 ; i < credList->n_values ; i++) {
800                 GValue *cred = g_value_array_get_nth(credList, i);
801                 if (data[i]) {
802                         if (vnc_display_set_credential(VNC_DISPLAY(vnc),
803                                                        g_value_get_enum(cred),
804                                                        data[i])) {
805                                 DEBUG("Failed to set credential type %d",
806                                       g_value_get_enum(cred));
807                                 vnc_display_close(VNC_DISPLAY(vnc));
808                         }
809                 } else {
810                         DEBUG("Unsupported credential type %d",
811                               g_value_get_enum(cred));
812                         vnc_display_close(VNC_DISPLAY(vnc));
813                 }
814         }
815
816         g_free(data);
817         if (dialog)
818                 gtk_widget_destroy(GTK_WIDGET(dialog));
819 }
820
821 #if defined(HAVE_SOCKET) && defined(HAVE_CONNECT) && defined(HAVE_HTONS) && defined(HAVE_GETHOSTBYNAME)
822
823 static int 
824 viewer_open_vnc_socket(const char* vnchost, int vncport)
825 {
826   int socketfd;
827   struct hostent *serv;
828   struct sockaddr_in serv_addr;
829
830   socketfd = socket(PF_INET, SOCK_STREAM, 0);
831   if(socketfd < 0){
832       return -1;
833   }
834
835   serv = gethostbyname(vnchost);
836   if(serv == NULL){
837       return -1;
838   }
839
840   serv_addr.sin_family = PF_INET;
841   serv_addr.sin_port = htons(vncport);
842   serv_addr.sin_addr.s_addr = ((struct in_addr *)(serv->h_addr))->s_addr; 
843
844   if (connect(socketfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0){
845       return -1;
846   }
847
848   return socketfd;
849 }
850
851 #endif /* defined(HAVE_SOCKET) && defined(HAVE_CONNECT) && defined(HAVE_HTONS) && defined(HAVE_GETHOSTBYNAME) */
852
853 /* Remove all menu items from the Connect menu. */
854 static void
855 remove_menu_item (GtkWidget *menu_item, gpointer data)
856 {
857   gtk_container_remove (GTK_CONTAINER (connectmenu), menu_item);
858 }
859
860 static void
861 clear_connectmenu (void)
862 {
863   DEBUG ("clear Connect menu");
864   gtk_container_foreach (GTK_CONTAINER (connectmenu), remove_menu_item, NULL);
865 }
866
867 /* The WUI thread has changed its state to connected. */
868 gboolean
869 main_connected (gpointer data)
870 {
871   DEBUG ("connected");
872   ASSERT_IS_MAIN_THREAD ();
873
874   gtk_label_set_text (GTK_LABEL (ca_error), NULL);
875
876   gtk_widget_hide (connection_area);
877   if (!wui_thread_is_logged_in ())
878     gtk_widget_show (login_area);
879   return FALSE;
880 }
881
882 /* The WUI thread has changed its state to disconnected. */
883 gboolean
884 main_disconnected (gpointer data)
885 {
886   DEBUG ("disconnected");
887   ASSERT_IS_MAIN_THREAD ();
888
889   gtk_widget_show (connection_area);
890   gtk_widget_hide (login_area);
891
892   clear_connectmenu ();
893   gtk_menu_append (GTK_MENU (connectmenu), no_connections);
894   gtk_widget_show_all (connectmenu);
895
896   return FALSE;
897 }
898
899 /* The WUI thread has changed its state to logged in. */
900 gboolean
901 main_logged_in (gpointer data)
902 {
903   DEBUG ("logged in");
904   ASSERT_IS_MAIN_THREAD ();
905
906   gtk_widget_hide (login_area);
907   return FALSE;
908 }
909
910 /* The WUI thread has changed its state to logged out. */
911 gboolean
912 main_logged_out (gpointer data)
913 {
914   DEBUG ("logged out");
915   ASSERT_IS_MAIN_THREAD ();
916
917   if (wui_thread_is_connected ())
918     gtk_widget_show (login_area);
919   return FALSE;
920 }
921
922 /* The WUI thread has changed its state to busy. */
923 gboolean
924 main_busy (gpointer data)
925 {
926   GdkWindow *gdk_window;
927
928   DEBUG ("busy");
929   ASSERT_IS_MAIN_THREAD ();
930
931   gdk_window = gtk_widget_get_window (window);
932   if (gdk_window) {
933     gdk_window_set_cursor (gdk_window, busy_cursor);
934     gdk_flush ();
935   }
936
937   return FALSE;
938 }
939
940 /* The WUI thread has changed its state to idle. */
941 gboolean
942 main_idle (gpointer data)
943 {
944   GdkWindow *gdk_window;
945
946   DEBUG ("idle");
947   ASSERT_IS_MAIN_THREAD ();
948
949   gdk_window = gtk_widget_get_window (window);
950   if (gdk_window) {
951     gdk_window_set_cursor (gdk_window, NULL);
952     gdk_flush ();
953   }
954
955   return FALSE;
956 }
957
958 /* The WUI thread had a connection error.  This function must
959  * free the string.
960  */
961 gboolean
962 main_connection_error (gpointer _str)
963 {
964   char *str = (char *) _str;
965
966   DEBUG ("connection error: %s", str);
967   ASSERT_IS_MAIN_THREAD ();
968
969   gtk_label_set_text (GTK_LABEL (ca_error), str);
970   g_free (str);
971
972   return FALSE;
973 }
974
975 /* The WUI thread had a login error.  This function must
976  * free the string.
977  */
978 gboolean
979 main_login_error (gpointer _str)
980 {
981   char *str = (char *) _str;
982
983   DEBUG ("login error: %s", str);
984   ASSERT_IS_MAIN_THREAD ();
985
986   gtk_label_set_text (GTK_LABEL (la_error), str);
987   g_free (str);
988
989   return FALSE;
990 }
991
992 /* The WUI thread reports a general status error.  This function
993  * must free the string.
994  */
995 gboolean
996 main_status_error (gpointer _str)
997 {
998   char *str = (char *) _str;
999
1000   DEBUG ("status error: %s", str);
1001   ASSERT_IS_MAIN_THREAD ();
1002
1003   gtk_statusbar_pop (GTK_STATUSBAR (statusbar), statusbar_ctx);
1004   gtk_statusbar_push (GTK_STATUSBAR (statusbar), statusbar_ctx, str);
1005   g_free (str);
1006
1007   return FALSE;
1008 }
1009
1010 /* The WUI thread has updated the vm list.  Here in the main thread
1011  * we keep our own copy of the vmlist.
1012  */
1013 static GSList *vmlist = NULL;
1014
1015 static void add_vm_to_connectmenu (gpointer _vm, gpointer data);
1016
1017 gboolean
1018 main_vmlist_updated (gpointer data)
1019 {
1020   GSList *new_vmlist;
1021
1022   DEBUG ("vmlist updated");
1023   ASSERT_IS_MAIN_THREAD ();
1024
1025   /* Get the new vmlist. */
1026   if (wui_thread_get_vmlist (&new_vmlist)) {
1027     /* Free the previous vmlist.  This invalidates all the vm pointers
1028      * contained in the Connect menu callbacks, but we're going to
1029      * delete those callbacks and create news ones in a moment anyway ...
1030      */
1031     free_vmlist (vmlist);
1032
1033     vmlist = new_vmlist;
1034
1035     clear_connectmenu ();
1036
1037     gtk_menu_append (GTK_MENU (connectmenu), refresh_vmlist);
1038
1039     if (vmlist != NULL) {
1040       gtk_menu_append (GTK_MENU (connectmenu), refresh_vmlist_separator);
1041       g_slist_foreach (vmlist, add_vm_to_connectmenu, NULL);
1042     }
1043
1044     /* Grrrr Gtk is stupid. */
1045     gtk_widget_show_all (connectmenu);
1046   }
1047
1048   return FALSE;
1049 }
1050
1051 static void
1052 add_vm_to_connectmenu (gpointer _vm, gpointer data)
1053 {
1054   struct vm *vm = (struct vm *) _vm;
1055   GtkWidget *item;
1056
1057   // TODO only present running vms ?
1058   // if(vm->state == "running")
1059
1060   DEBUG ("adding %s to Connect menu", vm->description);
1061
1062   item = gtk_menu_item_new_with_label (vm->description);
1063   gtk_menu_append (GTK_MENU (connectmenu), item);
1064
1065   g_signal_connect (G_OBJECT (item), "activate",
1066                     G_CALLBACK (connect_to_vm), vm);
1067 }