1 // Created on: 1995-02-23
2 // Created by: Remi LEQUETTE
3 // Copyright (c) 1995-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
6 // This file is part of Open CASCADE Technology software library.
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
17 #include <Draw_Interpretor.hxx>
19 #include <Draw_Appli.hxx>
20 #include <Message.hxx>
21 #include <Message_PrinterOStream.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Path.hxx>
25 #include <OSD_Process.hxx>
26 #include <Standard_SStream.hxx>
27 #include <Standard_RangeError.hxx>
28 #include <Standard_ErrorHandler.hxx>
29 #include <Standard_Macro.hxx>
30 #include <TCollection_AsciiString.hxx>
31 #include <TCollection_ExtendedString.hxx>
40 // for capturing of cout and cerr (dup(), dup2())
46 #if ! defined(STDOUT_FILENO)
47 #define STDOUT_FILENO fileno(stdout)
49 #if ! defined(STDERR_FILENO)
50 #define STDERR_FILENO fileno(stderr)
53 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 1)))
59 void dumpArgs (Standard_OStream& os, int argc, const char *argv[])
61 for (int i=0; i < argc; i++)
66 void flush_standard_streams ()
70 std::cerr << std::flush;
71 std::cout << std::flush;
74 int capture_start (int theFDStd, int theFDLog)
76 Standard_ASSERT_RETURN (theFDLog >= 0, "Invalid descriptor of log file", -1);
78 // Duplicate a file descriptor of the standard stream to be able to restore output to it later
79 int aFDSave = dup (theFDStd);
82 perror ("Error capturing standard stream to log: dup() returned");
86 // Redirect the stream to the log file
87 if (dup2 (theFDLog, theFDStd) < 0)
90 perror ("Error capturing standard stream to log: dup2() returned");
94 // remember saved file descriptor of standard stream
98 void capture_end (int theFDStd, int& theFDSave)
103 // restore normal descriptors of console stream
104 if (dup2(theFDSave, theFDStd) < 0)
106 perror ("Error returning capturing standard stream to log: dup2() returned");
110 // close saved file descriptor
115 } // anonymous namespace
117 static Standard_Integer CommandCmd (ClientData theClientData, Tcl_Interp* interp, Standard_Integer argc, const char* argv[])
119 Standard_Integer code = TCL_OK;
120 Draw_Interpretor::CallBackData* aCallback = (Draw_Interpretor::CallBackData* )theClientData;
121 Draw_Interpretor& di = *(aCallback->myDI);
123 // log command execution, except commands manipulating log itself and echo
124 Standard_Boolean isLogManipulation = (strcmp (argv[0], "dlog") == 0 ||
125 strcmp (argv[0], "decho") == 0);
126 Standard_Boolean doLog = (di.GetDoLog() && ! isLogManipulation);
127 Standard_Boolean doEcho = (di.GetDoEcho() && ! isLogManipulation);
129 // flush cerr and cout
130 flush_standard_streams();
132 // capture cout and cerr to log
133 int aFDstdout = STDOUT_FILENO;
134 int aFDstderr = STDERR_FILENO;
135 int aFDerr_save = -1;
136 int aFDout_save = -1;
139 aFDout_save = capture_start (aFDstdout, di.GetLogFileDescriptor());
140 aFDerr_save = capture_start (aFDstderr, di.GetLogFileDescriptor());
144 dumpArgs (std::cout, argc, argv);
151 // get exception if control-break has been pressed
154 Standard_Integer fres = aCallback->Invoke ( di, argc, argv /*anArgs.GetArgv()*/ );
160 catch (Standard_Failure const& anException)
162 // fail if Draw_ExitOnCatch is set
163 const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
164 if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
166 Message::SendFail() << "An exception was caught " << anException;
170 Tcl_Eval(interp,"exit");
175 ss << "An exception was caught " << anException << std::ends;
176 Tcl_SetResult(interp,(char*)(ss.str().c_str()),TCL_VOLATILE);
179 catch (std::exception const& theStdException)
181 const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
182 if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
184 Message::SendFail() << "An exception was caught " << theStdException.what() << " [" << typeid(theStdException).name() << "]";
188 Tcl_Eval (interp, "exit");
193 ss << "An exception was caught " << theStdException.what() << " [" << typeid(theStdException).name() << "]" << std::ends;
194 Tcl_SetResult(interp,(char*)(ss.str().c_str()),TCL_VOLATILE);
199 const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
200 if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
202 Message::SendFail() << "UNKNOWN exception was caught ";
206 Tcl_Eval (interp,"exit");
211 ss << "UNKNOWN exception was caught " << std::ends;
212 Tcl_SetResult(interp,(char*)(ss.str().c_str()),TCL_VOLATILE);
216 // log command result
219 const char* aResultStr = Tcl_GetStringResult (interp);
220 if (aResultStr != 0 && aResultStr[0] != '\0' )
222 std::cout << aResultStr << std::endl;
227 flush_standard_streams();
229 // end capturing cout and cerr
232 capture_end (aFDstderr, aFDerr_save);
233 capture_end (aFDstdout, aFDout_save);
239 static void CommandDelete (ClientData theClientData)
241 Draw_Interpretor::CallBackData* aCallback = (Draw_Interpretor::CallBackData* )theClientData;
245 //=======================================================================
246 //function : Draw_Interpretor
248 //=======================================================================
249 Draw_Interpretor::Draw_Interpretor()
250 : // the tcl interpreter is not created immediately as it is kept
251 // by a global variable and created and deleted before the main()
253 isAllocated (Standard_False),
254 myDoLog (Standard_False),
255 myDoEcho (Standard_False),
256 myToColorize (Standard_True),
262 //=======================================================================
263 //function : Draw_Interpretor
265 //=======================================================================
266 Draw_Interpretor::Draw_Interpretor (const Draw_PInterp& theInterp)
267 : myInterp (theInterp),
268 isAllocated (Standard_False),
269 myDoLog (Standard_False),
270 myDoEcho (Standard_False),
271 myToColorize (Standard_True),
277 //=======================================================================
279 //purpose : It is necessary to call this function
280 //=======================================================================
282 void Draw_Interpretor::Init()
285 Tcl_DeleteInterp(myInterp);
286 isAllocated=Standard_True;
287 myInterp=Tcl_CreateInterp();
290 //=======================================================================
291 //function : SetToColorize
293 //=======================================================================
294 void Draw_Interpretor::SetToColorize (Standard_Boolean theToColorize)
296 myToColorize = theToColorize;
297 for (Message_SequenceOfPrinters::Iterator aPrinterIter (Message::DefaultMessenger()->Printers());
298 aPrinterIter.More(); aPrinterIter.Next())
300 if (Handle(Message_PrinterOStream) aPrinter = Handle(Message_PrinterOStream)::DownCast (aPrinterIter.Value()))
302 aPrinter->SetToColorize (theToColorize);
307 //=======================================================================
310 //=======================================================================
311 void Draw_Interpretor::add (const Standard_CString theCommandName,
312 const Standard_CString theHelp,
313 const Standard_CString theFileName,
314 Draw_Interpretor::CallBackData* theCallback,
315 const Standard_CString theGroup)
317 Standard_ASSERT_RAISE (myInterp != NULL, "Attempt to add command to Null interpretor");
319 Standard_PCharacter aName = (Standard_PCharacter )theCommandName;
320 Standard_PCharacter aHelp = (Standard_PCharacter )theHelp;
321 Standard_PCharacter aGroup = (Standard_PCharacter )theGroup;
322 Tcl_CreateCommand (myInterp, aName, CommandCmd, (ClientData )theCallback, CommandDelete);
325 Tcl_SetVar2 (myInterp, "Draw_Helps", aName, aHelp, TCL_GLOBAL_ONLY);
326 Tcl_SetVar2 (myInterp, "Draw_Groups", aGroup, aName,
327 TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT);
329 // add path to source file (keep not more than two last subdirectories)
330 if (theFileName == NULL
331 || *theFileName == '\0')
336 OSD_Path aPath (theFileName);
337 Standard_Integer nbTrek = aPath.TrekLength();
338 for (Standard_Integer i = 2; i < nbTrek; ++i)
340 aPath.RemoveATrek (1);
344 TCollection_AsciiString aSrcPath;
345 aPath.SystemName (aSrcPath);
346 if (aSrcPath.Value(1) == '/')
348 Tcl_SetVar2 (myInterp, "Draw_Files", aName, aSrcPath.ToCString(), TCL_GLOBAL_ONLY);
351 //=======================================================================
354 //=======================================================================
356 Standard_Boolean Draw_Interpretor::Remove(Standard_CString const n)
358 Standard_PCharacter pN;
360 pN=(Standard_PCharacter)n;
362 Standard_Integer result = Tcl_DeleteCommand(myInterp,pN);
366 //=======================================================================
369 //=======================================================================
371 Standard_CString Draw_Interpretor::Result() const
373 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
374 return Tcl_GetStringResult(myInterp);
376 return myInterp->result;
380 //=======================================================================
383 //=======================================================================
385 void Draw_Interpretor::Reset()
387 Tcl_ResetResult(myInterp);
390 //=======================================================================
393 //=======================================================================
395 Draw_Interpretor& Draw_Interpretor::Append(const Standard_CString s)
397 Tcl_AppendResult(myInterp,s,(Standard_CString)0);
401 //=======================================================================
404 //=======================================================================
406 Draw_Interpretor& Draw_Interpretor::Append(const TCollection_AsciiString& s)
408 return Append (s.ToCString());
411 //=======================================================================
414 //=======================================================================
416 Draw_Interpretor& Draw_Interpretor::Append(const TCollection_ExtendedString& theString)
419 // Convert string to UTF-8 format for Tcl
420 char *str = new char[theString.LengthOfCString()+1];
421 theString.ToUTF8CString (str);
422 Tcl_AppendResult ( myInterp, str, (Standard_CString)0 );
425 // put as ascii string, replacing non-ascii characters by '?'
426 TCollection_AsciiString str (theString, '?');
427 Tcl_AppendResult(myInterp,str.ToCString(),(Standard_CString)0);
432 //=======================================================================
435 //=======================================================================
437 Draw_Interpretor& Draw_Interpretor::Append(const Standard_Integer i)
441 Tcl_AppendResult(myInterp,c,(Standard_CString)0);
445 //=======================================================================
448 //=======================================================================
450 Draw_Interpretor& Draw_Interpretor::Append(const Standard_Real r)
453 Sprintf(s,"%.17g",r);
454 Tcl_AppendResult(myInterp,s,(Standard_CString)0);
458 //=======================================================================
461 //=======================================================================
463 Draw_Interpretor& Draw_Interpretor::Append(const Standard_SStream& s)
465 return Append (s.str().c_str());
468 //=======================================================================
469 //function : AppendElement
471 //=======================================================================
473 void Draw_Interpretor::AppendElement(const Standard_CString s)
475 Tcl_AppendElement(myInterp, s);
478 //=======================================================================
481 //=======================================================================
483 Standard_Integer Draw_Interpretor::Eval(const Standard_CString line)
485 return Tcl_Eval(myInterp,line);
489 //=======================================================================
492 //=======================================================================
494 Standard_Integer Draw_Interpretor::RecordAndEval(const Standard_CString line,
495 const Standard_Integer flags)
497 return Tcl_RecordAndEval(myInterp,line,flags);
500 //=======================================================================
501 //function : EvalFile
503 //=======================================================================
505 Standard_Integer Draw_Interpretor::EvalFile(const Standard_CString fname)
507 return Tcl_EvalFile(myInterp,fname);
510 //=======================================================================
511 //function : PrintHelp
513 //=======================================================================
515 Standard_Integer Draw_Interpretor::PrintHelp (const Standard_CString theCommandName)
517 TCollection_AsciiString aCmd = TCollection_AsciiString ("help ") + theCommandName;
518 Standard_PCharacter aLinePtr = (Standard_PCharacter )aCmd.ToCString();
519 return Tcl_Eval (myInterp, aLinePtr);
522 //=======================================================================
525 //=======================================================================
527 Standard_Boolean Draw_Interpretor::Complete(const Standard_CString line)
529 Standard_PCharacter pLine;
531 pLine=(Standard_PCharacter)line;
532 return Tcl_CommandComplete (pLine) != 0;
535 //=======================================================================
538 //=======================================================================
540 Draw_Interpretor::~Draw_Interpretor()
542 SetDoLog (Standard_False);
550 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 4)))
555 catch (Standard_Failure const&) {
557 std::cout <<"Tcl_Exit have an exception" << std::endl;
567 //=======================================================================
570 //=======================================================================
572 Draw_PInterp Draw_Interpretor::Interp() const
574 Standard_DomainError_Raise_if (myInterp==NULL , "No call for Draw_Interpretor::Init()");
578 void Draw_Interpretor::Set(const Draw_PInterp& PIntrp)
581 Tcl_DeleteInterp(myInterp);
582 isAllocated = Standard_False;
586 //=======================================================================
589 //=======================================================================
591 void Draw_Interpretor::SetDoLog (Standard_Boolean doLog)
593 if (myDoLog == doLog)
596 // create log file if not opened yet
597 if (doLog && myFDLog < 0)
600 char tmpfile[L_tmpnam + 1];
602 myFDLog = open (tmpfile, O_RDWR | O_CREAT | O_EXCL | O_TEMPORARY, S_IREAD | S_IWRITE);
604 // according to Linux Filesystem Hierarchy Standard, 3.17,
605 // /tmp/ is the right directory for temporary files
606 char tmpfile[256] = "/tmp/occt_draw_XXXXXX";
607 myFDLog = mkstemp (tmpfile);
610 // printf ("Tmp file: %s\n", tmpfile);
611 unlink (tmpfile); // make sure the file will be deleted on close
616 perror ("Error creating temporary file for capturing console output");
617 printf ("path: %s\n", tmpfile);
625 void Draw_Interpretor::SetDoEcho (Standard_Boolean doEcho)
630 Standard_Boolean Draw_Interpretor::GetDoLog () const
635 Standard_Boolean Draw_Interpretor::GetDoEcho () const
640 void Draw_Interpretor::ResetLog ()
645 // flush cerr and cout, for the case if they are bound to the log
646 flush_standard_streams();
648 lseek (myFDLog, 0, SEEK_SET);
651 if (_chsize_s (myFDLog, 0) != 0)
653 if (ftruncate (myFDLog, 0) != 0)
656 perror ("Error truncating the console log");
660 void Draw_Interpretor::AddLog (const Standard_CString theStr)
662 if (myFDLog < 0 || ! theStr || ! theStr[0])
665 // flush cerr and cout, for the case if they are bound to the log
666 flush_standard_streams();
668 // write as plain bytes
669 if (write (myFDLog, theStr, (unsigned int)strlen(theStr)) <0)
671 perror ("Error writing to console log");
675 TCollection_AsciiString Draw_Interpretor::GetLog ()
677 TCollection_AsciiString aLog;
681 // flush cerr and cout
682 flush_standard_streams();
684 // rewind the file to its start
685 lseek (myFDLog, 0, SEEK_SET);
687 // read the whole log to string; this implementation
688 // is not optimized but should be sufficient
689 const int BUFSIZE = 4096;
690 char buffer[BUFSIZE + 1];
693 int nbRead = read (myFDLog, buffer, BUFSIZE);
698 buffer[nbRead] = '\0';
699 aLog.AssignCat (buffer);