[gparted/psusi/refactor: 5/19] Reduce threading (#685740)



commit 8691653472359ba9086bf52234a5f61f44cb1bed
Author: Phillip Susi <psusi ubuntu com>
Date:   Sat Jan 19 00:08:28 2013 -0500

    Reduce threading (#685740)
    
    Win_Gparted and Dialog_Progress were creating threads to perform most
    functions in the background.  Most of the time, the only reason the
    threads blocked was to execute an external command.  The external command
    execution has been changed to spawn the command asynchronously and wait
    for completion with a nested main loop.  While waiting for completion,
    the pipe output is captured via events.  In the future, this will allow
    for it to be parsed in real time to obtain progress information.
    
    Those tasks in GParted_Core that still block now spawn a background thread
    and wait for it to complete with a nested main loop to avoid hanging the
    gui.
    
    Part of Bug #685740 - Refactor to use asynchronous command execution

 include/Dialog_Progress.h |    4 +-
 include/FileSystem.h      |   15 ++--
 include/GParted_Core.h    |    1 +
 include/Makefile.am       |    3 +-
 include/PipeCapture.h     |   27 +++++++
 include/Utils.h           |    2 -
 include/Win_GParted.h     |   10 +--
 src/Dialog_Progress.cc    |   25 +------
 src/FileSystem.cc         |  107 +++++++++++++++++++--------
 src/GParted_Core.cc       |   20 +++++-
 src/Makefile.am           |    3 +-
 src/PipeCapture.cc        |   66 +++++++++++++++++
 src/Utils.cc              |  179 ++++++++++++++++++++++++--------------------
 src/Win_GParted.cc        |  142 ++++++++++++------------------------
 src/btrfs.cc              |    7 +-
 src/jfs.cc                |   10 +-
 src/nilfs2.cc             |    8 +-
 src/xfs.cc                |   28 ++++----
 18 files changed, 381 insertions(+), 276 deletions(-)
---
diff --git a/include/Dialog_Progress.h b/include/Dialog_Progress.h
index e4ede18..12532ce 100644
--- a/include/Dialog_Progress.h
+++ b/include/Dialog_Progress.h
@@ -46,11 +46,10 @@ public:
 		
 private:
 	void on_signal_update( const OperationDetail & operationdetail ) ;
-	void dispatcher_on_update_gui_elements() ;
+	void update_gui_elements() ;
 	void on_signal_show() ;
 	void on_expander_changed() ;
 	void on_cell_data_description( Gtk::CellRenderer * renderer, const Gtk::TreeModel::iterator & iter) ;
-	void thread_apply_operation();
 	void on_cancel() ;
 	void on_save() ;
 	void echo_operation_details( const OperationDetail & operation_detail, std::ofstream & out ) ;
@@ -97,7 +96,6 @@ private:
 	double fraction ;
 	unsigned int t, warnings ;
 	sigc::connection pulsetimer;
-	Glib::Dispatcher dispatcher_update_gui_elements ;
 	Glib::ustring label_current_sub_text ;
 };
 
diff --git a/include/FileSystem.h b/include/FileSystem.h
index de4270a..089a306 100644
--- a/include/FileSystem.h
+++ b/include/FileSystem.h
@@ -21,6 +21,7 @@
 #define DEFINE_FILESYSTEM
 
 #include "../include/Operation.h"
+#include "../include/PipeCapture.h"
 
 #include <fstream>
 #include <sys/stat.h>
@@ -56,12 +57,12 @@ public:
 			   OperationDetail & operationdetail ) = 0 ;
 	virtual bool check_repair( const Partition & partition, OperationDetail & operationdetail ) = 0 ;
 	virtual bool remove( const Partition & partition, OperationDetail & operationdetail ) = 0 ;
-
+	bool success;
 protected:
-	int execute_command( const Glib::ustring & command, OperationDetail & operationdetail ) ;
-	int execute_command_timed( const Glib::ustring & command
-	                         , OperationDetail & operationdetail
-	                         , bool check_status = true ) ;
+	int execute_command( const Glib::ustring & command, OperationDetail & operationdetail, bool checkstatus = false );
+	int execute_command_timed( const Glib::ustring & command, OperationDetail & operationdetail ) {
+		return execute_command( command, operationdetail, true ); }
+	void execute_command_eof();
 	Glib::ustring mk_temp_dir( const Glib::ustring & infix, OperationDetail & operationdetail ) ;
 	void rm_temp_dir( const Glib::ustring dir_name, OperationDetail & operationdetail ) ;
 
@@ -72,7 +73,9 @@ protected:
 	unsigned int index ;
 	
 private:
-
+	void store_exit_status( GPid pid, int status );
+	bool running;
+	int pipecount;
 };
 
 } //GParted
diff --git a/include/GParted_Core.h b/include/GParted_Core.h
index b993131..d10ffc1 100644
--- a/include/GParted_Core.h
+++ b/include/GParted_Core.h
@@ -42,6 +42,7 @@ public:
 	void find_supported_filesystems() ;
 	void set_user_devices( const std::vector<Glib::ustring> & user_devices ) ;
 	void set_devices( std::vector<Device> & devices ) ;
+	void set_devices_thread( std::vector<Device> * pdevices );
 	void guess_partition_table(const Device & device, Glib::ustring &buff);
 	
 	bool snap_to_cylinder( const Device & device, Partition & partition, Glib::ustring & error ) ;
diff --git a/include/Makefile.am b/include/Makefile.am
index 136da21..5c3f554 100644
--- a/include/Makefile.am
+++ b/include/Makefile.am
@@ -55,4 +55,5 @@ EXTRA_DIST = \
 	reiser4.h   			\
 	reiserfs.h  			\
 	ufs.h  				\
-	xfs.h
+	xfs.h				\
+	PipeCapture.h
diff --git a/include/PipeCapture.h b/include/PipeCapture.h
new file mode 100644
index 0000000..bd39aa3
--- /dev/null
+++ b/include/PipeCapture.h
@@ -0,0 +1,27 @@
+#ifndef PIPECAPTURE_H
+#define PIPECAPTURE_H
+
+#include <glibmm/ustring.h>
+#include <glibmm/main.h>
+
+namespace GParted {
+
+// captures output pipe of subprocess into a ustring and emits a signal on eof
+class PipeCapture
+{
+	Glib::ustring &buff;
+	unsigned int backcount;
+	unsigned int linelength;
+	Glib::RefPtr<Glib::IOChannel> channel;
+	sigc::connection connection;
+	bool OnReadable( Glib::IOCondition condition );
+public:
+	PipeCapture( int fd, Glib::ustring &buffer );
+	~PipeCapture();
+	sigc::signal<void> eof;
+	sigc::signal<void> update;
+};
+
+} // namepace GParted
+
+#endif
diff --git a/include/Utils.h b/include/Utils.h
index 870cfeb..5094890 100644
--- a/include/Utils.h
+++ b/include/Utils.h
@@ -178,7 +178,6 @@ public:
                     const char drive_letter, const Glib::ustring & device_path ) ;
 	static Glib::ustring delete_mtoolsrc_file( const char file_name[] ) ;
 	static Glib::ustring trim( const Glib::ustring & src, const Glib::ustring & c = " \t\r\n" ) ;
-	static Glib::ustring cleanup_cursor( const Glib::ustring & text ) ;
 	static Glib::ustring get_lang() ;
 	static void tokenize( const Glib::ustring& str,
 	                      std::vector<Glib::ustring>& tokens,
@@ -196,7 +195,6 @@ private:
 	static bool get_kernel_version( int & major_ver, int & minor_ver, int & patch_ver ) ;
 };
 
-
 }//GParted
 
 #endif //UTILS
diff --git a/include/Win_GParted.h b/include/Win_GParted.h
index 15a4f34..dab5fbd 100644
--- a/include/Win_GParted.h
+++ b/include/Win_GParted.h
@@ -55,7 +55,7 @@ private:
 
 	void refresh_combo_devices() ;
 	void show_pulsebar( const Glib::ustring & status_message ) ;
-	
+	void hide_pulsebar();
 	//Fill txtview_device_info_buffer with some information about the selected device
 	void Fill_Label_Device_Info( bool clear = false );
 
@@ -126,12 +126,7 @@ private:
 	}
 		
 	//threads..
-	void thread_refresh_devices() ;
-	void thread_unmount_partition( bool * succes, Glib::ustring * error ) ;
-	void thread_mount_partition( Glib::ustring mountpoint, bool * succes, Glib::ustring * error ) ;
-	void thread_toggle_swap( bool * succes, Glib::ustring * error ) ;
-	void thread_toggle_lvm2_pv( bool * succes, Glib::ustring * error ) ;
-	void thread_guess_partition_table();
+	void unmount_partition( bool * succes, Glib::ustring * error );
 		
 	//signal handlers
 	void open_operationslist() ;
@@ -260,6 +255,7 @@ private:
 					
 	//stuff for progress overview and pulsebar
 	bool pulsebar_pulse();
+	sigc::connection pulsetimer;
 };
 
 } //GParted
diff --git a/src/Dialog_Progress.cc b/src/Dialog_Progress.cc
index 822ac94..4560560 100644
--- a/src/Dialog_Progress.cc
+++ b/src/Dialog_Progress.cc
@@ -38,9 +38,6 @@ Dialog_Progress::Dialog_Progress( const std::vector<Operation *> & operations )
 
 	fraction = 1.00 / operations .size() ;
 		
-	dispatcher_update_gui_elements .connect( 
-		sigc::mem_fun( this, &Dialog_Progress::dispatcher_on_update_gui_elements ) ) ;
-
 	{
 		Gtk::VBox* vbox(manage(new Gtk::VBox()));
 
@@ -158,12 +155,12 @@ void Dialog_Progress::on_signal_update( const OperationDetail & operationdetail
 		if ( operationdetail .get_status() == STATUS_EXECUTE )
 			label_current_sub_text = operationdetail .get_description() ;
 
-		dispatcher_update_gui_elements() ;
 		if ( operationdetail.fraction >= 0 ) {
 			pulsetimer.disconnect();
 			progressbar_current.set_fraction( operationdetail.fraction > 1.0 ? 1.0 : operationdetail.fraction );
 		} else if( !pulsetimer.connected() )
 			pulsetimer = Glib::signal_timeout().connect( sigc::mem_fun(*this, &Dialog_Progress::pulsebar_pulse), 100 );
+		update_gui_elements();
 	}
 	else//it's an new od which needs to be added to the model.
 	{
@@ -182,7 +179,7 @@ void Dialog_Progress::on_signal_update( const OperationDetail & operationdetail
 	}
 }
 
-void Dialog_Progress::dispatcher_on_update_gui_elements()
+void Dialog_Progress::update_gui_elements()
 {
 	label_current_sub .set_markup( "<i>" + label_current_sub_text + "</i>\n" ) ;
 	
@@ -216,11 +213,7 @@ void Dialog_Progress::on_signal_show()
 		//set focus...
 		treeview_operations .set_cursor( static_cast<Gtk::TreePath>( treerow ) ) ;
 		
-		//and start..
-		Glib::Thread::create( sigc::mem_fun(
-					*this, &Dialog_Progress::thread_apply_operation ),
-				      false );
-		Gtk::Main::run();
+		succes = signal_apply_operation.emit( operations[t] );
 
 		//set status (succes/error) for this operation
 		operations[ t ] ->operation_detail .set_status( succes ? STATUS_SUCCES : STATUS_ERROR ) ;
@@ -299,18 +292,6 @@ void Dialog_Progress::on_cell_data_description( Gtk::CellRenderer * renderer, co
 		static_cast<Gtk::TreeRow>( *iter )[ treeview_operations_columns .operation_description ] ;
 }
 
-static bool _mainquit( void *dummy )
-{
-	Gtk::Main::quit();
-	return false;
-}
-
-void Dialog_Progress::thread_apply_operation()
-{
-	succes = signal_apply_operation.emit( operations[t] );
-	g_idle_add( (GSourceFunc)_mainquit, NULL );
-}
-
 void Dialog_Progress::on_cancel()
 {
 	Gtk::MessageDialog dialog( *this,
diff --git a/src/FileSystem.cc b/src/FileSystem.cc
index 8b02404..775d5de 100644
--- a/src/FileSystem.cc
+++ b/src/FileSystem.cc
@@ -17,12 +17,16 @@
  
  
 #include "../include/FileSystem.h"
+#include "../include/GParted_Core.h"
 
 #include <cerrno>
+#include <iostream>
+#include <gtkmm/main.h>
+#include <fcntl.h>
 
 namespace GParted
 {
-	
+
 FileSystem::FileSystem()
 {
 }
@@ -48,44 +52,85 @@ const Glib::ustring FileSystem::get_generic_text( CUSTOM_TEXT ttype, int index )
 	}
 }
 
-int FileSystem::execute_command( const Glib::ustring & command, OperationDetail & operationdetail ) 
+void FileSystem::store_exit_status( GPid pid, int status )
 {
-	operationdetail .add_child( OperationDetail( command, STATUS_NONE, FONT_BOLD_ITALIC ) ) ;
-
-	int exit_status = Utils::execute_command( "nice -n 19 " + command, output, error ) ;
-
-	if ( ! output .empty() )
-		operationdetail .get_last_child() .add_child( OperationDetail( output, STATUS_NONE, FONT_ITALIC ) ) ;
-	
-	if ( ! error .empty() )
-		operationdetail .get_last_child() .add_child( OperationDetail( error, STATUS_NONE, FONT_ITALIC ) ) ;
-
-	return exit_status ;
+	exit_status = status;
+	running = false;
+	if (pipecount == 0) // pipes finished first
+		Gtk::Main::quit();
+	Glib::spawn_close_pid( pid );
 }
 
-//Time command, add results to operation detail and by default set success or failure
-int FileSystem::execute_command_timed( const Glib::ustring & command
-                                     , OperationDetail & operationdetail
-                                     , bool check_status )
+static void relay_update( OperationDetail *operationdetail, Glib::ustring *str )
 {
-	operationdetail .add_child( OperationDetail( command, STATUS_EXECUTE, FONT_BOLD_ITALIC ) ) ;
+	operationdetail->set_description( *str, FONT_ITALIC );
+}
 
-	int exit_status = Utils::execute_command( "nice -n 19 " + command, output, error ) ;
-	if ( check_status )
-	{
-		if ( ! exit_status )
-			operationdetail .get_last_child() .set_status( STATUS_SUCCES ) ;
+int FileSystem::execute_command( const Glib::ustring & command, OperationDetail & operationdetail, bool checkstatus )
+{
+	operationdetail .add_child( OperationDetail( command, checkstatus ? STATUS_EXECUTE : STATUS_NONE, FONT_BOLD_ITALIC ) ) ;
+	Glib::Pid pid;
+	// set up pipes for capture
+	int out, err;
+	// spawn external process
+	running = true;
+	try {
+		Glib::spawn_async_with_pipes(
+			std::string(),
+			Glib::shell_parse_argv( command ),
+			Glib::SPAWN_DO_NOT_REAP_CHILD | Glib::SPAWN_SEARCH_PATH,
+			sigc::slot< void >(),
+			&pid,
+			0,
+			&out,
+			&err );
+	} catch (Glib::SpawnError &e) {
+		std::cerr << e.what() << std::endl;
+		operationdetail.get_last_child().add_child(
+			OperationDetail( e.what(), STATUS_ERROR, FONT_ITALIC ) );
+		return 1;
+	}
+	fcntl( out, F_SETFL, O_NONBLOCK );
+	fcntl( err, F_SETFL, O_NONBLOCK );
+	Glib::signal_child_watch().connect( sigc::mem_fun( *this, &FileSystem::store_exit_status ), pid );
+	output.clear();
+	error.clear();
+	pipecount = 2;
+	PipeCapture outputcapture( out, output );
+	PipeCapture errorcapture( err, error );
+	outputcapture.eof.connect( sigc::mem_fun( *this, &FileSystem::execute_command_eof ) );
+	errorcapture.eof.connect( sigc::mem_fun( *this, &FileSystem::execute_command_eof ) );
+	operationdetail.add_child(
+		OperationDetail( output, STATUS_NONE, FONT_ITALIC ) );
+	operationdetail.add_child(
+		OperationDetail( error, STATUS_NONE, FONT_ITALIC ) );
+	std::vector<OperationDetail> &children = operationdetail.get_childs();
+	outputcapture.update.connect( sigc::bind( sigc::ptr_fun( relay_update ),
+						  &(children[children.size() - 2]),
+						  &output ) );
+	errorcapture.update.connect( sigc::bind( sigc::ptr_fun( relay_update ),
+						 &(children[children.size() - 1]),
+						 &error ) );
+
+	Gtk::Main::run();
+
+	if (checkstatus) {
+		if ( !exit_status )
+			children[children.size() - 3].set_status( STATUS_SUCCES );
 		else
-			operationdetail .get_last_child() .set_status( STATUS_ERROR ) ;
+			children[children.size() - 3].set_status( STATUS_ERROR );
 	}
+	close( out );
+	close( err );
+	return exit_status;
+}
 
-	if ( ! output .empty() )
-		operationdetail .get_last_child() .add_child( OperationDetail( output, STATUS_NONE, FONT_ITALIC ) ) ;
-
-	if ( ! error .empty() )
-		operationdetail .get_last_child() .add_child( OperationDetail( error, STATUS_NONE, FONT_ITALIC ) ) ;
-
-	return exit_status ;
+void FileSystem::execute_command_eof()
+{
+	if (--pipecount)
+		return; // wait for second pipe to eof
+	if ( !running ) // already got exit status
+		Gtk::Main::quit();
 }
 
 //Create uniquely named temporary directory and add results to operation detail
diff --git a/src/GParted_Core.cc b/src/GParted_Core.cc
index 1f0bcc0..8f1c7cc 100644
--- a/src/GParted_Core.cc
+++ b/src/GParted_Core.cc
@@ -57,6 +57,7 @@
 #include <dirent.h>
 #include <mntent.h>
 #include <gtkmm/messagedialog.h>
+#include <gtkmm/main.h>
 
 std::vector<Glib::ustring> libparted_messages ; //see ped_exception_handler()
 
@@ -138,6 +139,22 @@ void GParted_Core::set_user_devices( const std::vector<Glib::ustring> & user_dev
 	
 void GParted_Core::set_devices( std::vector<Device> & devices )
 {
+	Glib::Thread::create( sigc::bind(
+				sigc::mem_fun( *this, &GParted_Core::set_devices_thread ),
+				&devices),
+			      false );
+	Gtk::Main::run();
+}
+
+static bool _mainquit( void *dummy )
+{
+	Gtk::Main::quit();
+	return false;
+}
+
+void GParted_Core::set_devices_thread( std::vector<Device> * pdevices )
+{
+	std::vector<Device> &devices = *pdevices;
 	devices .clear() ;
 	Device temp_device ;
 	Proc_Partitions_Info pp_info( true ) ;  //Refresh cache of proc partition information
@@ -325,6 +342,7 @@ void GParted_Core::set_devices( std::vector<Device> & devices )
 	//NOTE that we cannot clear mountinfo since it might be needed in get_all_mountpoints()
 	set_thread_status_message("") ;
 	fstab_info .clear() ;
+	g_idle_add( (GSourceFunc)_mainquit, NULL );
 }
 
 // runs gpart on the specified parameter
@@ -3548,7 +3566,7 @@ struct ped_exception_ctx {
 
 static bool _ped_exception_handler( struct ped_exception_ctx *ctx )
 {
-        std::cout << ctx->e->message << std::endl;
+        std::cerr << ctx->e->message << std::endl;
 
         libparted_messages.push_back( ctx->e->message );
 	char optcount = 0;
diff --git a/src/Makefile.am b/src/Makefile.am
index d5ec826..8c0541f 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -65,7 +65,8 @@ gpartedbin_SOURCES = \
 	reiser4.cc 			\
 	reiserfs.cc			\
 	ufs.cc				\
-	xfs.cc
+	xfs.cc				\
+	PipeCapture.cc
 
 gpartedbin_LDFLAGS = -lparted
 
diff --git a/src/PipeCapture.cc b/src/PipeCapture.cc
new file mode 100644
index 0000000..1e0570b
--- /dev/null
+++ b/src/PipeCapture.cc
@@ -0,0 +1,66 @@
+#include "../include/PipeCapture.h"
+#include <iostream>
+
+namespace GParted {
+
+PipeCapture::PipeCapture( int fd, Glib::ustring &string ) : buff( string ), backcount( 0 ), linelength( 0 )
+{
+	// tie fd to string
+	// make channel
+	channel = Glib::IOChannel::create_from_fd( fd );
+	connection = Glib::signal_io().connect(
+		sigc::mem_fun( *this, &PipeCapture::OnReadable ),
+		fd,
+		Glib::IO_IN | Glib::IO_HUP | Glib::IO_ERR );
+}
+
+bool PipeCapture::OnReadable( Glib::IOCondition condition )
+{
+	// read from pipe and store in buff
+	Glib::ustring str;
+	Glib::IOStatus status = channel->read( str, 512 );
+	if (status == Glib::IO_STATUS_NORMAL)
+	{
+		for( Glib::ustring::iterator s = str.begin();
+		     s != str.end(); s++ )
+		{
+			if( *s == '\b' )
+				backcount++;
+			else if( *s == '\r' ) {
+				backcount = linelength;
+				linelength = 0;
+			} else if( *s == '\n' ) {
+				linelength = 0;
+				buff += '\n';
+				backcount = 0;
+			}
+			else {
+				if (backcount) {
+					buff.erase( buff.length() - backcount, backcount );
+					linelength -= backcount;
+					backcount = 0;
+				}
+				buff += *s;
+				if( ++linelength == 80 ) {
+					buff += '\n';
+					linelength = 0;
+				}
+			}
+		}
+		update();
+		return true;
+	}
+	if (status != Glib::IO_STATUS_EOF)
+		std::cerr << "Pipe IOChannel read failed" << std::endl;
+	// signal completion
+	eof();
+	connection.disconnect();
+	return false;
+}
+
+PipeCapture::~PipeCapture()
+{
+	connection.disconnect();
+}
+
+} // namespace GParted
diff --git a/src/Utils.cc b/src/Utils.cc
index e66b1f4..53fbdb5 100644
--- a/src/Utils.cc
+++ b/src/Utils.cc
@@ -17,6 +17,8 @@
  */
 
 #include "../include/Utils.h"
+#include "../include/GParted_Core.h"
+#include "../include/PipeCapture.h"
 
 #include <sstream>
 #include <fstream>
@@ -26,7 +28,8 @@
 #include <uuid/uuid.h>
 #include <cerrno>
 #include <sys/statvfs.h>
-
+#include <gtkmm/main.h>
+#include <fcntl.h>
 
 namespace GParted
 {
@@ -269,7 +272,7 @@ bool Utils::kernel_supports_fs( const Glib::ustring & fs )
 		return true ;
 
 	Glib::ustring output, error ;
-	execute_command( "modprobe " + fs, output, error, true ) ;
+	execute_command( "modprobe " + fs, output, error, true );
 
 	input .open( "/proc/filesystems" ) ;
 	if ( input )
@@ -380,62 +383,107 @@ int Utils::execute_command( const Glib::ustring & command )
 	return execute_command( command, dummy, dummy ) ;
 }
 
-int Utils::execute_command( const Glib::ustring & command,
-		     	    Glib::ustring & output,
-			    Glib::ustring & error,
-		     	    bool use_C_locale )
+class utils_execute_command_status
 {
-	int exit_status = -1 ;
-	std::string std_out, std_error ;
-
-	try
+public:
+	bool running;
+	int pipecount;
+	int exit_status;
+	bool foreground;
+	Glib::Threads::Mutex mutex;
+	Glib::Threads::Cond cond;
+	void store_exit_status( GPid pid, int status );
+	void execute_command_eof();
+};
+
+void utils_execute_command_status::store_exit_status( GPid pid, int status )
+{
+	exit_status = status;
+	running = false;
+	if (pipecount == 0) // pipes finished first
 	{
-		std::vector<std::string>argv;
-		argv .push_back( "sh" ) ;
-		argv .push_back( "-c" ) ;
-		argv .push_back( command ) ;
-
-		if ( use_C_locale )
-		{
-			//Spawn command using the C language environment
-			std::vector<std::string> envp ;
-			envp .push_back( "LC_ALL=C" ) ;
-			envp .push_back( "PATH=" + Glib::getenv( "PATH" ) ) ;
-
-			Glib::spawn_sync( "."
-			                , argv
-			                , envp
-			                , Glib::SPAWN_SEARCH_PATH
-			                , sigc::slot<void>()
-			                , &std_out
-			                , &std_error
-			                , &exit_status
-			                ) ;
-		}
-		else
-		{
-			//Spawn command inheriting the parent's environment
-			Glib::spawn_sync( "."
-			                , argv
-			                , Glib::SPAWN_SEARCH_PATH
-			                , sigc::slot<void>()
-			                , &std_out
-			                , &std_error
-			                , &exit_status
-			                ) ;
+		if (foreground)
+			Gtk::Main::quit();
+		else {
+			mutex.lock();
+			cond.signal();
+			mutex.unlock();
 		}
 	}
-	catch ( Glib::Exception & e )
-	{
-		 error = e .what() ;
+	Glib::spawn_close_pid( pid );
+}
 
-		 return -1 ;
+void utils_execute_command_status::execute_command_eof()
+{
+	if (--pipecount)
+		return; // wait for second pipe to eof
+	if ( !running ) // already got exit status
+	{
+		if (foreground)
+			Gtk::Main::quit();
+		else {
+			mutex.lock();
+			cond.signal();
+			mutex.unlock();
+		}
 	}
+}
 
-	output = Utils::cleanup_cursor( std_out ) ;
-	error = std_error ;
+static void set_locale()
+{
+	setenv( "LC_ALL", "C", 1 );
+}
 
-	return exit_status ;
+int Utils::execute_command( const Glib::ustring & command,
+			    Glib::ustring & output,
+			    Glib::ustring & error,
+			    bool use_C_locale )
+{
+	Glib::Pid pid;
+	// set up pipes for capture
+	int out, err;
+	utils_execute_command_status status;
+	// spawn external process
+	status.running = true;
+	status.pipecount = 2;
+	status.foreground = (Glib::Thread::self() == GParted_Core::mainthread);
+	try {
+		Glib::spawn_async_with_pipes(
+			std::string(),
+			Glib::shell_parse_argv( command ),
+			Glib::SPAWN_DO_NOT_REAP_CHILD | Glib::SPAWN_SEARCH_PATH,
+			use_C_locale ? sigc::ptr_fun( set_locale ) : sigc::slot< void >(),
+			&pid,
+			0,
+			&out,
+			&err );
+	} catch (Glib::SpawnError &e) {
+		std::cerr << e.what() << std::endl;
+		return 1;
+	}
+	fcntl( out, F_SETFL, O_NONBLOCK );
+	fcntl( err, F_SETFL, O_NONBLOCK );
+	Glib::signal_child_watch().connect( sigc::mem_fun(
+			  status, &utils_execute_command_status::store_exit_status ),
+					    pid );
+	output.clear();
+	error.clear();
+	PipeCapture outputcapture( out, output );
+	PipeCapture errorcapture( err, error );
+	outputcapture.eof.connect( sigc::mem_fun(
+		 status, &utils_execute_command_status::execute_command_eof ));
+	errorcapture.eof.connect( sigc::mem_fun(
+		 status, &utils_execute_command_status::execute_command_eof ));
+
+	if( status.foreground)
+		Gtk::Main::run();
+	else {
+		status.mutex.lock();
+		status.cond.wait( status.mutex );
+	}
+	close( out );
+	close( err );
+	return status.exit_status;
 }
 
 Glib::ustring Utils::regexp_label( const Glib::ustring & text
@@ -468,37 +516,6 @@ Glib::ustring Utils::trim( const Glib::ustring & src, const Glib::ustring & c /*
 	return src.substr(p1, (p2-p1)+1);
 }
 
-Glib::ustring Utils::cleanup_cursor( const Glib::ustring & text )
-{
-	std::istringstream in(text);
-	std::ostringstream out;
-	char ch;
-	std::streampos startofline = out.tellp();
-
-	while (in.get(ch))
-	{
-		switch(ch)
-		{
-			case '\r':
-				if ('\n' != in.peek()) // for windows CRLF
-					out.seekp(startofline);
-				else
-					out.put(ch);
-				break;
-			case '\b':
-				if (out.tellp() > startofline)
-					out.seekp(out.tellp() - std::streamoff(1));
-				break;
-			default:
-				out.put(ch);
-		}
-		if (ch == '\n')
-		 	startofline = out.tellp();
-	}
-
-	return out.str();
-}
-
 Glib::ustring Utils::get_lang()
 {
 	//Extract base language from string that may look like "en_CA.UTF-8"
diff --git a/src/Win_GParted.cc b/src/Win_GParted.cc
index 62ad11b..61e3802 100644
--- a/src/Win_GParted.cc
+++ b/src/Win_GParted.cc
@@ -621,8 +621,6 @@ bool Win_GParted::pulsebar_pulse()
 
 void Win_GParted::show_pulsebar( const Glib::ustring & status_message ) 
 {
-	sigc::connection pulsetimer;
-
 	pulsebar .show();
 	statusbar .push( status_message) ;
 	
@@ -636,10 +634,13 @@ void Win_GParted::show_pulsebar( const Glib::ustring & status_message )
 		
 	// connect pulse update timer
 	pulsetimer = Glib::signal_timeout().connect( sigc::mem_fun(*this, &Win_GParted::pulsebar_pulse), 100 );
-	Gtk::Main::run();
+}
+
+void Win_GParted::hide_pulsebar()
+{
 	pulsetimer.disconnect();
 	pulsebar .hide();
-	statusbar .pop() ;
+	statusbar.remove_all_messages();
 		
 	//enable all disabled stuff
 	toolbar_main .set_sensitive( true ) ;
@@ -1199,17 +1200,11 @@ void Win_GParted::on_show()
 	menu_gparted_refresh_devices() ;
 }
 	
-void Win_GParted::thread_refresh_devices() 
-{
-	gparted_core .set_devices( devices ) ;
-	Gtk::Main::quit();
-}
-
 void Win_GParted::menu_gparted_refresh_devices()
 {
-	Glib::Thread::create( sigc::mem_fun( *this, &Win_GParted::thread_refresh_devices ), false );
-
 	show_pulsebar( _("Scanning all devices...") ) ;
+	gparted_core.set_devices( devices );
+	hide_pulsebar();
 	
 	//check if current_device is still available (think about hotpluggable stuff like usbdevices)
 	if ( current_device >= devices .size() )
@@ -1981,7 +1976,7 @@ void Win_GParted::activate_format( GParted::FILESYSTEM new_fs )
 	}
 }
 
-void Win_GParted::thread_unmount_partition( bool * succes, Glib::ustring * error ) 
+void Win_GParted::unmount_partition( bool * succes, Glib::ustring * error ) 
 {
 	std::vector<Glib::ustring> errors, failed_mountpoints, mountpoints = gparted_core .get_all_mountpoints() ;
 	Glib::ustring dummy ;
@@ -2013,63 +2008,15 @@ void Win_GParted::thread_unmount_partition( bool * succes, Glib::ustring * error
 	}
 	else
 		*error = "<i>" + Glib::build_path( "\n", errors ) + "</i>" ;
-
-	Gtk::Main::quit();
 }
 	
-void Win_GParted::thread_mount_partition( Glib::ustring mountpoint, bool * succes, Glib::ustring * error ) 
-{
-	Glib::ustring dummy ;
-	std::vector<Glib::ustring> errors ;
-	
-	*succes = ! Utils::execute_command( "mount -v " + selected_partition .get_path() + " \"" + mountpoint + "\"",
-					    dummy,
-					    *error ) ;
-	Gtk::Main::quit();
-}
-
-void Win_GParted::thread_toggle_swap( bool * succes, Glib::ustring * error ) 
-{	
-	Glib::ustring dummy ;
-	
-	if ( selected_partition .busy )
-		*succes = ! Utils::execute_command( "swapoff -v " + selected_partition .get_path() + " && sync",
-						    dummy,
-						    *error ) ;
-	else
-		*succes = ! Utils::execute_command( "swapon -v " + selected_partition .get_path() + " && sync",
-						    dummy,
-						    *error ) ;
-	Gtk::Main::quit();
-}
-
-void Win_GParted::thread_toggle_lvm2_pv( bool * success, Glib::ustring * error )
-{
-	Glib::ustring dummy ;
-
-	if ( selected_partition .busy )
-		//VGNAME from mount point
-		*success = ! Utils::execute_command( "lvm vgchange -a n " + selected_partition .get_mountpoint(),
-		                                     dummy,
-		                                     *error ) ;
-	else
-		*success = ! Utils::execute_command( "lvm vgchange -a y " + selected_partition .get_mountpoint(),
-		                                     dummy,
-		                                     *error ) ;
-	Gtk::Main::quit();
-}
-
-// Runs gpart in a thread
-void Win_GParted::thread_guess_partition_table()
-{
-	this->gpart_output="";
-	this->gparted_core.guess_partition_table(devices[ current_device ], this->gpart_output);
-	Gtk::Main::quit();
-}
-
 void Win_GParted::toggle_busy_state()
 {
 	int operation_count = partition_in_operation_queue_count( selected_partition ) ;
+	bool success = false ;
+	Glib::ustring error ;
+	Glib::ustring output;
+
 	if ( operation_count > 0 )
 	{
 		//Note that this situation will only occur when trying to swapon a partition
@@ -2112,20 +2059,22 @@ void Win_GParted::toggle_busy_state()
 		return ;
 	}
 
-	bool succes = false ;
-	Glib::ustring error ;
-
 	if ( selected_partition .filesystem == GParted::FS_LINUX_SWAP )
 	{
-		Glib::Thread::create( sigc::bind<bool *, Glib::ustring *>( 
-			sigc::mem_fun( *this, &Win_GParted::thread_toggle_swap ), &succes, &error ), false );
-
 		show_pulsebar( 
 			String::ucompose( 
 				selected_partition .busy ? _("Deactivating swap on %1") : _("Activating swap on %1"),
 				selected_partition .get_path() ) ) ;
-
-		if ( ! succes )
+		if ( selected_partition .busy )
+			success = ! Utils::execute_command( "swapoff -v " + selected_partition .get_path(),
+							    output,
+							    error );
+		else
+			success = ! Utils::execute_command( "swapon -v " + selected_partition .get_path(),
+							    output,
+							    error );
+		hide_pulsebar();
+		if ( ! success )
 		{
 			Gtk::MessageDialog dialog( 
 				*this,
@@ -2142,17 +2091,24 @@ void Win_GParted::toggle_busy_state()
 	}
 	else if ( selected_partition .filesystem == GParted::FS_LVM2_PV )
 	{
-		Glib::Thread::create( sigc::bind<bool *, Glib::ustring *>(
-			sigc::mem_fun( *this, &Win_GParted::thread_toggle_lvm2_pv ), &succes, &error ), false );
-
 		show_pulsebar(
 			String::ucompose(
 				selected_partition .busy ? _("Deactivating Volume Group %1")
 				                         : _("Activating Volume Group %1"),
 				//VGNAME from mount point
 				selected_partition .get_mountpoint() ) ) ;
+		if ( selected_partition .busy )
+			//VGNAME from mount point
+			success = ! Utils::execute_command( "lvm vgchange -a n " + selected_partition .get_mountpoint(),
+							    output,
+							    error );
+		else
+			success = ! Utils::execute_command( "lvm vgchange -a y " + selected_partition .get_mountpoint(),
+							     output,
+							     error );
+		hide_pulsebar();
 
-		if ( ! succes )
+		if ( ! success )
 		{
 			Gtk::MessageDialog dialog(
 				*this,
@@ -2170,12 +2126,10 @@ void Win_GParted::toggle_busy_state()
 	}
 	else if ( selected_partition .busy )
 	{
-		Glib::Thread::create( sigc::bind<bool *, Glib::ustring *>( 
-			sigc::mem_fun( *this, &Win_GParted::thread_unmount_partition ), &succes, &error ), false );
-
 		show_pulsebar( String::ucompose( _("Unmounting %1"), selected_partition .get_path() ) ) ;
-	
-		if ( ! succes )
+		unmount_partition( &success, &error );
+		hide_pulsebar();
+		if ( ! success )
 		{
 			Gtk::MessageDialog dialog( *this, 
 						   String::ucompose( _("Could not unmount %1"), selected_partition .get_path() ),
@@ -2222,21 +2176,19 @@ void Win_GParted::activate_mount_partition( unsigned int index )
 		return ;
 	}
 
-	bool succes = false ;
+	bool success = false ;
 	Glib::ustring error ;
-
-	Glib::Thread::create( sigc::bind<Glib::ustring, bool *, Glib::ustring *>( 
-						sigc::mem_fun( *this, &Win_GParted::thread_mount_partition ),
-						selected_partition .get_mountpoints()[ index ],
-						&succes,
-						&error ),
-				       false );
+	Glib::ustring stdout;
 
 	show_pulsebar( String::ucompose( _("mounting %1 on %2"),
 					 selected_partition .get_path(),
 					 selected_partition .get_mountpoints()[ index ] ) ) ;
-
-	if ( ! succes )
+	success = !Utils::execute_command( "mount -v " + selected_partition .get_path() + " \"" +
+					   selected_partition.get_mountpoints()[ index ] + "\"",
+					   stdout,
+					   error ) ;
+	hide_pulsebar();
+	if ( ! success )
 	{
 		Gtk::MessageDialog dialog( *this, 
 					   String::ucompose( _("Could not mount %1 on %2"),
@@ -2375,11 +2327,11 @@ void Win_GParted::activate_attempt_rescue_data()
 
 	messageDialog.hide();
 
-	Glib::Thread::create( sigc::mem_fun( *this, &Win_GParted::thread_guess_partition_table ), false );
-
 	/*TO TRANSLATORS: looks like	Searching for file systems on /deb/sdb */
 	show_pulsebar(String::ucompose( _("Searching for file systems on %1"), devices[ current_device ] .get_path()));
-
+	gpart_output="";
+	gparted_core.guess_partition_table(devices[ current_device ], gpart_output);
+	hide_pulsebar();
 	Dialog_Rescue_Data dialog;
 	dialog .set_transient_for( *this );
 
diff --git a/src/btrfs.cc b/src/btrfs.cc
index e7b5c11..e3d11ce 100644
--- a/src/btrfs.cc
+++ b/src/btrfs.cc
@@ -195,7 +195,8 @@ bool btrfs::resize( const Partition & partition_new, OperationDetail & operation
 	if ( mount_point .empty() )
 		return false ;
 
-	success &= ! execute_command_timed( "mount -v -t btrfs " + partition_new .get_path() + " " + mount_point, operationdetail ) ;
+	success &= ! execute_command( "mount -v -t btrfs " + partition_new .get_path() + " " + mount_point,
+				      operationdetail, true ) ;
 
 	if ( success )
 	{
@@ -210,7 +211,7 @@ bool btrfs::resize( const Partition & partition_new, OperationDetail & operation
 			cmd = "btrfs filesystem resize " + size + " " + mount_point ;
 		else
 			cmd = "btrfsctl -r " + size + " " + mount_point ;
-		exit_status = execute_command_timed( cmd, operationdetail, false ) ;
+		exit_status = execute_command( cmd, operationdetail, false ) ;
 		bool resize_succeeded = ( exit_status == 0 ) ;
 		if ( resize_to_same_size_fails )
 		{
@@ -235,7 +236,7 @@ bool btrfs::resize( const Partition & partition_new, OperationDetail & operation
 		operationdetail .get_last_child() .set_status( resize_succeeded ? STATUS_SUCCES : STATUS_ERROR ) ;
 		success &= resize_succeeded ;
 
-		success &= ! execute_command_timed( "umount -v " + mount_point, operationdetail ) ;
+		success &= ! execute_command( "umount -v " + mount_point, operationdetail, true ) ;
 	}
 
 	rm_temp_dir( mount_point, operationdetail ) ;
diff --git a/src/jfs.cc b/src/jfs.cc
index d938903..5d8cbf0 100644
--- a/src/jfs.cc
+++ b/src/jfs.cc
@@ -160,15 +160,15 @@ bool jfs::resize( const Partition & partition_new, OperationDetail & operationde
 	if ( mount_point .empty() )
 		return false ;
 
-	success &= ! execute_command_timed( "mount -v -t jfs " + partition_new .get_path() + " " + mount_point,
-	                                    operationdetail ) ;
+	success &= ! execute_command( "mount -v -t jfs " + partition_new .get_path() + " " + mount_point,
+				      operationdetail, true ) ;
 
 	if ( success )
 	{
-		success &= ! execute_command_timed( "mount -v -t jfs -o remount,resize " + partition_new .get_path() + " " + mount_point,
-		                                    operationdetail ) ;
+		success &= ! execute_command( "mount -v -t jfs -o remount,resize " + partition_new .get_path() + " " + mount_point,
+					      operationdetail, true ) ;
 
-		success &= ! execute_command_timed( "umount -v " + mount_point, operationdetail ) ;
+		success &= ! execute_command( "umount -v " + mount_point, operationdetail, true ) ;
 	}
 
 	rm_temp_dir( mount_point, operationdetail ) ;
diff --git a/src/nilfs2.cc b/src/nilfs2.cc
index 250fb17..1256cd2 100644
--- a/src/nilfs2.cc
+++ b/src/nilfs2.cc
@@ -163,8 +163,8 @@ bool nilfs2::resize( const Partition & partition_new, OperationDetail & operatio
 	if ( mount_point .empty() )
 		return false ;
 
-	success &= ! execute_command_timed( "mount -v -t nilfs2 " + partition_new .get_path() + " " + mount_point,
-	                                    operationdetail ) ;
+	success &= ! execute_command( "mount -v -t nilfs2 " + partition_new .get_path() + " " + mount_point,
+				      operationdetail, true ) ;
 
 	if ( success )
 	{
@@ -175,9 +175,9 @@ bool nilfs2::resize( const Partition & partition_new, OperationDetail & operatio
 					partition_new .get_sector_length(), partition_new .sector_size, UNIT_KIB ) ) ) + "K" ;
 			cmd += " " + size ;
 		}
-		success &= ! execute_command_timed( cmd, operationdetail ) ;
+		success &= ! execute_command( cmd, operationdetail, true ) ;
 
-		success &= ! execute_command_timed( "umount -v " + mount_point, operationdetail ) ;
+		success &= ! execute_command( "umount -v " + mount_point, operationdetail, true ) ;
 	}
 
 	rm_temp_dir( mount_point, operationdetail ) ;
diff --git a/src/xfs.cc b/src/xfs.cc
index a03782a..ab11102 100644
--- a/src/xfs.cc
+++ b/src/xfs.cc
@@ -175,14 +175,14 @@ bool xfs::resize( const Partition & partition_new, OperationDetail & operationde
 	if ( mount_point .empty() )
 		return false ;
 
-	success &= ! execute_command_timed( "mount -v -t xfs " + partition_new .get_path() + " " + mount_point,
-	                                    operationdetail ) ;
+	success &= ! execute_command( "mount -v -t xfs " + partition_new .get_path() + " " + mount_point,
+				      operationdetail, true ) ;
 
 	if ( success )
 	{
-		success &= ! execute_command_timed( "xfs_growfs " + mount_point, operationdetail ) ;
+		success &= ! execute_command( "xfs_growfs " + mount_point, operationdetail, true ) ;
 
-		success &= ! execute_command_timed( "umount -v " + mount_point, operationdetail ) ;
+		success &= ! execute_command( "umount -v " + mount_point, operationdetail, true ) ;
 	}
 
 	rm_temp_dir( mount_point, operationdetail ) ;
@@ -204,7 +204,7 @@ bool xfs::copy( const Glib::ustring & src_part_path,
 {
 	bool success = true ;
 
-	success &= ! execute_command_timed( "mkfs.xfs -f " + dest_part_path, operationdetail ) ;
+	success &= ! execute_command( "mkfs.xfs -f " + dest_part_path, operationdetail, true ) ;
 	if ( ! success )
 		return false ;
 
@@ -219,24 +219,24 @@ bool xfs::copy( const Glib::ustring & src_part_path,
 		return false ;
 	}
 
-	success &= ! execute_command_timed( "mount -v -t xfs -o noatime,ro " + src_part_path +
-	                                    " " + src_mount_point, operationdetail ) ;
+	success &= ! execute_command( "mount -v -t xfs -o noatime,ro " + src_part_path +
+				      " " + src_mount_point, operationdetail, true ) ;
 
 	if ( success )
 	{
-		success &= ! execute_command_timed( "mount -v -t xfs " + dest_part_path +
-		                                    " " + dest_mount_point, operationdetail ) ;
+		success &= ! execute_command( "mount -v -t xfs " + dest_part_path +
+					      " " + dest_mount_point, operationdetail, true ) ;
 
 		if ( success )
 		{
-			success &= ! execute_command_timed( "xfsdump -J - " + src_mount_point +
-			                                    " | xfsrestore -J - " + dest_mount_point,
-			                                    operationdetail ) ;
+			success &= ! execute_command( "sh -c 'xfsdump -J - " + src_mount_point +
+						      " | xfsrestore -J - " + dest_mount_point + "'",
+						      operationdetail, true );
 
-			success &= ! execute_command_timed( "umount -v " + dest_part_path, operationdetail ) ;
+			success &= ! execute_command( "umount -v " + dest_part_path, operationdetail, true ) ;
 		}
 
-		success &= ! execute_command_timed( "umount -v " + src_part_path, operationdetail ) ;
+		success &= ! execute_command( "umount -v " + src_part_path, operationdetail, true ) ;
 	}
 
 	rm_temp_dir( dest_mount_point, operationdetail ) ;



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]