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