0031682: Visualization - Prs3d_ShadingAspect::SetTransparency() has no effect with...
[occt.git] / src / Draw / Draw_Interpretor.cxx
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
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
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.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 #include <Draw_Interpretor.hxx>
18 #include <Draw_Appli.hxx>
19 #include <Standard_SStream.hxx>
20 #include <Standard_RangeError.hxx>
21 #include <Standard_ErrorHandler.hxx>
22 #include <Standard_Macro.hxx>
23
24 #include <TCollection_AsciiString.hxx>
25 #include <TCollection_ExtendedString.hxx>
26 #include <OSD_Process.hxx>
27 #include <OSD_Path.hxx>
28 #include <OSD.hxx>
29 #include <OSD_File.hxx>
30
31 #include <string.h>
32 #include <tcl.h>
33 #include <fcntl.h>
34 #ifndef _WIN32
35 #include <unistd.h>
36 #endif
37
38 // for capturing of cout and cerr (dup(), dup2())
39 #ifdef _WIN32
40 #include <io.h>
41 #include <sys/stat.h>  
42 #endif
43
44 #if ! defined(STDOUT_FILENO)
45 #define STDOUT_FILENO fileno(stdout)
46 #endif
47 #if ! defined(STDERR_FILENO)
48 #define STDERR_FILENO fileno(stderr)
49 #endif
50
51 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 1)))
52 #define TCL_USES_UTF8
53 #endif
54
55 // logging helpers
56 namespace {
57   void dumpArgs (Standard_OStream& os, int argc, const char *argv[])
58   {
59     for (int i=0; i < argc; i++)
60       os << argv[i] << " ";
61     os << std::endl;
62   }
63
64   void flush_standard_streams ()
65   {
66     fflush (stderr);
67     fflush (stdout);
68     std::cerr << std::flush;
69     std::cout << std::flush;
70   }
71
72   int capture_start (int theFDStd, int theFDLog)
73   {
74     Standard_ASSERT_RETURN (theFDLog >= 0, "Invalid descriptor of log file", -1);
75
76     // Duplicate a file descriptor of the standard stream to be able to restore output to it later
77     int aFDSave = dup (theFDStd);
78     if (aFDSave < 0)
79     {
80       perror ("Error capturing standard stream to log: dup() returned");
81       return -1;
82     }
83
84     // Redirect the stream to the log file
85     if (dup2 (theFDLog, theFDStd) < 0)
86     {
87       close (aFDSave);
88       perror ("Error capturing standard stream to log: dup2() returned");
89       return -1;
90     }
91
92     // remember saved file descriptor of standard stream
93     return aFDSave;
94   }
95
96   void capture_end (int theFDStd, int& theFDSave)
97   {
98     if (theFDSave < 0)
99       return;
100
101     // restore normal descriptors of console stream
102     if (dup2(theFDSave, theFDStd) < 0)
103     {
104       perror ("Error returning capturing standard stream to log: dup2() returned");
105       return;
106     }
107
108     // close saved file descriptor
109     close(theFDSave);
110     theFDSave = -1;
111   }
112
113 } // anonymous namespace
114
115 static Standard_Integer CommandCmd (ClientData theClientData, Tcl_Interp* interp, Standard_Integer argc, const char* argv[])
116 {
117   static Standard_Integer code;
118   code = TCL_OK;
119   Draw_Interpretor::CallBackData* aCallback = (Draw_Interpretor::CallBackData* )theClientData;
120   Draw_Interpretor& di = *(aCallback->myDI);
121
122   // log command execution, except commands manipulating log itself and echo
123   Standard_Boolean isLogManipulation = (strcmp (argv[0], "dlog") == 0 || 
124                                         strcmp (argv[0], "decho") == 0);
125   Standard_Boolean doLog  = (di.GetDoLog() && ! isLogManipulation);
126   Standard_Boolean doEcho = (di.GetDoEcho() && ! isLogManipulation);
127
128   // flush cerr and cout
129   flush_standard_streams();
130
131   // capture cout and cerr to log
132   int aFDstdout = STDOUT_FILENO;
133   int aFDstderr = STDERR_FILENO;
134   int aFDerr_save = -1;
135   int aFDout_save = -1;
136   if (doLog)
137   {
138     aFDout_save = capture_start (aFDstdout, di.GetLogFileDescriptor());
139     aFDerr_save = capture_start (aFDstderr, di.GetLogFileDescriptor());
140   }
141
142   if (doEcho || doLog)
143     dumpArgs (std::cout, argc, argv);
144
145   // run command
146   try {
147     OCC_CATCH_SIGNALS
148
149     // get exception if control-break has been pressed 
150     OSD::ControlBreak();
151
152     // OCC680: Transfer UTF-8 directly to OCC commands without locale usage
153       
154     Standard_Integer fres = aCallback->Invoke ( di, argc, argv /*anArgs.GetArgv()*/ );
155     if (fres != 0) 
156       code = TCL_ERROR;
157   }
158   catch (Standard_Failure const& anException) {
159     // fail if Draw_ExitOnCatch is set
160     std::cout << "An exception was caught " << anException << std::endl;
161     const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
162     if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
163     {
164 #ifdef _WIN32
165       Tcl_Exit(0);
166 #else      
167       Tcl_Eval(interp,"exit");
168 #endif
169     }
170
171     // get the error message
172     Standard_SStream ss;
173     ss << "** Exception ** " << anException << std::ends;
174     Tcl_SetResult(interp,(char*)(ss.str().c_str()),TCL_VOLATILE);
175     code = TCL_ERROR;
176   }
177   catch (std::exception const& theStdException)
178   {
179     std::cout << "An exception was caught " << theStdException.what() << " [" << typeid(theStdException).name() << "]" << std::endl;
180     const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
181     if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
182     {
183     #ifdef _WIN32
184       Tcl_Exit (0);
185     #else
186       Tcl_Eval (interp, "exit");
187     #endif
188     }
189
190     // get the error message
191     Standard_SStream ss;
192     ss << "** Exception ** " << theStdException.what() << " [" << typeid(theStdException).name() << "]" << std::ends;
193     Tcl_SetResult (interp, (char*)(ss.str().c_str()), TCL_VOLATILE);
194     code = TCL_ERROR;
195   }
196   catch (...)
197   {
198     std::cout << "UNKNOWN exception was caught " << std::endl;
199     const char* toExitOnCatch = Tcl_GetVar (interp, "Draw_ExitOnCatch", TCL_GLOBAL_ONLY);
200     if (toExitOnCatch != NULL && Draw::Atoi (toExitOnCatch))
201     {
202     #ifdef _WIN32
203       Tcl_Exit (0);
204     #else
205       Tcl_Eval (interp,"exit");
206     #endif
207     }
208
209     // get the error message
210     Standard_SStream ss;
211     ss << "** Exception ** UNKNOWN" << std::ends;
212     Tcl_SetResult (interp, (char* )(ss.str().c_str()), TCL_VOLATILE);
213     code = TCL_ERROR;
214   }
215
216   // log command result
217   if (doLog || doEcho)
218   {
219     const char* aResultStr = Tcl_GetStringResult (interp);
220     if (aResultStr != 0 && aResultStr[0] != '\0' )
221     {
222       std::cout << aResultStr << std::endl;
223     }
224   }
225
226   // flush streams
227   flush_standard_streams();
228
229   // end capturing cout and cerr 
230   if (doLog) 
231   {
232     capture_end (aFDstderr, aFDerr_save);
233     capture_end (aFDstdout, aFDout_save);
234   }
235
236   return code;
237 }
238
239 static void CommandDelete (ClientData theClientData)
240 {
241   Draw_Interpretor::CallBackData* aCallback = (Draw_Interpretor::CallBackData* )theClientData;
242   delete aCallback;
243 }
244
245 //=======================================================================
246 //function : Draw_Interpretor
247 //purpose  : 
248 //=======================================================================
249
250 Draw_Interpretor::Draw_Interpretor() :
251   isAllocated(Standard_False), myDoLog(Standard_False), myDoEcho(Standard_False), myFDLog(-1)
252 {
253 // The tcl interpreter is not created immediately as it is kept 
254 // by a global variable and created and deleted before the main().
255   myInterp  = NULL;
256 }
257
258 //=======================================================================
259 //function : Init
260 //purpose  : It is necessary to call this function
261 //=======================================================================
262
263 void Draw_Interpretor::Init()
264 {
265   if (isAllocated) 
266     Tcl_DeleteInterp(myInterp);
267   isAllocated=Standard_True;
268   myInterp=Tcl_CreateInterp();
269 }
270
271 //=======================================================================
272 //function : Draw_Interpretor
273 //purpose  : 
274 //=======================================================================
275
276 Draw_Interpretor::Draw_Interpretor(const Draw_PInterp& p) :
277   isAllocated(Standard_False),
278   myInterp(p),
279   myDoLog(Standard_False),
280   myDoEcho(Standard_False),
281   myFDLog(-1)
282 {
283 }
284
285 //=======================================================================
286 //function : add
287 //purpose  :
288 //=======================================================================
289 void Draw_Interpretor::add (const Standard_CString          theCommandName,
290                             const Standard_CString          theHelp,
291                             const Standard_CString          theFileName,
292                             Draw_Interpretor::CallBackData* theCallback,
293                             const Standard_CString          theGroup)
294 {
295   Standard_ASSERT_RAISE (myInterp != NULL, "Attempt to add command to Null interpretor");
296
297   Standard_PCharacter aName  = (Standard_PCharacter )theCommandName;
298   Standard_PCharacter aHelp  = (Standard_PCharacter )theHelp;
299   Standard_PCharacter aGroup = (Standard_PCharacter )theGroup;
300   Tcl_CreateCommand (myInterp, aName, CommandCmd, (ClientData )theCallback, CommandDelete);
301
302   // add the help
303   Tcl_SetVar2 (myInterp, "Draw_Helps",  aName,  aHelp, TCL_GLOBAL_ONLY);
304   Tcl_SetVar2 (myInterp, "Draw_Groups", aGroup, aName,
305                      TCL_GLOBAL_ONLY | TCL_APPEND_VALUE | TCL_LIST_ELEMENT);
306
307   // add path to source file (keep not more than two last subdirectories)
308   if (theFileName  == NULL
309    || *theFileName == '\0')
310   {
311     return;
312   }
313
314   OSD_Path aPath (theFileName);
315   Standard_Integer nbTrek = aPath.TrekLength();
316   for (Standard_Integer i = 2; i < nbTrek; ++i)
317   {
318     aPath.RemoveATrek (1);
319   }
320   aPath.SetDisk ("");
321   aPath.SetNode ("");
322   TCollection_AsciiString aSrcPath;
323   aPath.SystemName (aSrcPath);
324   if (aSrcPath.Value(1) == '/')
325     aSrcPath.Remove(1);
326   Tcl_SetVar2 (myInterp, "Draw_Files", aName, aSrcPath.ToCString(), TCL_GLOBAL_ONLY);
327 }
328
329 //=======================================================================
330 //function : Remove
331 //purpose  : 
332 //=======================================================================
333
334 Standard_Boolean Draw_Interpretor::Remove(Standard_CString const n)
335 {
336   Standard_PCharacter pN;
337   //
338   pN=(Standard_PCharacter)n;
339  
340   Standard_Integer result = Tcl_DeleteCommand(myInterp,pN);
341   return result == 0;
342 }
343
344 //=======================================================================
345 //function : Result
346 //purpose  : 
347 //=======================================================================
348
349 Standard_CString Draw_Interpretor::Result() const
350 {
351 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
352   return Tcl_GetStringResult(myInterp);
353 #else
354   return myInterp->result;
355 #endif
356 }
357
358 //=======================================================================
359 //function : Reset
360 //purpose  : 
361 //=======================================================================
362
363 void Draw_Interpretor::Reset()
364 {
365   Tcl_ResetResult(myInterp);
366 }
367
368 //=======================================================================
369 //function : Append
370 //purpose  : 
371 //=======================================================================
372
373 Draw_Interpretor& Draw_Interpretor::Append(const Standard_CString s)
374 {
375   Tcl_AppendResult(myInterp,s,(Standard_CString)0);
376   return *this;
377 }
378
379 //=======================================================================
380 //function : Append
381 //purpose  : 
382 //=======================================================================
383
384 Draw_Interpretor& Draw_Interpretor::Append(const TCollection_AsciiString& s)
385 {
386   return Append (s.ToCString());
387 }
388
389 //=======================================================================
390 //function : Append
391 //purpose  : 
392 //=======================================================================
393
394 Draw_Interpretor& Draw_Interpretor::Append(const TCollection_ExtendedString& theString)
395 {
396 #ifdef TCL_USES_UTF8
397   // Convert string to UTF-8 format for Tcl
398   char *str = new char[theString.LengthOfCString()+1];
399   theString.ToUTF8CString (str);
400   Tcl_AppendResult ( myInterp, str, (Standard_CString)0 );
401   delete[] str;
402 #else
403   // put as ascii string, replacing non-ascii characters by '?'
404   TCollection_AsciiString str (theString, '?');
405   Tcl_AppendResult(myInterp,str.ToCString(),(Standard_CString)0);
406 #endif
407   return *this;
408 }
409
410 //=======================================================================
411 //function : Append
412 //purpose  : 
413 //=======================================================================
414
415 Draw_Interpretor& Draw_Interpretor::Append(const Standard_Integer i)
416 {
417   char c[100];
418   Sprintf(c,"%d",i);
419   Tcl_AppendResult(myInterp,c,(Standard_CString)0);
420   return *this;
421 }
422
423 //=======================================================================
424 //function : Append
425 //purpose  : 
426 //=======================================================================
427
428 Draw_Interpretor& Draw_Interpretor::Append(const Standard_Real r)
429 {
430   char s[100];
431   Sprintf(s,"%.17g",r);
432   Tcl_AppendResult(myInterp,s,(Standard_CString)0);
433   return *this;
434 }
435
436 //=======================================================================
437 //function : Append
438 //purpose  : 
439 //=======================================================================
440
441 Draw_Interpretor& Draw_Interpretor::Append(const Standard_SStream& s)
442 {
443   return Append (s.str().c_str());
444 }
445
446 //=======================================================================
447 //function : AppendElement
448 //purpose  : 
449 //=======================================================================
450
451 void Draw_Interpretor::AppendElement(const Standard_CString s)
452 {
453   Tcl_AppendElement(myInterp, s);
454 }
455
456 //=======================================================================
457 //function : Eval
458 //purpose  : 
459 //=======================================================================
460
461 Standard_Integer Draw_Interpretor::Eval(const Standard_CString line)
462 {
463   return Tcl_Eval(myInterp,line);
464 }
465
466
467 //=======================================================================
468 //function : Eval
469 //purpose  : 
470 //=======================================================================
471
472 Standard_Integer Draw_Interpretor::RecordAndEval(const Standard_CString line,
473                                                  const Standard_Integer flags)
474 {
475   return Tcl_RecordAndEval(myInterp,line,flags);
476 }
477
478 //=======================================================================
479 //function : EvalFile
480 //purpose  : 
481 //=======================================================================
482
483 Standard_Integer Draw_Interpretor::EvalFile(const Standard_CString fname)
484 {
485   return Tcl_EvalFile(myInterp,fname);
486 }
487
488 //=======================================================================
489 //function : PrintHelp
490 //purpose  :
491 //=======================================================================
492
493 Standard_Integer Draw_Interpretor::PrintHelp (const Standard_CString theCommandName)
494 {
495   TCollection_AsciiString aCmd     = TCollection_AsciiString ("help ") + theCommandName;
496   Standard_PCharacter     aLinePtr = (Standard_PCharacter )aCmd.ToCString();
497   return Tcl_Eval (myInterp, aLinePtr);
498 }
499
500 //=======================================================================
501 //function :Complete
502 //purpose  : 
503 //=======================================================================
504
505 Standard_Boolean Draw_Interpretor::Complete(const Standard_CString line)
506 {
507   Standard_PCharacter pLine;
508   //
509   pLine=(Standard_PCharacter)line;
510   return Tcl_CommandComplete (pLine) != 0;
511 }
512
513 //=======================================================================
514 //function : Destroy
515 //purpose  : 
516 //=======================================================================
517
518 Draw_Interpretor::~Draw_Interpretor()
519 {
520   SetDoLog (Standard_False);
521   if (myFDLog >=0)
522   {
523     close (myFDLog);
524     myFDLog = 0;
525   }
526
527   // MKV 01.02.05
528 #if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 4)))
529   try {
530     OCC_CATCH_SIGNALS
531     Tcl_Exit(0);
532   }
533   catch (Standard_Failure const&) {
534 #ifdef OCCT_DEBUG
535     std::cout <<"Tcl_Exit have an exeption" << std::endl;
536 #endif
537   }
538 #else
539 #ifdef _WIN32
540   Tcl_Exit(0);
541 #endif  
542 #endif
543 }
544
545 //=======================================================================
546 //function : Interp
547 //purpose  : 
548 //=======================================================================
549
550 Draw_PInterp Draw_Interpretor::Interp() const
551 {
552   Standard_DomainError_Raise_if (myInterp==NULL , "No call for  Draw_Interpretor::Init()");
553   return myInterp;
554 }
555
556 void Draw_Interpretor::Set(const Draw_PInterp& PIntrp)
557 {
558   if (isAllocated)
559     Tcl_DeleteInterp(myInterp);
560   isAllocated = Standard_False;
561   myInterp = PIntrp;
562 }
563
564 //=======================================================================
565 //function : Logging
566 //purpose  : 
567 //=======================================================================
568
569 void Draw_Interpretor::SetDoLog (Standard_Boolean doLog)
570 {
571   if (myDoLog == doLog)
572     return;
573
574   // create log file if not opened yet
575   if (doLog && myFDLog < 0)
576   {
577 #ifdef _WIN32
578     char tmpfile[L_tmpnam + 1];
579     tmpnam(tmpfile);
580     myFDLog = open (tmpfile, O_RDWR | O_CREAT | O_EXCL | O_TEMPORARY, S_IREAD | S_IWRITE);
581 #else
582     // according to Linux Filesystem Hierarchy Standard, 3.17,
583     // /tmp/ is the right directory for temporary files
584     char tmpfile[256] = "/tmp/occt_draw_XXXXXX";
585     myFDLog = mkstemp (tmpfile);
586     if (myFDLog >= 0)
587     {
588 //      printf ("Tmp file: %s\n", tmpfile);
589       unlink (tmpfile); // make sure the file will be deleted on close
590     }
591 #endif
592     if (myFDLog < 0)
593     {
594       perror ("Error creating temporary file for capturing console output");
595       printf ("path: %s\n", tmpfile);
596       return;
597     }
598   }
599
600   myDoLog = doLog;
601 }
602
603 void Draw_Interpretor::SetDoEcho (Standard_Boolean doEcho)
604 {
605   myDoEcho = doEcho;
606 }
607
608 Standard_Boolean Draw_Interpretor::GetDoLog () const
609 {
610   return myDoLog;
611 }
612
613 Standard_Boolean Draw_Interpretor::GetDoEcho () const
614 {
615   return myDoEcho;
616 }
617
618 void Draw_Interpretor::ResetLog ()
619 {
620   if (myFDLog < 0)
621     return;
622
623   // flush cerr and cout, for the case if they are bound to the log
624   flush_standard_streams();
625
626   lseek (myFDLog, 0, SEEK_SET);
627
628 #ifdef _WIN32
629   if (_chsize_s (myFDLog, 0) != 0)
630 #else
631   if (ftruncate (myFDLog, 0) != 0)
632 #endif
633   {
634     perror ("Error truncating the console log");
635   }
636 }
637
638 void Draw_Interpretor::AddLog (const Standard_CString theStr)
639 {
640   if (myFDLog < 0 || ! theStr || ! theStr[0])
641     return;
642
643   // flush cerr and cout, for the case if they are bound to the log
644   flush_standard_streams();
645
646   // write as plain bytes
647   if (write (myFDLog, theStr, (unsigned int)strlen(theStr)) <0)
648   {
649     perror ("Error writing to console log");
650   }
651 }
652
653 TCollection_AsciiString Draw_Interpretor::GetLog ()
654 {
655   TCollection_AsciiString aLog;
656   if (myFDLog < 0)
657     return aLog;
658
659   // flush cerr and cout
660   flush_standard_streams();
661
662   // rewind the file to its start
663   lseek (myFDLog, 0, SEEK_SET);
664
665   // read the whole log to string; this implementation
666   // is not optimized but should be sufficient
667   const int BUFSIZE = 4096;
668   char buffer[BUFSIZE + 1];
669   for (;;)
670   {
671     int nbRead = read (myFDLog, buffer, BUFSIZE);
672     if (nbRead <= 0)
673     {
674       break;
675     }
676     buffer[nbRead] = '\0';
677     aLog.AssignCat (buffer);
678   }
679
680   return aLog;
681 }