diff --git a/Makefile b/Makefile index ba43b81c..6b0192b5 100644 --- a/Makefile +++ b/Makefile @@ -96,7 +96,8 @@ UTILS_DIRS := \ ${TRICK_HOME}/trick_source/trick_utils/comm \ ${TRICK_HOME}/trick_source/trick_utils/shm \ ${TRICK_HOME}/trick_source/trick_utils/math \ - ${TRICK_HOME}/trick_source/trick_utils/units + ${TRICK_HOME}/trick_source/trick_utils/units \ + ${TRICK_HOME}/trick_source/trick_utils/unicode UTILS_OBJS := $(addsuffix /object_$(TRICK_HOST_CPU)/*.o ,$(UTILS_DIRS)) # filter out the directories that make their own libraries diff --git a/autoconf/configure.ac b/autoconf/configure.ac old mode 100644 new mode 100755 index d26b589b..7664933d --- a/autoconf/configure.ac +++ b/autoconf/configure.ac @@ -121,6 +121,15 @@ AC_DEFUN([AX_GTEST_HOME],[ [AC_CHECK_HEADER(gtest/gtest.h, [GTEST_HOME="/usr"], [GTEST_HOME=""])] ) AC_SUBST([GTEST_HOME]) +]) + +AC_DEFUN([AX_SWIG_BIN],[ + AC_ARG_WITH([swig], + AS_HELP_STRING([--with-swig@<:@=DIR@:>@], [path of directory containing the SWIG executable.]), + SWIG_BIN="$withval", + SWIG_BIN=/bin:/usr/bin:/usr/local/bin:/sw/bin + ) + AC_SUBST([SWIG_BIN]) ]) AC_DEFUN([AX_UDUNITS_HOME],[ @@ -244,13 +253,12 @@ AC_PATH_PROG(PERL, perl, noperl) AS_IF([test "$ac_cv_path_PERL" = "noperl"],AC_MSG_ERROR([could not find perl]),[]) AC_PATH_PROG(PYTHON, python${PYTHON_VERSION}, nopython) AS_IF([test "$ac_cv_path_PYTHON" = "nopython"],AC_MSG_ERROR([could not find python]),[]) -AC_PATH_PROG(SWIG, swig, noswig, "/bin:/usr/bin:/usr/local/bin:/sw/bin") -AS_IF([test "$ac_cv_path_SWIG" = "noswig"],AC_MSG_ERROR([could not find swig]),[]) AC_PATH_PROG(GNUPLOT, gnuplot, nognuplot) AS_IF([test "$ac_cv_path_GNUPLOT" = "nognuplot"],AC_MSG_NOTICE([could not find gnuplot]),[]) - +AX_SWIG_BIN([]) +AC_PATH_PROG(SWIG, swig, noswig, $SWIG_BIN) +AS_IF([test "$ac_cv_path_SWIG" = "noswig"],AC_MSG_ERROR([could not find swig]),[]) AX_JAVA - dnl look for libraries and headers we need to compile AC_PATH_X AS_IF([test "$no_x" = "yes"],AC_MSG_ERROR([could not find Xwindows development libraries and/or headers]),[]) diff --git a/bin/trick-CP b/bin/trick-CP index 7ec8865b..3ff9d311 100755 --- a/bin/trick-CP +++ b/bin/trick-CP @@ -6,6 +6,8 @@ use File::Basename ; use Cwd ; use Cwd 'abs_path'; +use Pod::Usage ; +use Pod::Text ; $trick_bin = dirname(abs_path($0)) ; $trick_home = dirname($trick_bin) ; @@ -21,6 +23,8 @@ foreach $argnum (0 .. $#ARGV) { $makefileAddArgs = $makefileAddArgs . " debug "; } elsif ($arg =~ /-t/ ) { $makefileAddArgs = $makefileAddArgs . " test "; + } elsif($arg=~ /-h/ ) { + pod2usage(-sections => "NAME|SYNOPSIS|DESCRIPTION|OPTIONS|FILES", -verbose => 99) ; } else { $ENV{TRICK_CPFLAGS} .= " $arg" ; } @@ -45,6 +49,81 @@ if ( -f "S_define" ) { print "S_define does not exist" ; exit 1 ; } + +# trick-CP help message + +=pod + +=head1 NAME + +trick-CP - Trick Configuration Processor + +=head1 SYNOPSIS + +trick-CP [OPTION]... + +=head1 DESCRIPTION + +trick-CP is the Trick environment Configuration Processor. trick-CP +parses the simulation definition file, S_define, searching for math +models to include in the simulation. trick-CP will search for the math +models within the search paths included in TRICK_CFLAGS and +TRICK_CXXFLAGS environment variables. trick-CP will generate code to +call math models listed in the S_define file and will generate a make‐ +file to build these math models. + +=head1 OPTIONS + +=over 8 + +=item B<-g> | B<--debug> + +Print the S_define file as it is processed by trick-CP. (This +may help the user find problems with his/her simulation configu‐ +ration). + +=item B<-h> | B<--help> + +Print the trick-CP help message (this message) + +=item B<-o> | B<--outfile> I + +Send CP output to FILE_NAME + +=item B<-p> | B<--no-python> + +Exclude python input processor from simulation. + +=item B<-t> + +Create a unit test simulation where TRICK_UNIT_TEST is defined during compilation + +=item B<-v> | B<--verbose> + +Set the verbose level. Valid entries are 0-3 + +=back + +=head1 FILES + +=over 8 + +=item B + +The simulation-specific executive source code file. + +=item B + +The simulation-specific object code link list file. + +=item B + +The simulation-specific default initialization data file. + +=back + +=cut + __END__ # CP found at SUB_TRICK_BIN @@ -100,6 +179,7 @@ ICG: $(PRINT_ICG) $(ECHO_CMD)${TRICK_HOME}/bin/trick-ICG -m ${TRICK_ICGFLAGS} ${TRICK_CXXFLAGS} ${TRICK_SYSTEM_CXXFLAGS} S_source.hh + force_ICG: $(PRINT_ICG) $(ECHO_CMD)${TRICK_HOME}/bin/trick-ICG -f -m ${TRICK_ICGFLAGS} ${TRICK_CXXFLAGS} ${TRICK_SYSTEM_CXXFLAGS} S_source.hh @@ -135,6 +215,11 @@ convert_swig: build/S_library_swig S_define_exp: $(TRICK_CC) -E -C -xc++ ${TRICK_SFLAGS} $(TRICK_SYSTEM_SFLAGS) S_define > $@ +# prints the value of a makefile variable, example invocation "make print-TRICK_CXXFLAGS" +# This rule is used by trick-config +print-%: + @echo '$*=$($*)' + help: @echo -e "\ Simulation make options:\n\ @@ -142,7 +227,8 @@ Simulation make options:\n\ make sie - Builds the S_sie.resource file.\n\ make clean - Removes all object files in simulation directory\n\ make spotless - Performs a clean\n\ - make apocalypse - Performs a clean" + make apocalypse - Performs a clean\n\ + make print- - Prints a makefile or environment variable" CLEAN_TARGETS = tidy clean spotless distclean apocalypse ifeq ($(findstring ${MAKECMDGOALS},$(CLEAN_TARGETS)),) @@ -189,4 +275,3 @@ distclean: clean apocalypse: clean @echo "I love the smell of napalm in the morning" - diff --git a/bin/trick-config b/bin/trick-config index 29e3a21d..fc9257b3 100755 --- a/bin/trick-config +++ b/bin/trick-config @@ -26,7 +26,7 @@ sub print_prefix() { # Run a special rule in Makefile.sim that prints the value of the environment variable we request sub print_makefile_var($) { - open(README, "make -f $ENV{TRICK_HOME}/share/trick/makefiles/Makefile.sim print-@_ | ") or + open(README, "make -f $ENV{TRICK_HOME}/share/trick/makefiles/Makefile.trickconfig print-@_ | ") or die "Couldn't fork $!\n" ; while () { /=(.*)/ && print "$1\n" ; diff --git a/configure b/configure index fd2b6502..e9c313e1 100755 --- a/configure +++ b/configure @@ -660,8 +660,9 @@ ac_ct_JAVA_CC JAVA_CC_FLAGS JAVA_CC USE_JAVA -GNUPLOT SWIG +SWIG_BIN +GNUPLOT PYTHON PERL CURL @@ -732,6 +733,7 @@ SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking +with_swig enable_java with_x with_llvm @@ -1385,6 +1387,7 @@ Optional Features: Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-swig[=DIR] path of directory containing the SWIG executable. --with-x use the X Window System --with-llvm[=DIR] LLVM root directory --with-zlib=DIR root directory path of zlib installation [defaults to @@ -2397,6 +2400,8 @@ ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + @@ -4082,51 +4087,6 @@ fi if test "$ac_cv_path_PYTHON" = "nopython"; then : as_fn_error $? "could not find python" "$LINENO" 5 fi -# Extract the first word of "swig", so it can be a program name with args. -set dummy swig; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_SWIG+:} false; then : - $as_echo_n "(cached) " >&6 -else - case $SWIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_SWIG="$SWIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_dummy=""/bin:/usr/bin:/usr/local/bin:/sw/bin"" -for as_dir in $as_dummy -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_SWIG="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - test -z "$ac_cv_path_SWIG" && ac_cv_path_SWIG="noswig" - ;; -esac -fi -SWIG=$ac_cv_path_SWIG -if test -n "$SWIG"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SWIG" >&5 -$as_echo "$SWIG" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -if test "$ac_cv_path_SWIG" = "noswig"; then : - as_fn_error $? "could not find swig" "$LINENO" 5 -fi # Extract the first word of "gnuplot", so it can be a program name with args. set dummy gnuplot; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 @@ -4174,6 +4134,61 @@ $as_echo "$as_me: could not find gnuplot" >&6;} fi +# Check whether --with-swig was given. +if test "${with_swig+set}" = set; then : + withval=$with_swig; SWIG_BIN="$withval" +else + SWIG_BIN=/bin:/usr/bin:/usr/local/bin:/sw/bin + +fi + + + +# Extract the first word of "swig", so it can be a program name with args. +set dummy swig; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_SWIG+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $SWIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_SWIG="$SWIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $SWIG_BIN +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_SWIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_SWIG" && ac_cv_path_SWIG="noswig" + ;; +esac +fi +SWIG=$ac_cv_path_SWIG +if test -n "$SWIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SWIG" >&5 +$as_echo "$SWIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +if test "$ac_cv_path_SWIG" = "noswig"; then : + as_fn_error $? "could not find swig" "$LINENO" 5 +fi + # Check whether --enable-java was given. if test "${enable_java+set}" = set; then : enableval=$enable_java; if test "x$enable_java" = xyes; then : @@ -4388,7 +4403,6 @@ $as_echo "no" >&6; } fi - ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' diff --git a/include/trick/MonteCarlo.hh b/include/trick/MonteCarlo.hh index aa7537ec..5cd56172 100644 --- a/include/trick/MonteCarlo.hh +++ b/include/trick/MonteCarlo.hh @@ -36,13 +36,13 @@ namespace Trick { public: /** Details the manner in which this run exited. */ enum ExitStatus { - INCOMPLETE, /**< not completed */ - COMPLETE, /**< completed with no errors */ - CORED, /**< core dumped */ - TIMEDOUT, /**< timed out */ - NO_PERM, /**< could not write output files */ - BAD_INPUT, /**< problem parseing monte carlo input */ - UNKNOWN /**< unrecognized return code */ + MC_RUN_INCOMPLETE, /**< not completed */ + MC_RUN_COMPLETE, /**< completed with no errors */ + MC_RUN_DUMPED_CORE, /**< core dumped */ + MC_RUN_TIMED_OUT, /**< timed out */ + MC_CANT_CREATE_OUTPUT_DIR, /**< could not write output files */ + MC_PROBLEM_PARSING_INPUT, /**< problem parseing monte carlo input */ + MC_UNRECOGNIZED_RETURN_CODE /**< unrecognized return code */ }; /** Unique identifier sequentially assigned, starting at zero, by the master. */ @@ -73,7 +73,7 @@ namespace Trick { num_tries(0), start_time(0), end_time(0), - exit_status(INCOMPLETE) {} + exit_status(MC_RUN_INCOMPLETE) {} }; @@ -93,23 +93,23 @@ namespace Trick { public: /** Operational state. */ enum State { - UNINITIALIZED, /**< newly created */ - INITIALIZING, /**< starting up */ - READY, /**< awaiting new run */ - RUNNING, /**< processing a run */ - STOPPING, /**< stopping after current run */ - STOPPED, /**< not accepting new runs */ - FINISHED, /**< completed all runs */ - UNRESPONSIVE_RUNNING, /**< timed out and in a running state */ - UNRESPONSIVE_STOPPING, /**< timed out and in a stopping state */ - DISCONNECTED /**< lost connection */ + MC_UNINITIALIZED, /**< newly created */ + MC_INITIALIZING, /**< starting up */ + MC_READY, /**< awaiting new run */ + MC_RUNNING, /**< processing a run */ + MC_STOPPING, /**< stopping after current run */ + MC_STOPPED, /**< not accepting new runs */ + MC_FINISHED, /**< completed all runs */ + MC_UNRESPONSIVE_RUNNING, /**< timed out and in a running state */ + MC_UNRESPONSIVE_STOPPING, /**< timed out and in a stopping state */ + MC_DISCONNECTED /**< lost connection */ }; /** Master-to-slave commands. */ enum Command { - PROCESS_RUN, /**< process a new run */ - SHUTDOWN, /**< kill any executing run, call shutdown jobs, and shutdown cleanly */ - DIE /**< kill any executing run, do not call shutdown jobs, and exit */ + MC_PROCESS_RUN, /**< process a new run */ + MC_SHUTDOWN, /**< kill any executing run, call shutdown jobs, and shutdown cleanly */ + MC_DIE /**< kill any executing run, do not call shutdown jobs, and exit */ }; /** Unique identifier assigned by the master. */ @@ -166,7 +166,7 @@ namespace Trick { */ MonteSlave(std::string name = "localhost") : id(0), - state(UNINITIALIZED), + state(MC_UNINITIALIZED), port(0), current_run(NULL), num_dispatches(0), @@ -248,10 +248,10 @@ namespace Trick { public: /** Verbosity of message reporting. */ enum Verbosity { - NONE, /**< report no messages */ - ERROR, /**< report error messages */ - INFORMATIONAL, /**< report error and informational messages, no warning messages */ - ALL /**< report all messages (error, informational & warning) */ + MC_NONE, /**< report no messages */ + MC_ERROR, /**< report error messages */ + MC_INFORMATIONAL, /**< report error and informational messages, no warning messages */ + MC_ALL /**< report all messages (error, informational & warning) */ }; /** Options to be passed to the slave sim. */ diff --git a/include/trick/checkpoint_map.hh b/include/trick/checkpoint_map.hh index 8c2cdf82..5c4d926c 100644 --- a/include/trick/checkpoint_map.hh +++ b/include/trick/checkpoint_map.hh @@ -51,7 +51,13 @@ int checkpoint_map_ik_id(STL & in_map , std::string object_name , std::string va std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*keys).name(), 0, 0, &status )) ; + std::string type_string ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*keys).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_keys[" << cont_size << "]" ; keys = (typename STL::key_type *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -61,7 +67,12 @@ int checkpoint_map_ik_id(STL & in_map , std::string object_name , std::string va var_declare.str("") ; var_declare.clear() ; - type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_data[" << cont_size << "]" ; items = (typename STL::mapped_type *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -111,7 +122,13 @@ int checkpoint_map_ik_sd(STL & in_map , std::string object_name , std::string va std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*keys).name(), 0, 0, &status )) ; + std::string type_string ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*keys).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_keys[" << cont_size << "]" ; keys = (typename STL::key_type *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -187,7 +204,13 @@ int checkpoint_map_sk_id(STL & in_map , std::string object_name , std::string va var_declare.str("") ; var_declare.clear() ; - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + std::string type_string ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_data[" << cont_size << "]" ; items = (typename STL::mapped_type *)TMM_declare_var_s(var_declare.str().c_str()) ; diff --git a/include/trick/checkpoint_pair.hh b/include/trick/checkpoint_pair.hh index 5b710c51..c2f350d2 100644 --- a/include/trick/checkpoint_pair.hh +++ b/include/trick/checkpoint_pair.hh @@ -34,7 +34,13 @@ int checkpoint_stl(std::pair & in_pair , std::string object_name SECOND * second = nullptr ; std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*first).name(), 0, 0, &status )) ; + std::string type_string ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*first).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_first[1]" ; first = (FIRST *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -44,7 +50,12 @@ int checkpoint_stl(std::pair & in_pair , std::string object_name var_declare.str("") ; var_declare.clear() ; - type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*second).name(), 0, 0, &status )) ; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*second).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_second[1]" ; second = (SECOND *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -68,8 +79,13 @@ int checkpoint_stl(std::pair & in_pair , std::string object_name FIRST * first = nullptr ; std::string * second = nullptr ; std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); - - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*first).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*first).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_first[1]" ; first = (FIRST *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -111,7 +127,13 @@ int checkpoint_stl(std::pair & in_pair , std::string object_name var_declare.str("") ; var_declare.clear() ; - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*second).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*second).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "_second[1]" ; second = (SECOND *)TMM_declare_var_s(var_declare.str().c_str()) ; diff --git a/include/trick/checkpoint_queue.hh b/include/trick/checkpoint_queue.hh index 3cf1ee64..a062766a 100644 --- a/include/trick/checkpoint_queue.hh +++ b/include/trick/checkpoint_queue.hh @@ -43,7 +43,13 @@ int checkpoint_stl(std::queue & in_stl , std::string object std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "[" << cont_size << "]" ; items = (ITEM_TYPE *)TMM_declare_var_s(var_declare.str().c_str()) ; @@ -116,7 +122,13 @@ int checkpoint_stl(std::priority_queue & in_stl std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "[" << cont_size << "]" ; items = (ITEM_TYPE *)TMM_declare_var_s(var_declare.str().c_str()) ; diff --git a/include/trick/checkpoint_sequence_stl.hh b/include/trick/checkpoint_sequence_stl.hh index 1f992864..608b50ed 100644 --- a/include/trick/checkpoint_sequence_stl.hh +++ b/include/trick/checkpoint_sequence_stl.hh @@ -46,7 +46,13 @@ int checkpoint_sequence_i(STL & in_stl , std::string object_name , std::string v std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "[" << cont_size << "]" ; items = (typename STL::value_type *)TMM_declare_var_s(var_declare.str().c_str()) ; diff --git a/include/trick/checkpoint_stack.hh b/include/trick/checkpoint_stack.hh index 84d66304..e99ecddd 100644 --- a/include/trick/checkpoint_stack.hh +++ b/include/trick/checkpoint_stack.hh @@ -40,7 +40,13 @@ int checkpoint_stl(std::stack & in_stl , std::string object std::replace_if(object_name.begin(), object_name.end(), std::ptr_fun(&std::ispunct), '_'); if ( cont_size > 0 ) { - std::string type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + std::string type_string; + try { + type_string = stl_type_name_convert(abi::__cxa_demangle(typeid(*items).name(), 0, 0, &status )) ; + } catch (const std::bad_typeid& e) { + message_publish(1, "Error, having difficulty checkpointing %s.%s\n", object_name.c_str(), var_name.c_str()) ; + return 0 ; + } var_declare << type_string << " " << object_name << "_" << var_name << "[" << cont_size << "]" ; items = (ITEM_TYPE *)TMM_declare_var_s(var_declare.str().c_str()) ; diff --git a/include/trick/clock_proto.h b/include/trick/clock_proto.h index 9bbae26a..9530b88d 100644 --- a/include/trick/clock_proto.h +++ b/include/trick/clock_proto.h @@ -6,12 +6,12 @@ extern "C" { #endif -long long clock_time() ; -long long clock_wall_time() ; +long long clock_time(void) ; +long long clock_wall_time(void) ; long long clock_reset(long long ref) ; int clock_spin(long long ref) ; int clock_set_reference(long long ref) ; -double clock_get_rt_clock_ratio() ; +double clock_get_rt_clock_ratio(void) ; int clock_set_rt_clock_ratio(double in_rt_clock_ratio) ; #ifdef __cplusplus diff --git a/include/trick/command_line_protos.h b/include/trick/command_line_protos.h index b5886c01..a3e56ab3 100644 --- a/include/trick/command_line_protos.h +++ b/include/trick/command_line_protos.h @@ -22,17 +22,17 @@ extern "C" { int command_line_args_process_sim_args(int argc , char ** argv) ; -int command_line_args_get_argc() ; -char ** command_line_args_get_argv() ; -const char * command_line_args_get_output_dir() ; -const char * command_line_args_get_user_output_dir() ; -const char * command_line_args_get_input_file() ; +int command_line_args_get_argc(void) ; +char ** command_line_args_get_argv(void) ; +const char * command_line_args_get_output_dir(void) ; +const char * command_line_args_get_user_output_dir(void) ; +const char * command_line_args_get_input_file(void) ; -const char * command_line_args_get_default_dir() ; -const char * command_line_args_get_cmdline_name() ; +const char * command_line_args_get_default_dir(void) ; +const char * command_line_args_get_cmdline_name(void) ; -int output_dir_timestamped_on() ; -int output_dir_timestamped_off() ; +int output_dir_timestamped_on(void) ; +int output_dir_timestamped_off(void) ; void set_output_dir(const char* output_directory); @@ -42,7 +42,7 @@ void set_output_dir(const char* output_directory); #ifdef __cplusplus #include -std::string & command_line_args_get_input_file_ref() ; +std::string & command_line_args_get_input_file_ref(void) ; #endif #endif diff --git a/include/trick/data_record_proto.h b/include/trick/data_record_proto.h index bb1d557c..d5b18e35 100644 --- a/include/trick/data_record_proto.h +++ b/include/trick/data_record_proto.h @@ -8,14 +8,14 @@ extern "C" { #endif -int dr_remove_files() ; -int dr_enable() ; -int dr_disable() ; +int dr_remove_files(void) ; +int dr_enable(void) ; +int dr_disable(void) ; int dr_enable_group( const char * in_name ) ; int dr_disable_group( const char * in_name ) ; int dr_record_now_group( const char * in_name ) ; int dr_set_max_file_size ( uint64_t bytes ) ; -void remove_all_data_record_groups() ; +void remove_all_data_record_groups(void) ; int set_max_size_record_group (const char * in_name, uint64_t bytes ) ; diff --git a/include/trick/debug_pause_proto.h b/include/trick/debug_pause_proto.h index 245775a8..cc0308f4 100644 --- a/include/trick/debug_pause_proto.h +++ b/include/trick/debug_pause_proto.h @@ -6,9 +6,9 @@ extern "C" { #endif -int debug_pause_on() ; -int debug_pause_off() ; -int debug_signal() ; +int debug_pause_on(void) ; +int debug_pause_off(void) ; +int debug_signal(void) ; #ifdef __cplusplus } diff --git a/include/trick/dllist.h b/include/trick/dllist.h index 53649a65..3f04ccb4 100644 --- a/include/trick/dllist.h +++ b/include/trick/dllist.h @@ -1,7 +1,6 @@ /* PURPOSE: (link list) - ICG: (No) */ /*********** doubly linked list types *************/ diff --git a/include/trick/echojobs_proto.h b/include/trick/echojobs_proto.h index 016525ee..d7546521 100644 --- a/include/trick/echojobs_proto.h +++ b/include/trick/echojobs_proto.h @@ -6,8 +6,8 @@ extern "C" { #endif -int echo_jobs_on() ; -int echo_jobs_off() ; +int echo_jobs_on(void) ; +int echo_jobs_off(void) ; #ifdef __cplusplus } diff --git a/include/trick/external_application_c_intf.h b/include/trick/external_application_c_intf.h index 1f354b10..0fceb588 100644 --- a/include/trick/external_application_c_intf.h +++ b/include/trick/external_application_c_intf.h @@ -12,31 +12,31 @@ extern "C" { // Convenience functions for backwards compatibility that, dolphins willing, will one day be removed. void sim_control_panel_set_enabled(int enabled); -int sim_control_panel_get_enabled(); +int sim_control_panel_get_enabled(void); void sim_control_panel_auto_exit_set_enabled(int enabled); void trick_view_set_enabled(int enabled); -int trick_view_get_enabled(); +int trick_view_get_enabled(void); void malfunctions_trick_view_set_enabled(int enabled); -int malfunctions_trick_view_get_enabled(); +int malfunctions_trick_view_get_enabled(void); void monte_monitor_set_enabled(int enabled); -int monte_monitor_get_enabled(); +int monte_monitor_get_enabled(void); void stripchart_set_enabled(int enabled); -int stripchart_get_enabled(); +int stripchart_get_enabled(void); void sim_control_panel_set_startup_command(const char *command); -const char *sim_control_panel_get_startup_command(); +const char *sim_control_panel_get_startup_command(void); void trick_view_set_startup_command(const char *command); -const char *trick_view_get_startup_command(); +const char *trick_view_get_startup_command(void); void malfunctions_trick_view_set_startup_command(const char *command); -const char *malfunctions_trick_view_get_startup_command(); +const char *malfunctions_trick_view_get_startup_command(void); void monte_monitor_set_startup_command(const char *command); -const char *monte_monitor_get_startup_command(); +const char *monte_monitor_get_startup_command(void); void stripchart_set_startup_command(const char *command); -const char *stripchart_get_startup_command(); -void sim_control_panel_launch(); -void trick_view_launch(); -void malfunctions_trick_view_launch(); -void monte_monitor_launch(); -void stripchart_launch(); +const char *stripchart_get_startup_command(void); +void sim_control_panel_launch(void); +void trick_view_launch(void); +void malfunctions_trick_view_launch(void); +void monte_monitor_launch(void); +void stripchart_launch(void); void trick_view_set_cycle_period(double period); void trick_view_add_auto_load_file(const char *file); diff --git a/include/trick/files_to_ICG.hh b/include/trick/files_to_ICG.hh index e3f59623..9a4fe312 100644 --- a/include/trick/files_to_ICG.hh +++ b/include/trick/files_to_ICG.hh @@ -93,4 +93,7 @@ #include "trick/rand_generator.h" #include "trick/units_conv.h" +#include "trick/lqueue.h" +#include "trick/lstack.h" + #endif diff --git a/include/trick/framelog_proto.h b/include/trick/framelog_proto.h index 7f92f3a3..22be0f74 100644 --- a/include/trick/framelog_proto.h +++ b/include/trick/framelog_proto.h @@ -6,8 +6,8 @@ extern "C" { #endif -int frame_log_on() ; -int frame_log_off() ; +int frame_log_on(void) ; +int frame_log_off(void) ; int frame_log_set_max_samples(int num) ; #ifdef __cplusplus diff --git a/include/trick/lqueue.h b/include/trick/lqueue.h index 1b8666dd..6e24c88d 100644 --- a/include/trick/lqueue.h +++ b/include/trick/lqueue.h @@ -1,4 +1,6 @@ -/***************** queue functions ***************/ +/* + PURPOSE: (queue functions) +*/ #ifndef LQUEUE_H #define LQUEUE_H @@ -13,7 +15,7 @@ extern "C" { typedef struct _LQUEUE { - DLLIST list; /* implementing queue using a linked-list */ + DLLIST list; /* -- implementing queue using a linked-list */ }LQUEUE; diff --git a/include/trick/lstack.h b/include/trick/lstack.h index da76e75c..4bf71ef4 100644 --- a/include/trick/lstack.h +++ b/include/trick/lstack.h @@ -1,4 +1,6 @@ -/************** stack functions *****************/ +/* + PURPOSE: (stack functions) +*/ #ifndef LSTACK_H #define LSTACK_H @@ -12,7 +14,7 @@ extern "C" { typedef struct _LSTACK { - DLLIST list; /* implementing the stack using a list */ + DLLIST list; /* -- implementing the stack using a list */ }LSTACK; diff --git a/include/trick/master_proto.h b/include/trick/master_proto.h index cf5d2917..1f25f68f 100644 --- a/include/trick/master_proto.h +++ b/include/trick/master_proto.h @@ -6,8 +6,8 @@ extern "C" { #endif - int ms_master_enable() ; - int ms_master_disable() ; + int ms_master_enable(void) ; + int ms_master_disable(void) ; #ifdef __cplusplus } diff --git a/include/trick/montecarlo_c_intf.h b/include/trick/montecarlo_c_intf.h index 4d7d88a0..4db49ed8 100644 --- a/include/trick/montecarlo_c_intf.h +++ b/include/trick/montecarlo_c_intf.h @@ -21,7 +21,7 @@ void mc_set_enabled(int enabled); * @relates Trick::MonteCarlo * @copydoc get_enabled */ -int mc_get_enabled(); +int mc_get_enabled(void); /** * @relates Trick::MonteCarlo @@ -33,13 +33,13 @@ void mc_set_dry_run(int dry_run); * @relates Trick::MonteCarlo * @copydoc get_dry_run */ -int mc_get_dry_run(); +int mc_get_dry_run(void); /** * @relates Trick::MonteCarlo * @copydoc is_slave */ -int mc_is_slave(); +int mc_is_slave(void); /** * @relates Trick::MonteCarlo @@ -51,7 +51,7 @@ void mc_set_localhost_as_remote(int localhost_as_remote); * @relates Trick::MonteCarlo * @copydoc get_localhost_as_remote */ -int mc_get_localhost_as_remote(); +int mc_get_localhost_as_remote(void); /** * @relates Trick::MonteCarlo @@ -63,7 +63,7 @@ void mc_set_custom_slave_dispatch(int custom_slave_dispatch); * @relates Trick::MonteCarlo * @copydoc get_custom_slave_dispatch */ -int mc_get_custom_slave_dispatch(); +int mc_get_custom_slave_dispatch(void); /** * @relates Trick::MonteCarlo @@ -75,7 +75,7 @@ void mc_set_timeout(double timeout); * @relates Trick::MonteCarlo * @copydoc get_timeout */ -double mc_get_timeout(); +double mc_get_timeout(void); /** * @relates Trick::MonteCarlo @@ -87,7 +87,7 @@ void mc_set_max_tries(unsigned int max_tries); * @relates Trick::MonteCarlo * @copydoc get_max_tries */ -unsigned int mc_get_max_tries(); +unsigned int mc_get_max_tries(void); /** * @relates Trick::MonteCarlo @@ -105,13 +105,13 @@ void mc_set_slave_sim_options(const char *slave_sim_options); * @relates Trick::MonteCarlo * get #Trick::MonteCarlo::slave_sim_options */ -const char *mc_get_slave_sim_options(); +const char *mc_get_slave_sim_options(void); /** * @relates Trick::MonteCarlo * @copydoc get_user_cmd_string */ -const char *mc_get_user_cmd_string(); +const char *mc_get_user_cmd_string(void); /** * @relates Trick::MonteCarlo @@ -123,7 +123,7 @@ void mc_set_custom_pre_text(const char *custom_pre_text); * @relates Trick::MonteCarlo * @copydoc get_custom_pre_text */ -const char *mc_get_custom_pre_text(); +const char *mc_get_custom_pre_text(void); /** * @relates Trick::MonteCarlo @@ -135,7 +135,7 @@ void mc_set_custom_post_text(const char *custom_post_text); * @relates Trick::MonteCarlo * @copydoc get_custom_post_text */ -const char *mc_get_custom_post_text(); +const char *mc_get_custom_post_text(void); /** * @relates Trick::MonteCarlo @@ -147,7 +147,7 @@ void mc_set_verbosity(int verbosity); * @relates Trick::MonteCarlo * @copydoc get_verbosity */ -int mc_get_verbosity(); +int mc_get_verbosity(void); /** * @relates Trick::MonteCarlo @@ -159,19 +159,19 @@ void mc_set_num_runs(unsigned int num_runs); * @relates Trick::MonteCarlo * @copydoc get_num_runs */ -unsigned int mc_get_num_runs(); +unsigned int mc_get_num_runs(void); /** * @relates Trick::MonteCarlo * @copydoc get_num_results */ -unsigned int mc_get_num_results(); +unsigned int mc_get_num_results(void); /** * @relates Trick::MonteCarlo * @copydoc get_slave_id */ -unsigned int mc_get_slave_id(); +unsigned int mc_get_slave_id(void); /** * @relates Trick::MonteCarlo @@ -213,7 +213,7 @@ void mc_read(char *buffer, int size); * @relates Trick::MonteCarlo * Gets the current run being processed. */ -unsigned int mc_get_current_run() ; +unsigned int mc_get_current_run(void) ; /** * @relates Trick::MonteCarlo @@ -237,13 +237,13 @@ void mc_set_connection_device_port(int port_number) ; * @relates Trick::MonteCarlo * Gets the port for the listen_device. */ -int mc_get_listen_device_port() ; +int mc_get_listen_device_port(void) ; /** * @relates Trick::MonteCarlo * Gets the port for the connection_device. */ -int mc_get_connection_device_port() ; +int mc_get_connection_device_port(void) ; #ifdef __cplusplus } diff --git a/include/trick/outdllist.h b/include/trick/outdllist.h index 25c4fea5..a3e45413 100644 --- a/include/trick/outdllist.h +++ b/include/trick/outdllist.h @@ -32,7 +32,7 @@ typedef struct _DLLIST { }DLLIST; -DLLIST* DLL_Create(); +DLLIST* DLL_Create(void); void DLL_Delete(DLLIST*); diff --git a/include/trick/realtimesync_proto.h b/include/trick/realtimesync_proto.h index f61b14ff..0efa05e2 100644 --- a/include/trick/realtimesync_proto.h +++ b/include/trick/realtimesync_proto.h @@ -13,11 +13,11 @@ int real_time_change_timer(Trick::Timer * in_sleep_timer ) ; extern "C" { #endif -int real_time_enable() ; -int real_time_disable() ; +int real_time_enable(void) ; +int real_time_disable(void) ; int real_time_restart(long long ref_time ) ; -int is_real_time() ; -const char * real_time_clock_get_name() ; +int is_real_time(void) ; +const char * real_time_clock_get_name(void) ; int real_time_set_rt_clock_ratio(double in_clock_ratio) ; int real_time_lock_memory(int yes_no) ; diff --git a/include/trick/sie_c_intf.h b/include/trick/sie_c_intf.h index ef5f7a42..642ea35e 100644 --- a/include/trick/sie_c_intf.h +++ b/include/trick/sie_c_intf.h @@ -3,10 +3,10 @@ extern "C" { #endif -void sie_print_xml() ; -void sie_class_attr_map_print_xml() ; -void sie_enum_attr_map_print_xml() ; -void sie_top_level_objects_print_xml() ; +void sie_print_xml(void) ; +void sie_class_attr_map_print_xml(void) ; +void sie_enum_attr_map_print_xml(void) ; +void sie_top_level_objects_print_xml(void) ; #ifdef __cplusplus } diff --git a/include/trick/simtime_proto.h b/include/trick/simtime_proto.h index f615d7be..167fd5ef 100644 --- a/include/trick/simtime_proto.h +++ b/include/trick/simtime_proto.h @@ -8,13 +8,13 @@ extern "C" { #endif -double get_rettime() ; -double get_gmttime() ; -double get_mettime() ; +double get_rettime(void) ; +double get_gmttime(void) ; +double get_mettime(void) ; -GMTTIME * get_rettime_struct() ; -GMTTIME * get_gmttime_struct() ; -GMTTIME * get_mettime_struct() ; +GMTTIME * get_rettime_struct(void) ; +GMTTIME * get_gmttime_struct(void) ; +GMTTIME * get_mettime_struct(void) ; #ifdef __cplusplus } diff --git a/include/trick/trick_tests.h b/include/trick/trick_tests.h index 0e6a6a53..72487dab 100644 --- a/include/trick/trick_tests.h +++ b/include/trick/trick_tests.h @@ -81,7 +81,7 @@ extern "C" { #endif -int trick_test_enable() ; +int trick_test_enable(void) ; int trick_test_set_file_name( const char * in_file_name ) ; @@ -94,7 +94,7 @@ int trick_test_add_parent(const char * in_test_suite_name, int add_test_result( const char * in_test_suite_name , const char * in_test_case , const char * in_failure_string ) ; -int call_write_output() ; +int call_write_output(void) ; #ifdef __cplusplus } diff --git a/include/trick/unicode_utils.h b/include/trick/unicode_utils.h new file mode 100644 index 00000000..1d966e5d --- /dev/null +++ b/include/trick/unicode_utils.h @@ -0,0 +1,51 @@ +#ifndef UNITCODE_UTILS_H +#define UNITCODE_UTILS_H +#include + +/* Maintainer: John M. Penn */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Convert Unicode codepoint to UTF-32. Validates that it's a legal unicode value. + Returns 1, if successful, 0 otherwise. */ +size_t ucodepoint_to_utf32(unsigned int codePoint, int32_t *out); + +/* Convert Unicode codepoint to UTF-16. + Returns the number of UTF-16 elements (1..2) necessary to represent the codepoint, + or 0 on failure. + */ +size_t ucodepoint_to_utf16(unsigned int codePoint, int16_t (*out)[2]); + +/* Convert Unicode codepoint to UTF-8. + Returns the number of UTF_8 elements (1..4) )necessary to represent the codepoint, + or 0 on failure. + */ +size_t ucodepoint_to_utf8(unsigned int codePoint, char (*out)[4]); + + + +/* Un-escape C escape sequences, including \u and \U Unicode escape sequences, + in an ASCII character array, producing a UTF-8 character array. Return the + number of elements in the character string. +*/ +size_t ascii_to_utf8(const char *in, char *out, size_t outSize); + +/* Escape ('\' escape codes) all unicode and non-printable ASCII characters + in a UTF-8 character string. Return the number of elements in the character string. +*/ +size_t utf8_to_printable_ascii(const char *in, char *out, size_t outSize); + +/* Convert a UTF-8 character array to a wchar_t array. Supports 16, and 32 bit wchar_t. + Return the number of elements in the wchar_t string. */ +size_t utf8_to_wchar(const char *in, wchar_t *out, size_t outSize); + +/* Convert wchar_t character array to UTF-8. Return the number of elements in + the character (utf-8) string.*/ +size_t wchar_to_utf8(const wchar_t *in, char *out, size_t outSize); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/trick/variable_server_proto.h b/include/trick/variable_server_proto.h index 06739e64..d3d7dade 100644 --- a/include/trick/variable_server_proto.h +++ b/include/trick/variable_server_proto.h @@ -6,16 +6,16 @@ extern "C" { #endif -const char * var_server_get_hostname() ; +const char * var_server_get_hostname(void) ; -unsigned short var_server_get_port() ; +unsigned short var_server_get_port(void) ; void var_server_set_port(unsigned short port) ; void var_server_set_source_address(const char * address) ; -const char * var_server_get_user_tag() ; +const char * var_server_get_user_tag(void) ; void var_server_set_user_tag(const char * tag) ; -int var_server_get_enabled() ; +int var_server_get_enabled(void) ; void var_server_set_enabled(int on_off) ; int var_server_create_tcp_socket(const char * address, unsigned short port) ; diff --git a/include/trick/wcs_ext.h b/include/trick/wcs_ext.h index 84ede408..27b329cd 100644 --- a/include/trick/wcs_ext.h +++ b/include/trick/wcs_ext.h @@ -16,10 +16,10 @@ extern "C" { #endif #if __Lynx__ -int wcs_to_ncs_len (); -int ncs_to_wcs_len (); -int wcs_to_ncs (); -int ncs_to_wcs(); +int wcs_to_ncs_len (void); +int ncs_to_wcs_len (void); +int wcs_to_ncs (void); +int ncs_to_wcs(void); #else #include #include diff --git a/libexec/trick/convert_swig b/libexec/trick/convert_swig index 6caa904e..b1fbc49f 100755 --- a/libexec/trick/convert_swig +++ b/libexec/trick/convert_swig @@ -99,18 +99,18 @@ my $template_var_def = qr/(?:\:\:)?[_A-Za-z][:\w]*\s* # template name /sx ; # This list is the list of all STL types to ignore. -my %all_stl_names = qw(vector 1 list 1 deque 1 set 1 multiset 1 map 1 multimap 1 hash_set 1 +my %all_stl_names = qw(vector 1 list 1 deque 1 set 1 multiset 1 map 1 unordered_map 1 multimap 1 hash_set 1 hash_multiset 1 hash_map 1 hash_multimap 1 stack 1 queue 1 priority_queue 1 bitset 1 auto_ptr 1 array 1 - std::vector 1 std::list 1 std::deque 1 std::set 1 std::multiset 1 std::map 1 std::multimap 1 std::hash_set 1 + std::vector 1 std::list 1 std::deque 1 std::set 1 std::multiset 1 std::map 1 std::unordered_map 1 std::multimap 1 std::hash_set 1 std::hash_multiset 1 std::hash_map 1 std::hash_multimap 1 std::stack 1 std::queue 1 std::priority_queue 1 std::bitset 1 std::auto_ptr 1 pair 1 std::pair 1 std::tr1::shared_ptr 1 std::array 1) ; # This is a partial list of STL types to ignore. We do not ignore vector, map, list if we allow STLs -my %stl_names = qw(deque 1 set 1 multiset 1 multimap 1 hash_set 1 +my %stl_names = qw(deque 1 set 1 multiset 1 unordered_map 1 multimap 1 hash_set 1 hash_multiset 1 hash_map 1 hash_multimap 1 stack 1 queue 1 priority_queue 1 bitset 1 auto_ptr 1 array 1 - std::deque 1 std::set 1 std::multiset 1 std::multimap 1 std::hash_set 1 + std::deque 1 std::set 1 std::multiset 1 std::unordered_map 1 std::multimap 1 std::hash_set 1 std::hash_multiset 1 std::hash_map 1 std::hash_multimap 1 std::stack 1 std::queue 1 std::priority_queue 1 std::bitset 1 std::auto_ptr 1 pair 1 std::pair 1 std::tr1::shared_ptr 1 std::array 1) ; diff --git a/libexec/trick/java/lib/Makefile b/libexec/trick/java/lib/Makefile index f66ab9a0..d9445023 100644 --- a/libexec/trick/java/lib/Makefile +++ b/libexec/trick/java/lib/Makefile @@ -9,35 +9,42 @@ EXTERNAL_JARS = \ bsaf-1.9.2.jar \ - itext-2.1.7.jar \ jcommon-1.0.23.jar \ jfreechart-1.0.19.jar \ jfreesvg-2.1.jar \ jopt-simple-4.8.jar \ junit-4.12.jar \ swingx-1.6.1.jar \ - hamcrest-core-1.3.jar + hamcrest-core-1.3.jar \ + pdfbox-2.0.11.jar \ + fontbox-2.0.11.jar \ + commons-logging-1.2.jar + external_jars : ${EXTERNAL_JARS} bsaf-1.9.2.jar : - curl -O http://repo.maven.apache.org/maven2/org/jdesktop/bsaf/bsaf/1.9.2/bsaf-1.9.2.jar -itext-2.1.7.jar : - curl -O http://repo.maven.apache.org/maven2/com/lowagie/itext/2.1.7/itext-2.1.7.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/jdesktop/bsaf/bsaf/1.9.2/bsaf-1.9.2.jar jcommon-1.0.23.jar : - curl -O http://repo.maven.apache.org/maven2/org/jfree/jcommon/1.0.23/jcommon-1.0.23.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/jfree/jcommon/1.0.23/jcommon-1.0.23.jar jfreechart-1.0.19.jar : - curl -O http://repo.maven.apache.org/maven2/org/jfree/jfreechart/1.0.19/jfreechart-1.0.19.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/jfree/jfreechart/1.0.19/jfreechart-1.0.19.jar jfreesvg-2.1.jar : - curl -O http://repo.maven.apache.org/maven2/org/jfree/jfreesvg/2.1/jfreesvg-2.1.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/jfree/jfreesvg/2.1/jfreesvg-2.1.jar jopt-simple-4.8.jar : - curl -O http://repo.maven.apache.org/maven2/net/sf/jopt-simple/jopt-simple/4.8/jopt-simple-4.8.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/net/sf/jopt-simple/jopt-simple/4.8/jopt-simple-4.8.jar junit-4.12.jar: - curl -O http://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar + curl --retry 4 -O http://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar swingx-1.6.1.jar : - curl -O http://repo.maven.apache.org/maven2/org/swinglabs/swingx/1.6.1/swingx-1.6.1.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/swinglabs/swingx/1.6.1/swingx-1.6.1.jar hamcrest-core-1.3.jar : - curl -O http://repo.maven.apache.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar +pdfbox-2.0.11.jar : + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/apache/pdfbox/pdfbox/2.0.11/pdfbox-2.0.11.jar +fontbox-2.0.11.jar : + curl --retry 4 -O http://repo.maven.apache.org/maven2/org/apache/pdfbox/fontbox/2.0.11/fontbox-2.0.11.jar +commons-logging-1.2.jar : + curl --retry 4 -O https://repo1.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar clean: rm -f ${EXTERNAL_JARS} diff --git a/libexec/trick/make_makefile_src b/libexec/trick/make_makefile_src index 325a0dac..0348c8a4 100755 --- a/libexec/trick/make_makefile_src +++ b/libexec/trick/make_makefile_src @@ -123,7 +123,6 @@ my @all_cfly_files ; my @all_read_only_libs ; my @all_compile_libs ; my %files_by_dir ; -my ( $sp_dir , $src_dir , $sp_file , $base_name , $suffix) ; my @exclude_dirs ; @exclude_dirs = split /:/ , "$ENV{TRICK_EXCLUDE}:$ENV{TRICK_EXT_LIB_DIRS}"; @@ -146,45 +145,40 @@ if (scalar @exclude_dirs) { @all_compile_libs = sort (grep !/trick_source/ , @all_compile_libs) ; @all_cfly_files = sort (grep !/^-|trick_source|a$/ , @all_cfly_files) ; -# split off files by directory -foreach ( @all_cfly_files ) { - $sp_file = basename($_) ; - $_ = abs_path(dirname($_)) ; - - ( $sp_dir , $src_dir ) = /(.*?)(?:\/(src))?$/ ; - $src_dir .= "/" if ($src_dir ne "") ; - ($base_name , $suffix) = $sp_file =~ /(.*?)([cfly]$|C$|cc$|cxx$|cpp$|c\+\+$)/ ; - - $files_by_dir{$sp_dir}{src_dir} = $src_dir ; - push @{$files_by_dir{$sp_dir}{$suffix}} , $base_name ; +sub add_file($) { + my ($name, $path, $extension) = fileparse($_[0], qr/\.[^.]*/) ; + push @{$files_by_dir{$path}{$extension}} , $name ; } -# get all of the files required by compiled libraries -# compile all files as normal files, we're not going to make a library anymore. -foreach $n ( @all_compile_libs ) { - my @local_files ; - $sp_file = basename($n) ; - $sp_dir = dirname($n) ; - $sp_dir =~ s/\/object_\$\{TRICK_HOST_CPU\}?$// ; - $sp_dir = abs_path($sp_dir) ; - $src_dir = ( -e "$sp_dir/src" ) ? "src/" : "" ; - $files_by_dir{$sp_dir}{src_dir} = $src_dir ; - opendir THISDIR, "$sp_dir/$src_dir" or die "Could not open the directory $sp_dir/$src_dir"; - @local_files = grep !/^\.\.\./ , readdir THISDIR; - @local_files = grep /\.[cfly]$|C$|cc$|cxx$|cpp$|c\+\+$/ , @local_files; - foreach $k ( @local_files ) { - ($base_name , $suffix) = $k =~ /(.*?)([cfly]$|C$|cc$|cxx$|cpp$|c\+\+$)/ ; - push @{$files_by_dir{$sp_dir}{$suffix}} , $base_name ; +sub add_files_in_directory($) { + opendir THISDIR, "$_[0]" or die "Could not open $_[0]" ; + my @files = grep !/^\./ , readdir THISDIR ; + foreach ( @files ) { + add_file($_[0] . "/" . $_) ; } closedir THISDIR ; } +# split off files by directory +foreach ( @all_cfly_files ) { + add_file($_); +} + +# get all of the files required by compiled libraries +# compile all files as normal files, we're not going to make a library anymore. +foreach ( @all_compile_libs ) { + my $path = abs_path(dirname($_)); + add_files_in_directory($path) ; + $path .= "/src" ; + add_files_in_directory($path) if -e "$path" ; +} + # sort and weed out duplicate files -foreach $k ( keys %files_by_dir ) { +foreach my $directory ( keys %files_by_dir ) { my %temp_hash ; - foreach $n ( qw{ c f l y h C cc cxx cpp c++} ) { + foreach my $extension ( keys %{$files_by_dir{$directory}} ) { undef %temp_hash ; - @{$files_by_dir{$k}{$n}} = sort grep ++$temp_hash{$_} < 2, @{$files_by_dir{$k}{$n}} ; + @{$files_by_dir{$directory}{$extension}} = sort grep ++$temp_hash{$_} < 2, @{$files_by_dir{$directory}{$extension}} ; } } @@ -199,13 +193,6 @@ foreach $k ( sort keys %files_by_dir ) { } } -# set the "dir_num" of each directory. -foreach $k ( sort keys %files_by_dir ) { - $_ = $k ; - ($files_by_dir{$k}{dir_num} = $_) =~ s#^/## ; - $files_by_dir{$k}{dir_num} =~ s/[\/.]/_/g ; -} - my $wd = abs_path(cwd()) ; my $dt = localtime(); my ($trick_ver) = get_trick_version() ; @@ -256,74 +243,60 @@ build/S_source.d: ; " ; -my %object_files_by_type ; -my %model_build_dirs ; # List out all of the object files and put the list in a file that we can pass to the linker. # Passing all of them directly to the linker in the command line can exceed the line limit. open MODEL_LINK_LIST, ">build/model_link_list" or die "Could not open build/model_link_list" ; -foreach my $ext ( qw{ c C cc cxx cpp c++ } ) { - print MAKEFILE "MODEL_${ext}_OBJECTS :=" ; - foreach $k ( sort keys %files_by_dir ) { - foreach $f ( @{$files_by_dir{$k}{$ext}} ) { - print MAKEFILE " \\\n build$k/$files_by_dir{$k}{src_dir}$f" . "o" ; - print MODEL_LINK_LIST "build$k/$files_by_dir{$k}{src_dir}$f" . "o\n" ; + +my %files_by_extension ; +foreach my $directory ( keys %files_by_dir ) { + foreach my $extension ( grep { /^\.(c|cc|C|cxx|cpp|c\+\+)$/ } keys %{$files_by_dir{$directory}} ) { + foreach my $file ( @{$files_by_dir{$directory}{$extension}} ) { + push @{$files_by_extension{$extension}} , "build$directory$file.o" ; } } +} + +foreach my $extension ( keys %files_by_extension ) { + print MAKEFILE "MODEL_OBJECTS${extension} :=" ; + foreach my $file ( @{$files_by_extension{$extension}} ) { + print MAKEFILE " \\\n $file" ; + print MODEL_LINK_LIST "$file\n" ; + } print MAKEFILE "\n\n" } close MODEL_LINK_LIST ; print MAKEFILE "MODEL_OBJECTS :=" ; -foreach my $ext ( qw{ c C cc cxx cpp c++ } ) { - print MAKEFILE " \${MODEL_${ext}_OBJECTS}" ; +foreach my $extension ( keys %files_by_extension ) { + print MAKEFILE " \${MODEL_OBJECTS$extension}" ; } # Write out the compile rules for each type of file. print MAKEFILE " -# These targets should have an order-only dependency on their directories, which would require -# moving them to a .SECONDEXPANSION section and would complicate the rules. However, these -# directories appear to be created as part of the read_lib_deps function, so I'm leaving it out -# for now. +# We use .SECONDEXPANSION here to allow us to use automatic vairiables in the prerequisite list +# in order to add to each target an order-only dependency on its directory. +# See https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html +# and https://www.gnu.org/software/make/manual/html_node/Secondary-Expansion.html -\${MODEL_c_OBJECTS} : build/%.o : /%.c | build/%.d +.SECONDEXPANSION:" ; + +foreach my $extension ( keys %files_by_extension ) { + my $compiler = "TRICK_" . ($extension eq ".c" ? "CC" : "CPPC") ; + my $flags = $extension eq ".c" ? "C" : "CXX" ; + my $command = "\$($compiler) \$(TRICK_${flags}FLAGS) \$(TRICK_SYSTEM_${flags}FLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CC) \$(TRICK_CFLAGS) \$(TRICK_SYSTEM_CFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} +\t\@echo $command >> \$(MAKE_OUT) +\t\$(ECHO_CMD)$command 2>&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]}" ; +} -\${MODEL_cc_OBJECTS} : build/%.o : /%.cc | build/%.d -\t\$(PRINT_COMPILE) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} +print MAKEFILE " -\${MODEL_cpp_OBJECTS} : build/%.o : /%.cpp | build/%.d -\t\$(PRINT_COMPILE) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} - -\${MODEL_C_OBJECTS} : build/%.o : /%.C | build/%.d -\t\$(PRINT_COMPILE) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} - -\${MODEL_cxx_OBJECTS} : build/%.o : /%.cxx | build/%.d -\t\$(PRINT_COMPILE) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} - -\${MODEL_c++_OBJECTS} : build/%.o : /%.c++ | build/%.d -\t\$(PRINT_COMPILE) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) -I\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} - -#define compile_rule -#build/%.o: /%.\$1 -#\t\$\$(PRINT_COMPILE) -#\t\$\$(ECHO_CMD)\$\$(TRICK_CPPC) \$\$(TRICK_CXXFLAGS) \$\$(TRICK_SYSTEM_CXXFLAGS) -I\$\$(&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} -#endef -# -#EXTENSIONS := C cc cpp cxx c++ -#\$(foreach EXTENSION,\$(EXTENSIONS),\$(eval \$(call compile_rule,\$(EXTENSION)))) +\$(sort \$(dir \$(MODEL_OBJECTS))): +\t\@mkdir -p \$\@ \$(MODEL_OBJECTS:.o=.d): ; @@ -362,8 +335,14 @@ S_sie.resource: \$(S_MAIN) # write out the override files we have read in open MAKEFILEOVER, ">build/Makefile_overrides" or die "Could not open build/Makefile_overrides" ; foreach $k ( sort keys %files_by_dir ) { - # if a particular directory had an override file, save that into memory - if (open OV_FILE, "$k/makefile_overrides") { + # Look for makefile_overrides in the current directory. + # If no such file exists AND this directory is named "src", look for it one level up. + # Silly, but baggage we're stuck with. + my $makefile_overrides = "${k}makefile_overrides" ; + if (not -e $makefile_overrides and $k =~ /\/src\/$/) { + $makefile_overrides = dirname($k) . "/makefile_overrides" ; + } + if (open OV_FILE, $makefile_overrides) { while ( ) { s/(#.*)// ; my ($comment) = $1 ; @@ -373,25 +352,30 @@ foreach $k ( sort keys %files_by_dir ) { while ( s,/[^/.]+/\.\.,, ) {} s//$comment/ ; if ( s/^objects\s*:\s*// ) { - foreach my $ext ( qw{c C cc cxx cpp CPLUSPLUS l y} ) { - $files_by_dir{$k}{overrides} .= "\$(MODEL_${ext}_OBJ_$files_by_dir{$k}{dir_num}): $_" ; + foreach my $extension ( keys %files_by_extension ) { + foreach my $file (@{$files_by_dir{$k}{$extension}}) { + $files_by_dir{$k}{overrides} .= "build$k${file}.o \\\n" ; + } } + $files_by_dir{$k}{overrides} .= ": $_" } - elsif ( s/^depend\s*:\s*// ) { - $files_by_dir{$k}{overrides} .= "depend_$files_by_dir{$k}{dir_num}: $_" ; - } - elsif ( s/([cfhy]|C|cc|cxx|cpp|CPLUSPLUS)_objects\s*:\s*// ) { - $files_by_dir{$k}{overrides} .= "\$(MODEL_$1_OBJ_$files_by_dir{$k}{dir_num}): $_" ; + elsif ( s/(.+)_objects\s*:\s*// ) { + if (scalar @{$files_by_dir{$k}{".$1"}}) { + foreach my $file (@{$files_by_dir{$k}{".$1"}}) { + $files_by_dir{$k}{overrides} .= "build$k$file.o \\\n" ; + } + $files_by_dir{$k}{overrides} .= ": $_" + } } else { $files_by_dir{$k}{overrides} .= $_ ; } } close OV_FILE ; - print MAKEFILEOVER "\nMAKEFILE_LIST += $k/makefile_overrides\n" ; - print MAKEFILEOVER "\n# Overrides from $k\n\n" ; + print MAKEFILEOVER "# Overrides from $makefile_overrides\n" ; + print MAKEFILEOVER "MAKEFILE_LIST += $makefile_overrides\n\n" ; print MAKEFILEOVER "$files_by_dir{$k}{overrides}\n" ; - print MAKEFILEOVER "\nMAKEFILE_LIST := \$(filter-out $k/makefile_overrides,\$(MAKEFILE_LIST))\n" ; + print MAKEFILEOVER "MAKEFILE_LIST := \$(filter-out $makefile_overrides,\$(MAKEFILE_LIST))\n\n" ; } } close MAKEFILEOVER ; diff --git a/libexec/trick/make_makefile_swig b/libexec/trick/make_makefile_swig index cf5033cd..364d9d40 100755 --- a/libexec/trick/make_makefile_swig +++ b/libexec/trick/make_makefile_swig @@ -169,12 +169,12 @@ sub write_makefile_swig() { print PY_LINK_LIST "build/init_swig_modules.o\n" ; print PY_LINK_LIST "build/top.o\n" ; - print MAKEFILE "SWIG_CFLAGS := -I../include \${PYTHON_INCLUDES} -Wno-shadow -Wno-missing-field-initializers + print MAKEFILE "TRICK_SYSTEM_SWIG_CFLAGS := -I../include \${PYTHON_INCLUDES} -Wno-shadow -Wno-missing-field-initializers ifeq (\$(IS_CC_CLANG), 1) - SWIG_CFLAGS += -Wno-self-assign -Wno-sometimes-uninitialized -Wno-deprecated-register + TRICK_SYSTEM_SWIG_CFLAGS += -Wno-self-assign -Wno-sometimes-uninitialized -Wno-deprecated-register else - SWIG_CFLAGS += -Wno-unused-but-set-variable + TRICK_SYSTEM_SWIG_CFLAGS += -Wno-unused-but-set-variable endif ifndef TRICK_VERBOSE_BUILD @@ -231,8 +231,8 @@ SWIG_SRC = \$(subst .i,.cpp,\$(SWIG_I)) $swig_src_dir/top.cpp \$(SWIG_SRC) : %.cpp: %.i | \$(SWIG_I) \t\$(PRINT_SWIG) -\t\@echo \$(SWIG) \$(TRICK_INCLUDE) \$(TRICK_DEFINES) \$(TRICK_VERSIONS) \$(SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir trick -o \$@ \$< >> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(SWIG) \$(TRICK_INCLUDE) \$(TRICK_DEFINES) \$(TRICK_VERSIONS) \$(SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir trick -o \$@ \$< 2>&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} +\t\@echo \$(SWIG) \$(TRICK_INCLUDE) \$(TRICK_DEFINES) \$(TRICK_VERSIONS) \$(TRICK_SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir trick -o \$@ \$< >> \$(MAKE_OUT) +\t\$(ECHO_CMD)\$(SWIG) \$(TRICK_INCLUDE) \$(TRICK_DEFINES) \$(TRICK_VERSIONS) \$(TRICK_SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir trick -o \$@ \$< 2>&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} # SWIG_OBJECTS ================================================================= @@ -240,8 +240,8 @@ SWIG_OBJECTS = \$(subst .cpp,.o,\$(SWIG_SRC)) $swig_src_dir/init_swig_modules.o \$(SWIG_OBJECTS): %.o: %.cpp \t\$(PRINT_COMPILE_SWIG) -\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) \$(SWIG_CFLAGS) -Wno-unused-parameter -c -o \$@ \$< >> \$(MAKE_OUT) -\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) \$(SWIG_CFLAGS) -Wno-unused-parameter -c -o \$@ \$< 2>&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} +\t\@echo \$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) \$(TRICK_SWIG_CFLAGS) \$(TRICK_SYSTEM_SWIG_CFLAGS) \$-Wno-unused-parameter -c -o \$@ \$< >> \$(MAKE_OUT) +\t\$(ECHO_CMD)\$(TRICK_CPPC) \$(TRICK_CXXFLAGS) \$(TRICK_SYSTEM_CXXFLAGS) \$(TRICK_SWIG_CFLAGS) \$(TRICK_SYSTEM_SWIG_CFLAGS) -Wno-unused-parameter -c -o \$@ \$< 2>&1 | \$(TEE) -a \$(MAKE_OUT) ; exit \$\${PIPESTATUS[0]} \$(S_MAIN): \$(SWIG_OBJECTS) diff --git a/share/trick/makefiles/Makefile.common b/share/trick/makefiles/Makefile.common index 084d8307..94dfcc42 100644 --- a/share/trick/makefiles/Makefile.common +++ b/share/trick/makefiles/Makefile.common @@ -50,7 +50,8 @@ export TRICK_HOST_CPU := $(shell $(TRICK_HOME)/bin/trick-gte TRICK_HOST_CPU) export TRICK_EXEC_LINK_LIBS := ${PTHREAD_LIBS} $(PYTHON_LIB) $(UDUNITS_LDFLAGS) $(PLATFORM_LIBS) -lm -ldl export TRICK_LIBS := ${RPATH} -L${TRICK_LIB_DIR} -ltrick -ltrick_pyip -ltrick_comm -ltrick_math -ltrick_units -ltrick_mm export TRICK_SYSTEM_LDFLAGS := $(TRICK_SYSTEM_LDFLAGS) -export SWIG_FLAGS := $(SWIG_FLAGS) +export TRICK_SWIG_FLAGS := $(TRICK_SWIG_FLAGS) +export TRICK_SWIG_CFLAGS := $(TRICK_SWIG_CFLAGS) IO_SRC_DIR := io_src/ OBJ_DIR := object_${TRICK_HOST_CPU} diff --git a/share/trick/makefiles/Makefile.sim b/share/trick/makefiles/Makefile.sim deleted file mode 100644 index 96009683..00000000 --- a/share/trick/makefiles/Makefile.sim +++ /dev/null @@ -1,126 +0,0 @@ -include ${TRICK_HOME}/share/trick/makefiles/Makefile.common - -ifndef TRICK_VERBOSE_BUILD - PRINT_CP = $(info $(call COLOR,Running) configuration_processor) - PRINT_ICG = $(info $(call COLOR,Running) ICG) - PRINT_S_DEF_DEPS = $(info $(call COLOR,Tracing) S_define) - PRINT_CONVERT_SWIG = $(info $(call COLOR,Running) convert_swig) - PRINT_MAKEFILE_SRC = $(info $(call COLOR,Writing) Makefile_src) - PRINT_MAKEFILE_SWIG = $(info $(call COLOR,Writing) Makefile_swig) -endif - -.NOTPARALLEL: - -export TRICK_ICG_EXCLUDE - -# Use /bin/bash as the shell so we can use PIPESTATUS -SHELL = /bin/bash - -all test: $(TRICK_STATIC_LIB) S_source.hh \ - build/Makefile_io_src \ - build/Makefile_src \ - build/Makefile_swig \ - build/convert_swig_last_run - @$(MAKE) --no-print-directory -f build/Makefile_src $@ 2>&1 | tee build/MAKE_out ; exit $${PIPESTATUS[0]} - -build: - @mkdir $@ - -debug: all -debug: TRICK_CPFLAGS += --debug - -$(TRICK_STATIC_LIB): - $(info Cannot find $@. Please build Trick for this platform.) - @exit -1 - -# CP creates S_source.hh required for ICG and SWIG processing -S_source.hh build/S_define.lib_deps: S_define | build - $(PRINT_CP) - $(ECHO_CMD)${TRICK_HOME}/$(LIBEXEC)/trick/configuration_processor $(TRICK_CPFLAGS) - $(PRINT_S_DEF_DEPS) - $(ECHO_CMD)$(TRICK_CPPC) $(TRICK_SFLAGS) $(TRICK_SYSTEM_SFLAGS) -M -MT S_source.hh -MF build/S_define.deps -x c++ S_define - -# Automatic and manual ICG rules -build/Makefile_io_src: | S_source.hh build - $(PRINT_ICG) - $(ECHO_CMD)${TRICK_HOME}/bin/trick-ICG -m ${TRICK_ICGFLAGS} ${TRICK_CXXFLAGS} ${TRICK_SYSTEM_CXXFLAGS} S_source.hh - -ICG: - $(PRINT_ICG) - $(ECHO_CMD)${TRICK_HOME}/bin/trick-ICG -m ${TRICK_ICGFLAGS} ${TRICK_CXXFLAGS} ${TRICK_SYSTEM_CXXFLAGS} S_source.hh - -force_ICG: - $(PRINT_ICG) - $(ECHO_CMD)${TRICK_HOME}/bin/trick-ICG -f -m ${TRICK_ICGFLAGS} ${TRICK_CXXFLAGS} ${TRICK_SYSTEM_CXXFLAGS} S_source.hh - -# Create makefile for source code -build/Makefile_src: | build/Makefile_io_src build/S_define.lib_deps - $(PRINT_MAKEFILE_SRC) - $(ECHO_CMD)${TRICK_HOME}/$(LIBEXEC)/trick/make_makefile_src $? - -# Create makefile for SWIG code -build/Makefile_swig: | build/Makefile_io_src - $(PRINT_MAKEFILE_SWIG) - $(ECHO_CMD)${TRICK_HOME}/$(LIBEXEC)/trick/make_makefile_swig $? - -# Automatic and manual convert_swig rules -build/convert_swig_last_run: | build/Makefile_swig - $(PRINT_CONVERT_SWIG) - $(ECHO_CMD)${TRICK_HOME}/$(LIBEXEC)/trick/convert_swig ${TRICK_CONVERT_SWIG_FLAGS} - @touch $@ - -convert_swig: - $(PRINT_CONVERT_SWIG) - $(ECHO_CMD)${TRICK_HOME}/$(LIBEXEC)/trick/convert_swig ${TRICK_CONVERT_SWIG_FLAGS} - @touch build/convert_swig_last_run - -# prints the value of a makefile variable, example invocation "make print-TRICK_CXXFLAGS" -# This rule is used by trick-config -print-%: - @echo '$*=$($*)' - -# Force S_define_exp to be remade each time this rule runs -.PHONY: S_define_exp - -S_define_exp: - $(TRICK_CC) -E -C -xc++ ${TRICK_SFLAGS} $(TRICK_SYSTEM_SFLAGS) S_define > $@ - -# Pass these options -sie: - @if [ -f build/Makefile_src ] ; then $(MAKE) --no-print-directory -f build/Makefile_src $@ ; else echo "No build/Makefile_src found" ; fi - -help: - @echo -e "\ -Simulation make options:\n\ - make [debug] [TRICK_VERBOSE_BUILD=1] - Makes everything: S_main and S_sie.resource\n\ - make sie - Builds the S_sie.resource file.\n\ - make clean - Removes all object files in simulation directory\n\ - make spotless - Performs a clean\n\ - make apocalypse - Performs a clean" - -tidy: - -rm -f S_source.hh S_sie.resource - -rm -f S_main* T_main* - -rm -f build/Makefile_* - -rm -f S_default.dat - -clean: tidy - -rm -f DP_Product/DP_rt_frame DP_Product/DP_rt_itimer - -rm -f DP_Product/DP_rt_jobs DP_Product/DP_rt_timeline DP_Product/DP_mem_stats - -rm -rf build trick - -spotless: clean - -distclean: clean - -rm -f makefile - -apocalypse: distclean - @echo "I love the smell of napalm in the morning" - -CLEAN_RULES_DEFINED = 1 - -# Dependencies for the above rules generated by configuration_process, ICG, make_makefile and make_makefile_swig --include build/S_define.deps --include build/Makefile_ICG --include build/Makefile_convert_swig --include build/Makefile_src_deps diff --git a/share/trick/makefiles/Makefile.trickconfig b/share/trick/makefiles/Makefile.trickconfig new file mode 100644 index 00000000..b7308561 --- /dev/null +++ b/share/trick/makefiles/Makefile.trickconfig @@ -0,0 +1,9 @@ +# Utility makefile for trick-config + + +include ${TRICK_HOME}/share/trick/makefiles/Makefile.common + +# prints the value of a makefile variable, example invocation "make print-TRICK_CXXFLAGS" +# This rule is used by trick-config +print-%: + @echo '$*=$($*)' diff --git a/share/trick/makefiles/trickify.mk b/share/trick/makefiles/trickify.mk index e4e2c2ae..9fd586f9 100644 --- a/share/trick/makefiles/trickify.mk +++ b/share/trick/makefiles/trickify.mk @@ -70,7 +70,6 @@ # # For more information, see: # github.com/nasa/trick/wiki/Trickified-Project-Libraries - ifndef TRICKIFY_CXX_FLAGS $(error TRICKIFY_CXX_FLAGS must be set) endif @@ -80,7 +79,7 @@ TRICKIFY_PYTHON_DIR ?= python TRICK_HOME := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))/../../..) ifneq ($(wildcard build),) - SWIG_OBJECTS := $(shell tail -n +2 build/S_library_swig) + SWIG_OBJECTS := $(shell cat build/S_library_swig) SWIG_OBJECTS := $(addprefix build,$(addsuffix _py.o,$(basename $(SWIG_OBJECTS)))) IO_OBJECTS := $(shell find build -name "io_*.cpp") IO_OBJECTS := $(IO_OBJECTS:.cpp=.o) @@ -111,7 +110,7 @@ $(TRICKIFY_OBJECT_NAME): $(SWIG_OBJECTS) $(IO_OBJECTS) | $(dir $(TRICKIFY_OBJECT $(info $(call COLOR,Linking) $@) @ld -r -o $@ $^ -$(dir $(TRICKIFY_OBJECT_NAME)) $(TRICKIFY_PYTHON_DIR): +$(dir $(TRICKIFY_OBJECT_NAME)) $(TRICKIFY_PYTHON_DIR) build: @mkdir -p $@ $(IO_OBJECTS): %.o: %.cpp @@ -128,10 +127,11 @@ $(SWIG_OBJECTS): %.o: %.cpp $(SWIG_OBJECTS:.o=.cpp): %.cpp: %.i | $(TRICKIFY_PYTHON_DIR) $(SWIG_OBJECTS:.o=.i) $(info $(call COLOR,SWIGing) $<) - @$(SWIG) $(TRICK_INCLUDE) $(TRICK_DEFINES) $(TRICK_VERSIONS) $(SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir $(TRICKIFY_PYTHON_DIR) -o $@ $< + @$(SWIG) $(TRICK_INCLUDE) $(TRICK_DEFINES) $(TRICK_VERSIONS) $(TRICK_SWIG_FLAGS) -c++ -python -includeall -ignoremissing -w201,303,325,362,389,401,451 -outdir $(TRICKIFY_PYTHON_DIR) -o $@ $< define create_convert_swig_rule build/%_py.i: /%.$1 + $$(info $$(call COLOR,Converting) $$<) ${TRICK_HOME}/$(LIBEXEC)/trick/convert_swig ${TRICK_CONVERT_SWIG_FLAGS} $$< endef @@ -169,7 +169,7 @@ $(foreach EXTENSION,$(EXTENSIONS),$(eval $(call create_convert_swig_rule,$(EXTEN # dependency list. The method is laid out in more detail here: # http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/ -build/S_source.d: +build/S_source.d: | $(dir $@) @$(TRICK_HOME)/bin/trick-ICG $(TRICK_CXXFLAGS) $(TRICK_SYSTEM_CXXFLAGS) $(TRICK_ICGFLAGS) S_source.hh @$(TRICK_HOME)/$(LIBEXEC)/trick/make_makefile_swig @$(TRICK_CC) -MM -MP -MT $@ -MF $@ $(TRICKIFY_CXX_FLAGS) S_source.hh diff --git a/share/trick/trick_ver.txt b/share/trick/trick_ver.txt index fb4998dd..5c0d7189 100644 --- a/share/trick/trick_ver.txt +++ b/share/trick/trick_ver.txt @@ -1 +1 @@ -current_version = "17.2.dev" +current_version = "17.4.0" diff --git a/trick_sims/Ball/README.md b/trick_sims/Ball/README.md new file mode 100644 index 00000000..96199d11 --- /dev/null +++ b/trick_sims/Ball/README.md @@ -0,0 +1,51 @@ +# Ball Sims + +## SIM\_ball\_L1 + +This is a simulation of a ball under the influence of a force field. +The force on the ball is of constant magnitude, and always directed +toward a fixed point. + +![Picture of Sun](images/Ball_L1.png) + +#### Inputs +| Parameter | Units | Default | +|:---------------------------- |:-----:|:-------:| +| ball.force.input.origin[2] | m | { 0.0, 2.0 } | +| ball.force.input.force | N | 8.0 | +| ball.state.input.mass | kg | 10.0 | +| ball.state.input.speed | m/s | 2.0 | +| ball.state.input.elevation | rad | 45 ° x (180/π) | +| ball.state.input.position[2] | m | { 5.0, 5.0 } | + +#### Outputs +| Parameter | Units | +|:--------------------------------- |:-----:| +| ball.state.output.position[2] | m | +| ball.state.output.velocity[2] | m | +| ball.state.output.acceleration[2] | m | + + +## SIM\_ball\_L2 + +This simulation is a derivation of SIM\_ball\_L1. It uses Trick "dynamic-events" to simulate walls, off of which the ball can bounce. + +![Picture of Sun](images/Ball_L2.png) + +#### Inputs +*(In addition to those of SIM\_ball\_L1)* +These parameters define the coordinates of the walls. + +| Parameter | Units | Default | +|:----------------------------------- |:-----:|:-------:| +| ball.force.input.floor\_y\_pos | m | -10.0 | +| ball.force.input.right_wall\_x\_pos | m | 10.0 | +| ball.force.ceiling\_y\_pos | m | 10.0 | +| ball.force.left_wall\_x\_pos | m | -10.0 | + +The outputs are the same as those of SIM\_ball\_L1. + + +## SIM\_ball\_L3 + +This simulation is a derivation of SIM\_ball\_L2. The SIM\_ball\_L3 S_define instanciates two ballSimObject's rather than just one. \ No newline at end of file diff --git a/trick_sims/Ball/images/Ball_L1.png b/trick_sims/Ball/images/Ball_L1.png new file mode 100644 index 00000000..af61a106 Binary files /dev/null and b/trick_sims/Ball/images/Ball_L1.png differ diff --git a/trick_sims/Ball/images/Ball_L2.png b/trick_sims/Ball/images/Ball_L2.png new file mode 100644 index 00000000..0262eead Binary files /dev/null and b/trick_sims/Ball/images/Ball_L2.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/README.md b/trick_sims/Cannon/SIM_cannon_analytic/README.md index 94c705fe..290c3352 100644 --- a/trick_sims/Cannon/SIM_cannon_analytic/README.md +++ b/trick_sims/Cannon/SIM_cannon_analytic/README.md @@ -1,10 +1,13 @@ # SIM\_cannon\_analytic + --- + This is first of eight Trick-based simulations that one builds in the Trick -Tutorial (Section 3). It's purpose is to introduce some of the fundamentals +Tutorial (Section 4). It's purpose is to introduce some of the fundamentals of building a Trick simulation. -Here we simulate the flight of a cannon ball. We want to know the position and velocity of the cannon ball over time, given an initial position, and +Here we simulate the flight of a cannon ball. We want to know the position and +velocity of the cannon ball over time, given an initial position, and velocity, and subject to the following assumptions and limitations: * The **only** force acting on the cannon ball is gravity. @@ -14,45 +17,42 @@ velocity, and subject to the following assumptions and limitations: ![](images/CannonInit.png) -### Solution +## Parameterization +The following parameters are given default values in a "default_data" job called +**cannon\_default\_data**. Their values can be changed in the **input.py** file. -This problem has a closed-form solution, so that's what is used. +| Name | Sim Variable | Type | Units | Symbol | default | +|------------------|------------------------|-----------|---------|:---------------------------------:|---------| +| Barrel Angle | dyn.cannon.init\_angle | double | radians | ![theta](images/param_theta.png) | 30*(π/180) | +| Speed | dyn.cannon.init\_speed | double | m/s | ![speed](images/param_s.png) | 50.0 | +| Gravity | dyn.cannon.g | double | m/s | ![g](images/param_g.png) | 9.81 | +| Initial Position | dyn.cannon.pos0 | double[2] | m | ![x_0](images/init_position.png) | ![](images/zero_vector.png) | + +## Initialization +The initial velocity is calculated in an "initialization" job. + +| Name | Sim Variable | Type | Units | Calculation | +|------------------|:----------------|-----------|-------|-------------------------------| +| Initial Velocity | dyn.cannon.vel0 | double[2] | m/s | ![](images/init_velocity.png) | + +## State Propagation +For each time-step, the following are calculated in a "scheduled" job. Though acceleration is +constant in this simulation, it usually isn't for "F=ma" type simulations. + +| Name | Sim Variable | Type | Units | Calculation | +|------------------|:---------------|-----------|-----------|----------------------------------| +| Acceleration | dyn.cannon.acc | double[2] | m/s² | ![](images/acceleration.png) | +| Velocity(t) | dyn.cannon.vel | double[2] | m/s | ![](images/velocity_fn_of_t.png) | +| Position(t) | dyn.cannon.pos | double[2] | m | ![](images/position_fn_of_t.png) | + +## Calculating When the Ball Impacts the Ground. +The cannon ball will impact the ground, when y-element of the position vector is zero. + +| Name | Sim Variable | Type | Units | Calculation | +|------------------|:----------------------|--------|-------|--------------------------------| +| Time of Impact | dyn.cannon.impactTime | double | s | ![](images/time_of_impact.png) | -![](images/init_v_x_0.png) - - -![](images/init_v_y_0.png) - -![](images/init_a_x.png) - -![](images/init_a_y.png) - -![](images/solution_vx.png) - -![v_{y}(t) = gt +v_{y0}](images/solution_vy.png) - -![](images/solution_x.png) - -![](images/solution_y.png) - - -The cannon ball will impact the ground, when y(t)=0 at: - -![](images/time_of_impact.png) - - -### CANNON Object -Model Variable | Simulation Variable | Type | Units ---------------------------------------------|---------------------|---------|------- -![](images/x_0.png), ![](images/y_0.png) | CANNON.pos0[2] |double[2]| m -![](images/v_x_0.png), ![](images/v_y_0.png)| CANNON.vel0[2] |double[2]| m/s -![\theta](images/param_theta.png) | CANNON.init\_angle |double | r -![speed](images/param_s.png) | CANNON.init\_speed |double | m/s -![\vec{x}](images/vector_x.png) | CANNON.pos[2] |double[2]| m -![\vec{v}](images/vector_v.png) | CANNON.vel[2] |double[2]| m/s diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/acceleration.png b/trick_sims/Cannon/SIM_cannon_analytic/images/acceleration.png new file mode 100644 index 00000000..ea99ce43 Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/acceleration.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_x.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_x.png deleted file mode 100644 index 03b76a90..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_x.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_y.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_y.png deleted file mode 100644 index 57bcfd2e..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/init_a_y.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_position.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_position.png new file mode 100644 index 00000000..2c6db1bd Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/init_position.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_x_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_x_0.png deleted file mode 100644 index c286adf9..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_x_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_y_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_y_0.png deleted file mode 100644 index ec134e18..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/init_v_y_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/init_velocity.png b/trick_sims/Cannon/SIM_cannon_analytic/images/init_velocity.png new file mode 100644 index 00000000..625f61cb Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/init_velocity.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/param_g.png b/trick_sims/Cannon/SIM_cannon_analytic/images/param_g.png new file mode 100644 index 00000000..e4947ab9 Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/param_g.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/position_fn_of_t.png b/trick_sims/Cannon/SIM_cannon_analytic/images/position_fn_of_t.png new file mode 100644 index 00000000..b1513697 Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/position_fn_of_t.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vx.png b/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vx.png deleted file mode 100644 index 93309215..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vx.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vy.png b/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vy.png deleted file mode 100644 index 34002cbe..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_vy.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_x.png b/trick_sims/Cannon/SIM_cannon_analytic/images/solution_x.png deleted file mode 100644 index d1d3b8c5..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_x.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_y.png b/trick_sims/Cannon/SIM_cannon_analytic/images/solution_y.png deleted file mode 100644 index c87c3f85..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/solution_y.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/time_of_impact.png b/trick_sims/Cannon/SIM_cannon_analytic/images/time_of_impact.png index c27a1c35..1d8ded1b 100644 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/time_of_impact.png and b/trick_sims/Cannon/SIM_cannon_analytic/images/time_of_impact.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/v_x.png b/trick_sims/Cannon/SIM_cannon_analytic/images/v_x.png deleted file mode 100644 index ebbecdac..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/v_x.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/v_x_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/v_x_0.png deleted file mode 100644 index 673dc799..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/v_x_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/v_y.png b/trick_sims/Cannon/SIM_cannon_analytic/images/v_y.png deleted file mode 100644 index 8f0c71a8..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/v_y.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/v_y_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/v_y_0.png deleted file mode 100644 index d817767f..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/v_y_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/vector_v.png b/trick_sims/Cannon/SIM_cannon_analytic/images/vector_v.png deleted file mode 100644 index 782d2cd2..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/vector_v.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/vector_x.png b/trick_sims/Cannon/SIM_cannon_analytic/images/vector_x.png deleted file mode 100644 index 663c81bb..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/vector_x.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/velocity_fn_of_t.png b/trick_sims/Cannon/SIM_cannon_analytic/images/velocity_fn_of_t.png new file mode 100644 index 00000000..c7b3f5aa Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/velocity_fn_of_t.png differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/x_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/x_0.png deleted file mode 100644 index 501140cf..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/x_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/y_0.png b/trick_sims/Cannon/SIM_cannon_analytic/images/y_0.png deleted file mode 100644 index 6382e510..00000000 Binary files a/trick_sims/Cannon/SIM_cannon_analytic/images/y_0.png and /dev/null differ diff --git a/trick_sims/Cannon/SIM_cannon_analytic/images/zero_vector.png b/trick_sims/Cannon/SIM_cannon_analytic/images/zero_vector.png new file mode 100644 index 00000000..44a03325 Binary files /dev/null and b/trick_sims/Cannon/SIM_cannon_analytic/images/zero_vector.png differ diff --git a/trick_sims/Cannon/SIM_cannon_jet/README.md b/trick_sims/Cannon/SIM_cannon_jet/README.md index 8c8ab53a..44b39d5d 100644 --- a/trick_sims/Cannon/SIM_cannon_jet/README.md +++ b/trick_sims/Cannon/SIM_cannon_jet/README.md @@ -1,4 +1,4 @@ -#SIM\_cannon\_jet +# SIM\_cannon\_jet This simulation is described in the Trick Tutorial, Section 9. diff --git a/trick_sims/Cannon/SIM_cannon_numeric/README.md b/trick_sims/Cannon/SIM_cannon_numeric/README.md index b2579dc3..a55da54e 100644 --- a/trick_sims/Cannon/SIM_cannon_numeric/README.md +++ b/trick_sims/Cannon/SIM_cannon_numeric/README.md @@ -1,15 +1,31 @@ -# SIM\_cannon\_integ +# SIM\_cannon\_numeric + +--- + +This is the second in a series example cannon ball simulations that one builds in the Trick Tutorial (Sections 9, 10). It's purpose is to introduce Trick supported numerical methods. + +Rather than using the analytic solutions of SIM\_cannon\_analytic, this simulation uses Trick's numerical integration, and root-finding methods to: + +* Determine the cannon ball state (velocity, position) at each time step, and +* Determine when and where the cannon ball impacts the ground. + +The simulation is otherwise the same as SIM\_cannon\_analytic. ![CannonPicture](images/CannonInit.png) -### The Simulation +## Parameterization +Same as in SIM\_cannon\_analytic. -This is a simulation of a cannon shooting a cannonball. Given the initial position of the cannon ball, the muzzle velocity (speed) of the cannon ball, and the elevation angle of the cannon barrel the simulation computes the cannon ball's trajectory and time of impact with the ground. - -The acceleration of gravity is assumed to be -9.81 m/s2. +## Initialization +Same as in SIM\_cannon\_analytic. +## State Propagation +This Trick simulation calculates the cannonball state by numerical integration. +Acceleration is calculated in the "derivative" job **cannon\_deriv**. It is then +used in "integration" job **cannon\_integ** to calculate the cannonball's velocity and +position, using the Trick **integrate** function. - - - +## When and Where the Ball Impacts the Ground +The time and position of impact is determined by the "dynamic\_event" event job +**cannon\_impact**, using the Trick **regula_falsi** function. \ No newline at end of file diff --git a/trick_sims/Cannon/SIM_cannon_numeric/RUN_graphics/input.py b/trick_sims/Cannon/SIM_cannon_numeric/RUN_graphics/input.py index 43c8e768..66897bb8 100644 --- a/trick_sims/Cannon/SIM_cannon_numeric/RUN_graphics/input.py +++ b/trick_sims/Cannon/SIM_cannon_numeric/RUN_graphics/input.py @@ -1,7 +1,5 @@ execfile("Modified_data/realtime.py") -dyn_integloop.getIntegrator(trick.Runge_Kutta_4, 5) - #========================================== # Start the Cannonball Graphics Client #========================================== diff --git a/trick_sims/Cannon/SIM_cannon_numeric/RUN_test/input.py b/trick_sims/Cannon/SIM_cannon_numeric/RUN_test/input.py index 69198ba1..e56bcb45 100644 --- a/trick_sims/Cannon/SIM_cannon_numeric/RUN_test/input.py +++ b/trick_sims/Cannon/SIM_cannon_numeric/RUN_test/input.py @@ -1,5 +1,2 @@ - execfile("Modified_data/realtime.py") execfile("Modified_data/cannon.dr") - -dyn_integloop.getIntegrator(trick.Runge_Kutta_4, 5) diff --git a/trick_sims/Cannon/SIM_cannon_numeric/S_define b/trick_sims/Cannon/SIM_cannon_numeric/S_define index fdb8802b..e63fd141 100644 --- a/trick_sims/Cannon/SIM_cannon_numeric/S_define +++ b/trick_sims/Cannon/SIM_cannon_numeric/S_define @@ -29,3 +29,7 @@ class CannonSimObject : public Trick::SimObject { CannonSimObject dyn ; IntegLoop dyn_integloop (0.01) dyn; + +void create_connections() { + dyn_integloop.getIntegrator(Runge_Kutta_4, 5); +} diff --git a/trick_sims/Cannon/SIM_cannon_numeric/images/CannonInit.png b/trick_sims/Cannon/SIM_cannon_numeric/images/CannonInit.png index 404ff6c7..8801beed 100644 Binary files a/trick_sims/Cannon/SIM_cannon_numeric/images/CannonInit.png and b/trick_sims/Cannon/SIM_cannon_numeric/images/CannonInit.png differ diff --git a/trick_sims/Cannon/models/cannon/gravity/include/cannon.h b/trick_sims/Cannon/models/cannon/gravity/include/cannon.h index 1b4859b5..0416ff44 100644 --- a/trick_sims/Cannon/models/cannon/gravity/include/cannon.h +++ b/trick_sims/Cannon/models/cannon/gravity/include/cannon.h @@ -14,6 +14,7 @@ typedef struct { double pos0[2] ; /* *i m Init position of cannonball */ double init_speed ; /* *i m/s Init barrel speed */ double init_angle ; /* *i rad Angle of cannon */ + double g ; /* *i m/s2 acceleration of gravity */ double acc[2] ; /* m/s2 xy-acceleration */ double vel[2] ; /* m/s xy-velocity */ diff --git a/trick_sims/Cannon/models/cannon/gravity/src/cannon_analytic.c b/trick_sims/Cannon/models/cannon/gravity/src/cannon_analytic.c index 3db5292e..c0c1eff9 100644 --- a/trick_sims/Cannon/models/cannon/gravity/src/cannon_analytic.c +++ b/trick_sims/Cannon/models/cannon/gravity/src/cannon_analytic.c @@ -7,14 +7,14 @@ PURPOSE: ( Analytical Cannon ) int cannon_analytic( CANNON* C ) { - C->acc[0] = 0.00; - C->acc[1] = -9.81 ; + C->acc[0] = 0.0; + C->acc[1] = -C->g; C->vel[0] = C->vel0[0] + C->acc[0] * C->time ; C->vel[1] = C->vel0[1] + C->acc[1] * C->time ; C->pos[0] = C->pos0[0] + (C->vel0[0] + (0.5) * C->acc[0] * C->time) * C->time ; C->pos[1] = C->pos0[1] + (C->vel0[1] + (0.5) * C->acc[1] * C->time) * C->time ; if (C->pos[1] < 0.0) { - C->impactTime = (- C->vel0[1] - sqrt( C->vel0[1] * C->vel0[1] - 2 * C->pos0[1]))/C->acc[1]; + C->impactTime = (C->vel0[1] + sqrt( C->vel0[1] * C->vel0[1] - 2 * C->g * C->pos0[1])) / C->g; C->pos[0] = C->impactTime * C->vel0[0]; C->pos[1] = 0.0; C->vel[0] = 0.0; diff --git a/trick_sims/Cannon/models/cannon/gravity/src/cannon_init.c b/trick_sims/Cannon/models/cannon/gravity/src/cannon_init.c index d0f42e8b..78fe7c7c 100644 --- a/trick_sims/Cannon/models/cannon/gravity/src/cannon_init.c +++ b/trick_sims/Cannon/models/cannon/gravity/src/cannon_init.c @@ -10,8 +10,7 @@ PURPOSE: (Set the initial data values) /* default data job */ int cannon_default_data( CANNON* C ) { - C->acc[0] = 0.0; - C->acc[1] = -9.81; + C->g = 9.81; C->init_angle = M_PI/6 ; C->init_speed = 50.0 ; C->pos0[0] = 0.0 ; diff --git a/trick_sims/Cannon/models/cannon/gravity/src/cannon_numeric.c b/trick_sims/Cannon/models/cannon/gravity/src/cannon_numeric.c index 05d71443..73591729 100644 --- a/trick_sims/Cannon/models/cannon/gravity/src/cannon_numeric.c +++ b/trick_sims/Cannon/models/cannon/gravity/src/cannon_numeric.c @@ -9,8 +9,8 @@ PURPOSE: ( Numeric integration for SIM_cannon_numeric ) int cannon_deriv( CANNON* C ) { if (!C->impact) { - C->acc[0] = 0.00 ; - C->acc[1] = -9.81 ; + C->acc[0] = 0.0; + C->acc[1] = -C->g; C->timeRate = 1.00; } return 0 ; diff --git a/trick_sims/SIM_satellite/models/Satellite/graphics/SatelliteModel.c b/trick_sims/SIM_satellite/models/Satellite/graphics/SatelliteModel.c index 6be46e4c..1ad7eda0 100644 --- a/trick_sims/SIM_satellite/models/Satellite/graphics/SatelliteModel.c +++ b/trick_sims/SIM_satellite/models/Satellite/graphics/SatelliteModel.c @@ -35,8 +35,6 @@ GLuint MakeTexture(GLubyte* data , int width, int height) { void Satellite_initialize(void) { - FILE fp; - capsuleTextureID = MakeTexture(Capsule_texture, CAPSULE_TEXTURE_WIDTH, CAPSULE_TEXTURE_HEIGHT); nozzleTextureID = MakeTexture(Nozzle_texture, NOZZLE_TEXTURE_WIDTH, NOZZLE_TEXTURE_HEIGHT); diff --git a/trick_sims/SIM_satellite/models/Satellite/src/Satellite.cpp b/trick_sims/SIM_satellite/models/Satellite/src/Satellite.cpp index 527293ca..751c2d5d 100644 --- a/trick_sims/SIM_satellite/models/Satellite/src/Satellite.cpp +++ b/trick_sims/SIM_satellite/models/Satellite/src/Satellite.cpp @@ -28,8 +28,6 @@ void Satellite::get_force_of_gravity ( double* gForceV) { void Satellite::get_Force_and_Torque() { double gforcev[3]; - double thruster_force[3]; - double thruster_torque[3]; // Zero force. for (int ii=0; ii<3; ii++) { force[ii] = 0.0; } diff --git a/trick_sims/SIM_sun/RUN_test/input.py b/trick_sims/SIM_sun/RUN_test/input.py index 49357d86..fe1e64ed 100644 --- a/trick_sims/SIM_sun/RUN_test/input.py +++ b/trick_sims/SIM_sun/RUN_test/input.py @@ -101,7 +101,7 @@ if (os.path.isfile(SunDisplay_path)) : os.system( SunDisplay_cmd); else : print('==================================================================================') - print('SunDisplay needs to be built. Please \"cd\" into models/Graphics and type \"make\".') + print('SunDisplay needs to be built. Please \"cd\" into models/graphics and type \"make\".') print('==================================================================================') trick.stop(86400.0) diff --git a/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c b/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c index f8cee704..66722386 100644 --- a/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c +++ b/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c @@ -60,12 +60,12 @@ int sun_pred_fast_display( // sprintf(tmp_s," %ls %.6f",S->label_JD, S->JD); // strcat(message,tmp_s); if ( S->label_Azimuth != NULL ) { - sprintf(tmp_s," %ls %.3f%lc",S->label_Azimuth, S->solar_azimuth, DEGREE_SIGN); + sprintf(tmp_s," %ls %.3f%d",S->label_Azimuth, S->solar_azimuth, DEGREE_SIGN); } else { - sprintf(tmp_s," AZIMUTH %.3f%lc", S->solar_azimuth, DEGREE_SIGN); + sprintf(tmp_s," AZIMUTH %.3f%d", S->solar_azimuth, DEGREE_SIGN); } strcat(message,tmp_s); - sprintf(tmp_s," %ls %.3f%lc",S->label_Elevation, S->solar_elevation, DEGREE_SIGN); + sprintf(tmp_s," %ls %.3f%d",S->label_Elevation, S->solar_elevation, DEGREE_SIGN); strcat(message,tmp_s); send_hs(stdout,"%s\n",message); diff --git a/trick_source/codegen/Interface_Code_Gen/FieldVisitor.cpp b/trick_source/codegen/Interface_Code_Gen/FieldVisitor.cpp index a3600ab7..553aa895 100644 --- a/trick_source/codegen/Interface_Code_Gen/FieldVisitor.cpp +++ b/trick_source/codegen/Interface_Code_Gen/FieldVisitor.cpp @@ -237,7 +237,6 @@ bool FieldVisitor::VisitFieldDecl( clang::FieldDecl *field ) { if ( !qt.isCanonical() ) { fdes->setNonCanonicalTypeName(qt.getAsString()) ; clang::QualType ct = qt.getCanonicalType() ; - std::string tst_string = ct.getAsString() ; if ( debug_level >= 3 ) { std::cout << "\033[33mFieldVisitor VisitFieldDecl: Processing canonical type\033[00m" << std::endl ; ct.dump() ; @@ -271,8 +270,6 @@ bool FieldVisitor::ProcessTemplate(std::string in_name , clang::CXXRecordDecl * return false ; } - size_t pos ; - // Check to see if we've processed this template before // If not we need to create attributes for this template if ( processed_templates.find(in_name) == processed_templates.end() ) { diff --git a/trick_source/codegen/Interface_Code_Gen/FindTrickICG.cpp b/trick_source/codegen/Interface_Code_Gen/FindTrickICG.cpp index 082aeb1d..7dfc3ce4 100644 --- a/trick_source/codegen/Interface_Code_Gen/FindTrickICG.cpp +++ b/trick_source/codegen/Interface_Code_Gen/FindTrickICG.cpp @@ -82,7 +82,7 @@ void FindTrickICG::ElIf(clang::SourceLocation Loc, clang::SourceRange ConditionR If(Loc,ConditionRange,ConditionValue) ; } -#if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 5)) +#if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 7)) void FindTrickICG::Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) #else void FindTrickICG::Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDirective *MD) @@ -109,7 +109,7 @@ void FindTrickICG::Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNam } -#if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 5)) +#if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 7)) void FindTrickICG::Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) #else void FindTrickICG::Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDirective *MD) diff --git a/trick_source/codegen/Interface_Code_Gen/FindTrickICG.hh b/trick_source/codegen/Interface_Code_Gen/FindTrickICG.hh index ae9034ab..157fa7a7 100644 --- a/trick_source/codegen/Interface_Code_Gen/FindTrickICG.hh +++ b/trick_source/codegen/Interface_Code_Gen/FindTrickICG.hh @@ -24,11 +24,14 @@ class FindTrickICG : public clang::PPCallbacks { #if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 5)) virtual void If(clang::SourceLocation Loc, clang::SourceRange ConditionRange, clang::PPCallbacks::ConditionValueKind ConditionValue) ; virtual void ElIf(clang::SourceLocation Loc, clang::SourceRange ConditionRange, clang::PPCallbacks::ConditionValueKind ConditionValue) ; - virtual void Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) ; - virtual void Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) ; #else virtual void If(clang::SourceLocation Loc, clang::SourceRange ConditionRange, bool ConditionValue) ; virtual void ElIf(clang::SourceLocation Loc, clang::SourceRange ConditionRange, bool ConditionValue) ; +#endif +#if (LIBCLANG_MAJOR > 3) || ((LIBCLANG_MAJOR == 3) && (LIBCLANG_MINOR >= 7)) + virtual void Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) ; + virtual void Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) ; +#else virtual void Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDirective *MD) ; virtual void Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok, const clang::MacroDirective *MD) ; #endif diff --git a/trick_source/codegen/Interface_Code_Gen/PrintAttributes.cpp b/trick_source/codegen/Interface_Code_Gen/PrintAttributes.cpp index 2249d175..8583c5be 100644 --- a/trick_source/codegen/Interface_Code_Gen/PrintAttributes.cpp +++ b/trick_source/codegen/Interface_Code_Gen/PrintAttributes.cpp @@ -383,7 +383,6 @@ void PrintAttributes::printIOMakefile() { std::ofstream io_link_list ; std::ofstream ICG_processed ; std::ofstream ext_lib ; - unsigned int ii ; // Don't create a makefile if we didn't process any files. if ( out_of_date_io_files.empty() ) { diff --git a/trick_source/codegen/Interface_Code_Gen/main.cpp b/trick_source/codegen/Interface_Code_Gen/main.cpp index 47716b6e..bf0cd9fb 100644 --- a/trick_source/codegen/Interface_Code_Gen/main.cpp +++ b/trick_source/codegen/Interface_Code_Gen/main.cpp @@ -97,6 +97,9 @@ int main(int argc, char * argv[]) { ci.getLangOpts().CPlusPlus = true ; ci.getLangOpts().CPlusPlus11 = true ; ci.getLangOpts().CXXOperatorNames = true ; +#if (LIBCLANG_MAJOR >= 6) + ci.getLangOpts().DoubleSquareBracketAttributes = true ; +#endif // Create all of the necessary managers. ci.createFileManager(); diff --git a/trick_source/data_products/Apps/Trk2csv/makefile b/trick_source/data_products/Apps/Trk2csv/makefile index 1b7e9e7e..dd716a27 100644 --- a/trick_source/data_products/Apps/Trk2csv/makefile +++ b/trick_source/data_products/Apps/Trk2csv/makefile @@ -1,7 +1,7 @@ include ${TRICK_HOME}/share/trick/makefiles/Makefile.common -CC = c++ +CXX = c++ DP_CFLAGS = -g -I../.. OBJDIR = object_${TRICK_HOST_CPU} LIBDIR = ../../lib_${TRICK_HOST_CPU} @@ -23,10 +23,10 @@ endif all: $(ASCII_MAIN) $(ASCII_MAIN): $(OBJDIR)/trk2ascii.o - $(CC) $(DP_CFLAGS) -o $(ASCII_MAIN) $(OBJDIR)/trk2ascii.o $(DP_LIBS) $(DL_LIB) -lm + $(CXX) $(DP_CFLAGS) -o $(ASCII_MAIN) $(OBJDIR)/trk2ascii.o $(DP_LIBS) $(DL_LIB) -lm $(OBJDIR)/trk2ascii.o: trk2ascii.cpp | $(OBJDIR) - $(CC) $(DP_CFLAGS) -c trk2ascii.cpp -o $(OBJDIR)/trk2ascii.o + $(CXX) $(DP_CFLAGS) -c trk2ascii.cpp -o $(OBJDIR)/trk2ascii.o clean: rm -f trk2ascii diff --git a/trick_source/data_products/Apps/trkConvert/CSV_Formatter.cpp b/trick_source/data_products/Apps/trkConvert/CSV_Formatter.cpp index 62d2b237..573dc855 100644 --- a/trick_source/data_products/Apps/trkConvert/CSV_Formatter.cpp +++ b/trick_source/data_products/Apps/trkConvert/CSV_Formatter.cpp @@ -17,8 +17,8 @@ void CSV_Formatter::writeDatum(FILE* out_fp, int16_t datum) { fprintf(out_fp,"% void CSV_Formatter::writeDatum(FILE* out_fp, uint16_t datum) { fprintf(out_fp,"%u", datum); } void CSV_Formatter::writeDatum(FILE* out_fp, int32_t datum) { fprintf(out_fp,"%d", datum); } void CSV_Formatter::writeDatum(FILE* out_fp, uint32_t datum) { fprintf(out_fp,"%u", datum); } -void CSV_Formatter::writeDatum(FILE* out_fp, int64_t datum) { fprintf(out_fp,"%lld", datum); } -void CSV_Formatter::writeDatum(FILE* out_fp, uint64_t datum) { fprintf(out_fp,"%lld", datum); } +void CSV_Formatter::writeDatum(FILE* out_fp, int64_t datum) { fprintf(out_fp,"%ld", datum); } +void CSV_Formatter::writeDatum(FILE* out_fp, uint64_t datum) { fprintf(out_fp,"%lu", datum); } void CSV_Formatter::writeDatum(FILE* out_fp, float datum) { fprintf(out_fp,"%.7f", datum); } void CSV_Formatter::writeDatum(FILE* out_fp, double datum) { fprintf(out_fp,"%.15g", datum); } const char* CSV_Formatter::extension() { return ".csv"; }; diff --git a/trick_source/data_products/Apps/trkConvert/DocWindow.cpp b/trick_source/data_products/Apps/trkConvert/DocWindow.cpp new file mode 100644 index 00000000..29234ec4 --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/DocWindow.cpp @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "DocWindow.h" +#include "VarTableWidget.h" +#include "CSV_Formatter.hh" +#include "Varlist_Formatter.hh" + +DocWindow::DocWindow(TRK_DataLog* data_log ) + : QMainWindow( 0, 0) { + + QTextStream out(stdout); + + foundItemIndex = 0; + datalog = data_log; + + // Build the FILE menu + + QMenu *fileMenu = menuBar()->addMenu("&File"); + + QAction * fileLoadAction = new QAction( "&Open File...", this ); + fileLoadAction->setShortcut(tr("CTRL+O")); + fileMenu->addAction(fileLoadAction); + connect( fileLoadAction, &QAction::triggered , this, &DocWindow::load ); + + fileMenu->addSeparator(); + + QAction * csvSaveAction = new QAction( "&Export as CSV...", this ); + fileMenu->addAction(csvSaveAction); + connect( csvSaveAction, &QAction::triggered, this, &DocWindow::saveAsCSV ); + + QAction * varListSaveAction = new QAction( "&Export as Variable List...", this ); + fileMenu->addAction(varListSaveAction); + connect( varListSaveAction, &QAction::triggered, this, &DocWindow::saveAsVarList ); + + // Build the EDIT menu + + QMenu *editMenu = menuBar()->addMenu("&Edit"); + + QAction * editSelectAction = new QAction( "&Select All", this ); + editSelectAction->setShortcut(tr("CTRL+A")); + editMenu->addAction(editSelectAction); + connect( editSelectAction, &QAction::triggered, this, &DocWindow::checkAll ); + + QAction * editClearAction = new QAction( "&Clear All", this ); + editMenu->addAction(editClearAction); + connect( editClearAction, &QAction::triggered, this, &DocWindow::unCheckAll ); + + // Build the search interface. + + QHBoxLayout *hbox = new QHBoxLayout(); + + QPushButton *backward = new QPushButton(QChar(0x25C0), this); + hbox->addWidget(backward); + connect( backward, &QPushButton::released, this, &DocWindow::findAgainBackward); + + QPushButton *forward = new QPushButton(QChar(0x25B6), this); + hbox->addWidget(forward); + connect( forward, &QPushButton::released, this, &DocWindow::findAgainForward); + + searchLineEdit = new QLineEdit; + searchLineEdit->setPlaceholderText("Search Pattern"); + hbox->addWidget(searchLineEdit); + connect(searchLineEdit, SIGNAL(returnPressed()), this, SLOT(find())); + + QVBoxLayout *vbox = new QVBoxLayout(); + + // Build the Table Widget that displays the variable names, types, and units. + varTable = new VarTableWidget(this); + + int recordCount = datalog->parameterCount(); + for (int ii = 0; ii < recordCount; ii++) { + varTable->addRecord( Qt::Checked, + datalog->parameterName(ii), + datalog->parameterType(ii), + datalog->parameterUnits(ii)); + } + + vbox->addWidget(varTable); + vbox->addLayout(hbox); + + QWidget *window = new QWidget; + window->setLayout(vbox); + + setCentralWidget(window); +} + +void DocWindow::load() { + + QString newFileName; + + newFileName = QFileDialog::getOpenFileName(this, + tr("Open Data File"), ".", tr("Data Files (*.trk)")); + + QFileInfo trkFileInfo( newFileName); + TRK_DataLog* newdatalog = new TRK_DataLog( trkFileInfo.absoluteFilePath().toStdString()); + + if (!newFileName.isEmpty()) { + DocWindow* w = new DocWindow(newdatalog); + w->setWindowTitle(newFileName); + w->resize(800, 500); + w->show(); + } +} + +void DocWindow::formattedSave(LogFormatter &formatter) { + + QFileInfo trkFileInfo( datalog->getFileName().c_str()); + + QString outFileName = trkFileInfo.canonicalPath(); + outFileName += "/"; + outFileName += trkFileInfo.completeBaseName(); + outFileName += formatter.extension(); + + QTextStream out(stdout); + out << "outFileName = \"" << outFileName << "\"" << endl; + + int count = varTable->recordCount(); + for (int index=0 ; indexisChecked(index)) { + datalog->selectParameter(index); + } else { + datalog->deselectParameter(index); + } + } + + FILE *fp; + if (( fp = fopen(outFileName.toStdString().c_str(), "w") ) != NULL) { + datalog->formattedWrite(fp, &formatter); + } +} + +void DocWindow::saveAsCSV() { + CSV_Formatter csv_formatter; + formattedSave(csv_formatter); +} + +void DocWindow::saveAsVarList() { + Varlist_Formatter varlist_formatter; + formattedSave(varlist_formatter); +} + +void DocWindow::checkAll() { + varTable->checkAll(); +} + +void DocWindow::unCheckAll() { + varTable->unCheckAll(); +} + +void DocWindow::findAgain(int direction) { + if (foundItemIndex >= 0) { + varTable->unHighLightRecord(foundItemIndex); + int count = varTable->recordCount(); + int startIndex = (count + foundItemIndex + direction) % count; + if ((foundItemIndex = textSearch(searchPattern, startIndex, direction)) >= 0) { + varTable->scrollToRecord(foundItemIndex); + varTable->highLightRecord(foundItemIndex); + } + } +} + +void DocWindow::findAgainForward() { + findAgain(1); +} + +void DocWindow::findAgainBackward() { + findAgain(-1); +} + +void DocWindow::find() { + searchPattern = searchLineEdit->text(); + + if (foundItemIndex >= 0) { + varTable->unHighLightRecord(foundItemIndex); + } + if ((foundItemIndex = textSearch(searchPattern, 0, 1)) >= 0) { + varTable->scrollToRecord(foundItemIndex); + varTable->highLightRecord(foundItemIndex); + } +} + +int DocWindow::textSearch(QString pattern, int startIndex, int direction) { + + QRegExp rx(pattern); + int count = varTable->recordCount(); + int foundIx = -1; + for (int i=0 ; iparameterName(index),0)) >= 0) { + foundIx = index; + break; + } + } + return foundIx; +} diff --git a/trick_source/data_products/Apps/trkConvert/DocWindow.h b/trick_source/data_products/Apps/trkConvert/DocWindow.h new file mode 100644 index 00000000..33e1692a --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/DocWindow.h @@ -0,0 +1,40 @@ +#ifndef DOC_WINDOW +#define DOC_WINDOW + +#include +#include "VarTableWidget.h" +#include "TRK_DataLog.hh" + +class DocWindow : public QMainWindow { + + Q_OBJECT + + public: + DocWindow(TRK_DataLog* data_log ); + ~DocWindow(){}; + + void formattedSave(LogFormatter &formatter); + void textSearch(); + int textSearch(QString searchText, int startIndex, int direction); + void findAgain(int direction); + + private slots: + void load(); + void saveAsCSV(); + void saveAsVarList(); + void checkAll(); + void unCheckAll(); + void find(); + + void findAgainForward(); + void findAgainBackward(); + + private: + int foundItemIndex; + QString searchPattern; + QLineEdit* searchLineEdit; + VarTableWidget* varTable; + TRK_DataLog* datalog; +}; + +#endif diff --git a/trick_source/data_products/Apps/trkConvert/ParamDescription.cpp b/trick_source/data_products/Apps/trkConvert/ParamDescription.cpp new file mode 100644 index 00000000..2b2d7871 --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/ParamDescription.cpp @@ -0,0 +1,32 @@ +#include +#include +#include "ParamDescription.hh" + +ParamDescription::ParamDescription(FILE* in_fp) { + + int32_t nameStringLength; + if ( fread( &nameStringLength, 1, 4, in_fp) != 4) + throw std::runtime_error("fread() failed."); + + parameterName = new char[nameStringLength+1]; + if ( fread( parameterName, 1, nameStringLength, in_fp) != (size_t)nameStringLength) + throw std::runtime_error("fread() failed."); + + parameterName[nameStringLength] = 0; + + int32_t unitsStringLength; + if ( fread( &unitsStringLength, 1, 4 , in_fp) != 4) + throw std::runtime_error("fread() failed."); + + unitsName = new char[unitsStringLength+1]; + if ( fread( unitsName, 1, unitsStringLength, in_fp) != (size_t)unitsStringLength) + throw std::runtime_error("fread() failed."); + + unitsName[unitsStringLength] = 0; + + if ( fread( &dataType, 1, 4, in_fp) != 4) + throw std::runtime_error("fread() failed."); + + if ( fread( &dataSize, 1, 4, in_fp) != 4) + throw std::runtime_error("fread() failed."); +} diff --git a/trick_source/data_products/Apps/trkConvert/ParamDescription.hh b/trick_source/data_products/Apps/trkConvert/ParamDescription.hh new file mode 100644 index 00000000..beb312d7 --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/ParamDescription.hh @@ -0,0 +1,16 @@ +#ifndef PARAM_DESCRIPTION_H +#define PARAM_DESCRIPTION_H + +#include + +struct ParamDescription { + + char* parameterName; + char* unitsName; + int32_t dataType; + int32_t dataSize; + + ParamDescription(){} + ParamDescription(FILE* fp); +}; +#endif diff --git a/trick_source/data_products/Apps/trkConvert/README.md b/trick_source/data_products/Apps/trkConvert/README.md new file mode 100644 index 00000000..ba4df3ef --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/README.md @@ -0,0 +1,49 @@ +# trkConvert + +Convert selected sets of variables in Trick binary data recording files (.trk) to comma separated values (.csv). In the future, more formats may be added as needed. + +## Building trkConvert + +trkConvert requires the [Qt Application Framework](https://www.qt.io). + +When Qt is installed, building the application is as simple as: + +``` +% qmake +% make +% cp trkConvert $TRICK_HOME/bin/trkConvert +``` + +## Running trkConvert + +**% trkConvert [name.trk] &** + +``` +% trkConvert & +``` + +![fileSelectDialog](images/fileSelectDialog.png) + +``` +% trkConvert log_helios.trk & +``` +The resulting window displays the names, data types and units of the variables recorded in the .trk file. The check marks, to the left indicate which variables would be recorded in an exported format. + +![x](images/DocWindow.png) +The check boxes can be individually selected and cleared with a mouse-click. +They can be collectively selected and cleared from the Edit menu. + +![x](images/DocWindow2.png) + +## Variable Search + +Python-like regular expressions +A search pattern is Python-like regular expression that matches any part of a variable name. To search, type the pattern, and press **Return** or **Enter**. + +Subsequent searches for the pattern can be performed using the arrow buttons. + +* Right arror searches forward +* Left arrow searches backward. + +## Exporting Selected Values +Export selected values to CSV, or other format from the **File** menu. \ No newline at end of file diff --git a/trick_source/data_products/Apps/trkConvert/trkConvert.cpp b/trick_source/data_products/Apps/trkConvert/TRK_DataLog.cpp similarity index 51% rename from trick_source/data_products/Apps/trkConvert/trkConvert.cpp rename to trick_source/data_products/Apps/trkConvert/TRK_DataLog.cpp index e8b193e2..5fcb359f 100644 --- a/trick_source/data_products/Apps/trkConvert/trkConvert.cpp +++ b/trick_source/data_products/Apps/trkConvert/TRK_DataLog.cpp @@ -1,16 +1,9 @@ -#include -#include -#include // Requires C99 -#include +#include "TRK_DataLog.hh" #include -#include -#include -#include +#include #include - -#include "LogFormatter.hh" -#include "CSV_Formatter.hh" -#include "Varlist_Formatter.hh" +#include +#include typedef enum { TRICK_VOID = 0, /* No type */ @@ -41,83 +34,38 @@ typedef enum { TRICK_NUMBER_OF_TYPES } TRICK_TYPE ; -class ReadException: public std::exception { - virtual const char* what() const throw() { - return "fread() failed."; - } -} readException; - -/* ================================================================================ - * CLASS: ParamDescription - * ================================================================================ - */ -class ParamDescription { - public: - char* parameterName; - char* unitsName; - int32_t dataType; - int32_t dataSize; - - ParamDescription(){} - ParamDescription(FILE* fp); +const char* TypeName[] = { + "--0--", + "char", + "unsigned char", + "--3--", + "short", + "unsigned short", + "int", + "unsigned int", + "long", + "unsigned long", + "float", + "double", + "--12--", + "--13--", + "long long", + "unsigned long long", + "--16--", + "bool", + "--18--", + "--19--", + "--20--", + "--21--", + "--22--", + "--23--", + "--24--" }; -ParamDescription::ParamDescription(FILE* in_fp){ +const int TRK_DataLog::LittleEndian = 1; +const int TRK_DataLog::BigEndian = 2; - int32_t nameStringLength; - if ( fread( &nameStringLength, 1, 4, in_fp) != 4) throw readException; - - parameterName = new char[nameStringLength+1]; - if ( fread( parameterName, 1, nameStringLength, in_fp) != (size_t)nameStringLength) throw readException; - parameterName[nameStringLength] = 0; - - int32_t unitsStringLength; - if ( fread( &unitsStringLength, 1, 4 , in_fp) != 4) throw readException; - - unitsName = new char[unitsStringLength+1]; - if ( fread( unitsName, 1, unitsStringLength, in_fp) != (size_t)unitsStringLength) throw readException; - unitsName[unitsStringLength] = 0; - - if ( fread( &dataType, 1, 4, in_fp) != 4) throw readException; - if ( fread( &dataSize, 1, 4, in_fp) != 4) throw readException; -} - -/* ================================================================================ - * CLASS: DataLog - * ================================================================================ - */ -class DataLog { - - public: - std::string fileName; - FILE* in_fp; - int version; - int endianness; - uint32_t N_params; - fpos_t dataPosition; - int dataRecordSize; - char* dataRecord; - - static const int LittleEndian; - static const int BigEndian; - - std::vector paramDescriptions; - std::vector paramOffsets; - std::vector paramSelected; - - DataLog(){} - DataLog(std::string fileName); - void selectAllParameters(); - void selectParameter(unsigned int index); - void selectParameter(const char * paramName); - void deselectParameter(unsigned int index); - void formattedWrite(FILE* out_fp, LogFormatter* formatter); -}; - -const int DataLog::LittleEndian = 1; -const int DataLog::BigEndian = 2; - -DataLog::DataLog(std::string file_name) { +TRK_DataLog::TRK_DataLog(std::string file_name) { fileName = file_name; in_fp = fopen(fileName.c_str(), "rb"); @@ -125,7 +73,8 @@ DataLog::DataLog(std::string file_name) { if (in_fp != NULL) { char trick_header_string[11]; - if (fread( trick_header_string, 1, 10, in_fp) != 10) throw readException; + if (fread( trick_header_string, 1, 10, in_fp) != 10) + throw std::runtime_error("fread() failed."); trick_header_string[10] = 0; if (!strncmp( trick_header_string, "Trick-", 6)) { @@ -147,7 +96,8 @@ DataLog::DataLog(std::string file_name) { fprintf (stderr, "Trick header error. Endianness should be \"L\" or \"B\"."); } - if (fread( &N_params, 1, 4, in_fp) != 4) throw readException; + if (fread( &N_params, 1, 4, in_fp) != 4) + throw std::runtime_error("fread() failed."); dataRecordSize = 0; for (int ii = 0 ; ii < (int)N_params ; ii++ ) { @@ -174,19 +124,49 @@ DataLog::DataLog(std::string file_name) { } } -void DataLog::selectAllParameters() { +std::string TRK_DataLog::getFileName() const { + return fileName; +} + +int TRK_DataLog::parameterCount() const { + return (int)N_params; +} + +const char* TRK_DataLog::parameterName(unsigned int n) const { + if (n < N_params) + return paramDescriptions[n]->parameterName; + else + return "BadIndex"; +} + +const char* TRK_DataLog::parameterUnits(unsigned int n) const { + if (n < N_params) + return paramDescriptions[n]->unitsName; + else + return "BadIndex"; +} + +const char* TRK_DataLog::parameterType(unsigned int n) const { + if (n < N_params) + return TypeName[ paramDescriptions[n]->dataType ]; + else + return "BadIndex"; +} + + +void TRK_DataLog::selectAllParameters() { for (int ii = 1 ; ii < (int)N_params ; ii++ ) { paramSelected[ii] = true; } } -void DataLog::selectParameter(unsigned int index) { +void TRK_DataLog::selectParameter(unsigned int index) { if ((index > 0) && (index < N_params)) { paramSelected[index] = true; } } -void DataLog::selectParameter(const char * paramName) { +void TRK_DataLog::selectParameter(const char * paramName) { bool found = false; int ii = 1; while ((ii < (int)N_params) && (found == false)) { @@ -198,20 +178,21 @@ void DataLog::selectParameter(const char * paramName) { } } -void DataLog::deselectParameter(unsigned int index) { +void TRK_DataLog::deselectParameter(unsigned int index) { if ((index > 0) && (index < N_params)) { paramSelected[index] = false; } } -void DataLog::formattedWrite(FILE* out_fp, LogFormatter* formatter) { +void TRK_DataLog::formattedWrite(FILE* out_fp, LogFormatter* formatter) { formatter->writeHeader(out_fp, version, endianness); formatter->writeColumnLabel(out_fp, paramDescriptions[0]->parameterName, paramDescriptions[0]->unitsName); for (int ii = 1; ii < (int)N_params ; ii++) { - if (paramSelected[ii]) + if (paramSelected[ii]) { formatter->writeColumnLabelSeparator(out_fp); formatter->writeColumnLabel(out_fp, paramDescriptions[ii]->parameterName, paramDescriptions[ii]->unitsName); + } } if ( fsetpos(in_fp, &dataPosition) != 0 ) { @@ -276,120 +257,3 @@ void DataLog::formattedWrite(FILE* out_fp, LogFormatter* formatter) { } formatter->writeRecordSeparator(out_fp); } - -static const char *usage_doc[] = { -"----------------------------------------------------------------------------", -" trkConvert - ", -" ", -" USAGE: trkConvert -help ", -" trkConvert [-csv|-varlist] [-o ] ", -" Options: ", -" -help Print this message and exit. ", -" -csv (the default) Generates a comma-separated value (CSV) file from ", -" a Trick binary data file. CSV files are a common ", -" means of sharing data between applications. ", -" -varlist Generates a list of the names of the variables ", -" the are recorded in the Trick binary data file. ", -"----------------------------------------------------------------------------"}; -#define N_USAGE_LINES (sizeof(usage_doc)/sizeof(usage_doc[0])) - -void print_doc(char *doc[], int nlines) { - int i; - for (i=0; i < nlines; i++) { - std::cerr << doc[i] << '\n'; - } - std::cerr.flush(); -} - -void usage() { - print_doc((char **)usage_doc,N_USAGE_LINES); -} - -int main(int argc, char* argv[]) { - - std::string programName = argv[0]; - std::string trkFilePath; - std::string trkBaseName; - std::string outputName; - FILE *fp; - - CSV_Formatter csv_formatter; - LogFormatter* logFormatter = &csv_formatter; // default formatter. - Varlist_Formatter varlist_formatter; - - if (argc <= 1 ) { - std::cerr << programName << ": No arguments were supplied.\n"; - std::cerr.flush(); - usage(); - exit(1); - } else { - int i = 1; - std::string arg; - while ( i < argc ) { - arg = argv[i]; - - if (arg.find("-") == 0) { - if (arg == "-help" | arg == "--help" ) { - usage(); - exit(0); - } else if (arg == "-csv") { - logFormatter = &csv_formatter; - } else if (arg == "-varlist") { - logFormatter = &varlist_formatter; - } else if (arg == "-o") { - i++; - if (iextension(); - } - - std::cout << programName << ": Input = \"" << trkFilePath << "\"." << std::endl; - std::cout << programName << ": Output = \"" << outputName << "\"." << std::endl; - - DataLog* datalog = new DataLog(trkFilePath); - datalog->selectAllParameters(); - - if (( fp = fopen(outputName.c_str(), "w") ) != NULL) { - datalog->formattedWrite(fp, logFormatter); - return 0; - } - return 1; -} diff --git a/trick_source/data_products/Apps/trkConvert/TRK_DataLog.hh b/trick_source/data_products/Apps/trkConvert/TRK_DataLog.hh new file mode 100644 index 00000000..25448e6a --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/TRK_DataLog.hh @@ -0,0 +1,49 @@ +#ifndef TRK_DATA_LOG_HH +#define TRK_DATA_LOG_HH + +#include // FILE +#include // Requires C99 + +#include +#include + +#include "LogFormatter.hh" +#include "ParamDescription.hh" + +class TRK_DataLog { + + public: + static const int LittleEndian; + static const int BigEndian; + + std::vector paramDescriptions; + std::vector paramOffsets; + std::vector paramSelected; + + // Constructors + TRK_DataLog(){} + TRK_DataLog(std::string fileName); + + std::string getFileName() const; + int parameterCount() const; + const char* parameterName(unsigned int n) const; + const char* parameterUnits(unsigned int n) const; + const char* parameterType(unsigned int n) const; + + void selectAllParameters(); + void selectParameter(unsigned int index); + void selectParameter(const char * paramName); + void deselectParameter(unsigned int index); + void formattedWrite(FILE* out_fp, LogFormatter* formatter); + + private: + std::string fileName; + FILE* in_fp; + int version; + int endianness; + uint32_t N_params; + fpos_t dataPosition; + int dataRecordSize; + char* dataRecord; +}; +#endif diff --git a/trick_source/data_products/Apps/trkConvert/VarTableWidget.cpp b/trick_source/data_products/Apps/trkConvert/VarTableWidget.cpp new file mode 100644 index 00000000..60b5de81 --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/VarTableWidget.cpp @@ -0,0 +1,104 @@ +#include +#include "VarTableWidget.h" + +VarTableWidget::VarTableWidget (QWidget* parent) + : QTableWidget(parent) { + + setRowCount(0); + setColumnCount(4); + + QStringList strList; + strList << "" << "Name" << "Type" << "Units"; + setHorizontalHeaderLabels( strList); + + setColumnWidth(0,25); + setColumnWidth(1,200); + setColumnWidth(2,80); + setColumnWidth(3,80); + + setShowGrid(false); +} + +void VarTableWidget::addRecord( Qt::CheckState checkState, + std::string nameStr, + std::string typeStr, + std::string unitsStr ) { + +// Consider cloning prototype items, as in this example: +// https://stackoverflow.com/questions/15827886/set-default-alignment-for-cells-in-qtablewidget + + int row = rowCount(); + insertRow(row); + + Qt::ItemFlags flags; + + QTableWidgetItem * const selectItem = new QTableWidgetItem; + flags = selectItem->flags(); + flags &= ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable; + if (row != 0) // FIXME: This doesn't seem to work as expected. Row 0 still seems to be user editable. + flags |= Qt::ItemIsUserCheckable; + selectItem->setFlags(flags); + selectItem->setCheckState(checkState); + setItem(row, 0, selectItem); + + QTableWidgetItem * const nameItem = new QTableWidgetItem; + flags = nameItem->flags(); + flags &= ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable; + nameItem->setFlags(flags); + nameItem->setText(nameStr.c_str()); + setItem(row, 1, nameItem); + + QTableWidgetItem * const typeItem = new QTableWidgetItem; + flags = typeItem->flags(); + flags &= ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable; + typeItem->setFlags(flags); + typeItem->setTextAlignment(Qt::AlignCenter); + typeItem->setText(typeStr.c_str()); + setItem(row, 2, typeItem); + + QTableWidgetItem * const unitsItem = new QTableWidgetItem; + flags = unitsItem->flags(); + flags &= ~Qt::ItemIsSelectable & ~Qt::ItemIsEditable; + unitsItem->setFlags(flags); + unitsItem->setTextAlignment(Qt::AlignCenter); + unitsItem->setText(unitsStr.c_str()); + setItem(row, 3, unitsItem); + +} + +void VarTableWidget::highLightRecord(int index) { + QBrush brush(Qt::yellow); + item(index, 1)->setBackground(brush); +} + +void VarTableWidget::unHighLightRecord(int index) { + QBrush brush(Qt::white); + item(index, 1)->setBackground(brush); +} + +void VarTableWidget::scrollToRecord(int index) { + scrollToItem(item(index, 0)); +} + +bool VarTableWidget::isChecked(int index) { + return (item(index, 0)->checkState() == Qt::Checked) ? true : false; +} + +int VarTableWidget::recordCount() { + return rowCount(); +} + +void VarTableWidget::checkAll() { + int num_rows = rowCount(); + for (int i=0; isetCheckState(Qt::Checked); + } +} + +void VarTableWidget::unCheckAll() { + int num_rows = rowCount(); + // Note that we don't clear sys.exec.out.time + for (int i=1; isetCheckState(Qt::Unchecked); + } +} diff --git a/trick_source/data_products/Apps/trkConvert/VarTableWidget.h b/trick_source/data_products/Apps/trkConvert/VarTableWidget.h new file mode 100644 index 00000000..d0c07d88 --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/VarTableWidget.h @@ -0,0 +1,25 @@ +#ifndef VARIABLE_TABLE_WIDGET_H +#define VARIABLE_TABLE_WIDGET_H + +#include +#include // widgets + +class VarTableWidget : public QTableWidget { + Q_OBJECT + + public: + // Constructors + VarTableWidget(QWidget* parent = 0); + + void addRecord( Qt::CheckState checkState, std::string name, std::string type, std::string units ); + bool isChecked(int index); + int recordCount(); + void scrollToRecord(int index); + void highLightRecord(int index); + void unHighLightRecord(int index); + + public slots: + void checkAll(); + void unCheckAll(); +}; +#endif diff --git a/trick_source/data_products/Apps/trkConvert/images/DocWindow.png b/trick_source/data_products/Apps/trkConvert/images/DocWindow.png new file mode 100644 index 00000000..e215b8d2 Binary files /dev/null and b/trick_source/data_products/Apps/trkConvert/images/DocWindow.png differ diff --git a/trick_source/data_products/Apps/trkConvert/images/DocWindow2.png b/trick_source/data_products/Apps/trkConvert/images/DocWindow2.png new file mode 100644 index 00000000..3a9611a5 Binary files /dev/null and b/trick_source/data_products/Apps/trkConvert/images/DocWindow2.png differ diff --git a/trick_source/data_products/Apps/trkConvert/images/fileSelectDialog.png b/trick_source/data_products/Apps/trkConvert/images/fileSelectDialog.png new file mode 100644 index 00000000..99cd5eee Binary files /dev/null and b/trick_source/data_products/Apps/trkConvert/images/fileSelectDialog.png differ diff --git a/trick_source/data_products/Apps/trkConvert/main.cpp b/trick_source/data_products/Apps/trkConvert/main.cpp new file mode 100644 index 00000000..92279cbd --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/main.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include +#include "DocWindow.h" +#include +#include + +#include +static const char *usage_doc[] = { +"----------------------------------------------------------------------------", +" trkConvert - ", +" ", +" USAGE: trkConvert -help ", +" trkConvert ", +" Options: ", +" -help Print this message and exit. ", +"----------------------------------------------------------------------------"}; +#define N_USAGE_LINES (sizeof(usage_doc)/sizeof(usage_doc[0])) + +void print_doc(char *doc[], int nlines) { + int i; + for (i=0; i < nlines; i++) { + printf("%s\n",doc[i]); + } + fflush(stdout); +} + +void usage() { + print_doc((char **)usage_doc,N_USAGE_LINES); +} + +int main(int argc, char *argv[]) { + + QTextStream out(stdout); + + QApplication app(argc, argv); + + QStringList args = app.arguments(); + + QString programName = args.at(0); + QString trkFilePath; + QString outputName; + + int i = 1; + QString arg; + while (i < argc) { + arg = args.at(i); + if ( (QString::compare(arg, "-help") == 0) | + (QString::compare(arg, "--help") == 0) ) { + usage(); + exit(0); + } else if ((QString::compare(arg.right(4), ".trk") == 0)) { + trkFilePath = arg; + } else { + out << programName << ": Invalid argument \"" << arg << "\"." << endl; + usage(); + exit(1); + } + i++; + } + + if (trkFilePath.isEmpty()) { + trkFilePath = QFileDialog::getOpenFileName(0, "Open Data File", ".", "Data Files (*.trk)"); + } + + if (!trkFilePath.isEmpty()) { + QFileInfo trkFileInfo( trkFilePath); + + TRK_DataLog* datalog = + new TRK_DataLog( trkFileInfo.absoluteFilePath().toStdString().c_str() ); + + DocWindow* w1 = new DocWindow(datalog); + w1->setWindowTitle( trkFileInfo.fileName()); + w1->resize(800, 500); + w1->show(); + + return app.exec(); + } +} diff --git a/trick_source/data_products/Apps/trkConvert/makefile b/trick_source/data_products/Apps/trkConvert/makefile deleted file mode 100644 index ff1180c1..00000000 --- a/trick_source/data_products/Apps/trkConvert/makefile +++ /dev/null @@ -1,26 +0,0 @@ -CPP = g++ -CC = gcc - -CXXFLAGS = - -MAIN = trkConvert - -OBJECTS = CSV_Formatter.o Varlist_Formatter.o trkConvert.o - -.c.o: - ${CC} ${CFLAGS} ${INCDIRS} -c $< - -.cpp.o: - ${CPP} ${CFLAGS} ${INCDIRS} -c $< - -all: install - -trkConvert: $(OBJECTS) - $(CPP) -o trkConvert $(OBJECTS) - -install: trkConvert - cp trkConvert $${TRICK_HOME}/bin/trick-trkConvert - -clean: - rm -f *.o - rm -f trkConvert diff --git a/trick_source/data_products/Apps/trkConvert/trkConvert.pro b/trick_source/data_products/Apps/trkConvert/trkConvert.pro new file mode 100644 index 00000000..ee14bfcc --- /dev/null +++ b/trick_source/data_products/Apps/trkConvert/trkConvert.pro @@ -0,0 +1,39 @@ +###################################################################### +# Automatically generated by qmake (3.1) Wed Jun 27 14:55:58 2018 +###################################################################### + +TEMPLATE = app +TARGET = trkConvert +INCLUDEPATH += . + +# The following define makes your compiler warn you if you use any +# feature of Qt which has been marked as deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if you use deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +# Input +HEADERS += CSV_Formatter.hh \ + DocWindow.h \ + LogFormatter.hh \ + ParamDescription.hh \ + TRK_DataLog.hh \ + Varlist_Formatter.hh \ + VarTableWidget.h +SOURCES += CSV_Formatter.cpp \ + DocWindow.cpp \ + main.cpp \ + ParamDescription.cpp \ + TRK_DataLog.cpp \ + Varlist_Formatter.cpp \ + VarTableWidget.cpp + +QT += widgets + +# Inhibit creation of an Mac OS X App bundle. +CONFIG -= app_bundle diff --git a/trick_source/data_products/DPX/APPS/GXPLOT/gp_utilities.cpp b/trick_source/data_products/DPX/APPS/GXPLOT/gp_utilities.cpp index b6a7a065..2672115d 100644 --- a/trick_source/data_products/DPX/APPS/GXPLOT/gp_utilities.cpp +++ b/trick_source/data_products/DPX/APPS/GXPLOT/gp_utilities.cpp @@ -57,7 +57,7 @@ int filterPostScriptColor( const char *psName, GPViewPageNode* gp_view_page_node string next_lt ; string new_buf_ptr ; string line_color ; - int red , blue , green ; + unsigned int red , blue , green ; int number_of_plots = (int)gp_view_page_node->plot_node_list.size(); //! Populate buf with file content. diff --git a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_curve_node.cpp b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_curve_node.cpp index 91521f85..f15cc6d2 100644 --- a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_curve_node.cpp +++ b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_curve_node.cpp @@ -42,7 +42,6 @@ GPViewCurveNode::GPViewCurveNode( Widget Toplevel, std::string curve_symbol_style; std::string curve_symbol_size; std::string tmp_string; - std::stringstream tmp_stream; toplevel = Toplevel; dpc_curve = Curve; diff --git a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_plot_node.cpp b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_plot_node.cpp index 2ab89e8b..5a84d332 100644 --- a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_plot_node.cpp +++ b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_plot_node.cpp @@ -95,7 +95,6 @@ void GPViewPlotNode::finalize() { std::string plot_data_src_label; std::string plot_title; std::string plot_x_label; - std::string plot_x_units; std::string plot_x_scale; std::string plot_x_min_rng; std::string plot_x_max_rng; diff --git a/trick_source/data_products/makefile b/trick_source/data_products/makefile index 85b39c45..f9514b33 100644 --- a/trick_source/data_products/makefile +++ b/trick_source/data_products/makefile @@ -18,7 +18,6 @@ LIBDIRS += fermi-ware endif APPDIRS = DPX \ - Apps/trkConvert \ Apps/Trk2csv \ Apps/ExternalPrograms diff --git a/trick_source/java/src/trick/common/TrickApplication.java b/trick_source/java/src/trick/common/TrickApplication.java index e5696a7e..6a83affc 100644 --- a/trick_source/java/src/trick/common/TrickApplication.java +++ b/trick_source/java/src/trick/common/TrickApplication.java @@ -251,7 +251,7 @@ public abstract class TrickApplication extends SingleFrameApplication implements @Override public Object getSessionState(Component component) { if (component instanceof JToggleButton) { - return new Boolean(((JToggleButton)component).isSelected()); + return ((JToggleButton) component).isSelected(); } return null; } @@ -362,10 +362,9 @@ public abstract class TrickApplication extends SingleFrameApplication implements */ @Override protected void startup() { - // Add this exit listener if the sub class likes the confirmation dialog - String defaultValue = Boolean.toString(true); - boolean savedExitProperty = new Boolean(trickProperties.getProperty( - "confirmExit", defaultValue)).booleanValue(); + String defaultValue = Boolean.toString(false); + boolean savedExitProperty = Boolean.valueOf(trickProperties.getProperty( + "confirmExit", defaultValue)); if (( savedExitProperty == true ) && (getExitListeners().length==0)) { // initialize gets called again if you reconnect, so don't add another exitlistener addExitListener(exitListener); diff --git a/trick_source/java/src/trick/common/ui/UIUtils.java b/trick_source/java/src/trick/common/ui/UIUtils.java index 4dbeed51..95c4827e 100644 --- a/trick_source/java/src/trick/common/ui/UIUtils.java +++ b/trick_source/java/src/trick/common/ui/UIUtils.java @@ -284,7 +284,7 @@ public class UIUtils { public static boolean isRightMouseClick(MouseEvent e) { boolean rval = false; - if( (e.getModifiers()&MouseEvent.BUTTON3_MASK)==MouseEvent.BUTTON3_MASK ) { + if( (e.getModifiersEx()&MouseEvent.BUTTON3_DOWN_MASK)==MouseEvent.BUTTON3_DOWN_MASK ) { rval = true; } diff --git a/trick_source/java/src/trick/common/ui/components/FontChooser.java b/trick_source/java/src/trick/common/ui/components/FontChooser.java index d895d509..fdc7eff8 100644 --- a/trick_source/java/src/trick/common/ui/components/FontChooser.java +++ b/trick_source/java/src/trick/common/ui/components/FontChooser.java @@ -108,7 +108,7 @@ public class FontChooser extends JDialog implements ActionListener, ListSelectio currentFont = font; if (font != null) { fontList.setSelectedValue(font.getName(), true); - sizeList.setSelectedValue(new Integer(font.getSize()), true); + sizeList.setSelectedValue(font.getSize(), true); if (font.getStyle() == Font.PLAIN) { boldBox.setSelected(false); italicBox.setSelected(false); diff --git a/trick_source/java/src/trick/common/utils/DataReader.java b/trick_source/java/src/trick/common/utils/DataReader.java index be0f3096..37d8a0b7 100644 --- a/trick_source/java/src/trick/common/utils/DataReader.java +++ b/trick_source/java/src/trick/common/utils/DataReader.java @@ -323,7 +323,8 @@ public abstract class DataReader { varData = varData + theVar.getBias().doubleValue(); } - if (theVar.getUnits() != null) { + String theUnits = theVar.getUnits(); + if ((theUnits != null) && (theUnits != "")) { varData = convertUnits(varData, getLogVar(theVar.getName()), theVar); } diff --git a/trick_source/java/src/trick/dataproducts/plot/JXPlotApplication.java b/trick_source/java/src/trick/dataproducts/plot/JXPlotApplication.java index d123845a..3abfa78c 100644 --- a/trick_source/java/src/trick/dataproducts/plot/JXPlotApplication.java +++ b/trick_source/java/src/trick/dataproducts/plot/JXPlotApplication.java @@ -40,12 +40,14 @@ import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.xml.sax.SAXException; -import com.lowagie.text.Document; -import com.lowagie.text.DocumentException; -import com.lowagie.text.PageSize; -import com.lowagie.text.pdf.DefaultFontMapper; -import com.lowagie.text.pdf.PdfContentByte; -import com.lowagie.text.pdf.PdfWriter; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDPageContentStream; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.font.PDFont; +import org.apache.pdfbox.pdmodel.font.PDType1Font; +import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import trick.common.TrickApplication; import trick.common.ui.UIUtils; @@ -115,17 +117,7 @@ public class JXPlotApplication extends TrickApplication { try { int dpFileCount = productTreeRoot.getChildCount(); if (dpFileCount > 0) { - Document document = new Document(PageSize.A4); - PdfWriter writer = null; - PdfContentByte pdfContent = null; - try { - writer = PdfWriter.getInstance(document, new FileOutputStream(file)); - document.open(); - // this object can be reused which is used to write each page to the same PDF file - pdfContent = writer.getDirectContent(); - } catch (DocumentException e) { - e.printStackTrace(); - } + PDDocument document = new PDDocument(); for (int i = 0; i < dpFileCount; i++) { DefaultMutableTreeNode eachDPFile = (DefaultMutableTreeNode)productTree.getModel().getChild(productTreeRoot, i); int pageCount = eachDPFile.getChildCount(); @@ -133,14 +125,12 @@ public class JXPlotApplication extends TrickApplication { DefaultMutableTreeNode eachPage = (DefaultMutableTreeNode)productTree.getModel().getChild(eachDPFile, j); if (eachPage.getUserObject() instanceof TrickChartFrame) { TrickChartFrame theFrame = (TrickChartFrame)eachPage.getUserObject(); - theFrame.writePDFPage(pdfContent, new DefaultFontMapper()); + theFrame.writePDFPage(document); } } } // document needs to be closed after the PDF file is saved - if (document != null) { - document.close(); - } + document.save(file); } } catch (IOException e) { e.printStackTrace(); diff --git a/trick_source/java/src/trick/dataproducts/plot/utils/TrickChartFrame.java b/trick_source/java/src/trick/dataproducts/plot/utils/TrickChartFrame.java index d4a47409..b82a93b7 100644 --- a/trick_source/java/src/trick/dataproducts/plot/utils/TrickChartFrame.java +++ b/trick_source/java/src/trick/dataproducts/plot/utils/TrickChartFrame.java @@ -8,6 +8,7 @@ import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -21,15 +22,16 @@ import javax.swing.JSeparator; import org.jfree.chart.ChartPanel; -import com.lowagie.text.Document; -import com.lowagie.text.DocumentException; -import com.lowagie.text.PageSize; -import com.lowagie.text.pdf.BaseFont; -import com.lowagie.text.pdf.DefaultFontMapper; -import com.lowagie.text.pdf.FontMapper; -import com.lowagie.text.pdf.PdfContentByte; -import com.lowagie.text.pdf.PdfTemplate; -import com.lowagie.text.pdf.PdfWriter; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.PDPageContentStream; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.font.PDFont; +import org.apache.pdfbox.pdmodel.font.PDType1Font; +import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; +import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; + +import org.jfree.chart.JFreeChart; import trick.common.TrickApplication; import trick.common.ui.UIUtils; @@ -38,7 +40,7 @@ import trick.dataproducts.trickqp.utils.ProductPage; public class TrickChartFrame extends TrickFrame { - //======================================== + //======================================== // Public data //======================================== @@ -95,7 +97,7 @@ public class TrickChartFrame extends TrickFrame { } - //======================================== + //======================================== // Methods //======================================== /** @@ -179,100 +181,89 @@ public class TrickChartFrame extends TrickFrame { */ public void saveChartsAsPDF() throws IOException { File file = UIUtils.chooseSaveFile(null, "plot_", "pdf", this); - if (file == null) { - return; - } - Document document = new Document(PageSize.A4); - PdfWriter writer = null; - PdfContentByte pdfContent = null; - try { - writer = PdfWriter.getInstance(document, new FileOutputStream(file)); - document.open(); - pdfContent = writer.getDirectContent(); - } catch (DocumentException e) { - e.printStackTrace(); - } - writePDFPage(pdfContent, new DefaultFontMapper()); - - if (document != null) { - document.close(); - } + if (file != null) { + PDDocument document = new PDDocument(); // Default Paper size is US Letter. + writePDFPage(document); + document.save(file); } + } /** * Writes all plots shown to one page of PDF. * - * @param pdfContent an object containing the user positioned text and graphic contents of a page. - * @param mapper mapping between AWT fonts and PDF fonts. + * @param doc An Apache-PDFBox PDDocument object. * @throws IOException IOException */ - public void writePDFPage(PdfContentByte pdfContent, FontMapper mapper) throws IOException { - if (pdfContent == null) { - return; - } - Document document = pdfContent.getPdfDocument(); - int chartLocOffset = 30; - try { - int pageWidth = (int)document.getPageSize().getWidth(); - int pageHeight = (int)document.getPageSize().getHeight(); - document.newPage(); + public void writePDFPage(PDDocument doc) throws IOException { + + PDPage pdfPage = new PDPage(); // Default page size is 'US Letter' (8.5x11 inches). - BaseFont pageTitleFont = BaseFont.createFont(BaseFont.HELVETICA_BOLD, "Cp1252", false); + // This is the size of the page in PDF 'points'. One point = 1/72 inch. + PDRectangle mediaBox = pdfPage.getMediaBox(); + + float inches = 72F; // Conversion from inches to points. - // show page title text - pdfContent.beginText(); - pdfContent.setFontAndSize(pageTitleFont, 12); - pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, getChartTitle(), pageWidth / 2 , pageHeight - chartLocOffset / 2, 0); - pdfContent.endText(); + float topMargin = 0.5F * inches; + float bottomMargin = 0.75F * inches; + float leftMargin = 0.75F * inches; + float rightMargin = 0.5F * inches; - // draw all plots - PdfTemplate pdfTemplate = pdfContent.createTemplate(pageWidth, pageHeight); - Graphics2D g2 = pdfTemplate.createGraphics(pageWidth, pageHeight, mapper); - int rows = 1; - int columns = 1; - - if (getContentPane().getLayout() instanceof GridLayout) { - rows = ((GridLayout)getContentPane().getLayout()).getRows(); - columns = ((GridLayout)getContentPane().getLayout()).getColumns(); - } - - int eachChartWidth = pageWidth; - int eachChartHeight = pageHeight - chartLocOffset; - if (columns != 0) { - eachChartWidth = pageWidth / columns; - } - if (rows != 0) { - eachChartHeight = (pageHeight - chartLocOffset) / rows; - } - - int xLoc = 0; - int yLoc = chartLocOffset; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - int index = i * columns + j; - if (index >= getChartSize()) { - break; - } - TrickChartControlPanel eachPanel = (TrickChartControlPanel)getContentPane().getComponent(index); - if (eachPanel.getTheChart() != null) { - Rectangle2D r2D = new Rectangle2D.Double(xLoc, yLoc, eachChartWidth, eachChartHeight); - eachPanel.getTheChart().draw(g2, r2D); - } - xLoc = xLoc + eachChartWidth; - } - xLoc = 0; - yLoc = yLoc + eachChartHeight; - - } - g2.dispose(); - pdfContent.addTemplate(pdfTemplate, 0, 0); - } - catch (DocumentException de) { - de.printStackTrace(); - } + doc.addPage(pdfPage); + + try (PDPageContentStream content = new PDPageContentStream(doc, pdfPage)) { + + int fontSize = 12; + PDFont font = PDType1Font.TIMES_ROMAN; + + String chartTitle = getChartTitle(); + float chartTitleWidth = font.getStringWidth(chartTitle) / 1000F * fontSize; + float chartTitleHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000F * fontSize; + float chartTitleLowerLeftX = (mediaBox.getWidth() + leftMargin - rightMargin - chartTitleWidth) / 2F ; + float chartTitleLowerLeftY = mediaBox.getHeight() - topMargin - chartTitleHeight; + + content.beginText(); + content.setFont(font, fontSize); + content.newLineAtOffset(chartTitleLowerLeftX, chartTitleLowerLeftY); + content.showText(chartTitle); + content.endText(); + + // Define the box into which the chart(s) will go. + // The top of the box is 1/2 inch below the top margin. + // The rest is bounded by the left, right and bottom margins. + float chartBoxLowerLeftX = leftMargin; + float chartBoxLowerLeftY = bottomMargin; + float chartBoxUpperRightX = mediaBox.getUpperRightX() - rightMargin; + float chartBoxUpperRightY = mediaBox.getUpperRightY() - topMargin - 0.5F * inches; + float chartBoxWidth = chartBoxUpperRightX - chartBoxLowerLeftX; + float chartBoxHeight = chartBoxUpperRightY - chartBoxLowerLeftY; + + int rows = 1; int cols = 1; // If we're plotting one plot on this page, otherwise ... + if ( getContentPane().getLayout() instanceof GridLayout) { + rows = ((GridLayout)getContentPane().getLayout()).getRows(); + cols = ((GridLayout)getContentPane().getLayout()).getColumns(); + } + + // Calculate the size of the cells, into which each plot will be dawn. + int cellWidth = (int)chartBoxWidth / cols; + int cellHeight = (int)chartBoxHeight/ rows; + + for (int i = 0 ; i < rows ; ++i) { + int cellLowerLeftY = (int)chartBoxUpperRightY - (i+1) * cellHeight; + + for (int j = 0 ; j < cols ; ++j) { + int cellLowerLeftX = (int)chartBoxLowerLeftX + j * cellWidth; + + int whichPanel = i * cols + j; + TrickChartControlPanel panel = (TrickChartControlPanel)getContentPane().getComponent(whichPanel); + JFreeChart thechart = panel.getTheChart(); + BufferedImage bufferedImage = thechart.createBufferedImage((int)chartBoxWidth, (int)chartBoxHeight); + PDImageXObject image = JPEGFactory.createFromImage(doc, bufferedImage); + content.drawImage(image, cellLowerLeftX, cellLowerLeftY, cellWidth, cellHeight); + } + } + } } - /** * Sets this frame invisible. diff --git a/trick_source/java/src/trick/dataproducts/plot/utils/TrickXYPlot.java b/trick_source/java/src/trick/dataproducts/plot/utils/TrickXYPlot.java index 457265b2..b26784d6 100644 --- a/trick_source/java/src/trick/dataproducts/plot/utils/TrickXYPlot.java +++ b/trick_source/java/src/trick/dataproducts/plot/utils/TrickXYPlot.java @@ -112,6 +112,11 @@ public class TrickXYPlot extends XYPlot { maxY = Math.max(maxY, dataset.getSeries(i).getMaxY()); } guiXAxis.setRange(minX, maxX); + + if (minY == maxY) { + minY -= 1.0; + maxY += 1.0; + } guiYAxis.setRange(minY, maxY); } diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/CommonProduct.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/CommonProduct.java index 405dd9a2..de92cc09 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/CommonProduct.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/CommonProduct.java @@ -64,7 +64,7 @@ public abstract class CommonProduct { * @param tstart The start time of the related data. */ public void setTStart(double tstart) { - this.tstart = new Double(tstart); + this.tstart = tstart; } /** @@ -74,7 +74,7 @@ public abstract class CommonProduct { */ public void setTStart(String tstartStr) { try { - tstart = new Double(tstartStr); + tstart = Double.valueOf(tstartStr); } catch (NumberFormatException e) { tstart = null; } catch (NullPointerException e) { @@ -97,7 +97,7 @@ public abstract class CommonProduct { * @param tstop The stop time of the related data. */ public void setTStop(double tstop) { - this.tstop = new Double(tstop); + this.tstop = tstop; } /** @@ -107,7 +107,7 @@ public abstract class CommonProduct { */ public void setTStop(String tstopStr) { try { - tstop = new Double(tstopStr); + tstop = Double.valueOf(tstopStr); } catch (NumberFormatException e) { tstop = null; } catch (NullPointerException e) { @@ -130,7 +130,7 @@ public abstract class CommonProduct { * @param freq The frequency of the related data. */ public void setFrequency(double freq) { - frequency = new Double(freq); + frequency = freq; } /** @@ -140,7 +140,7 @@ public abstract class CommonProduct { */ public void setFrequency(String freqStr) { try { - frequency = new Double(freqStr); + frequency = Double.valueOf(freqStr); } catch (NumberFormatException e) { frequency = null; } catch (NullPointerException e) { diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductColumn.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductColumn.java index 4370ada3..e159404b 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductColumn.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductColumn.java @@ -34,6 +34,9 @@ public class ProductColumn { private static final int FORMAT_INDEX = 0; private String label; + // The element is OPTIONAL. It specifies the units + // to which the user wants the recorded data to be converted. + // The default value of units should be null, NOT "--". private String units; private ProductVar var; private String format; @@ -46,7 +49,7 @@ public class ProductColumn { */ public ProductColumn() { this.setLabel( "Column" ); - this.setUnits( "--" ); + this.setUnits(null); this.dataReader = null; } @@ -58,7 +61,7 @@ public class ProductColumn { */ public ProductColumn(ProductVar var) { this.setLabel( "Column" ); - this.setUnits( "--" ); + this.setUnits(null); this.setVar( var ); this.dataReader = null; } diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductMeasurement.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductMeasurement.java index 55a9e70e..344d9c25 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductMeasurement.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductMeasurement.java @@ -32,6 +32,9 @@ public class ProductMeasurement { // Private Data //======================================== private String name; + // The element is OPTIONAL. It specifies the units + // to which the user wants the recorded data to be converted. + // The default value of units should be null, NOT "--". private String units; private static final int UNITS_INDEX = 0; @@ -47,7 +50,7 @@ public class ProductMeasurement { */ public ProductMeasurement(String name) { this.name = name; - this.setUnits( "--" ); + this.setUnits(null); } //======================================== diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPage.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPage.java index 486c7c91..31e304c9 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPage.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPage.java @@ -45,8 +45,8 @@ public class ProductPage extends CommonProduct { //======================================== private List plotList; - private Integer hcells = new Integer(0); // default to 0 - private Integer vcells = new Integer(0); // default to 0 + private Integer hcells = 0; // default to 0 + private Integer vcells = 0; // default to 0 //======================================== // Constructors @@ -69,7 +69,7 @@ public class ProductPage extends CommonProduct { */ public void setHcells(String hcellsStr) { try { - hcells = new Integer(hcellsStr); + hcells = Integer.valueOf(hcellsStr); } catch (NumberFormatException e) { hcells = null; } catch (NullPointerException e) { @@ -83,7 +83,7 @@ public class ProductPage extends CommonProduct { */ public void setVcells(String vcellsStr) { try { - vcells = new Integer(vcellsStr); + vcells = Integer.valueOf(vcellsStr); } catch (NumberFormatException e) { vcells = null; } catch (NullPointerException e) { diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPlot.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPlot.java index 46bec085..7139d5a6 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPlot.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductPlot.java @@ -346,7 +346,7 @@ public class ProductPlot extends CommonProduct { * @param xmin The minimum value for X variable. */ public void setXMin(double xmin) { - this.xmin = new Double(xmin); + this.xmin = xmin; } /** @@ -356,7 +356,7 @@ public class ProductPlot extends CommonProduct { */ public void setXMin(String xminStr) { try { - xmin = new Double(xminStr); + xmin = Double.valueOf(xminStr); } catch (NumberFormatException e) { xmin = null; } catch (NullPointerException e) { @@ -379,7 +379,7 @@ public class ProductPlot extends CommonProduct { * @param xmax The maximum value for X variable. */ public void setXMax(double xmax) { - this.xmax = new Double(xmax); + this.xmax = xmax; } /** @@ -389,7 +389,7 @@ public class ProductPlot extends CommonProduct { */ public void setXMax(String xmaxStr) { try { - xmax = new Double(xmaxStr); + xmax = Double.valueOf(xmaxStr); } catch (NumberFormatException e) { xmax = null; } catch (NullPointerException e) { @@ -403,7 +403,7 @@ public class ProductPlot extends CommonProduct { * @param ymin The minimum value for Y variable. */ public void setYMin(double ymin) { - this.ymin = new Double(ymin); + this.ymin = ymin; } /** @@ -413,7 +413,7 @@ public class ProductPlot extends CommonProduct { */ public void setYMin(String yminStr) { try { - ymin = new Double(yminStr); + ymin = Double.valueOf(yminStr); } catch (NumberFormatException e) { ymin = null; } catch (NullPointerException e) { @@ -435,7 +435,7 @@ public class ProductPlot extends CommonProduct { * @param ymax The maximum value for Y variable. */ public void setYMax(double ymax) { - this.ymax = new Double(ymax); + this.ymax = ymax; } /** @@ -445,7 +445,7 @@ public class ProductPlot extends CommonProduct { */ public void setYMax(String ymaxStr) { try { - ymax = new Double(ymaxStr); + ymax = Double.valueOf(ymaxStr); } catch (NumberFormatException e) { ymax = null; } catch (NullPointerException e) { diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductVar.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductVar.java index 0ece7900..b1829faa 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductVar.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductVar.java @@ -286,7 +286,9 @@ public class ProductVar { private String name; // The label of the variable private String label; - // The units of the variable + // The element is OPTIONAL. It specifies the units + // to which the user wants the recorded data to be converted. + // The default value of units should be null, NOT "--". private String units; // The units from which needs to be converted. // Only needed when the data recording data doesn't provide the units for this variable. @@ -323,7 +325,7 @@ public class ProductVar { // If the label is entered by a user from GUI, that entered text // will be displayed and fxplot will not show the default label. //this.setLabel( name ); - setUnits("--"); + setUnits(null); } @@ -515,7 +517,7 @@ public class ProductVar { * @param bias The var bias. */ public void setBias(double bias) { - this.bias = new Double(bias); + this.bias = bias; } /** @@ -525,7 +527,7 @@ public class ProductVar { */ public void setBias(String biasStr) { try { - bias = new Double(biasStr); + bias = Double.valueOf(biasStr); } catch (NumberFormatException e) { bias = null; } catch (NullPointerException e) { @@ -539,7 +541,7 @@ public class ProductVar { * @param scale The var scale. */ public void setScale(double scale) { - this.scale = new Double(scale); + this.scale = scale; } /** @@ -549,7 +551,7 @@ public class ProductVar { */ public void setScale(String scaleStr) { try { - scale = new Double(scaleStr); + scale = Double.valueOf(scaleStr); } catch (NumberFormatException e) { scale = null; } catch (NullPointerException e) { @@ -563,7 +565,7 @@ public class ProductVar { * @param max The var max. */ public void setMax(double max) { - this.max = new Double(max); + this.max = max; } /** @@ -573,7 +575,7 @@ public class ProductVar { */ public void setMax(String maxStr) { try { - max = new Double(maxStr); + max = Double.valueOf(maxStr); } catch (NumberFormatException e) { max = null; } catch (NullPointerException e) { diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductXMLCreator.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductXMLCreator.java index d12fe29a..0b6898c3 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductXMLCreator.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/ProductXMLCreator.java @@ -163,8 +163,13 @@ public class ProductXMLCreator extends XMLCreator { Element measurementElem = dom.createElement("measurement"); // ... createChildElement(measurementElem, "var", eachOutput.getName()); - // ... - createChildElement(measurementElem, "units", eachOutput.getUnits()); + + // The units element is OPTIONAL and can be null, + // indicating that the user doesn't want units conversion. + String outPutUnits = eachOutput.getUnits(); + if (outPutUnits != null) { + createChildElement(measurementElem, "units", outPutUnits); + } outputsElem.appendChild(measurementElem); } } @@ -440,7 +445,13 @@ public class ProductXMLCreator extends XMLCreator { private Element createColumnElement(ProductColumn column) { Element columnElem = dom.createElement("column"); createChildElement(columnElem, "label", column.getLabel()); - createChildElement(columnElem, "units", column.getUnits()); + + // The units element is OPTIONAL and can be null, + // indicating that the user doesn't want units conversion. + String columnUnits = column.getUnits(); + if (columnUnits != null) { + createChildElement(columnElem, "units", columnUnits); + } columnElem.appendChild(createVarElement(column.getVar())); diff --git a/trick_source/java/src/trick/dataproducts/trickqp/utils/TrickQPActionController.java b/trick_source/java/src/trick/dataproducts/trickqp/utils/TrickQPActionController.java index 5096df25..5d931fa8 100644 --- a/trick_source/java/src/trick/dataproducts/trickqp/utils/TrickQPActionController.java +++ b/trick_source/java/src/trick/dataproducts/trickqp/utils/TrickQPActionController.java @@ -1676,7 +1676,6 @@ public class TrickQPActionController { // also need to add this newly generated output var to var list LogVar newOutVar = new LogVar(var.getName()); - newOutVar.setUnits("--"); application.varList.addData(newOutVar); } diff --git a/trick_source/java/src/trick/montemonitor/MonteMonitorApplication.java b/trick_source/java/src/trick/montemonitor/MonteMonitorApplication.java index 8cf36372..c58b4865 100644 --- a/trick_source/java/src/trick/montemonitor/MonteMonitorApplication.java +++ b/trick_source/java/src/trick/montemonitor/MonteMonitorApplication.java @@ -319,7 +319,7 @@ public class MonteMonitorApplication extends RunTimeTrickApplication { protected JComponent createMainPanel() { return new JXPanel(new BorderLayout()) { - Integer noRunNumber = new Integer(-1); + Integer noRunNumber = -1; { progressBar = new JProgressBar() {{ @@ -583,12 +583,12 @@ public class MonteMonitorApplication extends RunTimeTrickApplication { } slave.name = data[dataIndex++]; if (data[dataIndex++].equals("BAD_REF")) { - slave.currentRun = new Integer(-1); + slave.currentRun = -1; } else { - slave.currentRun = new Integer(data[dataIndex - 1]); + slave.currentRun = Integer.valueOf(data[dataIndex - 1]); } - slave.numResults = new Integer(data[dataIndex++]); + slave.numResults = Integer.valueOf(data[dataIndex++]); } for (int i = slaves.size() - 1; i >= 0; --i) { diff --git a/trick_source/java/src/trick/montemonitor/Slave.java b/trick_source/java/src/trick/montemonitor/Slave.java index 97a7bed4..5ddf2720 100644 --- a/trick_source/java/src/trick/montemonitor/Slave.java +++ b/trick_source/java/src/trick/montemonitor/Slave.java @@ -56,10 +56,10 @@ public class Slave { public String name; /** current run number */ - public Integer currentRun = new Integer(-1); + public Integer currentRun = -1; /** number or results returned */ - public Integer numResults = new Integer(0); + public Integer numResults = 0; /** * constructs a new Slave whose initial state is UNKNOWN diff --git a/trick_source/java/src/trick/mtv/MtvView.java b/trick_source/java/src/trick/mtv/MtvView.java index 6221f2f1..b0ff9a03 100644 --- a/trick_source/java/src/trick/mtv/MtvView.java +++ b/trick_source/java/src/trick/mtv/MtvView.java @@ -355,7 +355,7 @@ public class MtvView extends FrameView { if (eventname.length > 1) { // put grouped events on their own tab if (!tabmap.containsKey(eventname[0])) { - tabmap.put(eventname[0], new Integer(tabcount)); + tabmap.put(eventname[0], tabcount); tabs[tabcount] = new Tab(); tabs[tabcount].panel = new JPanel(); tabs[tabcount].panel.setName(eventname[0]); diff --git a/trick_source/java/src/trick/tv/DoubleComboBox.java b/trick_source/java/src/trick/tv/DoubleComboBox.java index 9aa77569..ab963785 100644 --- a/trick_source/java/src/trick/tv/DoubleComboBox.java +++ b/trick_source/java/src/trick/tv/DoubleComboBox.java @@ -33,8 +33,8 @@ public class DoubleComboBox extends JXPanel { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); for (int i = 0; i < count; i++) { - minimumBox.addItem(new Integer(i)); - maximumBox.addItem(new Integer(i)); + minimumBox.addItem(i); + maximumBox.addItem(i); } minimumBox.setSelectedIndex(0); @@ -43,12 +43,12 @@ public class DoubleComboBox extends JXPanel { minimumBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - int min = ((Integer)minimumBox.getSelectedItem()); + int min = (int)minimumBox.getSelectedItem(); for (int i = ((Integer)maximumBox.getItemAt(0)); i < min; ++i) { maximumBox.removeItemAt(0); } for (int i = ((Integer)maximumBox.getItemAt(0)); i > min; ) { - maximumBox.insertItemAt(new Integer(--i), 0); + maximumBox.insertItemAt(--i, 0); } } }); @@ -56,12 +56,12 @@ public class DoubleComboBox extends JXPanel { maximumBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { - int max = ((Integer)maximumBox.getSelectedItem()); + int max = (int)maximumBox.getSelectedItem(); for (int i = ((Integer)minimumBox.getItemAt(minimumBox.getItemCount() - 1)); i > max; --i) { minimumBox.removeItemAt(minimumBox.getItemCount() - 1); } for (int i = ((Integer)minimumBox.getItemAt(minimumBox.getItemCount() - 1)); i < max; ) { - minimumBox.addItem(new Integer(++i)); + minimumBox.addItem(++i); } } }); diff --git a/trick_source/java/src/trick/tv/StripChartManager.java b/trick_source/java/src/trick/tv/StripChartManager.java index 8d69758e..9458313d 100644 --- a/trick_source/java/src/trick/tv/StripChartManager.java +++ b/trick_source/java/src/trick/tv/StripChartManager.java @@ -239,7 +239,7 @@ public class StripChartManager { * updates the log by adding the most recent value */ public void update() { - values.add(new Double(variable.getValue().toVariableServer())); + values.add(Double.valueOf(variable.getValue().toVariableServer())); } /** diff --git a/trick_source/java/src/trick/tv/TVByte.java b/trick_source/java/src/trick/tv/TVByte.java index cec86409..74bf6acd 100644 --- a/trick_source/java/src/trick/tv/TVByte.java +++ b/trick_source/java/src/trick/tv/TVByte.java @@ -37,7 +37,8 @@ public class TVByte extends VSByte implements TrickViewFluent { Binary { public String format(byte value, boolean unsigned) { - return Integer.toBinaryString(value & 0xFF); + String result = Integer.toBinaryString(value & 0xFF); + return "00000000".substring(result.length()) + result; } public byte parse(String value) { diff --git a/trick_source/java/src/trick/tv/TVInteger.java b/trick_source/java/src/trick/tv/TVInteger.java index 8b988ebf..a8966737 100644 --- a/trick_source/java/src/trick/tv/TVInteger.java +++ b/trick_source/java/src/trick/tv/TVInteger.java @@ -32,12 +32,14 @@ public class TVInteger extends VSInteger implements TrickViewFluent { Binary { public String format(long value, boolean unsigned) { - return Long.toBinaryString(value); + String result = Long.toBinaryString(value); + return "0000000000000000000000000000000000000000000000000000000000000000" + .substring(result.length()) + result; } public long parse(String value) { diff --git a/trick_source/java/src/trick/tv/TVShort.java b/trick_source/java/src/trick/tv/TVShort.java index 4fb5cf38..1653b3e4 100644 --- a/trick_source/java/src/trick/tv/TVShort.java +++ b/trick_source/java/src/trick/tv/TVShort.java @@ -22,7 +22,8 @@ public class TVShort extends VSShort implements TrickViewFluent Binary { public String format(short value, boolean unsigned) { - return Integer.toBinaryString(value & 0xFFFF); + String result = Integer.toBinaryString(value & 0xFFFF); + return "0000000000000000".substring(result.length()) + result; } public short parse(String value) { diff --git a/trick_source/sim_services/Clock/clock_c_intf.cpp b/trick_source/sim_services/Clock/clock_c_intf.cpp index 3a1fae9e..c9894c6d 100644 --- a/trick_source/sim_services/Clock/clock_c_intf.cpp +++ b/trick_source/sim_services/Clock/clock_c_intf.cpp @@ -4,11 +4,11 @@ extern Trick::Clock * the_clock ; -extern "C" long long clock_time() { +extern "C" long long clock_time(void) { return the_clock->clock_time() ; } -extern "C" long long clock_wall_time() { +extern "C" long long clock_wall_time(void) { return the_clock->wall_clock_time() ; } @@ -24,7 +24,7 @@ extern "C" int clock_spin(long long ref) { return the_clock->clock_spin(ref) ; } -extern "C" double clock_get_rt_clock_ratio() { +extern "C" double clock_get_rt_clock_ratio(void) { return the_clock->get_rt_clock_ratio() ; } diff --git a/trick_source/sim_services/CommandLineArguments/command_line_c_intf.cpp b/trick_source/sim_services/CommandLineArguments/command_line_c_intf.cpp index 0d7aeb67..c6ea47ee 100644 --- a/trick_source/sim_services/CommandLineArguments/command_line_c_intf.cpp +++ b/trick_source/sim_services/CommandLineArguments/command_line_c_intf.cpp @@ -28,7 +28,7 @@ extern "C" int command_line_args_process_sim_args(int argc , char **argv) { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_argc() */ -extern "C" int command_line_args_get_argc() { +extern "C" int command_line_args_get_argc(void) { return(the_cmd_args->get_argc()) ; } @@ -36,7 +36,7 @@ extern "C" int command_line_args_get_argc() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_argv() */ -extern "C" char ** command_line_args_get_argv() { +extern "C" char ** command_line_args_get_argv(void) { return(the_cmd_args->get_argv()) ; } @@ -45,7 +45,7 @@ const char * empty_string = "" ; @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_output_dir() */ -extern "C" const char * command_line_args_get_output_dir() { +extern "C" const char * command_line_args_get_output_dir(void) { return(the_cmd_args->get_output_dir_ref().c_str()) ; } @@ -54,7 +54,7 @@ extern "C" const char * command_line_args_get_output_dir() { @copydoc Trick::CommandLineArguments::get_user_output_dir() */ -extern "C" const char * command_line_args_get_user_output_dir() { +extern "C" const char * command_line_args_get_user_output_dir(void) { return(the_cmd_args->get_user_output_dir_ref().c_str()) ; } @@ -62,7 +62,7 @@ extern "C" const char * command_line_args_get_user_output_dir() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_input_file() */ -extern "C" const char * command_line_args_get_input_file() { +extern "C" const char * command_line_args_get_input_file(void) { return(the_cmd_args->get_input_file_ref().c_str()) ; } @@ -70,7 +70,7 @@ extern "C" const char * command_line_args_get_input_file() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_default_dir() */ -extern "C" const char * command_line_args_get_default_dir() { +extern "C" const char * command_line_args_get_default_dir(void) { return(the_cmd_args->get_default_dir_ref().c_str()) ; } @@ -78,7 +78,7 @@ extern "C" const char * command_line_args_get_default_dir() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_cmdline_name() */ -extern "C" const char * command_line_args_get_cmdline_name() { +extern "C" const char * command_line_args_get_cmdline_name(void) { return(the_cmd_args->get_cmdline_name_ref().c_str()) ; } @@ -86,7 +86,7 @@ extern "C" const char * command_line_args_get_cmdline_name() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::output_dir_timestamped_on() */ -extern "C" int output_dir_timestamped_on() { +extern "C" int output_dir_timestamped_on(void) { return(the_cmd_args->output_dir_timestamped_on()) ; } @@ -94,7 +94,7 @@ extern "C" int output_dir_timestamped_on() { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::output_dir_timestamped_off() */ -extern "C" int output_dir_timestamped_off() { +extern "C" int output_dir_timestamped_off(void) { return(the_cmd_args->output_dir_timestamped_off()) ; } @@ -110,7 +110,7 @@ extern "C" void set_output_dir(const char* output_directory) { @relates Trick::CommandLineArguments @copydoc Trick::CommandLineArguments::get_input_file_ref() */ -std::string & command_line_args_get_input_file_ref() { +std::string & command_line_args_get_input_file_ref(void) { return(the_cmd_args->get_input_file_ref()) ; } diff --git a/trick_source/sim_services/DataRecord/DataRecordGroup.cpp b/trick_source/sim_services/DataRecord/DataRecordGroup.cpp index 13118098..375f6ad2 100644 --- a/trick_source/sim_services/DataRecord/DataRecordGroup.cpp +++ b/trick_source/sim_services/DataRecord/DataRecordGroup.cpp @@ -286,15 +286,18 @@ void Trick::DataRecordGroup::remove_variable( std::string in_name ) { void Trick::DataRecordGroup::remove_all_variables() { // remove all but the first variable, which is sim time - for (auto i = rec_buffer.begin() + 1; i != rec_buffer.end(); ++i) { - delete *i; + if(!rec_buffer.empty()) { + for (auto i = rec_buffer.begin() + 1; i != rec_buffer.end(); ++i) { + delete *i; + } + rec_buffer.erase(rec_buffer.begin() + 1, rec_buffer.end()); } - rec_buffer.erase(rec_buffer.begin() + 1, rec_buffer.end()); // remove everything for (auto variable : change_buffer) { delete variable; } + change_buffer.clear(); } @@ -363,6 +366,7 @@ int Trick::DataRecordGroup::init() { // Allocate recording space for time. rec_buffer[0]->buffer = (char *)calloc(max_num , rec_buffer[0]->ref->attr->size) ; + rec_buffer[0]->last_value = (char *)calloc(1 , rec_buffer[0]->ref->attr->size) ; /* Loop through all variables looking up names. Allocate recording space according to size of the variable */ @@ -593,7 +597,30 @@ int Trick::DataRecordGroup::data_record(double in_time) { *((double *)(rec_buffer[0]->last_value)) = in_time ; for (jj = 0; jj < rec_buffer.size() ; jj++) { drb = rec_buffer[jj] ; - memcpy( drb->buffer + (buffer_offset * drb->ref->attr->size) , drb->last_value , drb->ref->attr->size ) ; + REF2 * ref = drb->ref ; + int param_size = ref->attr->size ; + if ( buffer_offset == 0 ) { + drb->curr_buffer = drb->buffer ; + } else { + drb->curr_buffer += param_size ; + } + switch ( param_size ) { + case 8: + *(int64_t *)drb->curr_buffer = *(int64_t *)drb->last_value ; + break ; + case 4: + *(int32_t *)drb->curr_buffer = *(int32_t *)drb->last_value ; + break ; + case 2: + *(int16_t *)drb->curr_buffer = *(int16_t *)drb->last_value ; + break ; + case 1: + *(int8_t *)drb->curr_buffer = *(int8_t *)drb->last_value ; + break ; + default: + memcpy( drb->curr_buffer , drb->last_value , param_size ) ; + break ; + } } buffer_num++ ; } @@ -692,8 +719,10 @@ int Trick::DataRecordGroup::shutdown() { remove_all_variables(); // remove_all_variables does not remove sim time - delete rec_buffer[0]; - rec_buffer.clear(); + if(!rec_buffer.empty()){ + delete rec_buffer[0]; + rec_buffer.clear(); + } if ( writer_buff ) { free(writer_buff) ; diff --git a/trick_source/sim_services/DataRecord/data_record_utilities.cpp b/trick_source/sim_services/DataRecord/data_record_utilities.cpp index d5e4e469..479ac758 100644 --- a/trick_source/sim_services/DataRecord/data_record_utilities.cpp +++ b/trick_source/sim_services/DataRecord/data_record_utilities.cpp @@ -12,14 +12,14 @@ PROGRAMMERS: extern Trick::DataRecordDispatcher * the_drd ; -extern "C" int dr_remove_files() { +extern "C" int dr_remove_files(void) { if ( the_drd != NULL ) { return the_drd->remove_files() ; } return -1 ; } -extern "C" int dr_enable() { +extern "C" int dr_enable(void) { if ( the_drd != NULL ) { return the_drd->enable() ; } @@ -33,7 +33,7 @@ extern "C" int dr_enable_group( const char * in_name ) { return -1 ; } -extern "C" int dr_disable() { +extern "C" int dr_disable(void) { if ( the_drd != NULL ) { return the_drd->disable() ; } @@ -68,7 +68,7 @@ extern "C" int remove_data_record_group( Trick::DataRecordGroup * in_group ) { return -1 ; } -extern "C" void remove_all_data_record_groups() { +extern "C" void remove_all_data_record_groups(void) { the_drd->remove_all_groups() ; } diff --git a/trick_source/sim_services/DebugPause/DebugPause.cpp b/trick_source/sim_services/DebugPause/DebugPause.cpp index 21b00757..b95bcbd2 100644 --- a/trick_source/sim_services/DebugPause/DebugPause.cpp +++ b/trick_source/sim_services/DebugPause/DebugPause.cpp @@ -60,7 +60,6 @@ int Trick::DebugPause::debug_signal() { int Trick::DebugPause::debug_pause_on() { - std::map::iterator it ; std::stringstream sem_name_stream ; if ( debug_pause_flag == true ) { diff --git a/trick_source/sim_services/DebugPause/DebugPause_c_intf.cpp b/trick_source/sim_services/DebugPause/DebugPause_c_intf.cpp index 67bc2c25..b4b1e252 100644 --- a/trick_source/sim_services/DebugPause/DebugPause_c_intf.cpp +++ b/trick_source/sim_services/DebugPause/DebugPause_c_intf.cpp @@ -13,7 +13,7 @@ extern Trick::DebugPause * the_debug_pause ; * @copydoc Trick::DebugPause::debug_pause_on * C wrapper for Trick::DebugPause::debug_pause_on */ -extern "C" int debug_pause_on() { +extern "C" int debug_pause_on(void) { if (the_debug_pause != NULL) { return the_debug_pause->debug_pause_on() ; } @@ -25,14 +25,14 @@ extern "C" int debug_pause_on() { * @copydoc Trick::DebugPause::debug_pause_off * C wrapper for Trick::DebugPause::debug_pause_off */ -extern "C" int debug_pause_off() { +extern "C" int debug_pause_off(void) { if (the_debug_pause != NULL) { return the_debug_pause->debug_pause_off() ; } return(0) ; } -extern "C" int debug_signal() { +extern "C" int debug_signal(void) { if (the_debug_pause != NULL) { return the_debug_pause->debug_signal() ; } diff --git a/trick_source/sim_services/EchoJobs/EchoJobs_c_intf.cpp b/trick_source/sim_services/EchoJobs/EchoJobs_c_intf.cpp index f16b5e24..e0c577a1 100644 --- a/trick_source/sim_services/EchoJobs/EchoJobs_c_intf.cpp +++ b/trick_source/sim_services/EchoJobs/EchoJobs_c_intf.cpp @@ -13,7 +13,7 @@ extern Trick::EchoJobs * the_ej ; * @copydoc Trick::EchoJobs::echojobs_on * C wrapper for Trick::EchoJobs::echojobs_on */ -extern "C" int echo_jobs_on() { +extern "C" int echo_jobs_on(void) { if (the_ej != NULL) { return the_ej->echojobs_on() ; } @@ -25,7 +25,7 @@ extern "C" int echo_jobs_on() { * @copydoc Trick::EchoJobs::echojobs_off * C wrapper for Trick::EchoJobs::echojobs_off */ -extern "C" int echo_jobs_off() { +extern "C" int echo_jobs_off(void) { if (the_ej != NULL) { return the_ej->echojobs_off() ; } diff --git a/trick_source/sim_services/Executive/Executive.cpp b/trick_source/sim_services/Executive/Executive.cpp index cf5835d4..776c31ff 100644 --- a/trick_source/sim_services/Executive/Executive.cpp +++ b/trick_source/sim_services/Executive/Executive.cpp @@ -2,6 +2,9 @@ #include #include #include +#if __linux +#include +#endif #include "trick/Executive.hh" #include "trick/ExecutiveException.hh" @@ -48,6 +51,13 @@ Trick::Executive::Executive() { software_frame = 1.0; frame_count = 0 ; stack_trace = true ; + /** @li (if on new-enough Linux) allow any process to ptrace this one. + * This allows stack trace / debugger attach when ptrace is + * restricted (e.g. on Ubuntu 16). + */ + #if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY) + prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY); + #endif /** @li Assign default terminate time to MAX_LONG_LONG tics. */ terminate_time = TRICK_MAX_LONG_LONG - 1; time_last_pass_tics = 0 ; diff --git a/trick_source/sim_services/Executive/Executive_loop_multi_thread.cpp b/trick_source/sim_services/Executive/Executive_loop_multi_thread.cpp index 51e42255..34e348c1 100644 --- a/trick_source/sim_services/Executive/Executive_loop_multi_thread.cpp +++ b/trick_source/sim_services/Executive/Executive_loop_multi_thread.cpp @@ -38,7 +38,6 @@ int Trick::Executive::loop_multi_thread() { JobData * depend_job ; unsigned int ii ; - std::stringstream error_message ; Trick::ScheduledJobQueue * main_sched_queue ; int ret = 0 ; @@ -72,9 +71,28 @@ int Trick::Executive::loop_multi_thread() { exec_terminate_with_return(ret , curr_job->name.c_str() , 0 , "top_of_frame job did not return 0") ; } } + + for (ii = 1; ii < threads.size() ; ii++) { + + Trick::Threads * curr_thread = threads[ii]; + + if (curr_thread->process_type == Trick::PROCESS_TYPE_SCHEDULED) { + curr_thread->top_of_frame_queue.reset_curr_index() ; + while ( (curr_job = curr_thread->top_of_frame_queue.get_next_job()) != NULL ) { + ret = curr_job->call() ; + if ( ret != 0 ) { + exec_terminate_with_return(ret , curr_job->name.c_str() , 0 , "top_of_frame job did not return 0") ; + } + } + } + } + frame_count++ ; } + /* Loop through child threads calling their top of frame jobs */ + + /* Call thread sync jobs (wait for threads that are scheduled to finish by current time) */ thread_sync_queue.reset_curr_index() ; while ( (curr_job = thread_sync_queue.get_next_job()) != NULL ) { @@ -173,6 +191,21 @@ int Trick::Executive::loop_multi_thread() { exec_terminate_with_return(ret , curr_job->name.c_str() , 0 , "end_of_frame job did not return 0") ; } } + /* Loop through child threads calling their end of frame jobs */ + for (ii = 1; ii < threads.size() ; ii++) { + + Trick::Threads * curr_thread = threads[ii]; + + if (curr_thread->process_type == Trick::PROCESS_TYPE_SCHEDULED) { + curr_thread->end_of_frame_queue.reset_curr_index(); + while ( (curr_job = curr_thread->end_of_frame_queue.get_next_job()) != NULL ) { + ret = curr_job->call(); + if ( ret != 0 ) { + exec_terminate_with_return(ret , curr_job->name.c_str() , 0 , "end_of_frame job did not return 0"); + } + } + } + } next_frame_check_tics += software_frame_tics ; } diff --git a/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp b/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp index f6cd0428..79bcc9ee 100644 --- a/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp +++ b/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp @@ -76,7 +76,7 @@ int Trick::Executive::write_s_job_execution(FILE *fp) { fprintf(fp, "\n===================================================================================================\n") ; fprintf(fp, "Scheduled Loop:\n\n") ; for ( ii = 0 ; ii < threads.size() ; ii++ ) { - fprintf(fp, "Thread %d:\n", ii) ; + fprintf(fp, "Thread %u:\n", ii) ; threads[ii]->job_queue.write_sched_queue(fp) ; fprintf(fp, "\n") ; } @@ -87,7 +87,7 @@ int Trick::Executive::write_s_job_execution(FILE *fp) { fprintf(fp, "Thread 0:\n"); top_of_frame_queue.write_sched_queue(fp) ; for ( ii = 1 ; ii < threads.size() ; ii++ ) { - fprintf(fp, "Thread %d:\n", ii) ; + fprintf(fp, "Thread %u:\n", ii) ; threads[ii]->top_of_frame_queue.write_sched_queue(fp) ; fprintf(fp, "\n") ; } @@ -98,7 +98,7 @@ int Trick::Executive::write_s_job_execution(FILE *fp) { fprintf(fp, "Thread 0:\n"); end_of_frame_queue.write_sched_queue(fp) ; for ( ii = 1 ; ii < threads.size() ; ii++ ) { - fprintf(fp, "Thread %d:\n", ii) ; + fprintf(fp, "Thread %u:\n", ii) ; threads[ii]->end_of_frame_queue.write_sched_queue(fp) ; fprintf(fp, "\n") ; } diff --git a/trick_source/sim_services/ExternalApplications/ExternalApplication_c_intf.cpp b/trick_source/sim_services/ExternalApplications/ExternalApplication_c_intf.cpp index 3e3651d3..3d15b6c3 100644 --- a/trick_source/sim_services/ExternalApplications/ExternalApplication_c_intf.cpp +++ b/trick_source/sim_services/ExternalApplications/ExternalApplication_c_intf.cpp @@ -106,27 +106,27 @@ extern "C" void stripchart_set_enabled(int enabled) { } } -extern "C" int sim_control_panel_get_enabled() { +extern "C" int sim_control_panel_get_enabled(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); return getFirstInstanceOfType(typeid(Trick::SimControlPanel)) != NULL; } -extern "C" int trick_view_get_enabled() { +extern "C" int trick_view_get_enabled(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); return getFirstInstanceOfType(typeid(Trick::TrickView)) != NULL; } -extern "C" int malfunctions_trick_view_get_enabled() { +extern "C" int malfunctions_trick_view_get_enabled(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); return getFirstInstanceOfType(typeid(Trick::MalfunctionsTrickView)) != NULL; } -extern "C" int monte_monitor_get_enabled() { +extern "C" int monte_monitor_get_enabled(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); return getFirstInstanceOfType(typeid(Trick::MonteMonitor)) != NULL; } -extern "C" int stripchart_get_enabled() { +extern "C" int stripchart_get_enabled(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); return getFirstInstanceOfType(typeid(Trick::StripChart)) != NULL; } @@ -196,7 +196,7 @@ extern "C" void stripchart_set_startup_command(const char *startup_command) { externalApplication->set_startup_command(startup_command ? std::string(startup_command) : ""); } -extern "C" const char *sim_control_panel_get_startup_command() { +extern "C" const char *sim_control_panel_get_startup_command(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::SimControlPanel *externalApplication = (Trick::SimControlPanel *)getFirstInstanceOfType(typeid(Trick::SimControlPanel)); @@ -209,7 +209,7 @@ extern "C" const char *sim_control_panel_get_startup_command() { return externalApplication->get_startup_command().c_str(); } -extern "C" const char *trick_view_get_startup_command() { +extern "C" const char *trick_view_get_startup_command(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::TrickView *externalApplication = (Trick::TrickView *)getFirstInstanceOfType(typeid(Trick::TrickView)); @@ -222,7 +222,7 @@ extern "C" const char *trick_view_get_startup_command() { return externalApplication->get_startup_command().c_str(); } -extern "C" const char *malfunctions_trick_view_get_startup_command() { +extern "C" const char *malfunctions_trick_view_get_startup_command(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::MalfunctionsTrickView *externalApplication = (Trick::MalfunctionsTrickView *)getFirstInstanceOfType(typeid(Trick::MalfunctionsTrickView)); @@ -235,7 +235,7 @@ extern "C" const char *malfunctions_trick_view_get_startup_command() { return externalApplication->get_startup_command().c_str(); } -extern "C" const char *monte_monitor_get_startup_command() { +extern "C" const char *monte_monitor_get_startup_command(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::MonteMonitor *externalApplication = (Trick::MonteMonitor *)getFirstInstanceOfType(typeid(Trick::MonteMonitor)); @@ -248,7 +248,7 @@ extern "C" const char *monte_monitor_get_startup_command() { return externalApplication->get_startup_command().c_str(); } -extern "C" const char *stripchart_get_startup_command() { +extern "C" const char *stripchart_get_startup_command(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::StripChart *externalApplication = (Trick::StripChart *)getFirstInstanceOfType(typeid(Trick::StripChart)); @@ -261,7 +261,7 @@ extern "C" const char *stripchart_get_startup_command() { return externalApplication->get_startup_command().c_str(); } -extern "C" void sim_control_panel_launch() { +extern "C" void sim_control_panel_launch(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::SimControlPanel *externalApplication = (Trick::SimControlPanel *)getFirstInstanceOfType(typeid(Trick::SimControlPanel)); @@ -271,7 +271,7 @@ extern "C" void sim_control_panel_launch() { } } -extern "C" void trick_view_launch() { +extern "C" void trick_view_launch(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::TrickView *externalApplication = (Trick::TrickView *)getFirstInstanceOfType(typeid(Trick::TrickView)); @@ -281,7 +281,7 @@ extern "C" void trick_view_launch() { } } -extern "C" void malfunctions_trick_view_launch() { +extern "C" void malfunctions_trick_view_launch(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::MalfunctionsTrickView *externalApplication = (Trick::MalfunctionsTrickView *)getFirstInstanceOfType(typeid(Trick::MalfunctionsTrickView)); @@ -291,7 +291,7 @@ extern "C" void malfunctions_trick_view_launch() { } } -extern "C" void monte_monitor_launch() { +extern "C" void monte_monitor_launch(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::MonteMonitor *externalApplication = (Trick::MonteMonitor *)getFirstInstanceOfType(typeid(Trick::MonteMonitor)); @@ -301,7 +301,7 @@ extern "C" void monte_monitor_launch() { } } -extern "C" void stripchart_launch() { +extern "C" void stripchart_launch(void) { //printDeprecationMessage(__FILE__, __LINE__, __FUNCTION__); Trick::StripChart *externalApplication = (Trick::StripChart *)getFirstInstanceOfType(typeid(Trick::StripChart)); diff --git a/trick_source/sim_services/FrameLog/FrameLog.cpp b/trick_source/sim_services/FrameLog/FrameLog.cpp index 7ff87b6c..7893ca1d 100644 --- a/trick_source/sim_services/FrameLog/FrameLog.cpp +++ b/trick_source/sim_services/FrameLog/FrameLog.cpp @@ -782,7 +782,7 @@ int Trick::FrameLog::create_DP_job_files() { fprintf(fpx, " \n"); for ( ii = 0 ; ii < 8 and (page_count * 8 + ii + 1) < drg_users.size() ; ii++ ) { fprintf(fpx, " \n"); - fprintf(fpx, " Child thread %d Frame Scheduled Jobs\n", (page_count * 8 + ii + 1)); + fprintf(fpx, " Child thread %u Frame Scheduled Jobs\n", (page_count * 8 + ii + 1)); fprintf(fpx, " s \n"); fprintf(fpx, " \n"); fprintf(fpx, " \n"); diff --git a/trick_source/sim_services/FrameLog/FrameLog_c_intf.cpp b/trick_source/sim_services/FrameLog/FrameLog_c_intf.cpp index a13deb8f..f2b18c7b 100644 --- a/trick_source/sim_services/FrameLog/FrameLog_c_intf.cpp +++ b/trick_source/sim_services/FrameLog/FrameLog_c_intf.cpp @@ -13,7 +13,7 @@ extern Trick::FrameLog * the_fl ; * @copydoc Trick::FrameLog::framelog_on * C wrapper for Trick::FrameLog::framelog_on */ -extern "C" int frame_log_on() { +extern "C" int frame_log_on(void) { if (the_fl != NULL) { return the_fl->framelog_on() ; } @@ -25,7 +25,7 @@ extern "C" int frame_log_on() { * @copydoc Trick::FrameLog::framelog_off * C wrapper for Trick::FrameLog::framelog_off */ -extern "C" int frame_log_off() { +extern "C" int frame_log_off(void) { if (the_fl != NULL) { return the_fl->framelog_off() ; } diff --git a/trick_source/sim_services/InputProcessor/IPPython.cpp b/trick_source/sim_services/InputProcessor/IPPython.cpp index 96c3c9df..f940361f 100644 --- a/trick_source/sim_services/InputProcessor/IPPython.cpp +++ b/trick_source/sim_services/InputProcessor/IPPython.cpp @@ -79,8 +79,6 @@ int Trick::IPPython::init() { /** @par Detailed Design: */ FILE *input_fp ; - std::string shortcut ; - std::string verify_command ; int ret ; std::string error_message ; pthread_mutexattr_t m_attr ; diff --git a/trick_source/sim_services/InputProcessor/MTV.cpp b/trick_source/sim_services/InputProcessor/MTV.cpp index 560ecfb0..e2767c64 100644 --- a/trick_source/sim_services/InputProcessor/MTV.cpp +++ b/trick_source/sim_services/InputProcessor/MTV.cpp @@ -100,28 +100,28 @@ int Trick::MTV::send_event_data() { int jj; for (ii=0; ii < mtv_count; ii++) { - sprintf(varname, "%s[%d][0].name", mtv_name,ii); + sprintf(varname, "%s[%u][0].name", mtv_name,ii); var_add(varname); - sprintf(varname, "%s[%d][0].active", mtv_name,ii); + sprintf(varname, "%s[%u][0].active", mtv_name,ii); var_add(varname); - sprintf(varname, "%s[%d][0].added", mtv_name,ii); + sprintf(varname, "%s[%u][0].added", mtv_name,ii); var_add(varname); - sprintf(varname, "%s[%d][0].condition_count", mtv_name,ii); + sprintf(varname, "%s[%u][0].condition_count", mtv_name,ii); var_add(varname); - sprintf(varname, "%s[%d][0].action_count", mtv_name,ii); + sprintf(varname, "%s[%u][0].action_count", mtv_name,ii); var_add(varname); - sprintf(varname, "%s[%d][0].before_after", mtv_name,ii); + sprintf(varname, "%s[%u][0].before_after", mtv_name,ii); var_add(varname); for (jj=0; jj< mtv_list[ii]->condition_count; jj++) { - sprintf(varname, "%s[%d][0].cond[%d].comment", mtv_name,ii,jj); + sprintf(varname, "%s[%u][0].cond[%d].comment", mtv_name,ii,jj); var_add(varname); } for (jj=0; jj< mtv_list[ii]->action_count; jj++) { - sprintf(varname, "%s[%d][0].act[%d].comment", mtv_name,ii,jj); + sprintf(varname, "%s[%u][0].act[%d].comment", mtv_name,ii,jj); var_add(varname); } if (mtv_list[ii]->get_before_after() > 0) { - sprintf(varname, "%s[%d][0].target_name", mtv_name,ii); + sprintf(varname, "%s[%u][0].target_name", mtv_name,ii); var_add(varname); } } diff --git a/trick_source/sim_services/MasterSlave/Master.cpp b/trick_source/sim_services/MasterSlave/Master.cpp index 53e53895..02fa8578 100644 --- a/trick_source/sim_services/MasterSlave/Master.cpp +++ b/trick_source/sim_services/MasterSlave/Master.cpp @@ -640,7 +640,7 @@ int Trick::SlaveInfo::restart_dmtcp_slave() { * C binded function to toggle the master/slave synchronization flag to on. * @return always 0 */ -extern "C" int ms_master_enable() { +extern "C" int ms_master_enable(void) { the_ms_master->enable() ; return(0) ; } @@ -650,7 +650,7 @@ extern "C" int ms_master_enable() { * C binded function to toggle the master/slave synchronization flag to off. * @return always 0 */ -extern "C" int ms_master_disable() { +extern "C" int ms_master_disable(void) { the_ms_master->disable() ; return(0) ; } diff --git a/trick_source/sim_services/MemoryManager/MemoryManager_add_attr_info.cpp b/trick_source/sim_services/MemoryManager/MemoryManager_add_attr_info.cpp index bd7e91f7..14692ca7 100644 --- a/trick_source/sim_services/MemoryManager/MemoryManager_add_attr_info.cpp +++ b/trick_source/sim_services/MemoryManager/MemoryManager_add_attr_info.cpp @@ -21,14 +21,12 @@ int Trick::MemoryManager::add_attr_info( const std::string & user_type_string , std::string sub_attr_init_name ; std::string size_func_name ; size_t spos ; - std::string::iterator pos ; ATTRIBUTES* sub_attr = NULL ; ENUM_ATTR* enum_attr = NULL ; void (*init_sub_attr)(void) = NULL ; size_t (*size_func)(void) = NULL ; unsigned int ii ; std::set::iterator it ; - std::map::iterator mit; /** @par Design Details: */ diff --git a/trick_source/sim_services/MemoryManager/adef_parser.l b/trick_source/sim_services/MemoryManager/adef_parser.l index 7241e5e8..61c6e0e7 100644 --- a/trick_source/sim_services/MemoryManager/adef_parser.l +++ b/trick_source/sim_services/MemoryManager/adef_parser.l @@ -18,6 +18,10 @@ #include "trick/ADefParseContext.hh" #include "adef_parser.tab.h" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wunused-function" + #define YY_EXTRA_TYPE Trick::ADefParseContext* #define YY_USER_ACTION yylloc->first_line = yylineno; diff --git a/trick_source/sim_services/MemoryManager/adef_parser.y b/trick_source/sim_services/MemoryManager/adef_parser.y index e9e91f20..27286eb1 100644 --- a/trick_source/sim_services/MemoryManager/adef_parser.y +++ b/trick_source/sim_services/MemoryManager/adef_parser.y @@ -21,6 +21,8 @@ #include "trick/ADefParseContext.hh" #include "adef_parser.tab.h" +#pragma GCC diagnostic ignored "-Wunused-parameter" + using namespace std; int ADEF_lex( YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner ); diff --git a/trick_source/sim_services/MemoryManager/ref_parser.l b/trick_source/sim_services/MemoryManager/ref_parser.l index ff3c78f5..2eb7a5d0 100644 --- a/trick_source/sim_services/MemoryManager/ref_parser.l +++ b/trick_source/sim_services/MemoryManager/ref_parser.l @@ -19,6 +19,10 @@ #include "trick/RefParseContext.hh" #include "ref_parser.tab.h" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wunused-function" + #define YY_EXTRA_TYPE RefParseContext* #define YY_USER_ACTION yylloc->first_line = yylineno; diff --git a/trick_source/sim_services/MemoryManager/ref_parser.y b/trick_source/sim_services/MemoryManager/ref_parser.y index 539afa32..d27cd98b 100644 --- a/trick_source/sim_services/MemoryManager/ref_parser.y +++ b/trick_source/sim_services/MemoryManager/ref_parser.y @@ -21,6 +21,8 @@ #include "trick/var.h" #include "ref_parser.tab.h" +#pragma GCC diagnostic ignored "-Wunused-parameter" + using namespace std; int REF_lex( YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner ); diff --git a/trick_source/sim_services/MemoryManager/wcs_ext.c b/trick_source/sim_services/MemoryManager/wcs_ext.c index f332cf9d..0b06a81f 100644 --- a/trick_source/sim_services/MemoryManager/wcs_ext.c +++ b/trick_source/sim_services/MemoryManager/wcs_ext.c @@ -272,22 +272,22 @@ size_t ncs_to_wcs(const char *ncs, wchar_t * wcs, size_t w_max_size) } } #else -int wcs_to_ncs_len() +int wcs_to_ncs_len(void) { return (0); } -int ncs_to_wcs_len() +int ncs_to_wcs_len(void) { return (0); } -int wcs_to_ncs() +int wcs_to_ncs(void) { return (0); } -int ncs_to_wcs() +int ncs_to_wcs(void) { return (0); } diff --git a/trick_source/sim_services/Message/MessageThreadedCout.cpp b/trick_source/sim_services/Message/MessageThreadedCout.cpp index b833e570..c2ca6348 100644 --- a/trick_source/sim_services/Message/MessageThreadedCout.cpp +++ b/trick_source/sim_services/Message/MessageThreadedCout.cpp @@ -74,6 +74,7 @@ void * Trick::MessageThreadedCout::thread_body() { write_pending_messages() ; RELEASE() ; } + return (void*)0; } void Trick::MessageThreadedCout::write_pending_messages() { diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo.cpp index 688e040c..0cc791d5 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo.cpp @@ -10,7 +10,7 @@ Trick::MonteCarlo::MonteCarlo() : custom_slave_dispatch(false), timeout(120), max_tries(2), - verbosity(INFORMATIONAL), + verbosity(MC_INFORMATIONAL), num_runs(0), actual_num_runs(0), num_results(0), diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_c_intf.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_c_intf.cpp index 572b6899..a49ca28c 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_c_intf.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_c_intf.cpp @@ -12,7 +12,7 @@ extern "C" void mc_set_enabled(int enabled) { } } -extern "C" int mc_get_enabled() { +extern "C" int mc_get_enabled(void) { if ( the_mc != NULL ) { return the_mc->get_enabled(); } @@ -25,14 +25,14 @@ extern "C" void mc_set_dry_run(int dry_run) { } } -extern "C" int mc_get_dry_run() { +extern "C" int mc_get_dry_run(void) { if ( the_mc != NULL ) { return the_mc->get_dry_run(); } return 0 ; } -extern "C" int mc_is_slave() { +extern "C" int mc_is_slave(void) { if ( the_mc != NULL ) { return the_mc->is_slave(); } @@ -45,7 +45,7 @@ extern "C" void mc_set_localhost_as_remote(int localhost_as_remote) { } } -extern "C" int mc_get_localhost_as_remote() { +extern "C" int mc_get_localhost_as_remote(void) { if ( the_mc != NULL ) { return the_mc->get_localhost_as_remote(); } @@ -58,7 +58,7 @@ extern "C" void mc_set_custom_slave_dispatch(int custom_slave_dispatch) { } } -extern "C" int mc_get_custom_slave_dispatch() { +extern "C" int mc_get_custom_slave_dispatch(void) { if ( the_mc != NULL ) { return the_mc->get_custom_slave_dispatch(); } @@ -71,7 +71,7 @@ extern "C" void mc_set_timeout(double timeout) { } } -extern "C" double mc_get_timeout() { +extern "C" double mc_get_timeout(void) { if ( the_mc != NULL ) { return the_mc->get_timeout(); } @@ -84,7 +84,7 @@ extern "C" void mc_set_max_tries(unsigned int max_tries) { } } -extern "C" unsigned int mc_get_max_tries() { +extern "C" unsigned int mc_get_max_tries(void) { if ( the_mc != NULL ) { return the_mc->get_max_tries(); } @@ -97,7 +97,7 @@ extern "C" void mc_set_user_cmd_string(const char *user_cmd_string) { } } -extern "C" const char *mc_get_user_cmd_string() { +extern "C" const char *mc_get_user_cmd_string(void) { if ( the_mc != NULL ) { return the_mc->get_user_cmd_string().c_str(); } @@ -110,7 +110,7 @@ extern "C" void mc_set_slave_sim_options(const char *slave_sim_options) { } } -extern "C" const char *mc_get_slave_sim_options() { +extern "C" const char *mc_get_slave_sim_options(void) { if ( the_mc != NULL ) { return the_mc->slave_sim_options.c_str(); } @@ -123,7 +123,7 @@ extern "C" void mc_set_custom_pre_text(const char *custom_pre_text) { } } -extern "C" const char *mc_get_custom_pre_text() { +extern "C" const char *mc_get_custom_pre_text(void) { if ( the_mc != NULL ) { return the_mc->get_custom_pre_text().c_str(); } @@ -136,7 +136,7 @@ extern "C" void mc_set_custom_post_text(const char *custom_post_text) { } } -extern "C" const char *mc_get_custom_post_text() { +extern "C" const char *mc_get_custom_post_text(void) { if ( the_mc != NULL ) { return the_mc->get_custom_post_text().c_str(); } @@ -149,7 +149,7 @@ extern "C" void mc_set_verbosity(int verbosity) { } } -extern "C" int mc_get_verbosity() { +extern "C" int mc_get_verbosity(void) { if ( the_mc != NULL ) { return the_mc->get_verbosity(); } @@ -162,21 +162,21 @@ extern "C" void mc_set_num_runs(unsigned int num_runs) { } } -extern "C" unsigned int mc_get_num_runs() { +extern "C" unsigned int mc_get_num_runs(void) { if ( the_mc != NULL ) { return the_mc->get_num_runs(); } return 0 ; } -extern "C" unsigned int mc_get_num_results() { +extern "C" unsigned int mc_get_num_results(void) { if ( the_mc != NULL ) { return the_mc->get_num_results(); } return 0 ; } -extern "C" unsigned int mc_get_slave_id() { +extern "C" unsigned int mc_get_slave_id(void) { if ( the_mc != NULL ) { return the_mc->get_slave_id(); } @@ -219,7 +219,7 @@ extern "C" void mc_read(char *buffer, int size) { } } -extern "C" unsigned int mc_get_current_run() { +extern "C" unsigned int mc_get_current_run(void) { if ( the_mc != NULL ) { return the_mc->get_current_run(); } @@ -244,14 +244,14 @@ extern "C" void mc_set_connection_device_port(int port_number) { } } -extern "C" int mc_get_listen_device_port() { +extern "C" int mc_get_listen_device_port(void) { if ( the_mc != NULL ) { return the_mc->get_listen_device_port(); } return -1 ; } -extern "C" int mc_get_connection_device_port() { +extern "C" int mc_get_connection_device_port(void) { if ( the_mc != NULL ) { return the_mc->get_connection_device_port(); } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_dispatch_run_to_slave.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_dispatch_run_to_slave.cpp index 5132ab82..feeb19bb 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_dispatch_run_to_slave.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_dispatch_run_to_slave.cpp @@ -14,7 +14,7 @@ void Trick::MonteCarlo::dispatch_run_to_slave(MonteRun *run, MonteSlave *slave) if (prepare_run(run) == -1) { return; } - slave->state = MonteSlave::RUNNING; + slave->state = MonteSlave::MC_RUNNING; connection_device.hostname = (char*)slave->machine_name.c_str(); connection_device.port = slave->port; if (tc_connect(&connection_device) == TC_SUCCESS) { @@ -29,18 +29,18 @@ void Trick::MonteCarlo::dispatch_run_to_slave(MonteRun *run, MonteSlave *slave) buffer_stream << run->id ; buffer += std::string("trick.mc_set_current_run(") + buffer_stream.str() + std::string(")\n"); - if (verbosity >= INFORMATIONAL) { + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte [Master] Dispatching run %d to %s:%d.\n", run->id, slave->machine_name.c_str(), slave->id) ; } - int command = htonl(MonteSlave::PROCESS_RUN); + int command = htonl(MonteSlave::MC_PROCESS_RUN); tc_write(&connection_device, (char *)&command, (int)sizeof(command)); int num_bytes = htonl(buffer.length()); tc_write(&connection_device, (char*)&num_bytes, (int)sizeof(num_bytes)); tc_write(&connection_device, (char*)buffer.c_str(), (int)buffer.length()); - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Parameterization of run %d :\n%s\n", run->id, buffer.c_str()) ; } @@ -54,8 +54,8 @@ void Trick::MonteCarlo::dispatch_run_to_slave(MonteRun *run, MonteSlave *slave) run->start_time = time_val.tv_sec + (double)time_val.tv_usec / 1000000; ++run->num_tries; } else { - slave->state = Trick::MonteSlave::DISCONNECTED; - if (verbosity >= ERROR) { + slave->state = Trick::MonteSlave::MC_DISCONNECTED; + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Failed to connect to %s:%d to dispatch run.\n", slave->machine_name.c_str(), slave->id) ; } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_funcs.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_funcs.cpp index c6597608..c6786863 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_funcs.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_funcs.cpp @@ -201,38 +201,38 @@ void Trick::MonteCarlo::add_slave(Trick::MonteSlave *in_slave) { /** * @par Detailed Design: - * This function has an effect only if the slave exists and is in the STOPPING, UNRESPONSIVE_STOPPING, or STOPPED state. + * This function has an effect only if the slave exists and is in the MC_STOPPING, MC_UNRESPONSIVE_STOPPING, or MC_STOPPED state. */ void Trick::MonteCarlo::start_slave(unsigned int id) { if (MonteSlave *slave = get_slave(id)) { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [Master] Starting %s:%d.\n", slave->machine_name.c_str(), slave->id) ; } - if (slave->state == Trick::MonteSlave::STOPPING) { - slave->state = Trick::MonteSlave::RUNNING; - } else if (slave->state == Trick::MonteSlave::UNRESPONSIVE_STOPPING) { - slave->state = Trick::MonteSlave::UNRESPONSIVE_RUNNING; - } else if (slave->state == Trick::MonteSlave::STOPPED) { - slave->state = Trick::MonteSlave::READY; + if (slave->state == Trick::MonteSlave::MC_STOPPING) { + slave->state = Trick::MonteSlave::MC_RUNNING; + } else if (slave->state == Trick::MonteSlave::MC_UNRESPONSIVE_STOPPING) { + slave->state = Trick::MonteSlave::MC_UNRESPONSIVE_RUNNING; + } else if (slave->state == Trick::MonteSlave::MC_STOPPED) { + slave->state = Trick::MonteSlave::MC_READY; } } } /** * @par Detailed Design: - * This function has an effect only if the slave exists and is in the READY, RUNNING, or UNRESPONSIVE_RUNNING state. + * This function has an effect only if the slave exists and is in the MC_READY, MC_RUNNING, or MC_UNRESPONSIVE_RUNNING state. */ void Trick::MonteCarlo::stop_slave(unsigned int id) { if (MonteSlave *slave = get_slave(id)) { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [Master] Stopping %s:%d.\n", slave->machine_name.c_str(), slave->id) ; } - if (slave->state == Trick::MonteSlave::READY) { - slave->state = Trick::MonteSlave::STOPPED; - } else if (slave->state == Trick::MonteSlave::RUNNING) { - slave->state = Trick::MonteSlave::STOPPING; - } else if (slave->state == Trick::MonteSlave::UNRESPONSIVE_RUNNING) { - slave->state = Trick::MonteSlave::UNRESPONSIVE_STOPPING; + if (slave->state == Trick::MonteSlave::MC_READY) { + slave->state = Trick::MonteSlave::MC_STOPPED; + } else if (slave->state == Trick::MonteSlave::MC_RUNNING) { + slave->state = Trick::MonteSlave::MC_STOPPING; + } else if (slave->state == Trick::MonteSlave::MC_UNRESPONSIVE_RUNNING) { + slave->state = Trick::MonteSlave::MC_UNRESPONSIVE_STOPPING; } } } @@ -245,9 +245,9 @@ void Trick::MonteCarlo::disable_slave(std::string name, bool disabled){ for (std::vector::size_type i = 0; i < slaves.size(); ++i) { if (equals_ignore_case(slaves[i]->machine_name, name)) { if (disabled) { - slaves[i]->state = Trick::MonteSlave::STOPPED; + slaves[i]->state = Trick::MonteSlave::MC_STOPPED; } else { - slaves[i]->state = Trick::MonteSlave::UNINITIALIZED; + slaves[i]->state = Trick::MonteSlave::MC_UNINITIALIZED; } return; } @@ -278,8 +278,8 @@ int Trick::MonteCarlo::shutdown() { if (enabled && is_slave()) { connection_device.port = master_port; if (tc_connect(&connection_device) == TC_SUCCESS) { - int exit_status = MonteRun::COMPLETE; - if (verbosity >= ALL) { + int exit_status = MonteRun::MC_RUN_COMPLETE; + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [%s:%d] Sending run exit status to master: %d\n", machine_name.c_str(), slave_id, exit_status) ; } @@ -290,7 +290,7 @@ int Trick::MonteCarlo::shutdown() { run_queue(&slave_post_queue, "in slave_post queue"); tc_disconnect(&connection_device); } else { - if (verbosity >= ERROR) + if (verbosity >= MC_ERROR) message_publish( MSG_ERROR, "Monte [%s:%d] Failed to connect to master.\n", @@ -303,12 +303,12 @@ int Trick::MonteCarlo::shutdown() { void Trick::MonteCarlo::handle_retry(MonteSlave& slave, MonteRun::ExitStatus exit_status) { if (max_tries <= 0 || slave.current_run->num_tries < max_tries) { // Add the run to the retry queue. - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Queueing run %d for retry.\n", slave.current_run->id) ; } runs.push_back(slave.current_run); } else { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Run %d has reached its maximum allowed tries and has been skipped.\n", slave.current_run->id) ; } @@ -318,7 +318,7 @@ void Trick::MonteCarlo::handle_retry(MonteSlave& slave, MonteRun::ExitStatus exi /** @par Detailed Design: */ void Trick::MonteCarlo::resolve_run(MonteSlave& slave, MonteRun::ExitStatus exit_status) { - if (exit_status != MonteRun::COMPLETE) { + if (exit_status != MonteRun::MC_RUN_COMPLETE) { failed_runs.push_back(slave.current_run); } @@ -333,7 +333,7 @@ void Trick::MonteCarlo::resolve_run(MonteSlave& slave, MonteRun::ExitStatus exit ++num_results; - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [Master] Run %d has been resolved as: %d.\n",slave.current_run->id, exit_status) ; } } @@ -345,30 +345,30 @@ void Trick::MonteCarlo::check_timeouts() { /**
  • For every slave: */ for (std::vector::size_type i = 0; i < slaves.size(); ++i) { /**
    • If the slave has timed out: */ - if ((slaves[i]->state == MonteSlave::RUNNING || slaves[i]->state == MonteSlave::STOPPING) && + if ((slaves[i]->state == MonteSlave::MC_RUNNING || slaves[i]->state == MonteSlave::MC_STOPPING) && (time_val.tv_sec + (double)time_val.tv_usec / 1000000 - slaves[i]->current_run->start_time) * slaves[i]->multiplier > timeout) { /** *
      • This run might have been redispatched due to a previous timeout for which the slave actually returned * data later. Only process this timeout if the run hasn't been resolved yet. */ - if (slaves[i]->current_run->exit_status == MonteRun::INCOMPLETE) { - if (verbosity >= ERROR) { + if (slaves[i]->current_run->exit_status == MonteRun::MC_RUN_INCOMPLETE) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] %s:%d has not responded for run %d.\n", slaves[i]->machine_name.c_str(), slaves[i]->id, slaves[i]->current_run->id) ; } - handle_retry(*slaves[i], MonteRun::TIMEDOUT); + handle_retry(*slaves[i], MonteRun::MC_RUN_TIMED_OUT); } /**
    • Update the slave's state. */ - slaves[i]->state = slaves[i]->state == MonteSlave::RUNNING ? - MonteSlave::UNRESPONSIVE_RUNNING : MonteSlave::UNRESPONSIVE_STOPPING; + slaves[i]->state = slaves[i]->state == MonteSlave::MC_RUNNING ? + MonteSlave::MC_UNRESPONSIVE_RUNNING : MonteSlave::MC_UNRESPONSIVE_STOPPING; } } } Trick::MonteSlave * Trick::MonteCarlo::get_ready_slave() { for (std::vector::size_type i = 0; i < slaves.size(); ++i) { - if (slaves[i]->state == Trick::MonteSlave::READY) { + if (slaves[i]->state == Trick::MonteSlave::MC_READY) { return slaves[i]; } } @@ -402,7 +402,7 @@ Trick::MonteRun *Trick::MonteCarlo::get_next_dispatch() { return curr_run; /**
    • Otherwise, run the pre run jobs and dequeue it. */ } else { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_WARNING, "Monte [Master] Run %d is out of range and has been skipped.\n", curr_run->id) ; } prepare_run(curr_run); @@ -422,7 +422,7 @@ int Trick::MonteCarlo::prepare_run(MonteRun *curr_run) { for (std::vector::size_type i = 0; i < variables.size(); ++i) { curr_run->variables.push_back(variables[i]->get_next_value()); if (curr_run->variables.back() == "EOF") { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_WARNING, "Monte [Master] File variable '%s' reached end-of-file. Reducing number of runs to %d.\n", variables[i]->name.c_str(), curr_run->id) ; } @@ -484,7 +484,7 @@ void Trick::MonteCarlo::update_actual_num_runs() { } /**
    • Add one for every currently dispatched run. */ for (std::vector::size_type i = 0; i < slaves.size(); ++i) { - if (slaves[i]->state == MonteSlave::RUNNING || slaves[i]->state == MonteSlave::STOPPING) { + if (slaves[i]->state == MonteSlave::MC_RUNNING || slaves[i]->state == MonteSlave::MC_STOPPING) { ++actual_num_runs; } } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_initialize_sockets.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_initialize_sockets.cpp index 7fe95343..fac7325d 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_initialize_sockets.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_initialize_sockets.cpp @@ -17,7 +17,7 @@ int Trick::MonteCarlo::initialize_sockets() { /**
      • Initialize the sockets for communication with slaves. */ int return_value = tc_init(&listen_device); if (return_value != TC_SUCCESS) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Failed to initialize status communication socket.\n") ; } return return_value; @@ -26,7 +26,7 @@ int Trick::MonteCarlo::initialize_sockets() { /**
      • If no slaves were specified, add one on localhost. */ if (slaves.empty()) { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_WARNING, "Monte [Master] No slaves specified. Adding localhost as the sole slave.\n") ; } add_slave(new MonteSlave()); diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_master_file_io.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_master_file_io.cpp index f0acf19b..a69a5f7c 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_master_file_io.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_master_file_io.cpp @@ -13,7 +13,7 @@ int Trick::MonteCarlo::construct_run_directory() { if (run_directory.empty()) { std::string run_base_directory = command_line_args_get_output_dir(); if (run_base_directory.empty()) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Could not get the output directory.\n") ; } return -1; @@ -28,7 +28,7 @@ int Trick::MonteCarlo::construct_run_directory() { run_directory = basename((char *)command_line_args_get_output_dir()); if (run_directory.empty()) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Could not get the run directory name.\n") ; } return -1; @@ -48,7 +48,7 @@ int Trick::MonteCarlo::construct_run_directory() { int Trick::MonteCarlo::open_file(std::string file_name, FILE** file_ptr) { if ((*file_ptr = fopen(file_name.c_str(), "w")) == NULL) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Could not open %s for writing.\n", file_name.c_str()) ; } return -1; diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_master_shutdown.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_master_shutdown.cpp index 255816f6..73d7a637 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_master_shutdown.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_master_shutdown.cpp @@ -47,16 +47,16 @@ void Trick::MonteCarlo::master_shutdown() { void Trick::MonteCarlo::shutdown_slaves() { - if (verbosity >= INFORMATIONAL) { + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte [Master] Simulation complete. Shutting down slaves.\n\n") ; } for (std::vector::size_type i = 0; i < slaves.size() ; ++i) { - slaves[i]->state = MonteSlave::FINISHED; + slaves[i]->state = MonteSlave::MC_FINISHED; connection_device.hostname = (char*)slaves[i]->machine_name.c_str(); connection_device.port = slaves[i]->port; if (tc_connect(&connection_device) == TC_SUCCESS) { - int command = htonl(MonteSlave::SHUTDOWN); + int command = htonl(MonteSlave::MC_SHUTDOWN); tc_write(&connection_device, (char*)&command, sizeof(command)); } } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_receive_results.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_receive_results.cpp index 998ff55c..9ee6541c 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_receive_results.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_receive_results.cpp @@ -27,10 +27,10 @@ void Trick::MonteCarlo::receive_results() { } /** - *
      • If the slave is in the INITIALIZING state, it is sending us the + *
      • If the slave is in the MC_INITIALIZING state, it is sending us the * machine name and port over which it is listening for new runs. */ - if (slave->state == MonteSlave::INITIALIZING) { + if (slave->state == MonteSlave::MC_INITIALIZING) { handle_initialization(*slave); } /**
      • Otherwise, it's sending us run data. */ @@ -41,7 +41,7 @@ void Trick::MonteCarlo::receive_results() { } void Trick::MonteCarlo::handle_initialization(Trick::MonteSlave& slave) { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish( MSG_INFO, "Monte [Master] Receiving initialization information from %s:%d.\n", @@ -70,12 +70,12 @@ void Trick::MonteCarlo::handle_initialization(Trick::MonteSlave& slave) { } slave.port = ntohl(slave.port); - slave.state = MonteSlave::READY; + slave.state = MonteSlave::MC_READY; tc_disconnect(&connection_device); } void Trick::MonteCarlo::handle_run_data(Trick::MonteSlave& slave) { - if (verbosity >= INFORMATIONAL) { + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte [Master] Receiving results for run %d from %s:%d.\n", slave.current_run->id, slave.machine_name.c_str(), slave.id) ; } @@ -92,12 +92,12 @@ void Trick::MonteCarlo::handle_run_data(Trick::MonteSlave& slave) { * this slave was marked as having timed out. If that is the case, * discard these results. */ - if (slave.current_run->exit_status != MonteRun::INCOMPLETE) { + if (slave.current_run->exit_status != MonteRun::MC_RUN_INCOMPLETE) { // TODO: If a slave times out or core dumps in it's monte_slave_post - // jobs, the master will receive a COMPLETE status from the slave's + // jobs, the master will receive a MC_RUN_COMPLETE status from the slave's // child process and then an error status from the parent, rendering // this message incorrect. - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish( MSG_INFO, "Monte [Master] Run %d has already been resolved. Discarding results.\n", @@ -118,39 +118,39 @@ void Trick::MonteCarlo::handle_run_data(Trick::MonteSlave& slave) { switch (exit_status) { - case MonteRun::COMPLETE: - resolve_run(slave, MonteRun::COMPLETE); + case MonteRun::MC_RUN_COMPLETE: + resolve_run(slave, MonteRun::MC_RUN_COMPLETE); run_queue(&master_post_queue, "in master_post queue") ; break; - case MonteRun::BAD_INPUT: - if (verbosity >= ERROR) { + case MonteRun::MC_PROBLEM_PARSING_INPUT: + if (verbosity >= MC_ERROR) { message_publish( MSG_ERROR, "Monte [Master] %s:%d reported bad input for run %d. Skipping.\n", slave.machine_name.c_str(), slave.id, slave.current_run->id) ; } - resolve_run(slave, MonteRun::BAD_INPUT); + resolve_run(slave, MonteRun::MC_PROBLEM_PARSING_INPUT); break; - case MonteRun::CORED: - if (verbosity >= ERROR) { + case MonteRun::MC_RUN_DUMPED_CORE: + if (verbosity >= MC_ERROR) { message_publish( MSG_ERROR, "Monte [Master] %s:%d reported core dump for run %d. Skipping.\n", slave.machine_name.c_str(), slave.id, slave.current_run->id) ; } - resolve_run(slave, MonteRun::CORED); + resolve_run(slave, MonteRun::MC_RUN_DUMPED_CORE); break; - case MonteRun::NO_PERM: - if (verbosity >= ERROR) { + case MonteRun::MC_CANT_CREATE_OUTPUT_DIR: + if (verbosity >= MC_ERROR) { message_publish( MSG_ERROR, "Monte [Master] %s:%d reported a failure to create output directories for run %d.\n", slave.machine_name.c_str(), slave.id, slave.current_run->id); } - handle_retry(slave, MonteRun::NO_PERM); + handle_retry(slave, MonteRun::MC_CANT_CREATE_OUTPUT_DIR); break; /** @@ -159,43 +159,43 @@ void Trick::MonteCarlo::handle_run_data(Trick::MonteSlave& slave) { * can occur when the master determines that a slave has timed out, and * then that slave itself reports a timeout.
      */ - case MonteRun::TIMEDOUT: - if (verbosity >= ERROR) { + case MonteRun::MC_RUN_TIMED_OUT: + if (verbosity >= MC_ERROR) { message_publish( MSG_ERROR, "Monte [Master] %s:%d reported a timeout for run %d.\n", slave.machine_name.c_str(), slave.id, slave.current_run->id); } - if (slave.state != MonteSlave::UNRESPONSIVE_RUNNING && - slave.state != MonteSlave::UNRESPONSIVE_STOPPING) { - handle_retry(slave, MonteRun::TIMEDOUT); + if (slave.state != MonteSlave::MC_UNRESPONSIVE_RUNNING && + slave.state != MonteSlave::MC_UNRESPONSIVE_STOPPING) { + handle_retry(slave, MonteRun::MC_RUN_TIMED_OUT); } break; default: - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish( MSG_ERROR, "Monte [Master] %s:%d reported unrecognized exit status (%d) for run %d. Skipping.\n", slave.machine_name.c_str(), slave.id, exit_status, slave.current_run->id); } - resolve_run(slave, MonteRun::UNKNOWN); + resolve_run(slave, MonteRun::MC_UNRECOGNIZED_RETURN_CODE); break; } tc_disconnect(&connection_device); /**
    • Update the slave's state. */ - if (slave.state == MonteSlave::RUNNING || slave.state == MonteSlave::UNRESPONSIVE_RUNNING) { - slave.state = MonteSlave::READY; - } else if (slave.state == MonteSlave::STOPPING || slave.state == MonteSlave::UNRESPONSIVE_STOPPING) { - slave.state = MonteSlave::STOPPED; + if (slave.state == MonteSlave::MC_RUNNING || slave.state == MonteSlave::MC_UNRESPONSIVE_RUNNING) { + slave.state = MonteSlave::MC_READY; + } else if (slave.state == MonteSlave::MC_STOPPING || slave.state == MonteSlave::MC_UNRESPONSIVE_STOPPING) { + slave.state = MonteSlave::MC_STOPPED; } } void Trick::MonteCarlo::set_disconnected_state(Trick::MonteSlave& slave) { - slave.state = Trick::MonteSlave::DISCONNECTED; - if (verbosity >= ERROR) { + slave.state = Trick::MonteSlave::MC_DISCONNECTED; + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [Master] Lost connection to %s:%d.\n", slave.machine_name.c_str(), slave.id) ; } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave.cpp index 12d54f40..718515e6 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave.cpp @@ -9,13 +9,13 @@ int Trick::MonteCarlo::execute_as_slave() { /**
    • Forever: */ while (true) { - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [%s:%d] Waiting for new run.\n", machine_name.c_str(), slave_id) ; } /**
      • On a blocking read, wait for a MonteSlave::Command from the master. */ if (tc_accept(&listen_device, &connection_device) != TC_SUCCESS) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Lost connection to Master. Shutting down.\n", machine_name.c_str(), slave_id) ; } @@ -23,7 +23,7 @@ int Trick::MonteCarlo::execute_as_slave() { } int command; if (tc_read(&connection_device, (char *)&command, (int)sizeof(command)) != (int)sizeof(command)) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Lost connection to Master while receiving instructions. Shutting down.\n", machine_name.c_str(), slave_id) ; } @@ -31,9 +31,9 @@ int Trick::MonteCarlo::execute_as_slave() { } switch (command = ntohl(command)) { int return_value; - case MonteSlave::PROCESS_RUN: + case MonteSlave::MC_PROCESS_RUN: /** - *
        • MonteSlave::PROCESS_RUN: Call #slave_process_run. This will return a non-zero value when run in a + *
          • MonteSlave::MC_PROCESS_RUN: Call #slave_process_run. This will return a non-zero value when run in a * child process to indicate that this function should return so that the sim can complete. */ return_value = slave_process_run(); @@ -41,17 +41,17 @@ int Trick::MonteCarlo::execute_as_slave() { return return_value; } break; - case MonteSlave::SHUTDOWN: - /**
          • MonteSlave::SHUTDOWN: Call #slave_shutdown. */ - if (verbosity >= INFORMATIONAL) { + case MonteSlave::MC_SHUTDOWN: + /**
          • MonteSlave::MC_SHUTDOWN: Call #slave_shutdown. */ + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte [%s:%d] Shutdown command received from Master. Shutting down.\n", machine_name.c_str(), slave_id) ; } slave_shutdown(); break; - case MonteSlave::DIE: + case MonteSlave::MC_DIE: /**
          • MonteSlave::DIE: Call #slave_die. */ - if (verbosity >= INFORMATIONAL) { + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte [%s:%d] Killed by Master.\n", machine_name.c_str(), slave_id) ; } @@ -59,7 +59,7 @@ int Trick::MonteCarlo::execute_as_slave() { break; default: /**
          • default: Call #slave_shutdown. */ - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Unrecognized command %d received from Master. Shutting down.\n", machine_name.c_str(), slave_id, command) ; } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_init.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_init.cpp index dc2ecdfd..78a2bc5b 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_init.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_init.cpp @@ -15,7 +15,7 @@ int Trick::MonteCarlo::slave_init() { if (access(run_directory.c_str(), F_OK) != 0) { if (mkdir(run_directory.c_str(), 0775) == -1) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Unable to create directory %s.\nTerminating.\n", run_directory.c_str(), machine_name.c_str(), slave_id) ; } @@ -35,14 +35,14 @@ int Trick::MonteCarlo::slave_init() { /**
          • Connect to the master and write the port over which we are listening for new runs. */ connection_device.port = master_port; if (tc_connect(&connection_device) != TC_SUCCESS) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Failed to initialize communication sockets.\nTerminating.\n", machine_name.c_str(), slave_id) ; } exit(-1); } - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [%s:%d] Making initial connection with Master.\n", machine_name.c_str(), slave_id) ; } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_process_run.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_process_run.cpp index 0064e046..9767f0a0 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_process_run.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_slave_process_run.cpp @@ -16,7 +16,7 @@ int Trick::MonteCarlo::slave_process_run() { int size; /**
            • Read the length of the incoming message. */ if (tc_read(&connection_device, (char *)&size, (int)sizeof(size)) != (int)sizeof(size) || (size = ntohl(size)) < 0) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Lost connection to Master while receiving new run.\nShutting down.\n", machine_name.c_str(), slave_id) ; } @@ -25,7 +25,7 @@ int Trick::MonteCarlo::slave_process_run() { char *input = new char[size + 1]; /**
            • Read the incoming message. */ if (tc_read(&connection_device, input, size) != size) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Lost connection to Master while receiving new run.\nShutting down.\n", machine_name.c_str(), slave_id) ; } @@ -40,7 +40,7 @@ int Trick::MonteCarlo::slave_process_run() { */ pid_t pid = fork(); if (pid == -1) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Unable to fork new process for run.\nShutting down.\n", machine_name.c_str(), slave_id) ; } @@ -52,7 +52,7 @@ int Trick::MonteCarlo::slave_process_run() { if (waitpid(pid, &return_value, 0) == -1) { /* (Alex) On the Mac this check gives a lot of false positives. I've commented out the code for now. */ /* - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Error while waiting for run to finish.\nShutting down.\n", machine_name.c_str(), slave_id) ; } @@ -70,20 +70,20 @@ int Trick::MonteCarlo::slave_process_run() { int signal = WTERMSIG(return_value); /**
            • Extract the exit status of the child. */ - MonteRun::ExitStatus exit_status = signal == SIGALRM ? MonteRun::TIMEDOUT : MonteRun::CORED; - if (verbosity >= ERROR) { + MonteRun::ExitStatus exit_status = signal == SIGALRM ? MonteRun::MC_RUN_TIMED_OUT : MonteRun::MC_RUN_DUMPED_CORE; + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Run killed by signal %d: %s\n", machine_name.c_str(), slave_id, signal, strsignal(signal)) ; } connection_device.port = master_port; if (tc_connect(&connection_device) != TC_SUCCESS) { - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_ERROR, "Monte [%s:%d] Lost connection to Master before results could be returned.\nShutting down.\n", machine_name.c_str(), slave_id) ; } slave_shutdown(); } - if (verbosity >= ALL) { + if (verbosity >= MC_ALL) { message_publish(MSG_INFO, "Monte [%s:%d] Sending run exit status to master %d.\n", machine_name.c_str(), slave_id, exit_status) ; } @@ -99,14 +99,14 @@ int Trick::MonteCarlo::slave_process_run() { } else { input[size] = '\0'; if ( ip_parse(input) != 0 ) { - exit(MonteRun::BAD_INPUT); + exit(MonteRun::MC_PROBLEM_PARSING_INPUT); } /**
              • Create the run directory. */ std::string output_dir = command_line_args_get_output_dir(); if (access(output_dir.c_str(), F_OK) != 0) { if (mkdir(output_dir.c_str(), 0775) == -1) { - exit(MonteRun::NO_PERM); + exit(MonteRun::MC_CANT_CREATE_OUTPUT_DIR); } } diff --git a/trick_source/sim_services/MonteCarlo/MonteCarlo_spawn_slaves.cpp b/trick_source/sim_services/MonteCarlo/MonteCarlo_spawn_slaves.cpp index 3279781d..667da171 100644 --- a/trick_source/sim_services/MonteCarlo/MonteCarlo_spawn_slaves.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteCarlo_spawn_slaves.cpp @@ -19,7 +19,7 @@ void Trick::MonteCarlo::spawn_slaves() { /**
                • If the slave is in the UNINITIALZED state, then * set up the command string for starting the slave. */ - if (slaves[i]->state == MonteSlave::UNINITIALIZED) { + if (slaves[i]->state == MonteSlave::MC_UNINITIALIZED) { initialize_slave(slaves[i]) ; } } @@ -64,12 +64,12 @@ void Trick::MonteCarlo::initialize_slave(Trick::MonteSlave* slave_to_init) { buffer += std::string("' &"); } - if (verbosity >= INFORMATIONAL) { + if (verbosity >= MC_INFORMATIONAL) { message_publish(MSG_INFO, "Monte: Spawning Slave %s:%d :\n%s\n", slave_to_init->machine_name.c_str(), slave_to_init->id, buffer.c_str()) ; } - /**
                • Set the slave's state to INITIALIZING. */ - slave_to_init->state = MonteSlave::INITIALIZING; + /**
                • Set the slave's state to MC_INITIALIZING. */ + slave_to_init->state = MonteSlave::MC_INITIALIZING; /**
                • Make the system call to execute the shell. */ system(buffer.c_str()); } @@ -89,7 +89,7 @@ void Trick::MonteCarlo::default_slave_dispatch_pre_text(Trick::MonteSlave* slave case TRICK_USER_REMOTE_SH: if (slave_to_init->user_remote_shell.empty()) { slave_to_init->user_remote_shell = unix_ssh; - if (verbosity >= ERROR) { + if (verbosity >= MC_ERROR) { message_publish(MSG_WARNING, "Monte: TRICK_USER_REMOTE_SH specified for Slave %s:%d, but no shell given.\n" "Defaulting to %s.\n", machine_name.c_str(), slave_to_init->id, slave_to_init->user_remote_shell.c_str()) ; diff --git a/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp b/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp index b763926e..660e32fd 100644 --- a/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp @@ -72,7 +72,7 @@ std::string Trick::MonteVarFile::get_next_value() { // Verify the input column number is valid. if ((column == 0) || (column > ntokens)) { char string[100]; - sprintf(string, "Trick:MonteVarFile An invalid column number %d, valid column numbers are 1 - %d", column, ntokens); + sprintf(string, "Trick:MonteVarFile An invalid column number %u, valid column numbers are 1 - %u", column, ntokens); exec_terminate_with_return(-1, __FILE__, __LINE__, string); } diff --git a/trick_source/sim_services/MonteCarlo/test/MonteCarlo_test.cpp b/trick_source/sim_services/MonteCarlo/test/MonteCarlo_test.cpp index f17e8d9c..3a38fee1 100644 --- a/trick_source/sim_services/MonteCarlo/test/MonteCarlo_test.cpp +++ b/trick_source/sim_services/MonteCarlo/test/MonteCarlo_test.cpp @@ -245,7 +245,7 @@ TEST_F(MonteCarloTest , TestDefaultValues) { EXPECT_EQ(exec.get_custom_slave_dispatch(), false) ; EXPECT_EQ(exec.get_timeout(), 120) ; EXPECT_EQ(exec.get_max_tries(), 2) ; - EXPECT_EQ(exec.get_verbosity(), exec.INFORMATIONAL) ; + EXPECT_EQ(exec.get_verbosity(), exec.MC_INFORMATIONAL) ; EXPECT_EQ(exec.get_num_runs(), 0) ; EXPECT_EQ(exec.get_slave_id(), 0) ; EXPECT_EQ(exec.actual_num_runs, 0) ; @@ -268,14 +268,14 @@ TEST_F(MonteCarloTest, TestSettingValues) { EXPECT_EQ(exec.get_timeout(), 60) ; exec.set_max_tries(4) ; EXPECT_EQ(exec.get_max_tries(), 4) ; - exec.set_verbosity(exec.NONE) ; - EXPECT_EQ(exec.get_verbosity(), exec.NONE) ; - exec.set_verbosity(exec.ERROR) ; - EXPECT_EQ(exec.get_verbosity(), exec.ERROR) ; - exec.set_verbosity(exec.INFORMATIONAL) ; - EXPECT_EQ(exec.get_verbosity(), exec.INFORMATIONAL) ; - exec.set_verbosity(exec.ALL) ; - EXPECT_EQ(exec.get_verbosity(), exec.ALL) ; + exec.set_verbosity(exec.MC_NONE) ; + EXPECT_EQ(exec.get_verbosity(), exec.MC_NONE) ; + exec.set_verbosity(exec.MC_ERROR) ; + EXPECT_EQ(exec.get_verbosity(), exec.MC_ERROR) ; + exec.set_verbosity(exec.MC_INFORMATIONAL) ; + EXPECT_EQ(exec.get_verbosity(), exec.MC_INFORMATIONAL) ; + exec.set_verbosity(exec.MC_ALL) ; + EXPECT_EQ(exec.get_verbosity(), exec.MC_ALL) ; } @@ -307,13 +307,13 @@ TEST_F(MonteCarloTest, TestSlaves) { EXPECT_EQ(slave1.id, 2) ; EXPECT_EQ(exec.get_slave_index(1), 0) ; EXPECT_EQ(exec.get_slave_index(2), 1) ; - EXPECT_EQ(slave0.state, Trick::MonteSlave::UNINITIALIZED) ; - EXPECT_EQ(slave1.state, Trick::MonteSlave::UNINITIALIZED) ; + EXPECT_EQ(slave0.state, Trick::MonteSlave::MC_UNINITIALIZED) ; + EXPECT_EQ(slave1.state, Trick::MonteSlave::MC_UNINITIALIZED) ; exec.disable_slave("WonderWoman", true) ; - EXPECT_EQ(slave1.state, Trick::MonteSlave::STOPPED) ; + EXPECT_EQ(slave1.state, Trick::MonteSlave::MC_STOPPED) ; EXPECT_EQ(exec.slaves.size(), 2) ; exec.disable_slave("WonderWoman", false) ; - EXPECT_EQ(slave1.state, Trick::MonteSlave::UNINITIALIZED) ; + EXPECT_EQ(slave1.state, Trick::MonteSlave::MC_UNINITIALIZED) ; EXPECT_EQ(slave0.machine_name, "localhost") ; EXPECT_EQ(slave1.machine_name, "WonderWoman") ; } diff --git a/trick_source/sim_services/Sie/sie_c_intf.cpp b/trick_source/sim_services/Sie/sie_c_intf.cpp index f25f4023..784d5597 100644 --- a/trick_source/sim_services/Sie/sie_c_intf.cpp +++ b/trick_source/sim_services/Sie/sie_c_intf.cpp @@ -4,25 +4,25 @@ extern Trick::Sie * the_sie ; -extern "C" void sie_print_xml() { +extern "C" void sie_print_xml(void) { if ( the_sie != NULL ) { the_sie->sie_print_xml() ; } } -extern "C" void sie_class_attr_map_print_xml() { +extern "C" void sie_class_attr_map_print_xml(void) { if ( the_sie != NULL ) { the_sie->class_attr_map_print_xml() ; } } -extern "C" void sie_enum_attr_map_print_xml() { +extern "C" void sie_enum_attr_map_print_xml(void) { if ( the_sie != NULL ) { the_sie->enum_attr_map_print_xml() ; } } -extern "C" void sie_top_level_objects_print_xml() { +extern "C" void sie_top_level_objects_print_xml(void) { if ( the_sie != NULL ) { the_sie->top_level_objects_print_xml() ; } diff --git a/trick_source/sim_services/SimTime/SimTime_c_intf.cpp b/trick_source/sim_services/SimTime/SimTime_c_intf.cpp index 44616766..660dab26 100644 --- a/trick_source/sim_services/SimTime/SimTime_c_intf.cpp +++ b/trick_source/sim_services/SimTime/SimTime_c_intf.cpp @@ -4,27 +4,27 @@ extern Trick::SimTime * the_simtime ; -extern "C" double get_rettime() { +extern "C" double get_rettime(void) { return (the_simtime->get_rettime()) ; } -extern "C" double get_gmttime() { +extern "C" double get_gmttime(void) { return (the_simtime->get_gmttime()) ; } -extern "C" double get_mettime() { +extern "C" double get_mettime(void) { return (the_simtime->get_mettime()) ; } -extern "C" GMTTIME * get_rettime_struct() { +extern "C" GMTTIME * get_rettime_struct(void) { return (the_simtime->get_rettime_struct()) ; } -extern "C" GMTTIME * get_gmttime_struct() { +extern "C" GMTTIME * get_gmttime_struct(void) { return (the_simtime->get_gmttime_struct()) ; } -extern "C" GMTTIME * get_mettime_struct() { +extern "C" GMTTIME * get_mettime_struct(void) { return (the_simtime->get_mettime_struct()) ; } diff --git a/trick_source/sim_services/UdUnits/map_trick_units_to_udunits.cpp b/trick_source/sim_services/UdUnits/map_trick_units_to_udunits.cpp index 11869fc2..cddfd8c5 100644 --- a/trick_source/sim_services/UdUnits/map_trick_units_to_udunits.cpp +++ b/trick_source/sim_services/UdUnits/map_trick_units_to_udunits.cpp @@ -74,7 +74,6 @@ std::string map_trick_units_to_udunits( std::string orig_units ) { std::vector::iterator it ; tokenize_units(orig_units, tokens, "*/^()") ; for( it = tokens.begin() ; it != tokens.end() ; it++ ) { - std::string power ; char last_char = *((*it).rbegin()) ; // tokens can end in powers of 2 or 3 in the old system. // save the power if it is the last character diff --git a/trick_source/sim_services/UnitTest/UnitTest_c_intf.cpp b/trick_source/sim_services/UnitTest/UnitTest_c_intf.cpp index 784ca603..64200e4d 100644 --- a/trick_source/sim_services/UnitTest/UnitTest_c_intf.cpp +++ b/trick_source/sim_services/UnitTest/UnitTest_c_intf.cpp @@ -6,7 +6,7 @@ extern Trick::UnitTest * the_unit_test_output ; -extern "C" int trick_test_enable() { +extern "C" int trick_test_enable(void) { the_unit_test_output->enable() ; return(0) ; } @@ -36,7 +36,7 @@ extern "C" int trick_test_add_parent(const char * in_test_suite_name, const char } -extern "C" int call_write_output() { +extern "C" int call_write_output(void) { the_unit_test_output->write_output() ; return(0) ; } diff --git a/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp b/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp index b2dfe0f1..cb182d86 100644 --- a/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp +++ b/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp @@ -424,7 +424,7 @@ int Trick::VariableServerThread::transmit_file(std::string sie_file) { fseek(fp , 0L, SEEK_END) ; file_size = ftell(fp) ; - sprintf(buffer, "%d\t%d\n" , VS_SIE_RESOURCE, file_size) ; + sprintf(buffer, "%d\t%u\n" , VS_SIE_RESOURCE, file_size) ; tc_write(&connection , buffer , strlen(buffer)) ; rewind(fp) ; diff --git a/trick_source/sim_services/VariableServer/var_server_ext.cpp b/trick_source/sim_services/VariableServer/var_server_ext.cpp index 5220a7d6..104dd730 100644 --- a/trick_source/sim_services/VariableServer/var_server_ext.cpp +++ b/trick_source/sim_services/VariableServer/var_server_ext.cpp @@ -392,7 +392,7 @@ Trick::VariableServer * var_server_get_var_server() { * @copydoc Trick::VariableServer::get_hostname * C wrapper Trick::VariableServer::get_hostname */ -extern "C" const char * var_server_get_hostname() { +extern "C" const char * var_server_get_hostname(void) { return(the_vs->get_hostname()) ; } @@ -401,7 +401,7 @@ extern "C" const char * var_server_get_hostname() { * @copydoc Trick::VariableServer::get_port * C wrapper Trick::VariableServer::get_port */ -extern "C" unsigned short var_server_get_port() { +extern "C" unsigned short var_server_get_port(void) { return(the_vs->get_listen_thread().get_port()) ; } @@ -428,7 +428,7 @@ extern "C" void var_server_set_source_address(const char * source_address) { * @copydoc Trick::VariableServer::get_user_tag * C wrapper Trick::VariableServer::get_user_tag */ -extern "C" const char * var_server_get_user_tag() { +extern "C" const char * var_server_get_user_tag(void) { return(the_vs->get_listen_thread().get_user_tag().c_str()) ; } @@ -446,7 +446,7 @@ extern "C" void var_server_set_user_tag(const char * in_tag) { * @copydoc Trick::VariableServer::get_enabled * C wrapper Trick::VariableServer::get_enabled */ -extern "C" int var_server_get_enabled() { +extern "C" int var_server_get_enabled(void) { return(the_vs->get_enabled()) ; } diff --git a/trick_source/trick_utils/comm/test_programs/dr_client.c b/trick_source/trick_utils/comm/test_programs/dr_client.c index ff686b29..8ed307d2 100644 --- a/trick_source/trick_utils/comm/test_programs/dr_client.c +++ b/trick_source/trick_utils/comm/test_programs/dr_client.c @@ -34,9 +34,7 @@ void dump_data ( DataFiles* df, int main( int narg, char** args ) { DataFiles df ; - DataFiles headers ; TCDevice connection ; - int isAsciiData ; int ret ; char* file_name ; char* msg ; diff --git a/trick_source/trick_utils/math/src/deuler_123.c b/trick_source/trick_utils/math/src/deuler_123.c index 5fb6cd13..38d53afd 100644 --- a/trick_source/trick_utils/math/src/deuler_123.c +++ b/trick_source/trick_utils/math/src/deuler_123.c @@ -120,13 +120,12 @@ int euler123( /* Error: Out of normal range and beyond tolerance for asin function */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_123_quat.c b/trick_source/trick_utils/math/src/deuler_123_quat.c index 5e0a3eab..914e045c 100644 --- a/trick_source/trick_utils/math/src/deuler_123_quat.c +++ b/trick_source/trick_utils/math/src/deuler_123_quat.c @@ -116,13 +116,12 @@ int euler123_quat( /* Error: Out of normal range and beyond tolerance for asin function */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_132.c b/trick_source/trick_utils/math/src/deuler_132.c index 3dd6b860..deb77ce3 100644 --- a/trick_source/trick_utils/math/src/deuler_132.c +++ b/trick_source/trick_utils/math/src/deuler_132.c @@ -137,13 +137,12 @@ int euler132( * for asin function */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_132_quat.c b/trick_source/trick_utils/math/src/deuler_132_quat.c index 7b4c65d4..e04cd71f 100644 --- a/trick_source/trick_utils/math/src/deuler_132_quat.c +++ b/trick_source/trick_utils/math/src/deuler_132_quat.c @@ -117,13 +117,12 @@ int euler132_quat( * for asin function */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_213.c b/trick_source/trick_utils/math/src/deuler_213.c index 8781b834..a6b79eca 100644 --- a/trick_source/trick_utils/math/src/deuler_213.c +++ b/trick_source/trick_utils/math/src/deuler_213.c @@ -124,13 +124,12 @@ int euler213(double angle[3], /* In: r Method=0, 0=PITCH , 1=ROLL , 2=YAW */ /* Error: Out of normal range & beyond tolerance for asin func */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_213_quat.c b/trick_source/trick_utils/math/src/deuler_213_quat.c index ce90b5cc..03c85813 100644 --- a/trick_source/trick_utils/math/src/deuler_213_quat.c +++ b/trick_source/trick_utils/math/src/deuler_213_quat.c @@ -114,13 +114,12 @@ int euler213_quat( /* Error: Out of normal range & beyond tolerance for asin func */ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_231.c b/trick_source/trick_utils/math/src/deuler_231.c index 1cdce420..12e1f629 100644 --- a/trick_source/trick_utils/math/src/deuler_231.c +++ b/trick_source/trick_utils/math/src/deuler_231.c @@ -120,13 +120,12 @@ int euler231( /* Return: -- None. */ } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_231_quat.c b/trick_source/trick_utils/math/src/deuler_231_quat.c index 54bb5fbf..10776012 100644 --- a/trick_source/trick_utils/math/src/deuler_231_quat.c +++ b/trick_source/trick_utils/math/src/deuler_231_quat.c @@ -112,13 +112,12 @@ int euler231_quat( } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_312.c b/trick_source/trick_utils/math/src/deuler_312.c index 226ce03b..94ee7df6 100644 --- a/trick_source/trick_utils/math/src/deuler_312.c +++ b/trick_source/trick_utils/math/src/deuler_312.c @@ -118,13 +118,12 @@ int euler312( } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_312_quat.c b/trick_source/trick_utils/math/src/deuler_312_quat.c index 3e1bb2f1..af902883 100644 --- a/trick_source/trick_utils/math/src/deuler_312_quat.c +++ b/trick_source/trick_utils/math/src/deuler_312_quat.c @@ -112,13 +112,12 @@ int euler312_quat( } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_321.c b/trick_source/trick_utils/math/src/deuler_321.c index 2b7263d6..ed853341 100644 --- a/trick_source/trick_utils/math/src/deuler_321.c +++ b/trick_source/trick_utils/math/src/deuler_321.c @@ -120,13 +120,12 @@ int euler321( } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/math/src/deuler_321_quat.c b/trick_source/trick_utils/math/src/deuler_321_quat.c index c1d295dc..7fdb9613 100644 --- a/trick_source/trick_utils/math/src/deuler_321_quat.c +++ b/trick_source/trick_utils/math/src/deuler_321_quat.c @@ -112,13 +112,12 @@ int euler321_quat( } /* Error: Out of normal range & beyond tolerance for asin func*/ else { - double zero = 0.0; ret = TM_ANG_NAN; if ( error_flag[4] == 0 ) { tm_print_error(ret); error_flag[4]=1; } - angle[0] = angle[1] = angle[2] = 0.0 / zero; + angle[0] = angle[1] = angle[2] = NAN; } #undef TOLERANCE } else if (method == 2) { diff --git a/trick_source/trick_utils/unicode/Makefile b/trick_source/trick_utils/unicode/Makefile new file mode 100644 index 00000000..a181cedf --- /dev/null +++ b/trick_source/trick_utils/unicode/Makefile @@ -0,0 +1,5 @@ + +include ${TRICK_HOME}/share/trick/makefiles/Makefile.common +include ${TRICK_HOME}/share/trick/makefiles/Makefile.tricklib +-include Makefile_deps + diff --git a/trick_source/trick_utils/unicode/src/unicode_utils.c b/trick_source/trick_utils/unicode/src/unicode_utils.c new file mode 100644 index 00000000..e2229bef --- /dev/null +++ b/trick_source/trick_utils/unicode/src/unicode_utils.c @@ -0,0 +1,437 @@ +#include +#include +#include +#include +#include +#include +#include "trick/unicode_utils.h" + +/* Maintainer: John M. Penn */ + +size_t ucodepoint_to_utf32(unsigned int codePoint, int32_t *out) { + + if (codePoint < 0xd800 || codePoint >= 0xe000) { /* Not Surrogate */ + *out = (int32_t)codePoint; + return 1; + } else { + fprintf(stderr,"%s:ERROR: 0x%08x is reserved for UTF-16, as a surrogate codepoint.\n", __FUNCTION__, codePoint); + } + return 0; +} + +size_t ucodepoint_to_utf16(unsigned int codePoint, int16_t (*out)[2]) { + + if (codePoint > 0x10ffff) { + fprintf(stderr,"%s:ERROR: Invalid Unicode value (too big): 0x%04x.\n", __FUNCTION__, codePoint); + return 0; + } else if (codePoint > 0xffff) { + /* High-surrogate code points are in the range U+D800–U+DBFF. + * Low-surrogate code points are in the range U+DC00–U+DFFF. + * A high-surrogate code point followed by a low-surrogate code point form a + * surrogate pair in UTF-16 to represent code points greater than U+FFFF. + */ + (*out)[0] = (int16_t)(0xd800 + (codePoint >> 10)); /* Create High Surrogate */ + (*out)[1] = (int16_t)(0xdc00 + (codePoint & 0x03ff)); /* Create Low Surrogate */ + return 2; + } else if (codePoint < 0xd800 || codePoint >= 0xe000) { /* Not Surrogate */ + (*out)[0] = (int16_t)(codePoint); + return 1; + } else { + fprintf(stderr,"%s:ERROR: Invalid Unicode value (surrogate): 0x%04x.\n", __FUNCTION__, codePoint); + } + return 0; +} + +size_t ucodepoint_to_utf8(unsigned int codePoint, char (*out)[4]) { + + if (codePoint <= 0x7f) { /* ASCII */ + (*out)[0] = (char)codePoint; /* 0xxxxxxx 0x00..0x7F*/ + return 1; + + } else if (codePoint <= 0x7ff) { /* Two-byte Sequence */ + (*out)[0] = (char)(0xc0 | ((codePoint >> 6) & 0x1f)); /* 110xxxxx 0xC0..0xDF*/ + (*out)[1] = (char)(0x80 | (codePoint & 0x3f)); /* 10xxxxxx */ + return 2; + + } else if (codePoint <= 0xffff) { /* Three byte Sequence */ + (*out)[0] = (char)(0xe0 | ((codePoint >> 12) & 0x0f)); /* 1110xxxx 0xE0..0xEF*/ + (*out)[1] = (char)(0x80 | ((codePoint >> 6) & 0x3f)); /* 10xxxxxx */ + (*out)[2] = (char)(0x80 | (codePoint & 0x3f)); /* 10xxxxxx */ + return 3; + + } else { /* Four-byte Sequence */ + (*out)[0] = (char)(0xf0 | ((codePoint >> 18) & 0x07)); /* 11110xxx 0xF0..0xF7*/ + (*out)[1] = (char)(0x80 | ((codePoint >> 12) & 0x3f)); /* 10xxxxxx */ + (*out)[2] = (char)(0x80 | ((codePoint >> 6) & 0x3f)); /* 10xxxxxx */ + (*out)[3] = (char)(0x80 | (codePoint & 0x3f)); /* 10xxxxxx 0x80..0xBF */ + return 4; + } + return 0; +} + +size_t utf8_to_printable_ascii(const char *in, char *out, size_t outSize) { + + int state = 0; + unsigned int codePoint; + char wks[11]; + + if (out == NULL) { + fprintf(stderr,"%s:ERROR: ASCII char pointer (out) is NULL. No conversion performed.\n", __FUNCTION__); + return 0; + } + out[0] = 0; + + if (in == NULL) { + fprintf(stderr,"%s:ERROR: UTF8 char-pointer (in) is NULL. No conversion performed.\n", __FUNCTION__); + return 0; + } + + while (*in != 0) { + unsigned char ch = *in; + switch (state) { + case 0: { + if (ch >= 0xf0) { // Start of a 4-byte sequence. + codePoint = ch & 0x07; // Extract low 3 bits + state = 3; + } else if (ch >= 0xe0) { // Start of a 3-byte sequence. + codePoint = ch & 0x0f; // Extract low 4 bits + state = 2; + } else if (ch >= 0xc0) { // Start of a 2-byte sequence. + codePoint = ch & 0x1f; // Extract low 5 bits + state = 1; + } else if (ch >= 0x80) { // We should never find a continuation byte in isolation. + fprintf(stderr,"%s:ERROR: UTF8 string (in) appears to be corrupted.\n", __FUNCTION__); + state = 99; + } else { // ASCII + if (ch == '\a') { + sprintf(wks,"\\a"); + } else if (ch == '\b') { + sprintf(wks,"\\b"); + } else if (ch == '\f') { + sprintf(wks,"\\f"); + } else if (ch == '\n') { + sprintf(wks,"\\n"); + } else if (ch == '\r') { + sprintf(wks,"\\r"); + } else if (ch == '\t') { + sprintf(wks,"\\t"); + } else if (ch == '\v') { + sprintf(wks,"\\v"); + } else if (isprint(ch)) { + sprintf(wks,"%c",ch); + } else { + sprintf(wks,"\\x%02x",ch); + } + if ((strlen(out)+strlen(wks)) < outSize-1) { + strcat(out, wks); + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in (out) array.\n", __FUNCTION__); + state = 99; + } + } + } break; + case 1: { // Expecting one continuation byte. + if ((ch & 0xc0) == 0x80) { // If the next char is a continuation byte .. + codePoint = (codePoint << 6) | (ch & 0x3f); // Extract low 6 bits + state = 0; + + if (codePoint <= 0xffff) { + sprintf(wks,"\\u%04x", codePoint); + } else { + sprintf(wks,"\\U%08x", codePoint); + } + if ((strlen(out)+strlen(wks)) < outSize-1) { + strcat(out, wks); + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in (out) array.\n", __FUNCTION__); + state = 99; + } + + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + case 2: { /* Expecting two continuation bytes. */ + if ((ch & 0xc0) == 0x80) { + codePoint = (codePoint << 6) | (ch & 0x3f); + state = 1; + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + case 3: { /* Expecting three continuation bytes. */ + if ((ch & 0xc0) == 0x80) { + codePoint = (codePoint << 6) | (ch & 0x3f); + state = 2; + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + default: { + out[0] = 0; + return 0; + } break; + } + in ++; + } + + /* If we finished in state 0, then we're good. Just + terminate the string, otherwise we had an error. */ + if (state == 0) { + return strlen(out); + } else { + out[0] = 0; + return 0; + } +} + +/* Un-escapes ASCII and Unicode escape sequences, and encodes them into UTF-8. */ +size_t ascii_to_utf8(const char *in, char *out, size_t outSize) { + + unsigned int codePoint = 0; + size_t len = 0; + int state = 0; + int digitsExpected = 0; + + if (out == NULL) { + fprintf(stderr,"%s:ERROR: ASCII char pointer (out) is NULL. No conversion performed.\n", __FUNCTION__); + return 0; + } + out[0] = 0; + + if (in == NULL) { + fprintf(stderr,"%s:ERROR: UTF8 char-pointer (in) is NULL. No conversion performed.\n", __FUNCTION__); + return 0; + } + + while (*in != 0) { + unsigned char ch = *in; + if (ch > 0x7f) { /* All input characters must be ASCII. */ + fprintf(stderr,"%s:ERROR: ASCII string (in) contains non-ASCII values.\n", __FUNCTION__); + out[0] = 0; + return 0; + } + /* All escaped characters will be un-escaped. */ + switch(state) { + case 0: { // Normal State + if (ch =='\\') { + state = 1; + } else { + out[len++] = ch; + } + } break; + case 1: { // Escaped State ( that is: we've found a '\' character.) + switch(ch) { + case '\'': + case '\"': + case '\?': + case '\\': { + out[len++] = ch; state = 0; + } break; + + case 'a': { out[len++] = '\a'; state = 0; } break; + case 'b': { out[len++] = '\b'; state = 0; } break; + case 'f': { out[len++] = '\f'; state = 0; } break; + case 'n': { out[len++] = '\n'; state = 0; } break; + case 'r': { out[len++] = '\r'; state = 0; } break; + case 't': { out[len++] = '\t'; state = 0; } break; + case 'v': { out[len++] = '\b'; state = 0; } break; + case 'x': { digitsExpected = 2; state = 2; } break; + case 'u': { digitsExpected = 4; state = 2; } break; + case 'U': { digitsExpected = 8; state = 2; } break; + default : { + } + } // switch ch + } break; + case 2: { // Escaped Unicode ( that is: we've found '\x', '\u' or '\U'.) + int digit = 0; + if (ch >= '0' && ch <= '9') { + digit = ch - (int)'0'; + } else if (ch >= 'A' && ch <= 'F') { + digit = ch - (int)'A' + 10; + } else if (ch >= 'a' && ch <= 'f') { + digit = ch - (int)'a' + 10; + } else { + fprintf(stderr,"%s:ERROR: Insufficient hexidecimal digits following" + " \\x, \\u, or \\U escape code in char string (in).\n", __FUNCTION__); + out[0] = 0; + return 0; + } + codePoint = codePoint * 16 + digit; + digitsExpected -- ; + if ( digitsExpected == 0 ) { + char temp[4]; + size_t count = ucodepoint_to_utf8(codePoint, &temp); + if (count < (outSize-len)) { + memcpy( &out[len], temp, sizeof(char) * count ); + len += count; + state = 0; + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in char array (out).\n", __FUNCTION__); + out[0] = 0; + return 0; + } + codePoint = 0; + } + } break; + default: { + out[0] = 0; + return 0; + } break; + } + in ++; + } + out[len] = 0; /* NULL termination of string. */ + return len; +} + +size_t utf8_to_wchar(const char *in, wchar_t *out, size_t outSize) { + + unsigned int codePoint = 0; + size_t len = 0; + int state = 0; + + while (*in != 0) { + unsigned char ch = *in; + switch (state) { + case 0: { + if (ch >= 0xf0) { // Start of a 4-byte sequence. + codePoint = ch & 0x07; // Extract low 3 bits + state = 3; + } else if (ch >= 0xe0) { // Start of a 3-byte sequence. + codePoint = ch & 0x0f; // Extract low 4 bits + state = 2; + } else if (ch >= 0xc0) { // Start of a 2-byte sequence. + codePoint = ch & 0x1f; // Extract low 5 bits + state = 1; + } else if (ch >= 0x80) { // We should never find a continuation byte in isolation. + fprintf(stderr,"%s:ERROR: UTF8 string (in) appears to be corrupted.\n", __FUNCTION__); + state = 99; + } else { + codePoint = ch; // ASCII + if ((outSize-len) > 1) { + out[len++] = (wchar_t)codePoint; + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in wchar_t array (out).\n", __FUNCTION__); + state = 99; + } + } + } break; + case 1: { // Expecting one continuation byte. + if ((ch & 0xc0) == 0x80) { // If the next char is a continuation byte .. + codePoint = (codePoint << 6) | (ch & 0x3f); // Extract lower 6 bits + state = 0; + + if (sizeof(wchar_t) == 4) { // wchar_t is UTF-32 + int32_t temp; + if ( ucodepoint_to_utf32(codePoint, &temp) > 0) { + if ((outSize-len) > 1) { + out[len++] = (wchar_t)temp; + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in wchar_t array (out).\n", __FUNCTION__); + state = 99; + } + } else { + state = 99; + } + + } else if (sizeof(wchar_t) == 2) { // wchar_t is UTF-16 + int16_t temp[2]; + size_t count; + if (( count = ucodepoint_to_utf16(codePoint, &temp)) > 0) { + if (count < (outSize-len)) { + memcpy( &out[len], temp, sizeof(int16_t) * count ); + len += count; + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in wchar_t array (out).\n", __FUNCTION__); + state = 99; + } + } + + } else { + fprintf(stderr,"%s:ERROR: Unsupported wchar_t size.\n", __FUNCTION__); + state = 99; + } + + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + case 2: { /* Expecting two continuation bytes. */ + if ((ch & 0xc0) == 0x80) { + codePoint = (codePoint << 6) | (ch & 0x3f); + state = 1; + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + case 3: { /* Expecting three continuation bytes. */ + if ((ch & 0xc0) == 0x80) { + codePoint = (codePoint << 6) | (ch & 0x3f); + state = 2; + } else { + fprintf(stderr,"%s:ERROR: UTF8 string appears to be corrupted.\n", __FUNCTION__); + state = 99; + } + } break; + default: { /* Error State. */ + out[0] = 0; + return 0; + } break; + } + in ++; + } + + /* If we finished in state 0, then we're good. Just + terminate the string, otherwise we had an error. */ + if (state == 0) { + out[len] = 0; + return len; + } else { + out[0] = 0; + return 0; + } + return len; +} + +size_t wchar_to_utf8(const wchar_t *in, char *out, size_t outSize ) { + + unsigned int codePoint = 0; + size_t len = 0; + + while ( *in != 0 ) { + if (*in >= 0xd800 && *in <= 0xdbff) /* If High-surrogate. */ + codePoint = ((*in - 0xd800) << 10) + 0x10000; + else { + if (*in >= 0xdc00 && *in <= 0xdfff) { /* If Low-surrogate. */ + codePoint |= *in - 0xdc00; + } else if (*in <= 0x10ffff) { /* Max Unicode Value */ + codePoint = *in; + } else { + fprintf(stderr,"%s:ERROR: Invalid Unicode value.\n", __FUNCTION__); + out[0] = 0; + return 0; + } + + char temp[4]; + size_t count = ucodepoint_to_utf8(codePoint, &temp); + if (count < (outSize-len)) { + memcpy( &out[len], temp, sizeof(char) * count ); + len += count; + } else { + fprintf(stderr,"%s:ERROR: Insufficient room in char array (out).\n", __FUNCTION__); + out[0] = 0; + return 0; + } + codePoint = 0; + } + in++; + } + out[len] = L'\0'; /* NULL termination of string. */ + return len; +} diff --git a/trick_source/trick_utils/unicode/test/Makefile b/trick_source/trick_utils/unicode/test/Makefile new file mode 100644 index 00000000..a517ce5a --- /dev/null +++ b/trick_source/trick_utils/unicode/test/Makefile @@ -0,0 +1,41 @@ + +#SYNOPSIS: +# +# make [all] - makes everything. +# make TARGET - makes the given target. +# make clean - removes all files generated by make. + +include ${TRICK_HOME}/share/trick/makefiles/Makefile.common + +# Flags passed to the preprocessor. +TRICK_CPPFLAGS += -I$(GTEST_HOME)/include -I$(TRICK_HOME)/include -g -Wall -Wextra -DGTEST_HAS_TR1_TUPLE=0 + +TRICK_LIBS = ${TRICK_LIB_DIR}/libtrick.a +TRICK_EXEC_LINK_LIBS += -L${GTEST_HOME}/lib64 -L${GTEST_HOME}/lib -lgtest -lgtest_main -lpthread + +# Added for Ubuntu... not required for other systems. +TRICK_EXEC_LINK_LIBS += -lpthread + +# All tests produced by this Makefile. Remember to add new tests you +# created to the list. +TESTS = unicode_utils_test + +OTHER_OBJECTS = + +# House-keeping build targets. + +all : $(TESTS) + +test: $(TESTS) + ./unicode_utils_test --gtest_output=xml:${TRICK_HOME}/trick_test/Unicode_utils.xml + +clean : + rm -f $(TESTS) *.o + rm -rf io_src xml + +unicode_utils_test.o : unicode_utils_test.cpp + $(TRICK_CPPC) $(TRICK_CPPFLAGS) -c $< + +unicode_utils_test : unicode_utils_test.o + $(TRICK_CPPC) $(TRICK_CPPFLAGS) -o $@ $^ $(OTHER_OBJECTS) -L${TRICK_HOME}/lib_${TRICK_HOST_CPU} $(TRICK_LIBS) $(TRICK_EXEC_LINK_LIBS) + diff --git a/trick_source/trick_utils/unicode/test/unicode_utils_test.cpp b/trick_source/trick_utils/unicode/test/unicode_utils_test.cpp new file mode 100644 index 00000000..a2875e86 --- /dev/null +++ b/trick_source/trick_utils/unicode/test/unicode_utils_test.cpp @@ -0,0 +1,406 @@ +#include +#include +#include +#include +#include +#include "trick/unicode_utils.h" + +const char* ISO_6429_Restore_Default = "\x1b[00m"; +const char* ISO_6429_Bold = "\x1b[01m"; +const char* ISO_6429_Underline = "\x1b[04m"; +const char* ISO_6429_Black_Foreground = "\x1b[30m"; +const char* ISO_6429_Red_Foreground = "\x1b[31m"; +const char* ISO_6429_Green_Foreground = "\x1b[32m"; +const char* ISO_6429_Yellow_Foreground = "\x1b[33m"; +const char* ISO_6429_Blue_Foreground = "\x1b[34m"; +const char* ISO_6429_Purple_Foreground = "\x1b[35m"; +const char* ISO_6429_Cyan_Foreground = "\x1b[36m"; +const char* ISO_6429_White_Foreground = "\x1b[37m"; +const char* ISO_6429_Black_Background = "\x1b[40m"; +const char* ISO_6429_Red_Background = "\x1b[41m"; +const char* ISO_6429_Green_Background = "\x1b[42m"; +const char* ISO_6429_Yellow_Background = "\x1b[43m"; +const char* ISO_6429_Blue_Background = "\x1b[44m"; +const char* ISO_6429_Purple_Background = "\x1b[45m"; +const char* ISO_6429_Cyan_Background = "\x1b[46m"; +const char* ISO_6429_White_Background = "\x1b[47m"; + +void Error_Message_Expected() { + printf("%s%s%s", ISO_6429_Blue_Background, ISO_6429_White_Foreground, ISO_6429_Underline); + printf("An error message is expected from this test."); + printf("%s\n", ISO_6429_Restore_Default ); +} + +// ------------------------------------------------------- +// Test suite for ucodepoint_to_utf32() +// ------------------------------------------------------- +TEST(ucodepoint_to_utf32, valid ) { + /* Aegean Number Ten, U+10110 is a valid code point. */ + int32_t out; + size_t size = ucodepoint_to_utf32(0x10110, &out); + EXPECT_EQ(1, size); +} + +TEST(ucodepoint_to_utf32, invalid ) { + /* 0xdead is in the range [d800 .. dfff], and reserved for UTF-16 + surrogates. They are not valid unicode codepoints. So, if we + attempt to convert a surrogate as a codepoint, we should get + an error meassage. + */ + int32_t out; + Error_Message_Expected(); + size_t size = ucodepoint_to_utf32(0xdead, &out); + EXPECT_EQ(0, size); +} + +// ------------------------------------------------------- +// Test suite for ucodepoint_to_utf16() +// ------------------------------------------------------- +TEST(ucodepoint_to_utf16, two_16bit_element_sequence ) { + /* Note that unicode is a 21-bit encoding. + Because Aegean Number Ten (U+10110) is larger than can be stored in 16-bits, + UTF-16 requires two 16-bit values, called surrogates to encode it. + The high-surrogate "carries" the most significant 11 bits of the codepoint. + High-surrogate = 0xd800 + most significant 11 bits of the codepoint. + The low-surrogate carries the least significant 10 bits of the codepoint. + Low-surrogate = 0xde00 + least significant 10 bits of the codepoint. + */ + int16_t out[2]; + size_t size = ucodepoint_to_utf16(0x10110, &out); + EXPECT_EQ(2, size); + EXPECT_EQ((int16_t)0xd840, out[0]); + EXPECT_EQ((int16_t)0xdd10, out[1]); +} + +TEST(ucodepoint_to_utf16, one_16bit_element) { + int16_t out[2]; + /* A valid codepoint that can be stored within 16-bits should be + equal to its UTF-16 character value. */ + size_t size = ucodepoint_to_utf16(0x03d5, &out); + EXPECT_EQ(1, size); + EXPECT_EQ((int16_t)0x03d5, out[0]); +} + +TEST(ucodepoint_to_utf16, invalid_surrogate ) { + /* Input codepoint can not be a surrogate. */ + int16_t out[2]; + Error_Message_Expected(); + size_t size = ucodepoint_to_utf16(0xdead, &out); + EXPECT_EQ(0, size); +} + +TEST(ucodepoint_to_utf16, codepoint_too_big ) { + /* Input codepoint can not be > 0x10ffff, which is the largest valid unicode codepoint. */ + int16_t out[2]; + Error_Message_Expected(); + size_t size = ucodepoint_to_utf16(0x110000, &out); + EXPECT_EQ(0, size); +} + +// ------------------------------------------------------- +// Test suite for ucodepoint_to_utf8() +// ------------------------------------------------------- +TEST(ucodepoint_to_utf8, four_8bit_element_sequence ) { + char out[4]; + /* Aegean Number Ten, U+10110 is a valid codepoint that + requires four bytes to encode in utf-8. */ + size_t size = ucodepoint_to_utf8(0x10110, &out); + EXPECT_EQ(4, size); +} + +TEST(ucodepoint_to_utf8, three_8bit_element_sequence ) { + char out[4]; + /* Superscript Latin Small Letter I, U+2071 is a valid + codepoint that requires three bytes to encode in utf-8. */ + size_t size = ucodepoint_to_utf8(0x2071, &out); + EXPECT_EQ(3, size); +} + +TEST(ucodepoint_to_utf8, two_8bit_element_sequence ) { + char out[4]; + /* Greek Phi Symbol, U+03d5 is a valid codepoint that + requires two bytes to encode in utf-8. */ + size_t size = ucodepoint_to_utf8(0x03d5, &out); + EXPECT_EQ(2, size); +} + +TEST(ucodepoint_to_utf8, ascii ) { + char out[4]; + /* Latin Small Letter A, U+0061 is a valid codepoint that + requires one byte to encode in utf-8. Below 0x7f, Unicode + and ASCII are identical. */ + size_t size = ucodepoint_to_utf8('a', &out); + EXPECT_EQ(1, size); +} + +// ------------------------------------------------------- +// Test suite for utf8_to_printable_ascii() +// ------------------------------------------------------- +TEST(utf8_to_printable_ascii, null_input ) { + /* Should generate error message if input character pointer is NULL. */ + char resultant_ascii_s[128]; + char* null_ptr = (char*)0; + Error_Message_Expected(); + size_t size = utf8_to_printable_ascii( null_ptr, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(0, size); +} + +TEST(utf8_to_printable_ascii, null_output ) { + /* Should generate error message if output character pointer is NULL. */ + char* null_ptr = (char*)0; + const char* input = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)"; + Error_Message_Expected(); + size_t size = utf8_to_printable_ascii( input, null_ptr, size_t(5)); + EXPECT_EQ(0, size); +} + +TEST(utf8_to_printable_ascii, normal_1 ) { + char resultant_ascii_s[128]; + /* utf8_to_printable_ascii() should escape all Unicode and non-printable ASCII characters. */ + const char* utf8_s = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)\n"; + const char* expected_ascii_s = "e\\u2071\\u1d60 = cos(\\u03d5) + i*sin(\\u03d5)\\n"; + (void) utf8_to_printable_ascii( utf8_s, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_STREQ(expected_ascii_s, resultant_ascii_s); +} + +TEST(utf8_to_printable_ascii, normal_2 ) { + char resultant_ascii_s[256]; + /* utf8_to_printable_ascii() should escape all Unicode and non-printable ASCII characters. */ + const char ascii[128] = { '\x01','\x02','\x03','\x04','\x05','\x06','\x07','\x08','\x09','\x0a','\x0b','\x0c','\x0d','\x0e','\x0f', + '\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1d','\x1e','\x1f', + '\x20','\x21','\x22','\x23','\x24','\x25','\x26','\x27','\x28','\x29','\x2a','\x2b','\x2c','\x2d','\x2e','\x2f', + '\x30','\x31','\x32','\x33','\x34','\x35','\x36','\x37','\x38','\x39','\x3a','\x3b','\x3c','\x3d','\x3e','\x3f', + '\x40','\x41','\x42','\x43','\x44','\x45','\x46','\x47','\x48','\x49','\x4a','\x4b','\x4c','\x4d','\x4e','\x4f', + '\x50','\x51','\x52','\x53','\x54','\x55','\x56','\x57','\x58','\x59','\x5a','\x5b','\x5c','\x5d','\x5e','\x5f', + '\x60','\x61','\x62','\x63','\x64','\x65','\x66','\x67','\x68','\x69','\x6a','\x6b','\x6c','\x6d','\x6e','\x6f', + '\x70','\x71','\x72','\x73','\x74','\x75','\x76','\x77','\x78','\x79','\x7a','\x7b','\x7c','\x7d','\x7e','\x7f', + '\x00' + }; + + const char* expected_ascii_s = "\\x01\\x02\\x03\\x04\\x05\\x06\\a\\b\\t\\n\\v\\f" + "\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f" + " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"; + + size_t size = utf8_to_printable_ascii( ascii, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(209, size); + EXPECT_STREQ(expected_ascii_s, resultant_ascii_s); +} + +/* The following are the utf-8 encodings of four unicode characters used in the following tests. */ +// Greek Phi Symbol => U+03d5 => 0xcf 0x95 // see: https://www.compart.com/en/unicode/U+03D5 +// Superscript Latin Small Letter I => U+2071 => 0xe2 0x81 0xb1 // see: https://www.compart.com/en/unicode/U+2071 +// Modifier Letter Small Greek Phi => U+1D60 => 0xe1 0xb5 0xa0 // see: https://www.compart.com/en/unicode/U+1D60 +// Aegean Number Ten => U+10110 => 0xf0 0x90 0x84 0x90 // see: https://www.compart.com/en/unicode/U+10110 + +TEST(utf8_to_printable_ascii, demotest ) { + char resultant_ascii_s[128]; + + const char utf8_s[11] = {'P','h','i',' ','=',' ','\xcf','\x95','\0'}; + const char* expected_ascii_s = "Phi = \\u03d5"; + (void) utf8_to_printable_ascii( utf8_s, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_STREQ(expected_ascii_s, resultant_ascii_s); +} + +TEST(utf8_to_printable_ascii, detect_corruption_1 ) { + char resultant_ascii_s[128]; + /* The following string is deliberately corrupted with a spurious + continuation character (in corrupted_utf8_s[6]).*/ + const char corrupted_utf8_s[11] = {'P','h','i',' ','=',' ','\x80','\x95','\0'}; + Error_Message_Expected(); + size_t size = utf8_to_printable_ascii( corrupted_utf8_s, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(0, size); +} + +TEST(utf8_to_printable_ascii, detect_corruption_2 ) { + char resultant_ascii_s[128]; + /* The following string is deliberately corrupted: 0xcf is a header + for a two-byte sequence, it should be followed by a continuation + byte (most significant 2 bits are 10). 0x75 starts with 01 */ + const char corrupted_utf8_s[11] = {'P','h','i',' ','=',' ','\xcf','\x75','\0'}; + Error_Message_Expected(); + size_t size = utf8_to_printable_ascii( corrupted_utf8_s, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(0, size); +} + +TEST(utf8_to_printable_ascii, insufficient_result_array_size ) { + /* The result array must be of sufficient size. Here it is not. */ + char resultant_ascii_s[16]; + const char* utf8_s = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)\n"; + Error_Message_Expected(); + size_t size = utf8_to_printable_ascii( utf8_s, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(0, size); +} + +// ------------------------------------------------------- +// Test suite for ascii_to_utf8() +// ------------------------------------------------------- + +TEST(ascii_to_utf8, null_input ) { + /* Should generate error message if input character pointer is NULL. */ + char resultant_ascii_s[128]; + char* null_ptr = (char*)0; + Error_Message_Expected(); + size_t size = ascii_to_utf8( null_ptr, resultant_ascii_s, sizeof(resultant_ascii_s)); + EXPECT_EQ(0, size); +} + +TEST(ascii_to_utf8, null_output ) { + /* Should generate error message if output character pointer is NULL. */ + char* null_ptr = (char*)0; + const char* input = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)"; + + Error_Message_Expected(); + size_t size = ascii_to_utf8( input, null_ptr, size_t(5)); + EXPECT_EQ(0, size); +} + +TEST(ascii_to_utf8, normal_1) { + /* ascii_to_utf8() should un-escape all escaped ASCII and escaped unicode. + */ + char actual_output[256]; + const char* input = "e\\u2071\\u1d60 = cos(\\u03d5) + i*sin(\\u03d5)\\n"; + const char* expected_output = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)\n"; + + size_t size = ascii_to_utf8(input, actual_output, sizeof(actual_output)); + EXPECT_EQ(30, size); + EXPECT_STREQ(expected_output, actual_output); +} + +TEST(ascii_to_utf8, non_ascii_chars) { + char actual_output[256]; + /* The input string should only contain ASCII characters, that is, + each element should have a value < 128. That isn't the case in the + following string. Therefore, an error message should be emitted. + */ + const char* input = "eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + Error_Message_Expected(); + size_t size = ascii_to_utf8(input, actual_output, sizeof(actual_output)); + EXPECT_EQ(0, size); +} + +TEST(ascii_to_utf8, insufficient_hex_digits_1) { + /* The \U escape code expects exactly 8 hexidecimal digits to follow. + If fewer than 8 are present, then an error message should result. + Note: "\U10110" will fail in a C/C++ literal at compile time too, + because it is incomplete. It should be "\U00010110". + */ + char actual_output[256]; + const char* input = "Aegean Number Ten = \\U10110\n"; + + Error_Message_Expected(); + size_t size = ascii_to_utf8(input, actual_output, sizeof(actual_output)); + EXPECT_EQ(0, size); +} + +TEST(ascii_to_utf8, insufficient_hex_digits_2) { + /* The \u escape code expects exactly 4 hexidecimal digits to follow. + If fewer than 4 are present, then an error message should result. + Note: "\u3d5" will fail in a C/C++ literal at compile time too, + because it is incomplete. It should be "\u03d5". + */ + char actual_output[256]; + const char* input = "Phi = \\u3d5\n"; + + Error_Message_Expected(); + size_t size = ascii_to_utf8(input, actual_output, sizeof(actual_output)); + EXPECT_EQ(0, size); +} + +TEST(ascii_to_utf8, insufficient_result_array_size) { + /* The result array must be of sufficient size. If it isn't, then an error + message should be emitted. + */ + char actual_output[16]; + const char* input = "e\\u2071\\u1d60 = cos(\\u03d5) + i*sin(\\u03d5)\\n"; + + Error_Message_Expected(); + size_t size = ascii_to_utf8(input, actual_output, sizeof(actual_output)); + EXPECT_EQ(0, size); +} + +// ------------------------------------------------------- +// Test suite for utf8_to_wchar() +// ------------------------------------------------------- + +/* The following three tests demonstrate three different ways to + create the same input string. */ + +TEST(utf8_to_wchar, test1) { + wchar_t resultant_wchar_s[128]; + const char* input = "eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + const wchar_t* expected_wide_s = L"eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + (void) utf8_to_wchar(input, resultant_wchar_s, sizeof(resultant_wchar_s)/sizeof(wchar_t)); + bool test_result = (wcscmp(expected_wide_s, expected_wide_s) == 0); + EXPECT_EQ(true, test_result); +} + +TEST(utf8_to_wchar, test2) { + wchar_t resultant_wchar_s[128]; + const char* input = "e\u2071\u1d60 = cos(\u03d5) + i*sin(\u03d5)"; + const wchar_t* expected_wide_s = L"eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + (void) utf8_to_wchar(input, resultant_wchar_s, sizeof(resultant_wchar_s)/sizeof(wchar_t)); + bool test_result = (wcscmp(expected_wide_s, expected_wide_s) == 0); + EXPECT_EQ(true, test_result); +} + +TEST(utf8_to_wchar, test3) { + wchar_t resultant_wchar_s[128]; + const char input[30] = {'e','\xe2','\x81','\xb1','\xe1', '\xb5','\xa0',' ','=',' ', + 'c','o','s','(','\xcf','\x95',')',' ','+',' ','i','*','s', + 'i','n','(','\xcf','\x95',')','\0'}; + const wchar_t* expected_wide_s = L"eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + (void) utf8_to_wchar(input, resultant_wchar_s, sizeof(resultant_wchar_s)/sizeof(wchar_t)); + bool test_result = (wcscmp(expected_wide_s, expected_wide_s) == 0); + EXPECT_EQ(true, test_result); +} + +TEST(utf8_to_wchar, insufficient_result_array_size) { + wchar_t resultant_wchar_s[16]; + const char* input = "eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + Error_Message_Expected(); + size_t size = utf8_to_wchar(input, resultant_wchar_s, sizeof(resultant_wchar_s)/sizeof(wchar_t)); + EXPECT_EQ(0, size); +} + +TEST(utf8_to_wchar, corrupted_input) { + wchar_t resultant_wchar_s[128]; + char input[30] = {'e','\xe2','\x81','\xb1','\xe1', '\xb5','\xa0',' ','=',' ', + 'c','o','s','(','\xcf','\x95',')',' ','+',' ','i','*','s', + 'i','n','(','\xcf','\x95',')','\0'}; + + /* Deliberately corrupt input by changing input[2] to not being a continuation byte. */ + input[2] = 0x70; + + Error_Message_Expected(); + size_t size = utf8_to_wchar(input, resultant_wchar_s, sizeof(resultant_wchar_s)/sizeof(wchar_t)); + EXPECT_EQ(0, size); +} + +// ------------------------------------------------------- +// Test suite for wchar_to_utf8() +// ------------------------------------------------------- +TEST(wchar_to_utf8, test1) { + + char resultant_utf8_s[128]; + const wchar_t* wide_s = L"eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + const char* expected_utf8_s = "eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + wchar_to_utf8(wide_s, resultant_utf8_s, sizeof(resultant_utf8_s)/sizeof(char)); + bool test_result = (strcmp(expected_utf8_s, resultant_utf8_s) == 0); + EXPECT_EQ(true, test_result); +} + +TEST(wchar_to_utf8, insufficient_result_array_size) { + + char resultant_utf8_s[16]; + const wchar_t* wide_s = L"eⁱᵠ = cos(ϕ) + i*sin(ϕ)"; + + Error_Message_Expected(); + size_t size = wchar_to_utf8(wide_s, resultant_utf8_s, sizeof(resultant_utf8_s)/sizeof(char)); + EXPECT_EQ(0, size); +}