void saveCWDInPreferences() { const char * keys[] = {"use", "previous"}; char ** values = getPrefAttributesValues("//general/body/startup", keys, sizeof(keys) / sizeof(const char *)); if (values) { if (values[0] && stricmp(values[0], "previous") == 0) { int err; char * cwd = scigetcwd(&err); if (!err && cwd && values[1] && strcmp(cwd, values[1])) { const char * kv[] = {"previous", cwd}; setPrefAttributesValues("//general/body/startup", kv, sizeof(kv) / sizeof(const char *)); } if (cwd) { FREE(cwd); } } if (values[0]) { FREE(values[0]); } if (values[1]) { FREE(values[1]); } FREE(values); } }
/*--------------------------------------------------------------------------*/ int openHDF5File(const char *name, int _iAppendMode) { hid_t file; char *pathdest = getPathFilename(name); char *currentpath = NULL; char *filename = getFilenameWithExtension(name); int ierr = 0; void *oldclientdata = NULL; /* Used to avoid stack trace to be displayed */ H5E_auto2_t oldfunc; /* TO DO : remove when HDF5 will be fixed ... */ /* HDF5 does not manage no ANSI characters */ /* UGLY workaround :( */ /* We split path, move in this path, open file */ /* and return in previous place */ /* see BUG 6440 */ currentpath = scigetcwd(&ierr); //prevent error msg to change directory to "" if (strcmp(pathdest, "") != 0) { scichdir(pathdest); } /* Save old error handler */ H5Eget_auto2(H5E_DEFAULT, &oldfunc, &oldclientdata); /* Turn off error handling */ H5Eset_auto2(H5E_DEFAULT, NULL, NULL); if (_iAppendMode == 0) { //read only file = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT); } else { //read write to append file = H5Fopen(filename, H5F_ACC_RDWR, H5P_DEFAULT); } /* The following test will display the backtrace in case of error */ /* Deactivated because displayed each time we call 'load' to open a non-HDF5 file */ /*if (file < 0) { H5Eprint(stderr); }*/ /* Restore previous error handler */ H5Eset_auto2(H5E_DEFAULT, oldfunc, oldclientdata); scichdir(currentpath); FREE(currentpath); FREE(filename); FREE(pathdest); return file; }
/*--------------------------------------------------------------------------*/ int createHDF5File(const char *name) { hid_t file; hid_t fapl = H5Pcreate(H5P_FILE_ACCESS); char *pathdest = getPathFilename(name); char *currentpath = NULL; char *filename = getFilenameWithExtension(name); int ierr = 0; //H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG); /* TO DO : remove when HDF5 will be fixed ... */ /* HDF5 does not manage no ANSI characters */ /* UGLY workaround :( */ /* We split path, move in this path, open file */ /* and return in previous place */ /* see BUG 6440 */ currentpath = scigetcwd(&ierr); //prevent error msg to change directory to "" if (strcmp(pathdest, "") != 0) { scichdir(pathdest); } FREE(pathdest); /*bug 5629 : to prevent replace directory by file*/ if (isdir(filename)) { FREE(filename); FREE(currentpath); return -2; } if (FileExist(filename)) { deleteafile(filename); } /* * Create a new file using the default properties. */ file = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, fapl); scichdir(currentpath); FREE(currentpath); FREE(filename); return file; }
/*--------------------------------------------------------------------------*/ int isHDF5File(const char* _pstFilename) { int iRet = 0; char *pathdest = getPathFilename(_pstFilename); char *currentpath = NULL; char *filename = getFilenameWithExtension(_pstFilename); int ierr = 0; /* TO DO : remove when HDF5 will be fixed ... */ /* HDF5 does not manage no ANSI characters */ /* UGLY workaround :( */ /* We split path, move in this path, open file */ /* and return in previous place */ /* see BUG 6440 */ currentpath = scigetcwd(&ierr); //prevent error msg to change directory to "" if (strcmp(pathdest, "") != 0) { scichdir(pathdest); } FREE(pathdest); iRet = H5Fis_hdf5(filename); if (iRet == 0) { HDF5ErrorCleanup(); } FREE(filename); scichdir(currentpath); FREE(currentpath); return iRet > 0 ? 1 : 0; }
/*--------------------------------------------------------------------------*/ int sci_findfiles(char *fname, unsigned long fname_len) { static int l1 = 0, n1 = 0, m1 = 0; char *pathextented = NULL; char *path = NULL; char *filespec = NULL; char **FilesList = NULL; int sizeListReturned = 0; Rhs = Max(Rhs, 0); CheckRhs(0, 2); CheckLhs(0, 1); switch (Rhs) { default: case 0: { int ierr = 0; path = scigetcwd(&ierr); if (ierr) { Scierror(999, _("%s: Error while trying to retrieve the name of the current directory.\n"), fname); return 0; } else { filespec = strdup(DEFAULT_FILESPEC); } } break; case 1: { if (GetType(1) == sci_strings) { GetRhsVar(1, STRING_DATATYPE, &m1, &n1, &l1); path = strdup(cstk(l1)); filespec = strdup(DEFAULT_FILESPEC); } else { Scierror(999, _("%s: Wrong type for input argument #%d: String expected.\n"), fname, 1); return 0; } } break; case 2: { if ((GetType(1) == sci_strings) && (GetType(2) == sci_strings)) { GetRhsVar(1, STRING_DATATYPE, &m1, &n1, &l1); path = strdup(cstk(l1)); GetRhsVar(2, STRING_DATATYPE, &m1, &n1, &l1); filespec = strdup(cstk(l1)); } else { Scierror(999, _("%s: Wrong type for input arguments: Strings expected.\n"), fname); return 0; } } break; } pathextented = expandPathVariable(path); if (path) { FREE(path); path = NULL; } FilesList = findfiles(pathextented, filespec, &sizeListReturned, FALSE); if (pathextented) { FREE(pathextented); pathextented = NULL; } if (filespec) { FREE(filespec); filespec = NULL; } if (FilesList) { int ncol = 0, nrow = 0; ncol = 1; nrow = sizeListReturned; CreateVarFromPtr(Rhs + 1, MATRIX_OF_STRING_DATATYPE, &nrow, &ncol, FilesList); LhsVar(1) = Rhs + 1; } else { n1 = 0; m1 = 0; l1 = 0; CreateVarFromPtr(Rhs + 1, MATRIX_OF_DOUBLE_DATATYPE, &n1, &m1, &l1); LhsVar(1) = Rhs + 1; } freeArrayOfString(FilesList, sizeListReturned); PutLhsVar(); return 0; }
int StaticRunner::launch() { //set execution thread in java if (!initialJavaHooks && getScilabMode() != SCILAB_NWNI) { initialJavaHooks = true; // Execute the initial hooks registered in Scilab.java ExecuteInitialHooks(); } int iRet = 0; // get the runner to execute std::unique_ptr<Runner> runMe(getRunner()); // set if the current comment is interruptible setInterruptibleCommand(runMe->isInterruptible()); debugger::DebuggerMagager* manager = debugger::DebuggerMagager::getInstance(); ConfigVariable::resetExecutionBreak(); int oldMode = ConfigVariable::getPromptMode(); symbol::Context* pCtx = symbol::Context::getInstance(); int scope = pCtx->getScopeLevel(); // a TCL command display nothing int iOldPromptMode = 0; if (runMe->getCommandOrigin() == TCLSCI) { iOldPromptMode = ConfigVariable::getPromptMode(); ConfigVariable::setPromptMode(-1); } try { int level = ConfigVariable::getRecursionLevel(); try { runMe->getProgram()->accept(*(runMe->getVisitor())); } catch (const ast::RecursionException& re) { // management of pause if (ConfigVariable::getPauseLevel()) { ConfigVariable::DecreasePauseLevel(); throw re; } //close opened scope during try while (pCtx->getScopeLevel() > scope) { pCtx->scope_end(); } //decrease recursion to init value and close where while (ConfigVariable::getRecursionLevel() > level) { ConfigVariable::where_end(); ConfigVariable::decreaseRecursion(); } ConfigVariable::resetWhereError(); ConfigVariable::setPromptMode(oldMode); //print msg about recursion limit and trigger an error wchar_t sz[1024]; os_swprintf(sz, 1024, _W("Recursion limit reached (%d).\n").data(), ConfigVariable::getRecursionLimit()); throw ast::InternalError(sz); } } catch (const ast::InternalError& se) { if (runMe->getCommandOrigin() == TCLSCI) { ConfigVariable::setPromptMode(iOldPromptMode); } std::wostringstream ostr; ConfigVariable::whereErrorToString(ostr); scilabErrorW(ostr.str().c_str()); scilabErrorW(se.GetErrorMessage().c_str()); ConfigVariable::resetWhereError(); iRet = 1; } catch (const ast::InternalAbort& ia) { if (runMe->getCommandOrigin() == TCLSCI) { ConfigVariable::setPromptMode(iOldPromptMode); } // management of pause if (ConfigVariable::getPauseLevel()) { ConfigVariable::DecreasePauseLevel(); throw ia; } // close all scope before return to console scope symbol::Context* pCtx = symbol::Context::getInstance(); while (pCtx->getScopeLevel() > scope) { pCtx->scope_end(); } // send the good signal about the end of execution sendExecDoneSignal(runMe.get()); //clean debugger step flag if debugger is not interrupted ( end of debug ) manager->resetStep(); throw ia; } if (runMe->getCommandOrigin() == TCLSCI) { ConfigVariable::setPromptMode(iOldPromptMode); } if (getScilabMode() != SCILAB_NWNI && getScilabMode() != SCILAB_API) { char *cwd = NULL; int err = 0; UpdateBrowseVar(); cwd = scigetcwd(&err); if (cwd) { FileBrowserChDir(cwd); FREE(cwd); } } // reset error state when new prompt occurs ConfigVariable::resetError(); // send the good signal about the end of execution sendExecDoneSignal(runMe.get()); //clean debugger step flag if debugger is not interrupted ( end of debug ) manager->resetStep(); return iRet; }
int ScilabGateway::deff(char * fname, const int envId, void * pvApiCtx) { static int ONE = 1; static int TWO = 2; static int THREE = 3; SciErr err; char ** names[] = {0, 0, 0}; int ret = 0; std::ostringstream os; char * str; int * addr[] = {0, 0, 0}; int rows[] = {0, 0, 0}; int cols[] = {0, 0, 0}; int error = 0; char * cwd = 0; CheckInputArgument(pvApiCtx, 3, 3); ScilabAbstractEnvironment & env = ScilabEnvironments::getEnvironment(envId); ScilabGatewayOptions & options = env.getGatewayOptions(); OptionsHelper & helper = env.getOptionsHelper(); OptionsHelper::setCopyOccurred(false); ScilabObjects::initialization(env, pvApiCtx); options.setIsNew(false); for (int i = 0; i < 3; i++) { err = getVarAddressFromPosition(pvApiCtx, i + 1, &(addr[i])); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } if (!isStringType(pvApiCtx, addr[i])) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Wrong type for input argument #%d: A String expected."), 1); } err = getVarDimension(pvApiCtx, addr[i], &(rows[i]), &(cols[i])); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } if (rows[0] != 1 || cols[0] != 1) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid dimensions for input argument #%d: A single string expected."), 1); } if (rows[1] != rows[2] || cols[1] != cols[2]) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid dimensions: arguments #2 and #3 must have the same.")); } for (int i = 0; i < 3; i++) { if (getAllocatedMatrixOfString(pvApiCtx, addr[i], &(rows[i]), &(cols[i]), &(names[i]))) { for (int j = 0; j < i; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } cwd = scigetcwd(&error); if (error) { FREE(cwd); cwd = 0; } try { ret = env.loadclass(names[0][0], cwd, false, helper.getAllowReload()); } catch (std::exception & e) { FREE(cwd); for (int j = 0; j < 3; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } throw; } FREE(cwd); for (int i = 0; i < rows[1] * cols[1]; i++) { err = createMatrixOfString(pvApiCtx, ONE, 1, 1, (const char * const *) & (names[2][i])); if (err.iErr) { for (int j = 0; j < 3; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } env.removeobject(ret); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot create the data")); } os.str(""); os << "y=" << names[2][i] << "(varargin)" << std::flush; str = strdup(os.str().c_str()); err = createMatrixOfString(pvApiCtx, TWO, 1, 1, (const char * const *)&str); free(str); if (err.iErr) { for (int j = 0; j < 3; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } env.removeobject(ret); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot create the data")); } os.str(""); os << "y=invoke_lu(int32(" << ret << "),int32(" << envId << "),\"" << names[1][i] << "\",varargin)" << std::flush; str = strdup(os.str().c_str()); err = createMatrixOfString(pvApiCtx, THREE, 1, 1, (const char * const *)&str); free(str); if (err.iErr) { for (int j = 0; j < 3; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } env.removeobject(ret); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot create the data")); } SciString(&ONE, const_cast<char *>("!_deff_wrapper"), &ONE, &THREE); } for (int i = 0; i < 3; i++) { freeAllocatedMatrixOfString(rows[0], cols[0], names[i]); } LhsVar(1) = 0; PutLhsVar(); return 0; }
int ScilabGateway::deff(char * fname, const int envId, void * pvApiCtx) { static int ONE = 1; static int TWO = 2; static int THREE = 3; SciErr err; char ** names[] = {0, 0, 0}; int ret = 0; std::ostringstream os; int * addr[] = {0, 0, 0}; int rows[] = {0, 0, 0}; int cols[] = {0, 0, 0}; int error = 0; char * cwd = 0; CheckInputArgument(pvApiCtx, 3, 3); ScilabAbstractEnvironment & env = ScilabEnvironments::getEnvironment(envId); ScilabGatewayOptions & options = env.getGatewayOptions(); OptionsHelper & helper = env.getOptionsHelper(); OptionsHelper::setCopyOccurred(false); ScilabObjects::initialization(env, pvApiCtx); options.setIsNew(false); if (pCall == nullptr) { symbol::Context* ctx = symbol::Context::getInstance(); types::InternalType* pIT = ctx->get(symbol::Symbol(L"#_deff_wrapper")); if (pIT && pIT->isCallable()) { pCall = pIT->getAs<types::Callable>(); } else { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } for (int i = 0; i < 3; i++) { err = getVarAddressFromPosition(pvApiCtx, i + 1, &(addr[i])); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } if (!isStringType(pvApiCtx, addr[i])) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Wrong type for input argument #%d: A String expected."), 1); } err = getVarDimension(pvApiCtx, addr[i], &(rows[i]), &(cols[i])); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } if (rows[0] != 1 || cols[0] != 1) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid dimensions for input argument #%d: A single string expected."), 1); } if (rows[1] != rows[2] || cols[1] != cols[2]) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid dimensions: arguments #2 and #3 must have the same.")); } for (int i = 0; i < 3; i++) { if (getAllocatedMatrixOfString(pvApiCtx, addr[i], &(rows[i]), &(cols[i]), &(names[i]))) { for (int j = 0; j < i; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } cwd = scigetcwd(&error); if (error) { FREE(cwd); cwd = 0; } try { ret = env.loadclass(names[0][0], cwd, false, helper.getAllowReload()); } catch (std::exception & /*e*/) { FREE(cwd); for (int j = 0; j < 3; j++) { freeAllocatedMatrixOfString(rows[j], cols[j], names[j]); } throw; } FREE(cwd); for (int i = 0; i < rows[1] * cols[1]; i++) { //call #_deff_wrapper types::typed_list in, out; types::optional_list opt; //name in.push_back(new types::String(names[2][i])); //protopype os.str(""); os << "y=" << names[2][i] << "(varargin)" << std::flush; in.push_back(new types::String(os.str().c_str())); //body os.str(""); os << "y=invoke_lu(int32(" << ret << "),int32(" << envId << "),\"" << names[1][i] << "\",varargin)" << std::flush; in.push_back(new types::String(os.str().c_str())); ast::ExecVisitor exec; if (pCall->call(in, opt, 0, out, &exec) != types::Function::OK) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot create the data")); } } for (int i = 0; i < 3; i++) { freeAllocatedMatrixOfString(rows[0], cols[0], names[i]); } LhsVar(1) = 0; PutLhsVar(); return 0; }
/* * Previously called zzledt... Called by Fortran... * Now renamed to EventLoopPrompt * @TODO remove unused arg buf_size, menusflag, modex & dummy1 */ void C2F(eventloopprompt) (char *buffer, int *buf_size, int *len_line, int *eof) { if (getScilabMode() == SCILAB_API) { return; } if (!initialJavaHooks && getScilabMode() != SCILAB_NWNI) { initialJavaHooks = TRUE; // Execute the initial hooks registered in Scilab.java ExecuteInitialHooks(); } /* if not an interactive terminal */ #ifdef _MSC_VER /* if file descriptor returned is -2 stdin is not associated with an input stream */ /* example : echo plot3d | scilex -nw -e */ if (!isatty(fileno(stdin)) && (fileno(stdin) != -2) && getScilabMode() != SCILAB_STD) #else if (!isatty(fileno(stdin)) && getScilabMode() != SCILAB_STD) #endif { /* remove newline character if there */ if (__CommandLine != NULL) { /* read a line into the buffer, but not too * big */ *eof = (fgets(__CommandLine, *buf_size, stdin) == NULL); *len_line = (int)strlen(__CommandLine); /* remove newline character if there */ if (__CommandLine[*len_line - 1] == '\n') { (*len_line)--; } return; } } if (!initialized) { initAll(); } __LockSignal(pReadyForLaunch); if (__CommandLine) { FREE(__CommandLine); __CommandLine = NULL; } __CommandLine = strdup(""); if (ismenu() == 0) { if (!WatchGetCmdLineThreadAlive) { if (WatchGetCmdLineThread) { __WaitThreadDie(WatchGetCmdLineThread); } if (getScilabMode() != SCILAB_NWNI) { char *cwd = NULL; int err = 0; UpdateBrowseVar(TRUE); cwd = scigetcwd(&err); if (cwd) { FileBrowserChDir(cwd); FREE(cwd); } } __CreateThread(&WatchGetCmdLineThread, &watchGetCommandLine); WatchGetCmdLineThreadAlive = TRUE; } if (!WatchStoreCmdThreadAlive) { if (WatchStoreCmdThread) { __WaitThreadDie(WatchStoreCmdThread); } __CreateThread(&WatchStoreCmdThread, &watchStoreCommand); WatchStoreCmdThreadAlive = TRUE; } __Wait(&TimeToWork, pReadyForLaunch); } __UnLockSignal(pReadyForLaunch); /* ** WARNING : Old crappy f.... code ** do not change reference to buffer ** or fortran will be lost !!!! */ if (__CommandLine) { strcpy(buffer, __CommandLine); } else { strcpy(buffer, ""); } *len_line = (int)strlen(buffer); *eof = FALSE; }
int ScilabGateway::import(char * fname, const int envId, void * pvApiCtx) { SciErr err; int rows, cols; char ** className = 0; std::string * name = 0; int named = 1; int * addr = 0; int ret = 0; int nbArgs = Rhs; int error = 0; char * cwd = 0; CheckInputArgumentAtLeast(pvApiCtx, 1); ScilabAbstractEnvironment & env = ScilabEnvironments::getEnvironment(envId); OptionsHelper & helper = env.getOptionsHelper(); ScilabGatewayOptions & options = env.getGatewayOptions(); OptionsHelper::setCopyOccurred(false); ScilabObjects::initialization(env, pvApiCtx); options.setIsNew(false); err = getVarAddressFromPosition(pvApiCtx, Rhs, &addr); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } if (isBooleanType(pvApiCtx, addr)) { nbArgs = Rhs - 1; if (getScalarBoolean(pvApiCtx, addr, &named)) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } if (nbArgs == 1) { err = getVarAddressFromPosition(pvApiCtx, 1, &addr); if (err.iErr) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } if (!isStringType(pvApiCtx, addr)) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Wrong type for input argument #%d: A String expected."), 1); } if (getAllocatedMatrixOfString(pvApiCtx, addr, &rows, &cols, &className)) { throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } else { className = (char**)MALLOC(sizeof(char *) * nbArgs); for (int i = 1; i <= nbArgs; i++) { err = getVarAddressFromPosition(pvApiCtx, i, &addr); if (err.iErr) { freeAllocatedMatrixOfString(1, i, className); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } if (!isStringType(pvApiCtx, addr)) { freeAllocatedMatrixOfString(1, i, className); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Wrong type for input argument #%d: A String expected."), i); } if (getAllocatedSingleString(pvApiCtx, addr, &(className[i - 1]))) { freeAllocatedMatrixOfString(1, i, className); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Invalid variable: cannot retrieve the data")); } } rows = 1; cols = nbArgs; } if (named) { name = new std::string[rows * cols]; for (int i = 0; i < rows * cols; i++) { name[i] = std::string(className[i]); if (helper.getUseLastName()) { std::size_t pos = name[i].find_last_of('.'); if (pos != std::string::npos) { if (pos == name[i].size() - 1) { freeAllocatedMatrixOfString(rows, cols, className); delete[] name; throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("The class name cannot end with a dot.")); } name[i] = name[i].substr(pos + 1); } } else { std::size_t pos = name[i].find_first_of('.'); if (pos != std::string::npos) { if (pos == 0) { freeAllocatedMatrixOfString(rows, cols, className); delete[] name; throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("The class name cannot start with a dot.")); } name[i] = name[i].substr(0, pos); } } if (isNamedVarExist(pvApiCtx, name[i].c_str())) { addr = 0; err = getVarAddressFromName(pvApiCtx, name[i].c_str(), &addr); if (err.iErr || addr == 0 || !ScilabObjects::isValidExternal(addr, pvApiCtx) || ScilabObjects::getEnvironmentId(addr, pvApiCtx) != envId) { freeAllocatedMatrixOfString(rows, cols, className); delete[] name; throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("A variable with this name is already existing")); } } } } if (!named && rows * cols != Lhs) { freeAllocatedMatrixOfString(rows, cols, className); throw ScilabAbstractEnvironmentException(__LINE__, __FILE__, gettext("Bad number of output arguments"), __FILE__, __LINE__); } const int type = helper.getNewAllowed() ? EXTERNAL_CLASS : EXTERNAL_OBJECT; cwd = scigetcwd(&error); if (error) { FREE(cwd); cwd = 0; } for (int i = 0; i < rows * cols; i++) { try { ret = env.loadclass(className[i], cwd, static_cast<bool>(named), helper.getAllowReload()); } catch (std::exception & e) { FREE(cwd); freeAllocatedMatrixOfString(rows, cols, className); if (named) { delete[] name; } throw; } if (named) { try { ScilabObjects::createNamedEnvironmentObject(type, name[i].c_str(), ret, envId, pvApiCtx); } catch (ScilabAbstractEnvironmentException & e) { FREE(cwd); freeAllocatedMatrixOfString(rows, cols, className); delete[] name; throw; } } else { try { ScilabObjects::createEnvironmentObjectAtPos(type, Rhs + i + 1, ret, envId, pvApiCtx); } catch (ScilabAbstractEnvironmentException & e) { FREE(cwd); freeAllocatedMatrixOfString(rows, cols, className); env.removeobject(ret); throw; } LhsVar(i + 1) = Rhs + i + 1; } } FREE(cwd); freeAllocatedMatrixOfString(rows, cols, className); if (named) { delete[] name; LhsVar(1) = 0; } PutLhsVar(); return 0; }
/* ==================================================================== */ char *downloadFile(char *url, char *dest, char *username, char *password, char **content) { CURL *curl; CURLcode res; char *filename = NULL; FILE *file; inputString buffer; char *destdir = NULL; char *destfile = NULL; curl = curl_easy_init(); if (curl == NULL) { Scierror(999, "Failed opening the curl handle.\n"); return NULL; } res = curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); if (res != CURLE_OK) { Scierror(999, "Failed to set error buffer [%d]\n", res); return NULL; } // Get destination directory and filename if (dest != NULL) { // Destination is specified in argument char* pathdrive = (char*)MALLOC(sizeof(char) * (PATH_MAX + 1)); char* pathdir = (char*)MALLOC(sizeof(char) * (PATH_MAX + 1)); char* pathfile = (char*)MALLOC(sizeof(char) * (PATH_MAX + 1)); char* pathext = (char*)MALLOC(sizeof(char) * (PATH_MAX + 1)); splitpath(dest, TRUE, pathdrive, pathdir, pathfile, pathext); if (!isdir(dest)) { // Destination is a file destdir = (char *)MALLOC((strlen(pathdrive) + strlen(pathdir) + 1) * sizeof(char)); strcpy(destdir, pathdrive); strcat(destdir, pathdir); // Get filename destfile = (char *)MALLOC((strlen(pathfile) + strlen(pathext) + 1) * sizeof(char)); strcpy(destfile, pathfile); strcat(destfile, pathext); } else { // Destination is a directory destdir = (char *)MALLOC((strlen(pathdrive) + strlen(pathdir) + strlen(pathfile) + strlen(pathext) + strlen(DIR_SEPARATOR) + 1) * sizeof(char)); strcpy(destdir, pathdrive); strcat(destdir, pathdir); strcat(destdir, pathfile); strcat(destdir, pathext); strcat(destdir, DIR_SEPARATOR); // Retrieve filename from URL destfile = getFileNameFromURL(url); } FREE(pathdrive); FREE(pathdir); FREE(pathfile); FREE(pathext); } else { // Destination is not specified in argument // Destination directory is current dir int err = 0; char *currentdir; currentdir = scigetcwd(&err); if (!err) { destdir = (char *)MALLOC((strlen(currentdir) + strlen(DIR_SEPARATOR) + 1) * sizeof(char)); strcpy(destdir, currentdir); strcat(destdir, DIR_SEPARATOR); FREE(currentdir); } else { Scierror(999, _("Failed getting current dir, error code: %d\n"), err); return NULL; } // Destination filename retrieved from URL destfile = getFileNameFromURL(url); } if (destfile == NULL) { FREE(destdir); return NULL; } // Build file path filename = (char *)MALLOC((strlen(destdir) + strlen(destfile) + 1) * sizeof(char)); strcpy(filename, destdir); strcat(filename, destfile); FREE(destdir); FREE(destfile); res = curl_easy_setopt(curl, CURLOPT_URL, url); if (res != CURLE_OK) { Scierror(999, _("Failed to set URL [%s]\n"), errorBuffer); FREE(filename); return NULL; } //Set authentication variables if (username != NULL) { char * userpass; int uplen = (int)strlen(username); if (password != NULL) { uplen = uplen + (int)strlen(password); } res = curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); if (res != CURLE_OK) { Scierror(999, "Failed to set httpauth type to ANY [%s]\n", errorBuffer); return NULL; } userpass = (char *)MALLOC((uplen + 2) * sizeof(char)); strcpy(userpass, username); strcat(userpass, ":"); if (password != NULL) { strcat(userpass, password); } res = curl_easy_setopt(curl, CURLOPT_USERPWD, userpass); if (res != CURLE_OK) { FREE(filename); Scierror(999, _("Failed to set user:pwd [%s]\n"), errorBuffer); return NULL; } FREE(userpass); } /* end authentication section */ { //Set proxy variables char *proxyHost = NULL; char *proxyUserPwd = NULL; long proxyPort = 1080; int proxySet = 0; proxySet = getProxyValues(&proxyHost, &proxyPort, &proxyUserPwd); if (proxySet == 1) { res = curl_easy_setopt(curl, CURLOPT_PROXY, proxyHost); if (res != CURLE_OK) { FREE(proxyHost); FREE(proxyUserPwd); FREE(filename); Scierror(999, _("Failed to set proxy host [%s]\n"), errorBuffer); return NULL; } res = curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxyPort); if (res != CURLE_OK) { FREE(proxyHost); FREE(proxyUserPwd); FREE(filename); Scierror(999, _("Failed to set proxy port [%s]\n"), errorBuffer); return NULL; } if (proxyUserPwd != NULL) { res = curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxyUserPwd); if (res != CURLE_OK) { FREE(proxyHost); FREE(proxyUserPwd); FREE(filename); Scierror(999, _("Failed to set proxy user:password [%s]\n"), errorBuffer); return NULL; } } FREE(proxyHost); FREE(proxyUserPwd); } } /* end of the set of the proxy */ res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); if (res != CURLE_OK) { FREE(filename); Scierror(999, _("Failed to set write function [%s]\n"), errorBuffer); return NULL; } init_string(&buffer); //Get data to be written to the variable res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); if (res != CURLE_OK) { FREE(filename); free_string(&buffer); Scierror(999, _("Failed to set write data [%s]\n"), errorBuffer); return NULL; } // Follow redirects res = curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); if (res != CURLE_OK) { FREE(filename); free_string(&buffer); Scierror(999, _("Failed to set 'Follow Location' [%s]\n"), errorBuffer); return NULL; } res = curl_easy_perform(curl); if (res != 0) { FREE(filename); free_string(&buffer); Scierror(999, _("Transfer did not complete successfully: %s\n"), errorBuffer); return NULL; } wcfopen(file, (char*)filename, "wb"); if (file == NULL) { free_string(&buffer); Scierror(999, _("Failed opening '%s' for writing.\n"), filename); FREE(filename); return NULL; } /* Write the file */ fwrite(buffer.ptr, sizeof(char), buffer.len, file); /* Create the variable which contains the output argument */ *content = buffer.ptr; /* always cleanup */ curl_easy_cleanup(curl); fclose(file); return filename; }
/*--------------------------------------------------------------------------*/ types::Function::ReturnValue sci_genlib(types::typed_list &in, int _iRetCount, types::typed_list &out) { int succes = 1; std::vector<std::wstring> failed_files; std::vector<std::wstring> success_files; std::vector<std::wstring> funcs; wchar_t pstParseFile[PATH_MAX + FILENAME_MAX]; wchar_t pstVerbose[65535]; int iNbFile = 0; wchar_t *pstParsePath = NULL; int iParsePathLen = 0; wchar_t* pstLibName = NULL; bool bVerbose = false; bool bForce = false; if (in.size() < 1 || in.size() > 4) { Scierror(78, _("%s: Wrong number of input argument(s): %d to %d expected.\n"), "genlib", 1, 4); return types::Function::Error; } //param 1, library name types::InternalType* pIT = in[0]; if (pIT->isString() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), "genlib", 1); return types::Function::Error; } types::String *pS = pIT->getAs<types::String>(); if (pS->getSize() != 1) { Scierror(999, _("%s: Wrong size for input argument #%d: string expected.\n"), "genlib", 1); return types::Function::Error; } pstLibName = pS->get(0); //param 2, library path if (in.size() > 1) { pIT = in[1]; if (pIT->isString() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), "genlib", 2); return types::Function::Error; } } else { int ierr = 0; char* pstr = scigetcwd(&ierr); pIT = new types::String(pstr); FREE(pstr); } pS = pIT->getAs<types::String>(); if (pS->isScalar() == false) { Scierror(999, _("%s: Wrong size for input argument #%d: string expected.\n"), "genlib", 2); return types::Function::Error; } //param 3, force flag if (in.size() > 2) { pIT = in[2]; if (pIT->isBool() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: A scalar boolean expected.\n"), "genlib", 3); return types::Function::Error; } types::Bool* p = pIT->getAs<types::Bool>(); if (p->isScalar() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: A scalar boolean expected.\n"), "genlib", 3); return types::Function::Error; } bForce = p->get()[0] == 1; } if (in.size() > 3) { //verbose flag pIT = in[3]; if (pIT->isBool() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: A scalar boolean expected.\n"), "genlib", 3); return types::Function::Error; } types::Bool* p = pIT->getAs<types::Bool>(); if (p->isScalar() == false) { Scierror(999, _("%s: Wrong type for input argument #%d: A scalar boolean expected.\n"), "genlib", 3); return types::Function::Error; } bVerbose = p->get()[0] == 1; } wchar_t* pstFile = pS->get(0); pstParsePath = pathconvertW(pstFile, TRUE, TRUE, AUTO_STYLE); if (in.size() == 1) { delete pS; } os_swprintf(pstParseFile, PATH_MAX + FILENAME_MAX, L"%lslib", pstParsePath); if (bVerbose) { os_swprintf(pstVerbose, 65535, _W("-- Creation of [%ls] (Macros) --\n").c_str(), pstLibName); //save current prompt mode int oldVal = ConfigVariable::getPromptMode(); //set mode silent for errors ConfigVariable::setPromptMode(0); scilabWriteW(pstVerbose); //restore previous prompt mode ConfigVariable::setPromptMode(oldVal); } MacroInfoList lstOld; if (FileExistW(pstParseFile)) { //read it to get previous information like md5 std::wstring libname; parseLibFile(pstParseFile, lstOld, libname); deleteafileW(pstParseFile); } xmlTextWriterPtr pWriter = openXMLFile(pstParseFile, pstLibName); if (pWriter == NULL) { os_swprintf(pstVerbose, 65535, _W("%ls: Cannot open file ''%ls''.\n").c_str(), L"genlib", pstParseFile); scilabWriteW(pstVerbose); out.push_back(new types::Bool(0)); FREE(pstParsePath); return types::Function::OK; } wchar_t **pstPath = findfilesW(pstParsePath, L"*.sci", &iNbFile, FALSE); if (pstPath) { types::Library* pLib = new types::Library(pstParsePath); for (int k = 0 ; k < iNbFile ; k++) { //version with direct parsing //parse the file to find all functions std::wstring stFullPath = std::wstring(pstParsePath) + std::wstring(pstPath[k]); std::wstring stFullPathBin(stFullPath); stFullPathBin.replace(stFullPathBin.end() - 3, stFullPathBin.end(), L"bin"); std::wstring pstPathBin(pstPath[k]); pstPathBin.replace(pstPathBin.end() - 3, pstPathBin.end(), L"bin"); //compute file md5 FILE* fmdf5 = os_wfopen(stFullPath.data(), L"rb"); if (fmdf5 == NULL) { char* pstr = wide_string_to_UTF8(stFullPath.data()); Scierror(999, _("%s: Cannot open file ''%s''.\n"), "genlib", pstr); FREE(pstr); FREE(pstParsePath); freeArrayOfWideString(pstPath, iNbFile); pLib->killMe(); return types::Function::Error; } char* md5 = md5_file(fmdf5); fclose(fmdf5); wchar_t* wmd5 = to_wide_string(md5); FREE(md5); std::wstring wide_md5(wmd5); FREE(wmd5); if (bForce == false) { //check if is exist in old file MacroInfoList::iterator it = lstOld.find(pstPathBin); if (it != lstOld.end()) { if (wide_md5 == (*it).second.md5) { //file not change, we can skip it AddMacroToXML(pWriter, (*it).second.name, pstPathBin, wide_md5); pLib->add((*it).second.name, new types::MacroFile((*it).second.name, stFullPathBin, pstLibName)); success_files.push_back(stFullPath); funcs.push_back((*it).second.name); continue; } } } if (bVerbose) { sciprint(_("%ls: Processing file: %ls\n"), L"genlib", pstPath[k]); } Parser parser; parser.parseFile(stFullPath, ConfigVariable::getSCIPath()); if (parser.getExitStatus() != Parser::Succeded) { if (_iRetCount != 4) { std::wstring wstrErr = parser.getErrorMessage(); wchar_t errmsg[256]; os_swprintf(errmsg, 256, _W("%ls: Error in file %ls.\n").c_str(), L"genlib", stFullPath.data()); wstrErr += errmsg; char* str = wide_string_to_UTF8(wstrErr.c_str()); Scierror(999, str); FREE(str); FREE(pstParsePath); freeArrayOfWideString(pstPath, iNbFile); closeXMLFile(pWriter); delete pLib; return types::Function::Error; } failed_files.push_back(stFullPath); succes = 0; continue; } //serialize ast ast::SerializeVisitor* s = new ast::SerializeVisitor(parser.getTree()); unsigned char* serialAst = s->serialize(); // Header is : buffer size (4 bytes) + scilab version (4 bytes) unsigned int size = *((unsigned int*)serialAst); FILE* f = os_wfopen(stFullPathBin.c_str(), L"wb"); fwrite(serialAst, 1, size, f); fclose(f); ast::exps_t LExp = parser.getTree()->getAs<ast::SeqExp>()->getExps(); for (ast::exps_t::iterator j = LExp.begin(), itEnd = LExp.end() ; j != itEnd ; ++j) { if ((*j)->isFunctionDec()) { ast::FunctionDec* pFD = (*j)->getAs<ast::FunctionDec>(); const std::wstring& name = pFD->getSymbol().getName(); if (name + L".sci" == pstPath[k]) { if (AddMacroToXML(pWriter, name, pstPathBin, wide_md5) == false) { os_swprintf(pstVerbose, 65535, _W("%ls: Warning: %ls information cannot be added to file %ls. File ignored\n").c_str(), L"genlib", pFD->getSymbol().getName().c_str(), pstPath[k]); scilabWriteW(pstVerbose); } pLib->add(name, new types::MacroFile(name, stFullPathBin, pstLibName)); success_files.push_back(stFullPath); funcs.push_back(name); break; } } } delete s; free(serialAst); delete parser.getTree(); } symbol::Context* ctx = symbol::Context::getInstance(); symbol::Symbol sym = symbol::Symbol(pstLibName); if (ctx->isprotected(sym) == false) { ctx->put(symbol::Symbol(pstLibName), pLib); } else { Scierror(999, _("Redefining permanent variable.\n")); freeArrayOfWideString(pstPath, iNbFile); FREE(pstParsePath); closeXMLFile(pWriter); delete pLib; return types::Function::Error; } } freeArrayOfWideString(pstPath, iNbFile); out.push_back(new types::Bool(succes)); if (_iRetCount > 1) { int size = static_cast<int>(funcs.size()); if (size == 0) { out.push_back(types::Double::Empty()); } else { types::String* s = new types::String(size, 1); for (int i = 0; i < size; ++i) { s->set(i, funcs[i].data()); } out.push_back(s); } } if (_iRetCount > 2) { int size = static_cast<int>(success_files.size()); if (size == 0) { out.push_back(types::Double::Empty()); } else { types::String* s = new types::String(size, 1); for (int i = 0; i < size; ++i) { s->set(i, success_files[i].data()); } out.push_back(s); } } if (_iRetCount > 3) { int size = static_cast<int>(failed_files.size()); if (size == 0) { out.push_back(types::Double::Empty()); } else { types::String* s = new types::String(size, 1); for (int i = 0; i < size; ++i) { s->set(i, failed_files[i].data()); } out.push_back(s); } } FREE(pstParsePath); closeXMLFile(pWriter); return types::Function::OK; }
/*--------------------------------------------------------------------------*/ char *get_full_path(char *_FullPath, const char *_Path, size_t _SizeInBytes) { #if defined(_MSC_VER) char *returnedFullPath = NULL; wchar_t *wPath = to_wide_string((char *)_Path); wchar_t *wFullPath = (wchar_t *) MALLOC(sizeof(wchar_t) * _SizeInBytes); _wfullpath(wFullPath, wPath, _SizeInBytes); returnedFullPath = wide_string_to_UTF8(wFullPath); if (returnedFullPath) { strcpy(_FullPath, returnedFullPath); FREE(returnedFullPath); returnedFullPath = NULL; } if (wPath) { FREE(wPath); wPath = NULL; } if (wFullPath) { FREE(wFullPath); wFullPath = NULL; } return _FullPath; #else char *rp = NULL; int lenPath = (int)strlen(_Path); int lenFullPath = 0; int haveFileSep = ((lenPath > 1) && isDirSeparator(_Path[lenPath - 1])); int addFileSep = 0; rp = realpath(_Path, _FullPath); lenFullPath = (int)strlen(_FullPath); if (rp == NULL) { char * tofind; char * toadd; char * _Path_tmp; char * _Path_start; char * _FullPath_start; char* pstWorkingPath = NULL; //if argument is a relative path, add currentdir at start if (_Path[0] != '/') { int ierr = 0; char* pstCurrentPath = scigetcwd(&ierr); //alloc buffer + 2, 1 for '/' and 1 for null termination pstWorkingPath = (char*)CALLOC(sizeof(char), (lenPath + strlen(pstCurrentPath) + 2)); sprintf(pstWorkingPath, "%s/%s", pstCurrentPath, _Path); lenPath = strlen(pstWorkingPath); FREE(pstCurrentPath); } else { pstWorkingPath = strdup(_Path); } _Path_tmp = (char *)MALLOC(sizeof(char) * (lenPath + 1)); _Path_start = (char *)MALLOC(sizeof(char) * (lenPath + 1)); _FullPath_start = (char *)MALLOC(sizeof(char) * (lenFullPath + 1)); //First case(1): fullpath(TMPDIR+"/a/b/c"), second case(2): fullpath("a/b/c") or third case(3): fullpath("../a/b") strcpy(_Path_start, pstWorkingPath); // _Path_start=TMPDIR+"/a/b/c" (1) or _Path_start="a/b/c" (2) or _Path_start="../a/b/c" (3) strcpy(_FullPath_start, _FullPath); // _Fullpath_Start=TMPDIR+"/a" (1) or _FullPath_start=SCI+"/a" (2) or _FullPath_start=../SCI+"/a" (3) strtok(_Path_start, "/"); // _Path_start=/tmp (1) or _Path_start="a" (2) or _Path_start="a/b/c" (3) strtok(_FullPath_start, "/"); // _FullPath_start=/tmp (1) or _FullPath_start=/home (2) and (3) #if defined(__APPLE__) if (strcmp(_FullPath_start, "/private") == 0) // For case: fullpath(TMPDIR+"/a/b/c") (1) { normalizePath(_FullPath); } #else if (strcmp(_Path_start, _FullPath_start) == 0) // For case: fullpath(TMPDIR+"/a/b/c") (1) { strcpy(_FullPath, pstWorkingPath); normalizePath(_FullPath); } #endif else if (strcmp(_Path, _FullPath) != 0) // For case: fullpath("a/b/c") (2) or fullpath("../a/b/c") (3) { strcpy(_Path_tmp, pstWorkingPath); //_Path_tmp="a/b/c" (2) or _Path_tmp="../a/b/c" (3) strtok(_Path_tmp, "./"); // _Path_tmp becomes a (2) or ../a (3) toadd = strsub(pstWorkingPath, _Path_tmp, ""); // to add = "/b/c" strcat(_FullPath, toadd); //_FullPath=_Fullpath+toadd FREE(toadd); } FREE(pstWorkingPath); FREE(_FullPath_start); FREE(_Path_start); FREE(_Path_tmp); } lenFullPath = (int)strlen(_FullPath); addFileSep = ((lenFullPath > 1) && (!isDirSeparator(_FullPath[lenFullPath - 1])) && haveFileSep); if (addFileSep) { char *bufTmp = (char *)MALLOC(sizeof(char) * (lenFullPath + strlen(DIR_SEPARATOR) + 1)); if (bufTmp) { sprintf(bufTmp, "%s%s", _FullPath, DIR_SEPARATOR); strcpy(_FullPath, bufTmp); FREE(bufTmp); bufTmp = NULL; } } return _FullPath; #endif }