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