1 /* 2 Qalculate 3 4 Copyright (C) 2003-2007, 2008, 2016-2018 Hanna Knutsson (hanna.knutsson@protonmail.com) 5 6 This program is free software; you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation; either version 2 of the License, or 9 (at your option) any later version. 10 */ 11 12 #ifndef CALCULATOR_H 13 #define CALCULATOR_H 14 15 #include <libqalculate/includes.h> 16 #include <libqalculate/util.h> 17 #include <sys/time.h> 18 19 /** @file */ 20 21 /** \mainpage Index 22 * 23 * \section intro_sec Introduction 24 * 25 * libqalculate is math libary for expression evaluation with units, variables and functions support and CAS functionality. 26 * 27 * The main parts of the library is the almighty Calculator class, the MathStructure class for mathematical expressions and classes for objects in an expression, 28 * mostly of the class Numbers and sub classes of ExpressionItem. 29 * 30 * A simple application using libqalculate need only create a calculator object, perhaps load definitions (functions, variables, units, etc.), and calculate (and output) an expression as follows: 31 * \code 32 * new Calculator(); 33 * CALCULATOR->loadExchangeRates(); 34 * CALCULATOR->loadGlobalDefinitions(); 35 * CALCULATOR->loadLocalDefinitions(); 36 * cout << CALCULATOR->calculateAndPrint("1 + 1", 2000) << endl;\endcode 37 * In the above example, the calculation is terminated after two seconds (2000 ms), if it is not finished before then. 38 * Applications using localized numbers should first call Calculalor::unlocalizeExpression() on the expression. 39 * 40 * A less simple application might calculate and output the expression separately. 41 * \code 42 * EvaluationOptions eo; 43 * MathStructure result; 44 * CALCULATOR->calculate(&mstruct, unlocalizeExpression("1 + 1"), 2000, eo);\endcode 45 * 46 * More complex usage mainly involves manipulating objects of the MathStructure class directly. 47 * 48 * To display the resulting expression use Calculator::print() as follows: 49 * \code 50 * PrintOptions po; 51 * string result_str = CALCULATOR->print(result, 2000, po);\endcode 52 * Alternatively MathStructure::format() followed by MathStructure::print() can be used, whithout the possiblity to specify a time limit. 53 * 54 * Central to the flexiblity of libqalculate is the many options passed to evaluating and display functions with EvaluationOptions and PrintOptions. 55 * 56 * \section usage_sec Using the library 57 * 58 * libqalculate uses pkg-config. 59 * 60 * For a simple program use pkg-config on the command line: 61 * \code c++ `pkg-config --cflags --libs libqalculate` hello.c -o hello \endcode 62 * 63 * If the program uses autoconf, put the following in configure.ac: 64 * \code PKG_CHECK_MODULES(QALCULATE, [ 65 * libqalculate >= 1.0.0 66 * ]) 67 * AC_SUBST(QALCULATE_CFLAGS) 68 * AC_SUBST(QALCULATE_LIBS) \endcode 69 */ 70 71 typedef std::vector<Prefix*> p_type; 72 73 /// Parameters passed to plotting functions. 74 struct PlotParameters { 75 /// Title label. 76 std::string title; 77 /// Y-axis label. 78 std::string y_label; 79 /// X-axis label. 80 std::string x_label; 81 /// Image to save plot to. If empty shows plot in a window on the screen. 82 std::string filename; 83 /// The image type to save as. Set to PLOT_FILETYPE_AUTO to guess from file extension. 84 PlotFileType filetype; 85 /// Font used for text 86 std::string font; 87 /// Set to true for colored plot, false for monochrome. Default: true 88 bool color; 89 /// If the minimum y-axis value shall be set automatically (otherwise uses y_min). Default: true 90 bool auto_y_min; 91 /// If the minimum x-axis value shall be set automatically (otherwise uses x_min). Default: true 92 bool auto_x_min; 93 /// If the maximum y-axis value shall be set automatically (otherwise uses y_max). Default: true 94 bool auto_y_max; 95 /// If the maximum x-axis value shall be set automatically (otherwise uses x_max). Default: true 96 bool auto_x_max; 97 /// Minimum y-axis value. 98 float y_min; 99 /// Minimum x-axis value. 100 float x_min; 101 /// Maximum y-axis value. 102 float y_max; 103 /// Maximum x-axis value. 104 float x_max; 105 /// If a logarithimic scale shall be used for the y-axis. Default: false 106 bool y_log; 107 /// If a logarithimic scale shall be used for the x-axis. Default: false 108 bool x_log; 109 /// Logarithimic base for the y-axis. Default: 10 110 int y_log_base; 111 /// Logarithimic base for the x-axis. Default: 10 112 int x_log_base; 113 /// If a grid shall be shown in the plot. Default: false 114 bool grid; 115 /// Width of lines. Default: 2 116 int linewidth; 117 /// If the plot shall be surrounded by borders on all sides (not just axis). Default: false 118 bool show_all_borders; 119 /// Where the plot legend shall be placed. Default: PLOT_LEGEND_TOP_RIGHT 120 PlotLegendPlacement legend_placement; 121 PlotParameters(); 122 }; 123 124 /// Parameters for plot data series. 125 struct PlotDataParameters { 126 /// Title label. 127 std::string title; 128 /// Plot smoothing. 129 PlotSmoothing smoothing; 130 /// Plot style 131 PlotStyle style; 132 /// Use scale on second y-axis 133 bool yaxis2; 134 /// Use scale on second x-axis 135 bool xaxis2; 136 /// Check if data is continuous 137 bool test_continuous; 138 PlotDataParameters(); 139 }; 140 141 ///Message types 142 typedef enum { 143 MESSAGE_INFORMATION, 144 MESSAGE_WARNING, 145 MESSAGE_ERROR 146 } MessageType; 147 148 typedef enum { 149 AUTOMATIC_FRACTION_OFF, 150 AUTOMATIC_FRACTION_SINGLE, 151 AUTOMATIC_FRACTION_AUTO, 152 AUTOMATIC_FRACTION_DUAL 153 } AutomaticFractionFormat; 154 155 typedef enum { 156 AUTOMATIC_APPROXIMATION_OFF, 157 AUTOMATIC_APPROXIMATION_SINGLE, 158 AUTOMATIC_APPROXIMATION_AUTO, 159 AUTOMATIC_APPROXIMATION_DUAL 160 } AutomaticApproximation; 161 162 ///Message stages 163 #define MESSAGE_STAGE_CONVERSION -4 164 #define MESSAGE_STAGE_CONVERSION_PARSING -3 165 #define MESSAGE_STAGE_CALCULATION -2 166 #define MESSAGE_STAGE_PARSING -1 167 #define MESSAGE_STAGE_UNSET 0 168 169 ///Message categories 170 #define MESSAGE_CATEGORY_NONE 0 171 #define MESSAGE_CATEGORY_PARSING 1 172 #define MESSAGE_CATEGORY_WIDE_INTERVAL 10 173 174 175 /// A message with information to the user. Primarily used for errors and warnings. 176 class CalculatorMessage { 177 protected: 178 std::string smessage; 179 MessageType mtype; 180 int i_stage, i_cat; 181 public: 182 CalculatorMessage(std::string message_, MessageType type_ = MESSAGE_WARNING, int cat_ = MESSAGE_CATEGORY_NONE, int stage_ = MESSAGE_STAGE_UNSET); 183 CalculatorMessage(const CalculatorMessage &e); 184 std::string message() const; 185 const char* c_message() const; 186 MessageType type() const; 187 int stage() const; 188 int category() const; 189 }; 190 191 #include <libqalculate/MathStructure.h> 192 193 enum { 194 VARIABLE_ID_I = 200, 195 VARIABLE_ID_PLUS_INFINITY = 201, 196 VARIABLE_ID_MINUS_INFINITY = 202, 197 VARIABLE_ID_UNDEFINED = 203, 198 VARIABLE_ID_X = 300, 199 VARIABLE_ID_Y = 301, 200 VARIABLE_ID_Z = 302, 201 VARIABLE_ID_N = 303, 202 VARIABLE_ID_C = 304 203 }; 204 205 enum { 206 UNIT_ID_EURO = 510, 207 UNIT_ID_BYN = 515, 208 UNIT_ID_BTC = 520, 209 UNIT_ID_SECOND = 550, 210 UNIT_ID_MINUTE = 551, 211 UNIT_ID_HOUR = 552, 212 UNIT_ID_DAY = 553, 213 UNIT_ID_MONTH = 554, 214 UNIT_ID_YEAR = 555, 215 UNIT_ID_KELVIN = 560, 216 UNIT_ID_RANKINE = 561, 217 UNIT_ID_CELSIUS = 562, 218 UNIT_ID_FAHRENHEIT = 563 219 }; 220 221 enum { 222 ELEMENT_CLASS_NOT_DEFINED, 223 ALKALI_METALS, 224 ALKALI_EARTH_METALS, 225 LANTHANIDES, 226 ACTINIDES, 227 TRANSITION_METALS, 228 METALS, 229 METALLOIDS, 230 NONMETALS, 231 HALOGENS, 232 NOBLE_GASES, 233 TRANSACTINIDES 234 }; 235 236 typedef enum { 237 TEMPERATURE_CALCULATION_HYBRID, 238 TEMPERATURE_CALCULATION_ABSOLUTE, 239 TEMPERATURE_CALCULATION_RELATIVE 240 } TemperatureCalculationMode; 241 242 struct Element { 243 std::string symbol, name; 244 int number, group; 245 std::string weight; 246 int x_pos, y_pos; 247 }; 248 249 #define UFV_LENGTHS 20 250 251 class Calculate_p; 252 253 /// The almighty calculator class. 254 /** The calculator class is responsible for loading functions, variables and units, and keeping track of them, as well as parsing expressions and much more. A calculator object must be created before any other Qalculate! class is used. There should never be more than one calculator object, accessed with CALCULATOR. 255 * 256 * A simple application using libqalculate need only create a calculator object, perhaps load definitions (functions, variables, units, etc.) and use the calculate function as follows: 257 * \code new Calculator(); 258 * CALCULATOR->loadGlobalDefinitions(); 259 * CALCULATOR->loadLocalDefinitions(); 260 * MathStructure result = CALCULATOR->calculate("1 + 1");\endcode 261 */ 262 class Calculator { 263 264 protected: 265 266 std::vector<CalculatorMessage> messages; 267 268 int ianglemode; 269 int i_precision; 270 bool b_interval; 271 int i_stop_interval; 272 int i_start_interval; 273 char vbuffer[200]; 274 std::vector<void*> ufvl; 275 std::vector<char> ufvl_t; 276 std::vector<size_t> ufvl_i; 277 std::vector<void*> ufv[4][UFV_LENGTHS]; 278 std::vector<size_t> ufv_i[4][UFV_LENGTHS]; 279 280 std::vector<DataSet*> data_sets; 281 282 class Calculator_p *priv; 283 284 std::vector<std::string> signs; 285 std::vector<std::string> real_signs; 286 std::vector<std::string> default_signs; 287 std::vector<std::string> default_real_signs; 288 bool b_ignore_locale; 289 char *saved_locale; 290 int disable_errors_ref; 291 std::vector<int> stopped_errors_count; 292 std::vector<int> stopped_warnings_count; 293 std::vector<int> stopped_messages_count; 294 std::vector<std::vector<CalculatorMessage> > stopped_messages; 295 296 Thread *calculate_thread; 297 298 std::string NAME_NUMBER_PRE_S, NAME_NUMBER_PRE_STR, DOT_STR, DOT_S, COMMA_S, COMMA_STR, ILLEGAL_IN_NAMES, ILLEGAL_IN_UNITNAMES, ILLEGAL_IN_NAMES_MINUS_SPACE_STR; 299 300 bool b_argument_errors; 301 int current_stage; 302 303 time_t exchange_rates_time[3], exchange_rates_check_time[3]; 304 int b_exchange_rates_used; 305 bool b_exchange_rates_warning_enabled; 306 307 bool b_gnuplot_open; 308 std::string gnuplot_cmdline; 309 FILE *gnuplot_pipe; 310 311 bool local_to; 312 313 Assumptions *default_assumptions; 314 315 std::vector<Variable*> deleted_variables; 316 std::vector<MathFunction*> deleted_functions; 317 std::vector<Unit*> deleted_units; 318 319 bool b_var_units; 320 321 bool b_save_called; 322 323 int i_timeout; 324 struct timeval t_end; 325 int i_aborted; 326 bool b_controlled; 327 328 std::string per_str, times_str, plus_str, minus_str, and_str, AND_str, or_str, OR_str, XOR_str; 329 size_t per_str_len, times_str_len, plus_str_len, minus_str_len, and_str_len, AND_str_len, or_str_len, OR_str_len, XOR_str_len; 330 331 std::vector<MathStructure*> rpn_stack; 332 333 bool calculateRPN(MathStructure *mstruct, int command, size_t index, int msecs, const EvaluationOptions &eo, int function_arguments = 0); 334 bool calculateRPN(std::string str, int command, size_t index, int msecs, const EvaluationOptions &eo, MathStructure *parsed_struct, MathStructure *to_struct, bool make_to_division, int function_arguments = 0); 335 336 public: 337 338 KnownVariable *v_pi, *v_e, *v_euler, *v_catalan, *v_i, *v_pinf, *v_minf, *v_undef, *v_precision; 339 KnownVariable *v_percent, *v_permille, *v_permyriad; 340 KnownVariable *v_today, *v_yesterday, *v_tomorrow, *v_now; 341 UnknownVariable *v_x, *v_y, *v_z; 342 UnknownVariable *v_C, *v_n; 343 MathFunction *f_vector, *f_sort, *f_rank, *f_limits, *f_component, *f_dimension, *f_merge_vectors; 344 MathFunction *f_matrix, *f_matrix_to_vector, *f_area, *f_rows, *f_columns, *f_row, *f_column, *f_elements, *f_element, *f_transpose, *f_identity, *f_determinant, *f_permanent, *f_adjoint, *f_cofactor, *f_inverse, *f_magnitude, *f_hadamard, *f_entrywise; 345 MathFunction *f_factorial, *f_factorial2, *f_multifactorial, *f_binomial; 346 MathFunction *f_xor, *f_bitxor, *f_even, *f_odd, *f_shift, *f_bitcmp; 347 MathFunction *f_abs, *f_gcd, *f_lcm, *f_signum, *f_heaviside, *f_dirac, *f_round, *f_floor, *f_ceil, *f_trunc, *f_int, *f_frac, *f_rem, *f_mod; 348 MathFunction *f_polynomial_unit, *f_polynomial_primpart, *f_polynomial_content, *f_coeff, *f_lcoeff, *f_tcoeff, *f_degree, *f_ldegree; 349 MathFunction *f_re, *f_im, *f_arg, *f_numerator, *f_denominator; 350 MathFunction *f_interval, *f_uncertainty; 351 MathFunction *f_sqrt, *f_cbrt, *f_root, *f_sq; 352 MathFunction *f_exp; 353 MathFunction *f_ln, *f_logn; 354 MathFunction *f_lambert_w; 355 MathFunction *f_sin, *f_cos, *f_tan, *f_asin, *f_acos, *f_atan, *f_sinh, *f_cosh, *f_tanh, *f_asinh, *f_acosh, *f_atanh, *f_atan2, *f_sinc, *f_radians_to_default_angle_unit; 356 MathFunction *f_zeta, *f_gamma, *f_digamma, *f_beta, *f_airy, *f_besselj, *f_bessely, *f_erf, *f_erfc; 357 MathFunction *f_total, *f_percentile, *f_min, *f_max, *f_mode, *f_rand; 358 MathFunction *f_date, *f_datetime, *f_timevalue, *f_timestamp, *f_stamptodate, *f_days, *f_yearfrac, *f_week, *f_weekday, *f_month, *f_day, *f_year, *f_yearday, *f_time, *f_add_days, *f_add_months, *f_add_years; 359 MathFunction *f_lunarphase, *f_nextlunarphase; 360 MathFunction *f_bin, *f_oct, *f_hex, *f_base, *f_roman; 361 MathFunction *f_ascii, *f_char; 362 MathFunction *f_length, *f_concatenate; 363 MathFunction *f_replace, *f_stripunits; 364 MathFunction *f_genvector, *f_for, *f_sum, *f_product, *f_process, *f_process_matrix, *f_csum, *f_if, *f_is_number, *f_is_real, *f_is_rational, *f_is_integer, *f_represents_number, *f_represents_real, *f_represents_rational, *f_represents_integer, *f_function, *f_select; 365 MathFunction *f_diff, *f_integrate, *f_solve, *f_multisolve, *f_dsolve, *f_limit; 366 MathFunction *f_li, *f_Li, *f_Ei, *f_Si, *f_Ci, *f_Shi, *f_Chi, *f_igamma; 367 MathFunction *f_error, *f_warning, *f_message, *f_save, *f_load, *f_export, *f_title; 368 MathFunction *f_register, *f_stack; 369 MathFunction *f_plot; 370 371 Unit *u_rad, *u_gra, *u_deg, *u_euro, *u_btc, *u_second, *u_minute, *u_hour, *u_year, *u_month, *u_day; 372 DecimalPrefix *decimal_null_prefix; 373 BinaryPrefix *binary_null_prefix; 374 375 bool place_currency_code_before, place_currency_sign_before; 376 bool place_currency_code_before_negative, place_currency_sign_before_negative; 377 bool default_dot_as_separator; 378 std::string local_digit_group_separator, local_digit_group_format; 379 380 bool b_busy; 381 std::string expression_to_calculate; 382 EvaluationOptions tmp_evaluationoptions; 383 MathStructure *tmp_parsedstruct; 384 MathStructure *tmp_tostruct; 385 MathStructure *tmp_rpn_mstruct; 386 bool tmp_maketodivision; 387 int tmp_proc_command; 388 int tmp_proc_registers; 389 size_t tmp_rpnindex; 390 391 PrintOptions save_printoptions, message_printoptions; 392 393 std::vector<Variable*> variables; 394 std::vector<MathFunction*> functions; 395 std::vector<Unit*> units; 396 std::vector<Prefix*> prefixes; 397 std::vector<DecimalPrefix*> decimal_prefixes; 398 std::vector<BinaryPrefix*> binary_prefixes; 399 400 /** @name Constructor */ 401 //@{ 402 Calculator(); 403 Calculator(bool ignore_locale); 404 virtual ~Calculator(); 405 //@} 406 407 /** @name Functions for calculating expressions. */ 408 //@{ 409 /** Calculates an expression. The expression should be unlocalized first with unlocalizeExpression(). 410 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 411 * The calculation can then be stopped with abort(). 412 * 413 * @param[out] mstruct Math structure to fill with the result. 414 * @param str Expression. 415 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 416 * @param eo Options for the evaluation and parsing of the expression. 417 * @param[out] parsed_struct NULL or a math structure to fill with the result of the parsing of the expression. 418 * @param[out] to_struct NULL or a math structure to fill with unit expression parsed after "to". If expression does not contain a "to" string, and to_struct is a unit or a symbol (a unit expression string), to_struct will be used instead. 419 * @param make_to_division If true, the expression after "to" will be interpreted as a unit epxression to convert the result to. 420 * @returns true if the calculation was successfully started (and finished if msecs > 0). 421 */ 422 bool calculate(MathStructure *mstruct, std::string str, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 423 /** Calculates an expression. The expression should be unlocalized first with unlocalizeExpression(). 424 * 425 * @param str Expression. 426 * @param eo Options for the evaluation and parsing of the expression. 427 * @param[out] parsed_struct NULL or a math structure to fill with the result of the parsing of the expression. 428 * @param[out] to_struct NULL or a math structure to fill with unit expression parsed after "to". If expression does not contain a "to" string, and to_struct is a unit or a symbol (a unit expression string), to_struct will be used instead. 429 * @param make_to_division If true, the expression after "to" will be interpreted as a unit epxression to convert the result to. 430 * @returns The result of the calculation. 431 */ 432 MathStructure calculate(std::string str, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 433 /** Calculates a parsed value. 434 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 435 * The calculation can then be stopped with abort(). 436 * 437 * @param[out] mstruct Parsed value to evaluate and fill with the result. 438 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 439 * @param eo Options for the evaluation of the expression. 440 * @param to_str "to" expression for conversion. 441 * @returns The result of the calculation. 442 */ 443 bool calculate(MathStructure *mstruct, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, std::string to_str = ""); 444 /** Calculates a parsed value. 445 * 446 * @param mstruct Parsed value to evaluate. 447 * @param eo Options for the evaluation of the expression. 448 * @param to_str "to" expression for conversion. 449 * @returns The result of the calculation. 450 */ 451 MathStructure calculate(const MathStructure &mstruct, const EvaluationOptions &eo = default_user_evaluation_options, std::string to_str = ""); 452 /** Calculates an expression.and outputs the result to a text string. The expression should be unlocalized first with unlocalizeExpression(). 453 * 454 * Unlike other functions for expression evaluation this function handles ending "to"-commmands, in addition to unit conversion, such "to hexadecimal" or to "fractions", similar to the qalc application. 455 * 456 * 457 * @param str Expression. 458 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 459 * @param eo Options for the evaluation and parsing of the expression. 460 * @param po Result formatting options. 461 * @returns The result of the calculation. 462 * \since 2.6.0 463 */ 464 std::string calculateAndPrint(std::string str, int msecs = 10000, const EvaluationOptions &eo = default_user_evaluation_options, const PrintOptions &po = default_print_options); 465 std::string calculateAndPrint(std::string str, int msecs, const EvaluationOptions &eo, const PrintOptions &po, std::string *parsed_expression); 466 std::string calculateAndPrint(std::string str, int msecs, const EvaluationOptions &eo, const PrintOptions &po, AutomaticFractionFormat auto_fraction, AutomaticApproximation auto_approx = AUTOMATIC_APPROXIMATION_OFF, std::string *parsed_expression = NULL, int max_length = -1, bool *result_is_comparison = NULL); 467 int testCondition(std::string expression); 468 //@} 469 470 /** @name Functions for printing expressions with the option to set maximum time or abort. */ 471 //@{ 472 /** Calls MathStructure::format(po) and MathStructure::print(po). The process is aborted after msecs milliseconds. 473 */ 474 std::string print(const MathStructure &mstruct, int milliseconds = 100000, const PrintOptions &op = default_print_options); 475 ///Deprecated: use print() instead 476 std::string printMathStructureTimeOut(const MathStructure &mstruct, int milliseconds = 100000, const PrintOptions &op = default_print_options); 477 478 /** Called before calculation, formatting or printing of a MathStructure (Calculator::calculate(), without maximum time, MathStructure::eval(), MathStructure::format() and MathStructure::print(), etc.) or printing of a Number (using Number::print) to be able to abort the process. Always use Calculator::stopControl() after finishing. 479 * 480 * @param milliseconds The maximum time for the process in milliseconds. If msecs <= 0 the time will be unlimited (stop with abort()). 481 */ 482 void startControl(int milliseconds = 0); 483 /** Always call this function after Calculator::startControl() after formatting, printing or calculation has finished. 484 */ 485 void stopControl(void); 486 /** Abort formatting, printing or evaluation (after startControl() has been called). 487 * This function will normally be called from a thread that checks for user input or other conditions. 488 * 489 * @returns false if the calculation thread was forcibly stopped 490 */ 491 bool abort(); 492 bool aborted(void); 493 bool isControlled(void) const; 494 std::string abortedMessage(void) const; 495 std::string timedOutString(void) const; 496 497 ///Deprecated: use startControl() 498 void startPrintControl(int milliseconds = 0); 499 ///Deprecated: use abort() 500 void abortPrint(void); 501 ///Deprecated: use stopControl() 502 void stopPrintControl(void); 503 /// Deprecated: use aborted() 504 bool printingAborted(void); 505 /// Deprecated: use isControlled() 506 bool printingControlled(void) const; 507 /// Deprecated: use abortedMessage() 508 std::string printingAbortedMessage(void) const; 509 //@} 510 511 /** @name Functions for handling of threaded calculations */ 512 //@{ 513 /** Returns true if the calculate or print thread is busy. */ 514 bool busy(); 515 /// Deprecated: does nothing. 516 void saveState(); 517 /// Deprecated: does nothing. 518 void restoreState(); 519 /** Clears all stored values. Used internally after aborted calculation. */ 520 void clearBuffers(); 521 /** Terminate calculation and print threads if started. Do not use to terminate calculation. */ 522 void terminateThreads(); 523 //@} 524 525 /** @name Functions for manipulation of the RPN stack. */ 526 //@{ 527 /** Evaluates a value on the RPN stack. 528 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 529 * The calculation can then be stopped with abort(). 530 * 531 * @param index Index, starting at 1, on the RPN stack. 532 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 533 * @param eo Options for the evaluation and parsing of the expression. 534 * @returns true if the calculation was successfully started (and finished if msecs > 0). 535 */ 536 bool calculateRPNRegister(size_t index, int msecs, const EvaluationOptions &eo = default_user_evaluation_options); 537 /** Applies a mathematical operation to the first and second value on the RPN stack. The the second value is changed with input from the first value. 538 * For example, with OPERATION_SUBTRACT the first value is subtracted from the second. The first value on the stack is removed. 539 * If not enough registers is available, then zeros are added. 540 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 541 * The calculation can then be stopped with abort(). 542 * 543 * @param op Operation. 544 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 545 * @param eo Options for the evaluation and parsing of the expression. 546 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 547 * @returns true if the calculation was successfully started (and finished if msecs > 0). 548 */ 549 bool calculateRPN(MathOperation op, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 550 /** Applies a mathematical operation to the first value on the RPN stack. The value is set as the first argument of the function. 551 * If no register is available, then zero is added. 552 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 553 * The calculation can then be stopped with abort(). 554 * 555 * @param f Mathematical function. 556 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 557 * @param eo Options for the evaluation and parsing of the expression. 558 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 559 * @returns true if the calculation was successfully started (and finished if msecs > 0). 560 */ 561 bool calculateRPN(MathFunction *f, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 562 /** Applies bitwise not to the first value on the RPN stack. 563 * If no register is available, then zero is added. 564 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 565 * The calculation can then be stopped with abort(). 566 * 567 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 568 * @param eo Options for the evaluation and parsing of the expression. 569 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 570 * @returns true if the calculation was successfully started (and finished if msecs > 0). 571 */ 572 bool calculateRPNBitwiseNot(int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 573 /** Applies logical not to the first value on the RPN stack. 574 * If no register is available, then zero is added. 575 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 576 * The calculation can then be stopped with abort(). 577 * 578 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 579 * @param eo Options for the evaluation and parsing of the expression. 580 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 581 * @returns true if the calculation was successfully started (and finished if msecs > 0). 582 */ 583 bool calculateRPNLogicalNot(int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 584 /** Applies a mathematical operation to the first and second value on the RPN stack. The the second value is changed with input from the first value. 585 * For example, with OPERATION_SUBTRACT the first value is subtracted from the second. The first value on the stack is removed. 586 * If not enough registers is available, then zeros are added. 587 * 588 * @param op Operation. 589 * @param eo Options for the evaluation and parsing of the expression. 590 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 591 * @returns The first value on the stack. 592 */ 593 MathStructure *calculateRPN(MathOperation op, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 594 /** Applies a mathematical operation to the first value on the RPN stack. The value is set as the first argument of the function. 595 * If no register is available, then zero is added. 596 * 597 * @param f Mathematical function. 598 * @param eo Options for the evaluation and parsing of the expression. 599 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 600 * @returns The first value on the stack. 601 */ 602 MathStructure *calculateRPN(MathFunction *f, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 603 /** Applies bitwise not to the first value on the RPN stack. 604 * If no register is available, then zero is added. 605 * 606 * @param eo Options for the evaluation and parsing of the expression. 607 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 608 * @returns The first value on the stack. 609 */ 610 MathStructure *calculateRPNBitwiseNot(const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 611 /** Applies logical not to the first value on the RPN stack. 612 * If no register is available, then zero is added. 613 * 614 * @param eo Options for the evaluation and parsing of the expression. 615 * @param[out] parsed_struct NULL or a math structure to fill with the unevaluated result. 616 * @returns The first value on the stack. 617 */ 618 MathStructure *calculateRPNLogicalNot(const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL); 619 /** Evaluates a value and adds the result first on the RPN stack. 620 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 621 * The calculation can then be stopped with abort(). 622 * 623 * @param mstruct Value. 624 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 625 * @param eo Options for the evaluation of the expression. 626 * @returns true if the calculation was successfully started (and finished if msecs > 0). 627 */ 628 bool RPNStackEnter(MathStructure *mstruct, int msecs, const EvaluationOptions &eo = default_user_evaluation_options); 629 /** Calculates an expression and adds the result first on the RPN stack. The expression should be unlocalized first with unlocalizeExpression(). 630 * This function starts the calculation in a separate thread and will return when the calculation has started unless a maximum time has been specified. 631 * The calculation can then be stopped with abort(). 632 * 633 * @param str Expression. 634 * @param msecs The maximum time for the calculation in milliseconds. If msecs <= 0 the time will be unlimited. 635 * @param eo Options for the evaluation and parsing of the expression. 636 * @param[out] parsed_struct NULL or a math structure to fill with the result of the parsing of the expression. 637 * @param[out] to_struct NULL or a math structure to fill with unit expression parsed after "to". 638 * @param make_to_division If true, the expression after "to" will be interpreted as a unit epxression to convert the result to. 639 * @returns true if the calculation was successfully started (and finished if msecs > 0). 640 */ 641 bool RPNStackEnter(std::string str, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 642 /** Adds a value first on the RPN stack. 643 * 644 * @param mstruct Value. 645 * @param eval If true, the the mathematical structure will be evaluated first. 646 */ 647 void RPNStackEnter(MathStructure *mstruct, bool eval = false, const EvaluationOptions &eo = default_user_evaluation_options); 648 /** Calculates an expression adds the result first on the RPN stack. The expression should be unlocalized first with unlocalizeExpression(). 649 * 650 * @param str Expression. 651 * @param eo Options for the evaluation and parsing of the expression. 652 * @param[out] parsed_struct NULL or a math structure to fill with the result of the parsing of the expression. 653 * @param[out] to_struct NULL or a math structure to fill with unit expression parsed after "to". 654 * @param make_to_division If true, the expression after "to" will be interpreted as a unit epxression to convert the result to. 655 */ 656 void RPNStackEnter(std::string str, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 657 bool setRPNRegister(size_t index, MathStructure *mstruct, int msecs, const EvaluationOptions &eo = default_user_evaluation_options); 658 bool setRPNRegister(size_t index, std::string str, int msecs, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 659 void setRPNRegister(size_t index, MathStructure *mstruct, bool eval = false, const EvaluationOptions &eo = default_user_evaluation_options); 660 void setRPNRegister(size_t index, std::string str, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *parsed_struct = NULL, MathStructure *to_struct = NULL, bool make_to_division = true); 661 void deleteRPNRegister(size_t index); 662 MathStructure *getRPNRegister(size_t index = 1) const; 663 size_t RPNStackSize() const; 664 void clearRPNStack(); 665 void moveRPNRegister(size_t old_index, size_t new_index); 666 void moveRPNRegisterUp(size_t index); 667 void moveRPNRegisterDown(size_t index); 668 //@} 669 670 /** @name Functions for expression parsing. */ 671 //@{ 672 /** Returns a localized expressions. Affects decimal signs and argument separators. 673 * 674 * @param str The expression to localize. 675 * @returns A localized expression. 676 */ 677 std::string localizeExpression(std::string str, const ParseOptions &po = default_parse_options) const; 678 /** Returns an unlocalized expressions. Affects decimal signs and argument separators. 679 * 680 * @param str The expression to unlocalize. 681 * @returns An unlocalized expression. 682 */ 683 std::string unlocalizeExpression(std::string str, const ParseOptions &po = default_parse_options) const; 684 /** Split an expression string after and before " to ". 685 * 686 * @param[out] str The expression. Will be set to the string before " to ". 687 * @param[out] to_str Will be set to the string after " to ". 688 * @param eo Options for the evaluation and parsing of the expression (nothing will be done if units are not enabled). 689 * @returns true if " to " was found and the expression split. 690 */ 691 bool separateToExpression(std::string &str, std::string &to_str, const EvaluationOptions &eo, bool keep_modifiers = false, bool allow_empty_from = false) const; 692 bool hasToExpression(const std::string &str, bool allow_empty_from = false) const; 693 bool hasToExpression(const std::string &str, bool allow_empty_from, const EvaluationOptions &eo) const; 694 695 /// Split an expression string after and before " where ". 696 bool separateWhereExpression(std::string &str, std::string &where_str, const EvaluationOptions &eo) const; 697 bool hasWhereExpression(const std::string &str, const EvaluationOptions &eo) const; 698 699 std::string parseComments(std::string &str, const ParseOptions &po = default_parse_options, bool *double_tag = NULL); 700 void parseSigns(std::string &str, bool convert_to_internal_representation = false) const; 701 /** Parse an expression and place in a MathStructure object. 702 * 703 * @param str Expression 704 * @param po Parse options. 705 * @returns MathStructure with result of parse. 706 */ 707 MathStructure parse(std::string str, const ParseOptions &po = default_parse_options); 708 void parse(MathStructure *mstruct, std::string str, const ParseOptions &po = default_parse_options); 709 bool parseNumber(MathStructure *mstruct, std::string str, const ParseOptions &po = default_parse_options); 710 bool parseOperators(MathStructure *mstruct, std::string str, const ParseOptions &po = default_parse_options); 711 bool parseAdd(std::string &str, MathStructure *mstruct, const ParseOptions &po, MathOperation s, bool append = true); 712 bool parseAdd(std::string &str, MathStructure *mstruct, const ParseOptions &po); 713 //@} 714 715 /** @name Functions converting epxressions between units. */ 716 //@{ 717 /** Converts to a unit expression. 718 * The converted value is evaluated. 719 * 720 * @param mstruct The value to convert. 721 * @param composite_ Unit expression. 722 * @param eo Evaluation options. 723 * @param[out] units NULL or a math structure to fill with the parsed unit expression(or set to undefined if no units were found). 724 * @returns Converted value. 725 */ 726 MathStructure convert(const MathStructure &mstruct, std::string composite_, const EvaluationOptions &eo = default_user_evaluation_options, MathStructure *units = NULL); 727 /** Converts to a unit. 728 * The converted value is evaluated. 729 * 730 * @param mstruct The value to convert. 731 * @param composite_ Unit to convert to. 732 * @param eo Evaluation options. 733 * @param always_convert ... 734 * @returns Converted value. 735 */ 736 MathStructure convert(const MathStructure &mstruct, Unit *to_unit, const EvaluationOptions &eo = default_user_evaluation_options, bool always_convert = true, bool convert_to_mixed_units = true); 737 MathStructure convert(const MathStructure &mstruct, KnownVariable *to_var, const EvaluationOptions &eo = default_user_evaluation_options); 738 MathStructure convert(double value, Unit *from_unit, Unit *to_unit, const EvaluationOptions &eo = default_user_evaluation_options); 739 MathStructure convert(std::string str, Unit *from_unit, Unit *to_unit, int milliseconds, const EvaluationOptions &eo = default_user_evaluation_options); 740 /** Depecated: use convert() */ 741 MathStructure convertTimeOut(std::string str, Unit *from_unit, Unit *to_unit, int milliseconds, const EvaluationOptions &eo = default_user_evaluation_options); 742 MathStructure convert(std::string str, Unit *from_unit, Unit *to_unit, const EvaluationOptions &eo = default_user_evaluation_options); 743 MathStructure convertToBaseUnits(const MathStructure &mstruct, const EvaluationOptions &eo = default_user_evaluation_options); 744 /** Deprecated: use getOptimalUnit() */ 745 Unit *getBestUnit(Unit *u, bool allow_only_div = false, bool convert_to_local_currency = true); 746 Unit *getOptimalUnit(Unit *u, bool allow_only_div = false, bool convert_to_local_currency = true); 747 /** Deprecated: use convertToOptimalUnit() */ 748 MathStructure convertToBestUnit(const MathStructure &mstruct, const EvaluationOptions &eo = default_user_evaluation_options, bool convert_to_si_units = true); 749 MathStructure convertToOptimalUnit(const MathStructure &mstruct, const EvaluationOptions &eo = default_user_evaluation_options, bool convert_to_si_units = true); 750 MathStructure convertToCompositeUnit(const MathStructure &mstruct, CompositeUnit *cu, const EvaluationOptions &eo = default_user_evaluation_options, bool always_convert = true); 751 MathStructure convertToMixedUnits(const MathStructure &mstruct, const EvaluationOptions &eo = default_user_evaluation_options); 752 //@} 753 754 void setTemperatureCalculationMode(TemperatureCalculationMode temperature_calculation_mode); 755 TemperatureCalculationMode getTemperatureCalculationMode() const; 756 757 /** Used by the UI to find unit category for a mathematical expression.*/ 758 Unit *findMatchingUnit(const MathStructure &mstruct); 759 760 /** @name Functions for default assumptions for unknown variables and symbols */ 761 //@{ 762 /** Set assumptions for objects without own assumptions (unknown variables and symbols). 763 */ 764 void setDefaultAssumptions(Assumptions *ass); 765 /** Returns the default assumptions for objects without own assumptions (unknown variables and symbols). 766 */ 767 Assumptions *defaultAssumptions(); 768 //@} 769 770 /** @name Functions for retrieval of angle units */ 771 //@{ 772 /** Returns the gradians unit. 773 */ 774 Unit *getGraUnit(); 775 /** Returns the radians unit. 776 */ 777 Unit *getRadUnit(); 778 /** Returns the degrees unit. 779 */ 780 Unit *getDegUnit(); 781 //@} 782 783 /** @name Functions for finding a suitable prefix. */ 784 //@{ 785 /** Returns a decimal prefix with exactly the provided value, that fulfils the condition prefix->exponent(exp) == exp10. 786 * 787 * @param exp10 Base-10 exponent of the requested prefix. 788 * @param exp The exponent of the unit. 789 * @returns A prefix or NULL if not found. 790 */ 791 DecimalPrefix *getExactDecimalPrefix(int exp10, int exp = 1) const; 792 /** Returns a binary prefix with exactly the provided value, that fulfils the condition prefix->exponent(exp) == exp2. 793 * 794 * @param exp2 Base-2 exponent of the requested prefix. 795 * @param exp The exponent of the unit. 796 * @returns A prefix or NULL if not found. 797 */ 798 BinaryPrefix *getExactBinaryPrefix(int exp2, int exp = 1) const; 799 /** Returns a prefix with exactly the provided value, that fulfils the condition prefix->value(exp) == o. 800 * 801 * @param o Value of the requested prefix. 802 * @param exp The exponent of the unit. 803 * @returns A prefix or NULL if not found. 804 */ 805 Prefix *getExactPrefix(const Number &o, int exp = 1) const; 806 /** Returns the nearest decimal prefix for a value. 807 * 808 * @param exp10 Base-10 exponent of the value. 809 * @param exp The exponent of the unit. 810 * @returns A prefix or NULL if no decimal prefix is available. 811 */ 812 DecimalPrefix *getNearestDecimalPrefix(int exp10, int exp = 1) const; 813 /** Returns the best suited decimal prefix for a value. 814 * 815 * @param exp10 Base-10 exponent of the value. 816 * @param exp The exponent of the unit. 817 * @param all_prefixes If false, prefixes which is not a multiple of thousand (centi, deci, deka, hekto) will be skipped. 818 * @returns A prefix or NULL if the unit should be left without prefix. 819 */ 820 DecimalPrefix *getOptimalDecimalPrefix(int exp10, int exp = 1, bool all_prefixes = true) const; 821 /** Returns the best suited decimal prefix for a value. 822 * 823 * @param exp10 Base-10 exponent of the value. 824 * @param exp The exponent of the unit. 825 * @param all_prefixes If false, prefixes which is not a multiple of thousand (centi, deci, deka, hekto) will be skipped. 826 * @returns A prefix or NULL if the unit should be left without prefix. 827 */ 828 DecimalPrefix *getOptimalDecimalPrefix(const Number &exp10, const Number &exp, bool all_prefixes = true) const; 829 /** Returns the nearest binary prefix for a value. 830 * 831 * @param exp10 Base-2 exponent of the value. 832 * @param exp The exponent of the unit. 833 * @returns A prefix or NULL if no binary prefix is available. 834 */ 835 BinaryPrefix *getNearestBinaryPrefix(int exp2, int exp = 1) const; 836 /** Returns the best suited binary prefix for a value. 837 * 838 * @param exp10 Base-2 exponent of the value. 839 * @param exp The exponent of the unit. 840 * @returns A prefix or NULL if the unit should be left without prefix. 841 */ 842 BinaryPrefix *getOptimalBinaryPrefix(int exp2, int exp = 1) const; 843 /** Returns the best suited binary prefix for a value. 844 * 845 * @param exp10 Base-2 exponent of the value. 846 * @param exp The exponent of the unit. 847 * @returns A prefix or NULL if the unit should be left without prefix. 848 */ 849 BinaryPrefix *getOptimalBinaryPrefix(const Number &exp2, const Number &exp) const; 850 /** Controls if binary, instead of decimal, prefixes will be used by default. 851 * 1 = use binary prefixes for information units, 2 = use binary prefixes for all units. 852 */ 853 int usesBinaryPrefixes() const; 854 void useBinaryPrefixes(int use_binary_prefixes); 855 /** Add a new prefix to the calculator. */ 856 Prefix *addPrefix(Prefix *p); 857 /** Used internally. */ 858 void prefixNameChanged(Prefix *p, bool new_item = false); 859 //@} 860 861 /** @name Functions for managing functions, variables, units, prefixes and data sets. */ 862 //@{ 863 void expressionItemActivated(ExpressionItem *item); 864 void expressionItemDeactivated(ExpressionItem *item); 865 void expressionItemDeleted(ExpressionItem *item); 866 void nameChanged(ExpressionItem *item, bool new_item = false); 867 void deleteName(std::string name_, ExpressionItem *object = NULL); 868 void deleteUnitName(std::string name_, Unit *object = NULL); 869 Unit* addUnit(Unit *u, bool force = true, bool check_names = true); 870 void delPrefixUFV(Prefix *object); 871 void delUFV(ExpressionItem *object); 872 /** Checks if a variable exists/is registered in the calculator. */ 873 bool hasVariable(Variable *v); 874 /** Checks if a unit exists/is registered in the calculator. */ 875 bool hasUnit(Unit *u); 876 /** Checks if a function exists/is registered in the calculator. */ 877 bool hasFunction(MathFunction *f); 878 /** Checks if a pointer points to a variable that still exists in the calculator. 879 * As opposed to hasFunction(), this function only checks if the mathematical function has been deleted. 880 */ 881 bool stillHasVariable(Variable *v); 882 /** Checks if a pointer points to a unit that still exists in the calculator. 883 * As opposed to hasUnit(), this function only checks if the unit has been deleted. 884 */ 885 bool stillHasUnit(Unit *u); 886 /** Checks if a pointer points to a mathematical function that still exists in the calculator. 887 * As opposed to hasFunction(), this function only checks if the mathematical function has been deleted. 888 */ 889 bool stillHasFunction(MathFunction *f); 890 void saveFunctionCalled(); 891 bool checkSaveFunctionCalled(); 892 ExpressionItem *getActiveExpressionItem(std::string name, ExpressionItem *item = NULL); 893 ExpressionItem *getInactiveExpressionItem(std::string name, ExpressionItem *item = NULL); 894 ExpressionItem *getActiveExpressionItem(ExpressionItem *item); 895 ExpressionItem *getExpressionItem(std::string name, ExpressionItem *item = NULL); 896 Unit* getUnit(std::string name_); 897 Unit* getUnitById(int id) const; 898 Unit* getActiveUnit(std::string name_); 899 Unit* getCompositeUnit(std::string internal_name_); 900 Unit* getLocalCurrency(); 901 void setLocalCurrency(Unit *u); 902 /** Returns prefix for an index (starting at zero). All prefixes can be traversed by starting at index zero and increasing the index until NULL is returned. 903 * 904 * @param index Index of prefix. 905 * @returns Prefix for index or NULL if not found. 906 */ 907 Prefix *getPrefix(size_t index) const; 908 /** Returns prefix with provided name. 909 * 910 * @param name_ Name of prefix to retrieve. 911 * @returns Prefix with provided name or NULL if not found. 912 */ 913 Prefix *getPrefix(std::string name_) const; 914 Prefix *getDecimalNullPrefix() const; 915 Prefix *getBinaryNullPrefix() const; 916 Variable* addVariable(Variable *v, bool force = true, bool check_names = true); 917 void variableNameChanged(Variable *v, bool new_item = false); 918 void functionNameChanged(MathFunction *f, bool new_item = false); 919 void unitNameChanged(Unit *u, bool new_item = false); 920 Variable* getVariable(std::string name_); 921 Variable* getVariableById(int id) const; 922 Variable* getActiveVariable(std::string name_); 923 ExpressionItem *addExpressionItem(ExpressionItem *item, bool force = true); 924 MathFunction* addFunction(MathFunction *f, bool force = true, bool check_names = true); 925 DataSet* addDataSet(DataSet *dc, bool force = true, bool check_names = true); 926 DataSet* getDataSet(size_t index); 927 DataSet* getDataSet(std::string name); 928 MathFunction* getFunction(std::string name_); 929 MathFunction* getFunctionById(int id) const; 930 MathFunction* getActiveFunction(std::string name_); 931 /** Returns variable for an index (starting at zero). All variables can be traversed by starting at index zero and increasing the index until NULL is returned. 932 * 933 * @param index Index of variable. 934 * @returns Variable for index or NULL if not found. 935 */ 936 Variable *getVariable(size_t index) const; 937 /** Returns unit for an index (starting at zero). All units can be traversed by starting at index zero and increasing the index until NULL is returned. 938 * 939 * @param index Index of unit. 940 * @returns Unit for index or NULL if not found. 941 */ 942 Unit *getUnit(size_t index) const; 943 /** Returns function for an index (starting at zero). All functions can be traversed by starting at index zero and increasing the index until NULL is returned. 944 * 945 * @param index Index of function. 946 * @returns Function for index or NULL if not found. 947 */ 948 MathFunction *getFunction(size_t index) const; 949 bool unitIsUsedByOtherUnits(const Unit *u) const; 950 //@} 951 952 /** @name Functions for handling of builtin expression items */ 953 //@{ 954 /** Unloads all non-builtin variables. */ 955 void resetVariables(); 956 /** Unloads all non-builtin functions. */ 957 void resetFunctions(); 958 /** Unloads all non-builtin units. */ 959 void resetUnits(); 960 /** Unloads all non-builtin variables, functions and units. */ 961 void reset(); 962 /** Adds builtin variables. Called automatically when the calculator is created. */ 963 void addBuiltinVariables(); 964 /** Adds builtin functions. Called automatically when the calculator is created. */ 965 void addBuiltinFunctions(); 966 /** Adds builtin units. Called automatically when the calculator is created. */ 967 void addBuiltinUnits(); 968 //@} 969 970 void setVariableUnitsEnabled(bool enable_variable_units = true); 971 bool variableUnitsEnabled() const; 972 973 /** @name Functions for testing validity of functions, variable and unit names. */ 974 //@{ 975 /** Tests if a name is valid for a variable. 976 * 977 * @param name_ Variable name. 978 * @returns true if the name is valid for a variable. 979 */ 980 bool variableNameIsValid(const std::string &name_); 981 /** Tests if a name is valid for a variable. 982 * 983 * @param name_ Variable name. 984 * @returns true if the name is valid for a variable. 985 */ 986 bool variableNameIsValid(const char *name_); 987 bool variableNameIsValid(const char *name_, int version_numbers[3], bool is_user_defs); 988 bool variableNameIsValid(const std::string &name_, int version_numbers[3], bool is_user_defs); 989 std::string convertToValidVariableName(std::string name_); 990 bool functionNameIsValid(const std::string &name_); 991 bool functionNameIsValid(const char *name_); 992 bool functionNameIsValid(const char *name_, int version_numbers[3], bool is_user_defs); 993 bool functionNameIsValid(const std::string &name_, int version_numbers[3], bool is_user_defs); 994 std::string convertToValidFunctionName(std::string name_); 995 bool unitNameIsValid(const std::string &name_); 996 bool unitNameIsValid(const char *name_); 997 bool unitNameIsValid(const char *name_, int version_numbers[3], bool is_user_defs); 998 bool unitNameIsValid(const std::string &name_, int version_numbers[3], bool is_user_defs); 999 bool utf8_pos_is_valid_in_name(char *pos); 1000 std::string convertToValidUnitName(std::string name_); 1001 /** Checks if a name is used by another object which is not allowed to have the same name. 1002 * 1003 * @param name Name. 1004 * @param object Object to exclude from check. 1005 * @returns true if the name is used. 1006 */ 1007 bool nameTaken(std::string name, ExpressionItem *object = NULL); 1008 bool variableNameTaken(std::string name, Variable *object = NULL); 1009 bool unitNameTaken(std::string name, Unit *object = NULL); 1010 bool functionNameTaken(std::string name, MathFunction *object = NULL); 1011 std::string getName(std::string name = "", ExpressionItem *object = NULL, bool force = false, bool always_append = false); 1012 //@} 1013 1014 /** @name Functions for message handling. */ 1015 //@{ 1016 void error(bool critical, int message_category, const char *TEMPLATE,...); 1017 void error(bool critical, const char *TEMPLATE,...); 1018 /** Put a message in the message queue. 1019 */ 1020 void message(MessageType mtype, int message_category, const char *TEMPLATE,...); 1021 void message(MessageType mtype, const char *TEMPLATE,...); 1022 void message(MessageType mtype, int message_category, const char *TEMPLATE, va_list ap); 1023 /** Returns the first message in queue. 1024 */ 1025 CalculatorMessage *message(); 1026 /** Removes the first message in queue and returns the next. 1027 */ 1028 CalculatorMessage *nextMessage(); 1029 /** Clear the message queue. 1030 */ 1031 void clearMessages(); 1032 bool showArgumentErrors() const; 1033 void beginTemporaryStopMessages(); 1034 int endTemporaryStopMessages(int *message_count = NULL, int *warning_count = NULL, int release_messages_if_no_equal_or_greater_than_message_type = -1); 1035 void endTemporaryStopMessages(bool release_messages, std::vector<CalculatorMessage> *blocked_messages = NULL); 1036 void addMessages(std::vector<CalculatorMessage> *message_vector); 1037 const PrintOptions &messagePrintOptions() const; 1038 void setMessagePrintOptions(const PrintOptions &po); 1039 void cleanMessages(const MathStructure &mstruct, size_t first_message = 1); 1040 //@} 1041 1042 /** @name Functions for loading and saving definitions (variables, functions, units, etc.). */ 1043 //@{ 1044 /** Load all standard global (system wide) definitions from the global data directory ($PREFIX/share/qalculate). 1045 * 1046 * @returns true if the definitions were successfully loaded. 1047 */ 1048 bool loadGlobalDefinitions(); 1049 /** Load global (system wide) definitions from a file in the global data directory ($PREFIX/share/qalculate). 1050 * 1051 * @param filename Name of the file in the global data directory. 1052 * @returns true if the definitions were successfully loaded. 1053 */ 1054 bool loadGlobalDefinitions(std::string filename); 1055 /** Load prefixes. 1056 * 1057 * @returns true if the definitions were successfully loaded. 1058 */ 1059 bool loadGlobalPrefixes(); 1060 /** Load currencies. 1061 * 1062 * @returns true if the definitions were successfully loaded. 1063 */ 1064 bool loadGlobalCurrencies(); 1065 /** Load units. 1066 * 1067 * @returns true if the definitions were successfully loaded. 1068 */ 1069 bool loadGlobalUnits(); 1070 /** Load variables. 1071 * 1072 * @returns true if the definitions were successfully loaded. 1073 */ 1074 bool loadGlobalVariables(); 1075 /** Load functions. 1076 * 1077 * @returns true if the definitions were successfully loaded. 1078 */ 1079 bool loadGlobalFunctions(); 1080 /** Load data sets. 1081 * 1082 * @returns true if the definitions were successfully loaded. 1083 */ 1084 bool loadGlobalDataSets(); 1085 /** Load local, user specific, definitions from the local definitions directory (~/.qalculate/definitions). 1086 * All files in the directory and in the datasets subdirectory are loaded. 1087 * 1088 * @returns true if the definitions were successfully loaded. 1089 */ 1090 bool loadLocalDefinitions(); 1091 /** Load definitions from a file. 1092 * 1093 * @param file_name The path to the file to load. 1094 * @param is_user_defs true if the definitions are local, false if they are global. 1095 * @returns true if the definitions were successfully loaded. 1096 */ 1097 int loadDefinitions(const char *file_name, bool is_user_defs = true, bool check_duplicates_of_global = false); 1098 /** Save local definitions to ~/.qalculate/definitions/ 1099 * 1100 * @returns true if definitions was successfully saved. 1101 */ 1102 bool saveDefinitions(); 1103 int saveDataObjects(); 1104 int savePrefixes(const char *file_name, bool save_global = false); 1105 std::string temporaryCategory(void) const; 1106 int saveVariables(const char *file_name, bool save_global = false); 1107 int saveUnits(const char *file_name, bool save_global = false); 1108 int saveFunctions(const char *file_name, bool save_global = false); 1109 int saveDataSets(const char *file_name, bool save_global = false); 1110 //@} 1111 1112 /** @name Functions for CSV file import/export. */ 1113 //@{ 1114 bool importCSV(MathStructure &mstruct, const char *file_name, int first_row = 1, std::string delimiter = ",", std::vector<std::string> *headers = NULL); 1115 bool importCSV(const char *file_name, int first_row = 1, bool headers = true, std::string delimiter = ",", bool to_matrix = false, std::string name = "", std::string title = "", std::string category = ""); 1116 bool exportCSV(const MathStructure &mstruct, const char *file_name, std::string delimiter = ","); 1117 //@} 1118 1119 /** @name Functions for exchange rates. */ 1120 /** Checks if able to downloading exchange rates from the Internet (using libcurl). 1121 * 1122 * @returns true if exchange rates can downloaded (if libcurl is available). 1123 */ 1124 bool canFetch(); 1125 ///Deprecated: gvfs is not needed anymore. 1126 bool hasGVFS(); 1127 ///Deprecated: gvfs is not needed anymore. 1128 bool hasGnomeVFS(); 1129 /** Load exchange rates. Use before loadGlobalCurrencies() or loadGlobalDefinitions(). 1130 * 1131 * @returns true if operation successful. 1132 */ 1133 bool loadExchangeRates(); 1134 /** Name of the exchange rates file on local disc. 1135 * Multiple exchange rates sources might be used. Iterate over these, using the index parameter, until an empty string is returned. 1136 * 1137 * @param index The index (starting at one) of the exchange rate source 1138 * @returns name of local exchange rates file. 1139 */ 1140 std::string getExchangeRatesFileName(int index = 1); 1141 /** Url of the exchange rates file on the Internet. 1142 * Multiple exchange rates sources might be used. Iterate over these, using the index parameter, until an empty string is returned. 1143 * 1144 * @param index The index (starting at one) of the exchange rate source 1145 * @returns Url of exchange rates file. 1146 */ 1147 std::string getExchangeRatesUrl(int index = 1); 1148 /** Modification time of the exchange rates file. 1149 * 1150 * @returns Returns exchange rates modification time. 1151 */ 1152 time_t getExchangeRatesTime(int index = -1); 1153 ///Deprecated: wget arguments are not used 1154 bool fetchExchangeRates(int seconds, std::string wget_args); 1155 /** Download current exchange rates from the Internet to local disc with default wget arguments. 1156 * 1157 * @param seconds Maximum time for donwload try 1158 * @returns true if operation was successful. 1159 */ 1160 bool fetchExchangeRates(int seconds = 15, int n = -1); 1161 /** Check age of exchange rates on local disc. 1162 * 1163 * @param n_days How old in days exchange rates may be before exchange rates need updating 1164 * @param force_check If exchange rates date should be checked again even if found outdated within n_days before 1165 * @param send_warning If the standard exchange rates warning should be sent. 1166 * @returns false if exchange.rates need updating 1167 */ 1168 bool checkExchangeRatesDate(unsigned int n_days = 7, bool force_check = false, bool send_warning = false, int n = -1); 1169 /// Enable or disable old exchange rates warning (initial state is true). 1170 void setExchangeRatesWarningEnabled(bool enable); 1171 bool exchangeRatesWarningEnabled() const; 1172 /// Check if exchange rates has been used since resetExchangeRatesUsed() was last called 1173 int exchangeRatesUsed() const; 1174 void resetExchangeRatesUsed(); 1175 /// For internal use, called by currency units 1176 void setExchangeRatesUsed(int index); 1177 //@} 1178 1179 /** @name Functions for plotting */ 1180 //@{ 1181 /** Checks if gnuplot is available. 1182 * 1183 * @returns true if gnuplot was found. 1184 */ 1185 bool canPlot(); 1186 MathStructure expressionToPlotVector(std::string expression, const MathStructure &min, const MathStructure &max, int steps, MathStructure *x_vector = NULL, std::string x_var = "\\x", const ParseOptions &po = default_parse_options, int msecs = 5000); 1187 MathStructure expressionToPlotVector(std::string expression, float min, float max, int steps, MathStructure *x_vector = NULL, std::string x_var = "\\x", const ParseOptions &po = default_parse_options, int msecs = 5000); 1188 MathStructure expressionToPlotVector(std::string expression, const MathStructure &min, const MathStructure &max, const MathStructure &step, MathStructure *x_vector = NULL, std::string x_var = "\\x", const ParseOptions &po = default_parse_options, int msecs = 5000); 1189 MathStructure expressionToPlotVector(std::string expression, float min, float max, float step, MathStructure *x_vector = NULL, std::string x_var = "\\x", const ParseOptions &po = default_parse_options, int msecs = 5000); 1190 MathStructure expressionToPlotVector(std::string expression, const MathStructure &x_vector, std::string x_var = "\\x", const ParseOptions &po = default_parse_options, int msecs = 5000); 1191 bool plotVectors(PlotParameters *param, const std::vector<MathStructure> &y_vectors, const std::vector<MathStructure> &x_vectors, std::vector<PlotDataParameters*> &pdps, bool persistent = false, int msecs = 5000); 1192 bool invokeGnuplot(std::string commands, std::string commandline_extra = "", bool persistent = false); 1193 bool closeGnuplot(); 1194 bool gnuplotOpen(); 1195 //@} 1196 1197 /** @name Functions for global precision */ 1198 //@{ 1199 /** Set default precision for approximate calculations. 1200 * 1201 * @param precision Precision. 1202 */ 1203 void setPrecision(int precision = DEFAULT_PRECISION); 1204 /** Returns default precision for approximate calculations. 1205 */ 1206 int getPrecision() const; 1207 /** Set if interval should be produced for approximate functions and irrational numbers. 1208 * This does not affect calculation of lower precision explicit intervals (uncertainty propagation). 1209 * 1210 * @param use_interval_arithmetic Set true to activate, or false to deactivate, interval arithmetic. 1211 */ 1212 void useIntervalArithmetic(bool use_interval_arithmetic = true); 1213 /** Returns true if interval arithmetic are activated. 1214 */ 1215 bool usesIntervalArithmetic() const; 1216 void beginTemporaryStopIntervalArithmetic(); 1217 void endTemporaryStopIntervalArithmetic(); 1218 void beginTemporaryEnableIntervalArithmetic(); 1219 void endTemporaryEnableIntervalArithmetic(); 1220 //@} 1221 1222 void setCustomInputBase(Number nr); 1223 void setCustomOutputBase(Number nr); 1224 const Number &customInputBase() const; 1225 const Number &customOutputBase() const; 1226 1227 /** @name Functions for localization */ 1228 //@{ 1229 /** Returns the preferred decimal point character. 1230 */ 1231 const std::string &getDecimalPoint() const; 1232 /** Returns the preferred comma character for separating arguments.*/ 1233 const std::string &getComma() const; 1234 /** Sets argument separator and decimal sign from the current locale. Mainly for internal use. */ 1235 void setLocale(); 1236 ///Deprecated: use pass true to constructor instead 1237 void setIgnoreLocale(); 1238 bool getIgnoreLocale(); 1239 void useDecimalComma(); 1240 /** Use point as decimal separator. 1241 * To use comma as an ignored separator in numbers, must be invoked with comma_as_separator = true, to change the default function argument separator to semicolon, in addition to using ParseOptions::comma_as_separator. 1242 */ 1243 void useDecimalPoint(bool comma_as_separator = false); 1244 /** Resets argument separator and decimal sign. Mainly for internal use. */ 1245 void unsetLocale(); 1246 /** Returns the translated text string used in expressions for converting to a specific unit expression (ex "5 meters to feet.*/ 1247 std::string localToString(bool include_spaces = true) const; 1248 std::string localWhereString() const; 1249 //@} 1250 1251 /** @name Functions adding alternative symbols for operators and such */ 1252 //@{ 1253 void addStringAlternative(std::string replacement, std::string standard); 1254 bool delStringAlternative(std::string replacement, std::string standard); 1255 void addDefaultStringAlternative(std::string replacement, std::string standard); 1256 bool delDefaultStringAlternative(std::string replacement, std::string standard); 1257 //@} 1258 1259 /** @name Functions for storing values with associated identifiers */ 1260 //@{ 1261 /** Stores a value with an associated id. Mainly for internal use. 1262 * 1263 * @param mstruct The value to store. 1264 * @param persistent If false the values will be removed from storage when retrieved with getId(). 1265 * @returns Storage id. 1266 */ 1267 size_t addId(MathStructure *mstruct, bool persistent = false); 1268 /** Stores a function value with arguments parsed from a text string using Function::parse(), with an associated id. Mainly for internal use. 1269 * 1270 * @param f Mathematical function. 1271 * @param str Arguments. 1272 * @param po Parse options. 1273 * @param persistent If false the values will be removed from storage when retrieved with getId(). 1274 * @returns Storage id. 1275 */ 1276 size_t parseAddId(MathFunction *f, const std::string &str, const ParseOptions &po, bool persistent = false); 1277 size_t parseAddIdAppend(MathFunction *f, const MathStructure &append_mstruct, const std::string &str, const ParseOptions &po, bool persistent = false); 1278 size_t parseAddVectorId(const std::string &str, const ParseOptions &po, bool persistent = false); 1279 /** Returns a stored value. Mainly for internal use. 1280 * 1281 * @param id Storage id. 1282 * @returns A stored value. 1283 */ 1284 MathStructure *getId(size_t id); 1285 /** Removes and unreferences (value->unref() will be called) a value from storage. Mainly for internal use. 1286 * 1287 * @param id Storage id. 1288 */ 1289 void delId(size_t id); 1290 //@} 1291 1292 }; 1293 1294 #endif 1295