Fix search/replace mistakes...AnjutaSyncCommand should compile now.
[anjuta-git-plugin.git] / libanjuta / anjuta-launcher.c
blob5922c3c809466611cd5d3c6e8a787e25f98a392b
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3 * anjuta-launcher.c
4 * Copyright (C) 2003 Naba Kumar <naba@gnome.org>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 /**
22 * SECTION:anjuta-launcher
23 * @short_description: External process launcher with async input/output
24 * @see_also:
25 * @stability: Unstable
26 * @include: libanjuta/anjuta-launcher.h
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
34 #include <errno.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <signal.h>
39 #if !defined(__sun) && !defined(__NetBSD__)
40 # ifndef FREEBSD
41 # include <pty.h>
42 # else
43 # include <libutil.h>
44 # endif
45 #endif
46 #include "anjuta-utils-priv.h"
48 #include <assert.h>
49 #include <termios.h>
51 #include <string.h>
52 #include <time.h>
53 #include <glib/gi18n.h>
54 #include <glib.h>
56 #include <libgnome/gnome-macros.h>
58 #include "anjuta-utils.h"
59 #include "anjuta-marshal.h"
60 #include "resources.h"
61 #include "anjuta-launcher.h"
62 #include "anjuta-debug.h"
64 #define ANJUTA_PIXMAP_PASSWORD "password.png"
65 #define FILE_BUFFER_SIZE 1024
66 #define FILE_INPUT_BUFFER_SIZE 1048576
67 #ifndef __MAX_BAUD
68 #ifdef __CYGWIN__
69 #define __MAX_BAUD B256000
70 #else
71 #define __MAX_BAUD B460800
72 #endif
73 #endif
76 static gboolean
77 anjuta_launcher_pty_check_child_exit_code (AnjutaLauncher *launcher,
78 const gchar* line);
80 struct _AnjutaLauncherPriv
83 * Busy flag is TRUE if the Launcher
84 * is currently executing a child.
86 gboolean busy;
88 /* These flags are used to synchronize the IO operations. */
89 gboolean stdout_is_done;
90 gboolean stderr_is_done;
92 /* GIO channels */
93 GIOChannel *stdout_channel;
94 GIOChannel *stderr_channel;
95 /*GIOChannel *stdin_channel;*/
96 GIOChannel *pty_channel;
98 /* GIO watch handles */
99 guint stdout_watch;
100 guint stderr_watch;
101 guint pty_watch;
103 /* Output line buffers */
104 gchar *stdout_buffer;
105 gchar *stderr_buffer;
107 /* Output of the pty is constantly stored here.*/
108 gchar *pty_output_buffer;
110 /* Terminal echo */
111 gboolean terminal_echo_on;
113 /* The child */
114 pid_t child_pid;
115 guint source;
116 gint child_status;
117 gboolean child_has_terminated;
119 /* Synchronization in progress */
120 gboolean in_cleanup;
121 guint completion_check_timeout;
123 /* Terminate child on child exit */
124 gboolean terminate_on_exit;
126 /* Start time of execution */
127 time_t start_time;
129 /* Should the outputs be buffered */
130 gboolean buffered_output;
132 /* Should we check for password prompts in stdout and pty */
133 gboolean check_for_passwd_prompt;
135 /* Output callback */
136 AnjutaLauncherOutputCallback output_callback;
138 /* Callback data */
139 gpointer callback_data;
141 /* Encondig */
142 gboolean custom_encoding;
143 gchar* encoding;
145 /* Env */
146 GHashTable* env;
149 enum
151 /* OUTPUT_ARRIVED_SIGNAL, */
152 CHILD_EXITED_SIGNAL,
153 BUSY_SIGNAL,
154 LAST_SIGNAL
157 static void anjuta_launcher_class_init (AnjutaLauncherClass * klass);
158 static void anjuta_launcher_init (AnjutaLauncher * obj);
159 static gboolean anjuta_launcher_call_execution_done (gpointer data);
160 static gboolean anjuta_launcher_check_for_execution_done (gpointer data);
161 static void anjuta_launcher_execution_done_cleanup (AnjutaLauncher *launcher,
162 gboolean emit_signal);
164 static gboolean is_password_prompt(const gchar* line);
166 static guint launcher_signals[LAST_SIGNAL] = { 0 };
167 static AnjutaLauncherClass *parent_class;
169 static void
170 anjuta_launcher_initialize (AnjutaLauncher *obj)
172 /* Busy flag */
173 obj->priv->busy = FALSE;
175 /* These flags are used to synchronize the IO operations. */
176 obj->priv->stdout_is_done = FALSE;
177 obj->priv->stderr_is_done = FALSE;
179 /* GIO channels */
180 obj->priv->stdout_channel = NULL;
181 obj->priv->stderr_channel = NULL;
182 obj->priv->pty_channel = NULL;
184 /* Output line buffers */
185 obj->priv->stdout_buffer = NULL;
186 obj->priv->stderr_buffer = NULL;
188 /* Pty buffer */
189 obj->priv->pty_output_buffer = NULL;
191 obj->priv->terminal_echo_on = TRUE;
193 /* The child */
194 obj->priv->child_pid = 0;
195 obj->priv->child_status = -1;
196 obj->priv->child_has_terminated = TRUE;
198 /* Synchronization in progress */
199 obj->priv->in_cleanup = FALSE;
200 obj->priv->completion_check_timeout = -1;
202 /* Terminate child on child exit */
203 obj->priv->terminate_on_exit = FALSE;
205 /* Start time of execution */
206 obj->priv->start_time = 0;
208 obj->priv->buffered_output = TRUE;
209 obj->priv->check_for_passwd_prompt = TRUE;
211 /* Output callback */
212 obj->priv->output_callback = NULL;
213 obj->priv->callback_data = NULL;
215 /* Encoding */
216 obj->priv->custom_encoding = FALSE;
217 obj->priv->encoding = NULL;
219 /* Env */
220 obj->priv->env = g_hash_table_new_full (g_str_hash, g_str_equal,
221 g_free, g_free);
224 GType
225 anjuta_launcher_get_type ()
227 static GType obj_type = 0;
229 if (!obj_type)
231 static const GTypeInfo obj_info =
233 sizeof (AnjutaLauncherClass),
234 (GBaseInitFunc) NULL,
235 (GBaseFinalizeFunc) NULL,
236 (GClassInitFunc) anjuta_launcher_class_init,
237 (GClassFinalizeFunc) NULL,
238 NULL, /* class_data */
239 sizeof (AnjutaLauncher),
240 0, /* n_preallocs */
241 (GInstanceInitFunc) anjuta_launcher_init,
242 NULL /* value_table */
244 obj_type = g_type_register_static (G_TYPE_OBJECT,
245 "AnjutaLauncher", &obj_info, 0);
247 return obj_type;
250 static void
251 anjuta_launcher_dispose (GObject *obj)
253 AnjutaLauncher *launcher = ANJUTA_LAUNCHER (obj);
254 if (anjuta_launcher_is_busy (launcher))
256 pid_t child_pid_save = launcher->priv->child_pid;
257 guint child_source = launcher->priv->source;
258 g_source_remove (child_source);
259 anjuta_launcher_execution_done_cleanup (launcher, FALSE);
261 /* We can not call anjuta_launcher_reset (launcher) to kill the
262 * running child because launcher has been initialized in cleanup
264 kill (child_pid_save, SIGTERM);
265 launcher->priv->busy = FALSE;
268 GNOME_CALL_PARENT (G_OBJECT_CLASS, dispose, (obj));
271 static void
272 anjuta_launcher_finalize (GObject *obj)
274 AnjutaLauncher *launcher = ANJUTA_LAUNCHER (obj);
275 if (launcher->priv->custom_encoding && launcher->priv->encoding)
276 g_free (launcher->priv->encoding);
278 g_hash_table_destroy (launcher->priv->env);
280 g_free (launcher->priv);
281 GNOME_CALL_PARENT (G_OBJECT_CLASS, finalize, (obj));
284 static void
285 anjuta_launcher_class_init (AnjutaLauncherClass * klass)
287 GObjectClass *object_class;
288 g_return_if_fail (klass != NULL);
289 object_class = (GObjectClass *) klass;
291 /* DEBUG_PRINT ("Initializing launcher class"); */
293 parent_class = g_type_class_peek_parent (klass);
296 * AnjutaLauncher::child-exited
297 * @launcher: a #AnjutaLancher object.
298 * @child_pid: process ID of the child
299 * @status: status as returned by waitpid function
300 * @time: time in seconds taken by the child
302 * Emitted when the child has exited and all i/o channels have
303 * been closed. If the terminate on exit flag is set, the i/o
304 * channels are automatically closed when the child exit.
305 * You need to use WEXITSTATUS and friend to get the child exit
306 * code from the status returned.
308 launcher_signals[CHILD_EXITED_SIGNAL] =
309 g_signal_new ("child-exited",
310 G_TYPE_FROM_CLASS (object_class),
311 G_SIGNAL_RUN_FIRST,
312 G_STRUCT_OFFSET (AnjutaLauncherClass,
313 child_exited),
314 NULL, NULL,
315 anjuta_cclosure_marshal_VOID__INT_INT_ULONG,
316 G_TYPE_NONE, 3, G_TYPE_INT,
317 G_TYPE_INT, G_TYPE_ULONG);
320 * AnjutaLauncher::busy
321 * @launcher: a #AnjutaLancher object.
322 * @busy: TRUE is a child is currently running
324 * Emitted when a child starts after a call to one execute function
325 * (busy is TRUE) or when a child exits and all i/o channels are
326 * closed (busy is FALSE).
328 launcher_signals[BUSY_SIGNAL] =
329 g_signal_new ("busy",
330 G_TYPE_FROM_CLASS (object_class),
331 G_SIGNAL_RUN_FIRST,
332 G_STRUCT_OFFSET (AnjutaLauncherClass,
333 busy),
334 NULL, NULL,
335 anjuta_cclosure_marshal_VOID__BOOLEAN,
336 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
338 object_class->dispose = anjuta_launcher_dispose;
339 object_class->finalize = anjuta_launcher_finalize;
342 static void
343 anjuta_launcher_init (AnjutaLauncher * obj)
345 g_return_if_fail (obj != NULL);
346 obj->priv = g_new0 (AnjutaLauncherPriv, 1);
347 anjuta_launcher_initialize (obj);
351 * anjuta_launcher_is_busy:
352 * @launcher: a #AnjutaLancher object.
354 * Tells if the laucher is currently executing any command.
356 * Return value: TRUE if launcher is busy, otherwisee FALSE.
358 gboolean
359 anjuta_launcher_is_busy (AnjutaLauncher *launcher)
361 return launcher->priv->busy;
364 static void
365 anjuta_launcher_set_busy (AnjutaLauncher *launcher, gboolean flag)
367 gboolean old_busy = launcher->priv->busy;
368 launcher->priv->busy = flag;
369 if (old_busy != flag)
370 g_signal_emit_by_name (G_OBJECT (launcher), "busy", flag);
374 * anjuta_launcher_send_stdin:
375 * @launcher: a #AnjutaLancher object.
376 * @input_str: The string to send to STDIN of the process.
378 * Sends a string to Standard input of the process currently being executed.
380 void
381 anjuta_launcher_send_stdin (AnjutaLauncher *launcher, const gchar * input_str)
383 g_return_if_fail (launcher);
384 g_return_if_fail (input_str);
386 anjuta_launcher_send_ptyin (launcher, input_str);
390 * anjuta_launcher_send_stdin:
391 * @launcher: a #AnjutaLancher object.
393 * Sends a EOF to Standard input of the process currently being executed.
396 void
397 anjuta_launcher_send_stdin_eof (AnjutaLauncher *launcher)
399 GError* err = NULL;
400 g_io_channel_shutdown (launcher->priv->pty_channel, TRUE,
401 &err);
402 g_io_channel_unref (launcher->priv->pty_channel);
403 launcher->priv->pty_channel = NULL;
405 if (err)
407 g_warning ("g_io_channel_shutdown () failed: %s", err->message);
412 * anjuta_launcher_send_ptyin:
413 * @launcher: a #AnjutaLancher object.
414 * @input_str: The string to send to PTY of the process.
416 * Sends a string to TTY input of the process currently being executed.
417 * Mostly useful for entering passwords and other inputs which are directly
418 * read from TTY input of the process.
420 void
421 anjuta_launcher_send_ptyin (AnjutaLauncher *launcher, const gchar * input_str)
423 gsize bytes_written;
424 GError *err = NULL;
426 if (!input_str || strlen (input_str) == 0) return;
430 g_io_channel_write_chars (launcher->priv->pty_channel,
431 input_str, strlen (input_str),
432 &bytes_written, &err);
433 g_io_channel_flush (launcher->priv->pty_channel, NULL);
434 if (err)
436 g_warning ("Error encountered while writing to PTY!. %s",
437 err->message);
438 g_error_free (err);
440 return;
442 input_str += bytes_written;
444 while (*input_str);
448 * anjuta_launcher_reset:
449 * @launcher: a #AnjutaLancher object.
451 * Resets the launcher and kills (SIGTERM) current process, if it is still
452 * executing.
454 void
455 anjuta_launcher_reset (AnjutaLauncher *launcher)
457 if (anjuta_launcher_is_busy (launcher))
458 kill (launcher->priv->child_pid, SIGTERM);
462 * anjuta_launcher_signal:
463 * @launcher: a #AnjutaLancher object.
464 * @sig: kernel signal ID (e.g. SIGTERM).
466 * Sends a kernel signal to the process that is being executed.
468 void
469 anjuta_launcher_signal (AnjutaLauncher *launcher, int sig)
471 kill (launcher->priv->child_pid, sig);
475 * anjuta_launcher_get_child_pid:
476 * @launcher: a #AnjutaLancher object.
478 * Gets the Process ID of the child being executed.
480 * Return value: Process ID of the child.
482 pid_t
483 anjuta_launcher_get_child_pid (AnjutaLauncher *launcher)
485 if (anjuta_launcher_is_busy (launcher))
486 return launcher->priv->child_pid;
487 else
488 return -1;
491 static void
492 anjuta_launcher_synchronize (AnjutaLauncher *launcher)
494 if (launcher->priv->in_cleanup) return;
496 if (launcher->priv->child_has_terminated &&
497 launcher->priv->stdout_is_done &&
498 launcher->priv->stderr_is_done)
500 if (launcher->priv->completion_check_timeout >= 0)
501 g_source_remove (launcher->priv->completion_check_timeout);
502 launcher->priv->completion_check_timeout =
503 g_timeout_add (50, anjuta_launcher_check_for_execution_done,
504 launcher);
507 /* This case is not very good, but it blocks the whole IDE
508 because we never new if the child has finished */
509 else if (launcher->priv->stdout_is_done &&
510 launcher->priv->stderr_is_done)
512 /* DEBUG_PRINT ("Child has't exited yet waiting for 200ms"); */
513 if (launcher->priv->completion_check_timeout >= 0)
514 g_source_remove (launcher->priv->completion_check_timeout);
515 launcher->priv->completion_check_timeout =
516 g_timeout_add(200, anjuta_launcher_check_for_execution_done,
517 launcher);
519 /* Add this case for gdb. It creates child inheriting gdb
520 * pipes which are not closed if gdb crashes */
521 else if (launcher->priv->child_has_terminated &&
522 launcher->priv->terminate_on_exit)
524 if (launcher->priv->completion_check_timeout >= 0)
525 g_source_remove (launcher->priv->completion_check_timeout);
526 launcher->priv->completion_check_timeout =
527 g_timeout_add(0, anjuta_launcher_call_execution_done,
528 launcher);
532 /* Password dialog */
533 static GtkWidget*
534 create_password_dialog (const gchar* prompt)
536 GtkWidget *dialog;
537 GtkWidget *hbox;
538 GtkWidget *box;
539 GtkWidget *icon;
540 GtkWidget *label;
541 GtkWidget *entry;
543 g_return_val_if_fail (prompt, NULL);
545 dialog = gtk_dialog_new_with_buttons (prompt,
546 NULL, //FIXME: Pass the parent window here
547 // for transient purpose.
548 GTK_DIALOG_DESTROY_WITH_PARENT,
549 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
550 GTK_STOCK_OK, GTK_RESPONSE_OK, NULL);
551 gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK);
553 gtk_window_set_wmclass (GTK_WINDOW (dialog), "launcher-password-prompt",
554 "anjuta");
555 hbox = gtk_hbox_new (FALSE, 10);
556 gtk_widget_show (hbox);
557 gtk_container_add (GTK_CONTAINER (GTK_DIALOG(dialog)->vbox), hbox);
559 icon = anjuta_res_get_image (ANJUTA_PIXMAP_PASSWORD);
560 gtk_widget_show (icon);
561 gtk_box_pack_start_defaults (GTK_BOX(hbox), icon);
563 if (strlen (prompt) < 20) {
564 box = gtk_hbox_new (FALSE, 5);
565 } else {
566 box = gtk_vbox_new (FALSE, 5);
568 gtk_widget_show (box);
569 gtk_box_pack_start_defaults (GTK_BOX (hbox), box);
571 label = gtk_label_new (_(prompt));
572 gtk_widget_show (label);
573 gtk_box_pack_start (GTK_BOX (box), label, FALSE, FALSE, 0);
575 entry = gtk_entry_new ();
576 gtk_widget_show (entry);
577 gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
578 gtk_box_pack_start (GTK_BOX (box), entry, FALSE, FALSE, 0);
580 gtk_widget_ref (entry);
581 g_object_set_data_full (G_OBJECT (dialog), "password_entry",
582 gtk_widget_ref (entry),
583 (GDestroyNotify) gtk_widget_unref);
584 gtk_widget_grab_focus (entry);
585 gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE);
587 return dialog;
590 /* pty buffer check for password authentication */
591 static void
592 anjuta_launcher_check_password_real (AnjutaLauncher *launcher,
593 const gchar* last_line)
595 if (anjuta_launcher_is_busy (launcher) == FALSE)
596 return;
598 if (last_line) {
600 /* DEBUG_PRINT ("(In password) Last line = %s", last_line); */
601 if (is_password_prompt(last_line)) {
602 /* Password prompt detected */
603 GtkWidget* dialog;
604 gint button;
605 const gchar* passwd;
606 gchar* line;
608 dialog = create_password_dialog (last_line);
609 button = gtk_dialog_run (GTK_DIALOG(dialog));
610 switch (button) {
611 case GTK_RESPONSE_OK:
612 passwd = gtk_entry_get_text (
613 GTK_ENTRY (g_object_get_data (G_OBJECT (dialog),
614 "password_entry")));
615 line = g_strconcat (passwd, "\n", NULL);
616 anjuta_launcher_send_ptyin (launcher, line);
617 g_free (line);
618 break;
619 case GTK_RESPONSE_CANCEL:
620 anjuta_launcher_send_ptyin (launcher, "<canceled>\n");
621 anjuta_launcher_reset (launcher);
622 break;
623 default:
624 break;
626 gtk_widget_destroy (dialog);
631 static void
632 anjuta_launcher_check_password (AnjutaLauncher *launcher, const gchar *chars)
634 glong start, end;
635 gchar *last_line;
637 if (!chars || strlen(chars) <= 0)
638 return;
640 /* DEBUG_PRINT ("Chars buffer = %s", chars); */
641 start = end = strlen (chars);
642 while (start > 0 && chars[start-1] != '\n') start--;
644 if (end > start)
646 last_line = g_strndup (&chars[start], end - start + 1);
648 /* DEBUG_PRINT ("Last line = %s", last_line); */
649 /* Checks for password, again */
650 anjuta_launcher_check_password_real (launcher, last_line);
651 g_free (last_line);
655 static gboolean
656 is_password_prompt (const gchar* line)
658 const gchar* password = "assword";
659 const gchar* passphrase = "assphrase";
661 if (strlen (line) < strlen (password)
662 || strlen (line) < strlen (passphrase))
663 return FALSE;
665 if (g_strstr_len(line, 80, password) != NULL
666 || g_strstr_len(line, 80, passphrase) != NULL)
668 int i;
669 for (i = strlen(line) - 1; i != 0; --i)
671 if (line[i] == ':')
672 return TRUE;
673 if (g_ascii_isspace(line[i]))
674 continue;
675 else
676 return FALSE;
679 return FALSE;
682 static void
683 anjuta_launcher_buffered_output (AnjutaLauncher *launcher,
684 AnjutaLauncherOutputType output_type,
685 const gchar *chars)
687 gchar *all_lines;
688 gchar *incomplete_line;
689 gchar **buffer;
691 g_return_if_fail (chars != NULL);
692 g_return_if_fail (strlen (chars) > 0);
694 if (launcher->priv->output_callback == NULL)
695 return;
696 if (launcher->priv->buffered_output == FALSE)
698 (launcher->priv->output_callback)(launcher, output_type, chars,
699 launcher->priv->callback_data);
700 return;
702 switch (output_type)
704 case ANJUTA_LAUNCHER_OUTPUT_STDOUT:
705 buffer = &launcher->priv->stdout_buffer;
706 break;
707 case ANJUTA_LAUNCHER_OUTPUT_STDERR:
708 buffer = &launcher->priv->stderr_buffer;
709 break;
710 default:
711 g_warning ("Should not reach here");
712 return;
714 if (*buffer)
715 all_lines = g_strconcat (*buffer, chars, NULL);
716 else
717 all_lines = g_strdup (chars);
719 /* Buffer the last incomplete line */
720 incomplete_line = all_lines + strlen (all_lines);
721 while (incomplete_line > all_lines &&
722 *incomplete_line != '\n')
724 incomplete_line = g_utf8_prev_char (incomplete_line);
726 if (*incomplete_line == '\n')
727 incomplete_line++;
729 /* Update line buffer */
730 g_free(*buffer);
731 *buffer = NULL;
732 if (strlen(incomplete_line))
734 *buffer = g_strdup (incomplete_line);
735 /* DEBUG_PRINT ("Line buffer for %d: %s", output_type, incomplete_line); */
737 /* Check for password prompt */
738 if (launcher->priv->check_for_passwd_prompt)
739 anjuta_launcher_check_password (launcher, incomplete_line);
741 /* Deliver complete lines */
742 *incomplete_line = '\0';
743 if (strlen (all_lines) > 0)
744 (launcher->priv->output_callback)(launcher, output_type, all_lines,
745 launcher->priv->callback_data);
746 g_free (all_lines);
749 static gboolean
750 anjuta_launcher_scan_output (GIOChannel *channel, GIOCondition condition,
751 AnjutaLauncher *launcher)
753 gsize n;
754 gchar buffer[FILE_BUFFER_SIZE];
755 gboolean ret = TRUE;
757 if (condition & G_IO_IN)
759 GError *err = NULL;
762 g_io_channel_read_chars (channel, buffer, FILE_BUFFER_SIZE-1, &n, &err);
763 if (n > 0) /* There is output */
765 gchar *utf8_chars;
766 buffer[n] = '\0';
767 utf8_chars = anjuta_util_convert_to_utf8 (buffer);
768 anjuta_launcher_buffered_output (launcher,
769 ANJUTA_LAUNCHER_OUTPUT_STDOUT,
770 utf8_chars);
771 g_free (utf8_chars);
773 /* Ignore illegal characters */
774 if (err && err->domain == G_CONVERT_ERROR)
776 g_warning ("stdout: %s", err->message);
777 g_error_free (err);
778 err = NULL;
780 /* The pipe is closed on the other side */
781 /* if not related to non blocking read or interrupted syscall */
782 else if (err && errno != EAGAIN && errno != EINTR)
784 g_warning ("stdout: %s", err->message);
785 launcher->priv->stdout_is_done = TRUE;
786 anjuta_launcher_synchronize (launcher);
787 ret = FALSE;
789 /* Read next chars if buffer was too small
790 * (the maximum length of one character is 6 bytes) */
791 } while (!err && (n > FILE_BUFFER_SIZE - 7));
792 if (err)
793 g_error_free (err);
795 if ((condition & G_IO_ERR) || (condition & G_IO_HUP))
797 DEBUG_PRINT ("launcher.c: STDOUT pipe closed");
798 launcher->priv->stdout_is_done = TRUE;
799 anjuta_launcher_synchronize (launcher);
800 ret = FALSE;
802 return ret;
805 static gboolean
806 anjuta_launcher_scan_error (GIOChannel *channel, GIOCondition condition,
807 AnjutaLauncher *launcher)
809 gsize n;
810 gchar buffer[FILE_BUFFER_SIZE];
811 gboolean ret = TRUE;
813 if (condition & G_IO_IN)
815 GError *err = NULL;
818 g_io_channel_read_chars (channel, buffer, FILE_BUFFER_SIZE-1, &n, &err);
819 if (n > 0) /* There is stderr output */
821 gchar *utf8_chars;
822 buffer[n] = '\0';
823 utf8_chars = anjuta_util_convert_to_utf8 (buffer);
824 anjuta_launcher_buffered_output (launcher,
825 ANJUTA_LAUNCHER_OUTPUT_STDERR,
826 utf8_chars);
827 g_free (utf8_chars);
829 /* Ignore illegal characters */
830 if (err && err->domain == G_CONVERT_ERROR)
832 g_warning ("stderr: %s", err->message);
833 g_error_free (err);
834 err = NULL;
836 /* The pipe is closed on the other side */
837 /* if not related to non blocking read or interrupted syscall */
838 else if (err && errno != EAGAIN && errno != EINTR)
840 g_warning ("stderr: %s", err->message);
842 launcher->priv->stderr_is_done = TRUE;
843 anjuta_launcher_synchronize (launcher);
844 ret = FALSE;
846 /* Read next chars if buffer was too small
847 * (the maximum length of one character is 6 bytes) */
848 } while (!err && (n > FILE_BUFFER_SIZE - 7));
849 if (err)
850 g_error_free (err);
852 if ((condition & G_IO_ERR) || (condition & G_IO_HUP))
854 DEBUG_PRINT ("launcher.c: STDERR pipe closed");
855 launcher->priv->stderr_is_done = TRUE;
856 anjuta_launcher_synchronize (launcher);
857 ret = FALSE;
859 return ret;
862 static gboolean
863 anjuta_launcher_scan_pty (GIOChannel *channel, GIOCondition condition,
864 AnjutaLauncher *launcher)
866 gsize n;
867 gchar buffer[FILE_BUFFER_SIZE];
868 gboolean ret = TRUE;
870 if (condition & G_IO_IN)
872 GError *err = NULL;
875 g_io_channel_read_chars (channel, buffer, FILE_BUFFER_SIZE-1, &n, &err);
876 if (n > 0) /* There is stderr output */
878 gchar *utf8_chars;
879 gchar *old_str = launcher->priv->pty_output_buffer;
880 buffer[n] = '\0';
881 utf8_chars = anjuta_util_convert_to_utf8 (buffer);
882 if (old_str)
884 gchar *str = g_strconcat (old_str, utf8_chars, NULL);
885 launcher->priv->pty_output_buffer = str;
886 g_free (old_str);
888 else
889 launcher->priv->pty_output_buffer = g_strdup (utf8_chars);
890 g_free (utf8_chars);
892 /* Ignore illegal characters */
893 if (err && err->domain == G_CONVERT_ERROR)
895 g_warning ("pty: %s", err->message);
896 g_error_free (err);
897 err = NULL;
899 /* The pipe is closed on the other side */
900 /* if not related to non blocking read or interrupted syscall */
901 else if (err && errno != EAGAIN && errno != EINTR)
903 g_warning ("pty: %s", err->message);
904 ret = FALSE;
906 /* Read next chars if buffer was too small
907 * (the maximum length of one character is 6 bytes) */
908 } while (!err && (n > FILE_BUFFER_SIZE - 7));
909 if (err)
910 g_error_free (err);
911 if (launcher->priv->check_for_passwd_prompt
912 && launcher->priv->pty_output_buffer
913 && strlen (launcher->priv->pty_output_buffer) > 0)
915 anjuta_launcher_check_password (launcher,
916 launcher->priv->pty_output_buffer);
919 /* In pty case, we handle the cases in different invocations */
920 /* Do not hook up for G_IO_HUP */
921 if (condition & G_IO_ERR)
923 DEBUG_PRINT ("launcher.c: PTY pipe error!");
924 ret = FALSE;
926 return ret;
929 static void
930 anjuta_launcher_execution_done_cleanup (AnjutaLauncher *launcher,
931 gboolean emit_signal)
933 gint child_status, child_pid;
934 time_t start_time;
936 if (launcher->priv->in_cleanup)
937 return;
939 launcher->priv->in_cleanup = TRUE;
941 /* Remove pending timeout */
942 if (launcher->priv->completion_check_timeout >= 0)
943 g_source_remove (launcher->priv->completion_check_timeout);
945 /* Make sure all pending I/O are flushed out */
946 while (g_main_context_pending (NULL))
947 g_main_context_iteration (NULL, FALSE);
949 /* Can be called again, while waiting in the previous line
950 * Do nothing if clean up is already done */
951 if (launcher->priv->stdout_channel)
953 g_io_channel_shutdown (launcher->priv->stdout_channel, emit_signal, NULL);
954 g_io_channel_unref (launcher->priv->stdout_channel);
955 g_source_remove (launcher->priv->stdout_watch);
958 if (launcher->priv->stderr_channel)
960 g_io_channel_shutdown (launcher->priv->stderr_channel, emit_signal, NULL);
961 g_io_channel_unref (launcher->priv->stderr_channel);
962 g_source_remove (launcher->priv->stderr_watch);
965 if (launcher->priv->pty_channel)
967 g_io_channel_shutdown (launcher->priv->pty_channel, emit_signal, NULL);
968 g_io_channel_unref (launcher->priv->pty_channel);
970 g_source_remove (launcher->priv->pty_watch);
973 if (launcher->priv->pty_output_buffer)
974 g_free (launcher->priv->pty_output_buffer);
975 if (launcher->priv->stdout_buffer)
976 g_free (launcher->priv->stdout_buffer);
977 if (launcher->priv->stderr_buffer)
978 g_free (launcher->priv->stdout_buffer);
980 /* Save them before we re-initialize */
981 child_status = launcher->priv->child_status;
982 child_pid = launcher->priv->child_pid;
983 start_time = launcher->priv->start_time;
985 if (emit_signal)
986 anjuta_launcher_set_busy (launcher, FALSE);
988 anjuta_launcher_initialize (launcher);
991 /* Call this here, after set_busy (FALSE) so we are able to
992 launch a new child from the terminate function.
993 (by clubfan 2002-04-07)
995 /* DEBUG_PRINT ("Exit status: %d", child_status); */
996 if (emit_signal)
997 g_signal_emit_by_name (launcher, "child-exited", child_pid,
998 child_status,
999 time (NULL) - start_time);
1002 /* Using this function is necessary because
1003 * anjuta_launcher_execution_done_cleanup needs to be called in the same
1004 * thread than the gtk main loop */
1005 static gboolean
1006 anjuta_launcher_call_execution_done (gpointer data)
1008 AnjutaLauncher *launcher = data;
1010 launcher->priv->completion_check_timeout = -1;
1011 anjuta_launcher_execution_done_cleanup (launcher, TRUE);
1012 return FALSE;
1015 /* monitors closure of stdout stderr and pty through a gtk_timeout_add setup */
1016 static gboolean
1017 anjuta_launcher_check_for_execution_done (gpointer data)
1019 AnjutaLauncher *launcher = data;
1021 DEBUG_PRINT ("launcher_execution_done STDOUT:%d, STDERR:%d",
1022 launcher->priv->stdout_is_done ? 1 : 0,
1023 launcher->priv->stderr_is_done ? 1 : 0);
1025 if (launcher->priv->stdout_is_done == FALSE ||
1026 launcher->priv->stderr_is_done == FALSE)
1027 return TRUE;
1028 if (launcher->priv->child_has_terminated == FALSE)
1030 /* DEBUG_PRINT ("launcher: We missed the exit of the child"); */
1032 launcher->priv->completion_check_timeout = -1;
1033 anjuta_launcher_execution_done_cleanup (launcher, TRUE);
1034 return FALSE;
1037 static void
1038 anjuta_launcher_child_terminated (GPid pid, gint status, gpointer data)
1040 AnjutaLauncher *launcher = data;
1042 g_return_if_fail(ANJUTA_IS_LAUNCHER(launcher));
1044 /* Save child exit code */
1045 launcher->priv->child_status = status;
1046 launcher->priv->child_has_terminated = TRUE;
1047 anjuta_launcher_synchronize (launcher);
1051 static gboolean
1052 anjuta_launcher_set_encoding_real (AnjutaLauncher *launcher, const gchar *charset)
1054 GIOStatus s;
1055 gboolean r = TRUE;
1057 g_return_val_if_fail (launcher != NULL, FALSE);
1058 // charset can be NULL
1060 s = g_io_channel_set_encoding (launcher->priv->stderr_channel, charset, NULL);
1061 if (s != G_IO_STATUS_NORMAL) r = FALSE;
1062 s = g_io_channel_set_encoding (launcher->priv->stdout_channel, charset, NULL);
1063 if (s != G_IO_STATUS_NORMAL) r = FALSE;
1064 s = g_io_channel_set_encoding (launcher->priv->pty_channel, charset, NULL);
1065 if (s != G_IO_STATUS_NORMAL) r = FALSE;
1067 if (! r)
1069 g_warning ("launcher.c: Failed to set channel encoding!");
1071 return r;
1076 * anjuta_launcher_set_encoding:
1077 * @launcher: a #AnjutaLancher object.
1078 * @charset: Character set to use for Input/Output with the process.
1080 * Sets the character set to use for Input/Output with the process.
1083 void
1084 anjuta_launcher_set_encoding (AnjutaLauncher *launcher, const gchar *charset)
1086 if (launcher->priv->custom_encoding)
1087 g_free (launcher->priv->encoding);
1089 launcher->priv->custom_encoding = (charset != NULL);
1090 if (charset)
1091 launcher->priv->encoding = g_strdup(charset);
1092 else
1093 launcher->priv->encoding = NULL;
1097 * anjuta_launcher_set_env:
1098 * @launcher: a #AnjutaLancher object.
1099 * @name: Name of the environment variable to set
1100 * @value: Value of the environment variable to set
1102 * Set an environment variable for the forked process
1105 void
1106 anjuta_launcher_set_env (AnjutaLauncher *launcher,
1107 const gchar *name,
1108 const gchar *value)
1110 g_return_if_fail (launcher && ANJUTA_IS_LAUNCHER(launcher));
1111 g_return_if_fail (name != NULL);
1112 g_return_if_fail (value != NULL);
1114 g_hash_table_insert (launcher->priv->env,
1115 g_strdup(name),
1116 g_strdup(value));
1119 static void
1120 anjuta_launcher_fork_setenv (const gchar* name, const gchar* value)
1122 setenv (name, value, TRUE);
1125 static pid_t
1126 anjuta_launcher_fork (AnjutaLauncher *launcher, gchar *const args[])
1128 char *working_dir;
1129 int pty_master_fd, md;
1130 int stdout_pipe[2], stderr_pipe[2];
1131 pid_t child_pid;
1132 struct termios termios_flags;
1134 working_dir = g_get_current_dir ();
1136 /* The pipes */
1137 pipe (stderr_pipe);
1138 pipe (stdout_pipe);
1140 /* Fork the command */
1141 child_pid = forkpty (&pty_master_fd, NULL, NULL, NULL);
1142 if (child_pid == 0)
1144 close (2);
1145 dup (stderr_pipe[1]);
1146 close (1);
1147 dup (stdout_pipe[1]);
1149 /* Close unnecessary pipes */
1150 close (stderr_pipe[0]);
1151 close (stdout_pipe[0]);
1154 if ((ioctl(pty_slave_fd, TIOCSCTTY, NULL))
1155 perror ("Could not set new controlling tty");
1157 /* Set no delays for the write pipes (non_buffered) so
1158 that we get all the outputs immidiately */
1159 if ((md = fcntl (stdout_pipe[1], F_GETFL)) != -1)
1160 fcntl (stdout_pipe[1], F_SETFL, O_SYNC | md);
1161 if ((md = fcntl (stderr_pipe[1], F_GETFL)) != -1)
1162 fcntl (stderr_pipe[1], F_SETFL, O_SYNC | md);
1164 /* Set up environment */
1165 g_hash_table_foreach (launcher->priv->env,
1166 (GHFunc) anjuta_launcher_fork_setenv,
1167 NULL);
1169 execvp (args[0], args);
1170 g_warning (_("Cannot execute command: \"%s\""), args[0]);
1171 perror(_("execvp failed"));
1172 _exit(-1);
1174 g_free (working_dir);
1176 /* Close parent's side pipes */
1177 close (stderr_pipe[1]);
1178 close (stdout_pipe[1]);
1180 if (child_pid < 0)
1182 g_warning ("launcher.c: Fork failed!");
1183 /* Close parent's side pipes */
1184 close (stderr_pipe[0]);
1185 close (stdout_pipe[0]);
1186 return child_pid;
1190 * Set pipes none blocking, so we can read big buffers
1191 * in the callback without having to use FIONREAD
1192 * to make sure the callback doesn't block.
1194 if ((md = fcntl (stdout_pipe[0], F_GETFL)) != -1)
1195 fcntl (stdout_pipe[0], F_SETFL, O_NONBLOCK | md);
1196 if ((md = fcntl (stderr_pipe[0], F_GETFL)) != -1)
1197 fcntl (stderr_pipe[0], F_SETFL, O_NONBLOCK | md);
1198 if ((md = fcntl (pty_master_fd, F_GETFL)) != -1)
1199 fcntl (pty_master_fd, F_SETFL, O_NONBLOCK | md);
1201 launcher->priv->child_pid = child_pid;
1202 launcher->priv->stderr_channel = g_io_channel_unix_new (stderr_pipe[0]);
1203 launcher->priv->stdout_channel = g_io_channel_unix_new (stdout_pipe[0]);
1204 launcher->priv->pty_channel = g_io_channel_unix_new (pty_master_fd);
1206 g_io_channel_set_buffer_size (launcher->priv->pty_channel, FILE_INPUT_BUFFER_SIZE);
1208 if (!launcher->priv->custom_encoding)
1209 g_get_charset ((const gchar**)&launcher->priv->encoding);
1210 anjuta_launcher_set_encoding_real (launcher, launcher->priv->encoding);
1212 tcgetattr(pty_master_fd, &termios_flags);
1213 termios_flags.c_iflag &= ~(IGNPAR | INPCK | INLCR | IGNCR | ICRNL | IXON |
1214 IXOFF | ISTRIP);
1215 termios_flags.c_iflag |= IGNBRK | BRKINT | IMAXBEL | IXANY;
1216 termios_flags.c_oflag &= ~OPOST;
1217 // termios_flags.c_oflag |= 0;
1218 termios_flags.c_cflag &= ~(CSTOPB | CREAD | PARENB | HUPCL);
1219 termios_flags.c_cflag |= CS8 | CLOCAL;
1221 if (!launcher->priv->terminal_echo_on)
1223 termios_flags.c_lflag &= ~(ECHOKE | ECHOE | ECHO | ECHONL |
1224 #ifdef ECHOPRT
1225 ECHOPRT |
1226 #endif
1227 ECHOCTL | ISIG | ICANON | IEXTEN | NOFLSH | TOSTOP);
1229 // termios_flags.c_lflag |= 0;
1230 termios_flags.c_cc[VMIN] = 0;
1231 cfsetospeed(&termios_flags, __MAX_BAUD);
1232 tcsetattr(pty_master_fd, TCSANOW, &termios_flags);
1234 launcher->priv->stderr_watch =
1235 g_io_add_watch (launcher->priv->stderr_channel,
1236 G_IO_IN | G_IO_ERR | G_IO_HUP,
1237 (GIOFunc)anjuta_launcher_scan_error, launcher);
1238 launcher->priv->stdout_watch =
1239 g_io_add_watch (launcher->priv->stdout_channel,
1240 G_IO_IN | G_IO_ERR | G_IO_HUP,
1241 (GIOFunc)anjuta_launcher_scan_output, launcher);
1242 launcher->priv->pty_watch =
1243 g_io_add_watch (launcher->priv->pty_channel,
1244 G_IO_IN | G_IO_ERR, /* Do not hook up for G_IO_HUP */
1245 (GIOFunc)anjuta_launcher_scan_pty, launcher);
1247 /* DEBUG_PRINT ("Terminal child forked: %d", launcher->priv->child_pid); */
1248 launcher->priv->source = g_child_watch_add (launcher->priv->child_pid,
1249 anjuta_launcher_child_terminated, launcher);
1250 return child_pid;
1254 * anjuta_launcher_execute_v:
1255 * @launcher: a #AnjutaLancher object.
1256 * @argv: Command args.
1257 * @callback: The callback for delivering output from the process.
1258 * @callback_data: Callback data for the above callback.
1260 * The first of the @args is the command itself. The rest are sent to the
1261 * as it's arguments. This function works similar to anjuta_launcher_execute().
1263 * Return value: TRUE if successfully launched, otherwise FALSE.
1265 gboolean
1266 anjuta_launcher_execute_v (AnjutaLauncher *launcher, gchar *const argv[],
1267 AnjutaLauncherOutputCallback callback,
1268 gpointer callback_data)
1270 if (anjuta_launcher_is_busy (launcher))
1271 return FALSE;
1273 anjuta_launcher_set_busy (launcher, TRUE);
1275 launcher->priv->start_time = time (NULL);
1276 launcher->priv->child_status = 0;
1277 launcher->priv->stdout_is_done = FALSE;
1278 launcher->priv->stderr_is_done = FALSE;
1279 launcher->priv->child_has_terminated = FALSE;
1280 launcher->priv->in_cleanup = FALSE;
1281 launcher->priv->output_callback = callback;
1282 launcher->priv->callback_data = callback_data;
1284 /* On a fork error perform a cleanup and return */
1285 if (anjuta_launcher_fork (launcher, argv) < 0)
1287 anjuta_launcher_initialize (launcher);
1288 return FALSE;
1290 return TRUE;
1294 * anjuta_launcher_execute:
1295 * @launcher: a #AnjutaLancher object.
1296 * @command_str: The command to execute.
1297 * @callback: The callback for delivering output from the process.
1298 * @callback_data: Callback data for the above callback.
1300 * Executes a command in the launcher. Both outputs (STDOUT and STDERR) are
1301 * delivered to the above callback. The data are delivered as they arrive
1302 * from the process and could be of any lenght. If the process asks for
1303 * passwords, the user will be automatically prompted with a dialog to enter
1304 * it. Please note that not all formats of the password are recognized. Those
1305 * with the standard 'assword:' substring in the prompt should work well.
1307 * Return value: TRUE if successfully launched, otherwise FALSE.
1309 gboolean
1310 anjuta_launcher_execute (AnjutaLauncher *launcher, const gchar *command_str,
1311 AnjutaLauncherOutputCallback callback,
1312 gpointer callback_data)
1314 GList *args_list, *args_list_ptr;
1315 gchar **args, **args_ptr;
1316 gboolean ret;
1318 /* Prepare command args */
1319 args_list = anjuta_util_parse_args_from_string (command_str);
1320 args = g_new (char*, g_list_length (args_list) + 1);
1321 args_list_ptr = args_list;
1322 args_ptr = args;
1323 while (args_list_ptr)
1325 *args_ptr = (char*) args_list_ptr->data;
1326 args_list_ptr = g_list_next (args_list_ptr);
1327 args_ptr++;
1329 *args_ptr = NULL;
1331 ret = anjuta_launcher_execute_v (launcher, args,
1332 callback, callback_data);
1333 g_free (args);
1334 anjuta_util_glist_strings_free (args_list);
1335 return ret;
1339 * anjuta_launcher_set_buffered_output:
1340 * @launcher: a #AnjutaLancher object.
1341 * @buffered: buffer output.
1343 * Sets if output should buffered or not. By default, it is buffered.
1345 * Return value: Previous flag value
1347 gboolean
1348 anjuta_launcher_set_buffered_output (AnjutaLauncher *launcher, gboolean buffered)
1350 gboolean past_value = launcher->priv->buffered_output;
1351 launcher->priv->buffered_output = buffered;
1352 return past_value;
1356 * anjuta_launcher_set_check_passwd_prompt:
1357 * @launcher: a #AnjutaLancher object.
1358 * @check_passwd: check for password.
1360 * Set if output is checked for a password prompti. A special dialog box
1361 * is use to enter it in this case. By default, this behavior is enabled.
1363 * Return value: Previous flag value
1365 gboolean
1366 anjuta_launcher_set_check_passwd_prompt (AnjutaLauncher *launcher, gboolean check_passwd)
1368 gboolean past_value = launcher->priv->check_for_passwd_prompt;
1369 launcher->priv->check_for_passwd_prompt = check_passwd;
1370 return past_value;
1374 * anjuta_launcher_set_terminal_echo:
1375 * @launcher: a #AnjutaLancher object.
1376 * @echo_on: Echo ON flag.
1378 * Sets if input (those given in STDIN) should enabled or disabled. By default,
1379 * it is disabled.
1381 * Return value: Previous flag value
1383 gboolean
1384 anjuta_launcher_set_terminal_echo (AnjutaLauncher *launcher,
1385 gboolean echo_on)
1387 gboolean past_value = launcher->priv->terminal_echo_on;
1388 launcher->priv->terminal_echo_on = echo_on;
1389 return past_value;
1393 * anjuta_launcher_set_terminate_on_exit:
1394 * @launcher: a #AnjutaLancher object.
1395 * @terminate_on_exit: terminate on exit flag
1397 * When this flag is set, al i/o channels are closed and the child-exit
1398 * signal is emitted as soon as the child exit. By default, or when this
1399 * flag is clear, the launcher object wait until the i/o channels are
1400 * closed.
1402 * Return value: Previous flag value
1404 gboolean
1405 anjuta_launcher_set_terminate_on_exit (AnjutaLauncher *launcher,
1406 gboolean terminate_on_exit)
1408 gboolean past_value = launcher->priv->terminate_on_exit;
1409 launcher->priv->terminate_on_exit = terminate_on_exit;
1410 return past_value;
1414 * anjuta_launcher_new:
1416 * Sets if input (those given in STDIN) should enabled or disabled. By default,
1417 * it is disabled.
1419 * Return value: a new instance of #AnjutaLancher class.
1421 AnjutaLauncher*
1422 anjuta_launcher_new ()
1424 return g_object_new (ANJUTA_TYPE_LAUNCHER, NULL);