Main.cpp
上传用户:zhangwj668
上传日期:2013-07-28
资源大小:1993k
文件大小:19k
源码类别:

绘图程序

开发平台:

Visual C++

  1. /** file main.cpp
  2.  *  brief Main!
  3.  *  author $Author: jriegel $
  4.  *  version $Revision: 1.51 $
  5.  *  date    $Date: 2004/04/13 15:02:09 $
  6.  */
  7. /***************************************************************************
  8.  *   (c) J黵gen Riegel (juergen.riegel@web.de) 2002                        *   
  9.  *                                                                         *
  10.  *   This file is part of the FreeCAD CAx development system.              *
  11.  *                                                                         *
  12.  *   This program is free software; you can redistribute it and/or modify  *
  13.  *   it under the terms of the GNU General Public License (GPL)            *
  14.  *   as published by the Free Software Foundation; either version 2 of     *
  15.  *   the License, or (at your option) any later version.                   *
  16.  *   for detail see the LICENCE text file.                                 *
  17.  *                                                                         *
  18.  *   FreeCAD is distributed in the hope that it will be useful,            *
  19.  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        * 
  20.  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
  21.  *   GNU Library General Public License for more details.                  *
  22.  *                                                                         *
  23.  *   You should have received a copy of the GNU Library General Public     *
  24.  *   License along with FreeCAD; if not, write to the Free Software        * 
  25.  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
  26.  *   USA                                                                   *
  27.  *                                                                         *
  28.  *   Juergen Riegel 2002                                                   *
  29.  ***************************************************************************/
  30. #include "PreCompiled.h"
  31. #error "This main is depricated use MainGui, MainCmd or MainPy instead!!"
  32. #ifdef FC_LINUX
  33. #if HAVE_CONFIG_H
  34. # include <autoconfig.h>
  35. #endif // HAVE_CONFIG_H
  36. #endif // FC_LINUX
  37. #include <stdio.h>
  38. #include <list>
  39. #ifdef FC_OS_LINUX
  40. # include <unistd.h>
  41. #endif
  42. #ifdef FC_OS_WIN32
  43. # include <direct.h>
  44. # include <windows.h>
  45. #endif
  46. // FreeCAD Base header
  47. #include "../Base/Console.h"
  48. #include "../Base/Interpreter.h"
  49. #include "../Base/Parameter.h"
  50. #include "../Base/Exception.h"
  51. #include "../Base/EnvMacros.h"
  52. #include "../Base/Factory.h"
  53. // FreeCAD doc header
  54. #include "../App/Application.h"
  55. #include "Standard_Failure.hxx"
  56. #include <xercesc/util/XMLException.hpp>
  57. #include "iostream"
  58. // FreeCAD Gui header
  59. #ifdef  _FC_GUI_ENABLED_
  60. # ifndef _PreComp_
  61. # include <qtextbrowser.h>
  62. # include <qthread.h>
  63. # endif
  64. # include "../Gui/Application.h"
  65. # include "../Gui/GuiConsole.h"
  66. # include "../Gui/Splashscreen.h"
  67. # ifdef FC_OS_WIN32
  68. # pragma comment(lib,QTLIBNAME)
  69. # endif
  70. # include "GuiInitScript.h"
  71. #endif
  72. // scriptings (scripts are build in but can be overriden by command line option)
  73. #include "InitScript.h"
  74. #include "TestScript.h"
  75. const char sBanner[] = 
  76. "  #####                 ####  ###   ####  n" 
  77. "  #                    #      # #   #   # n" 
  78. "  #     ##  #### ####  #     #   #  #   # n" 
  79. "  ####  # # #  # #  #  #     #####  #   # n" 
  80. "  #     #   #### ####  #    #     # #   # n" 
  81. "  #     #   #    #     #    #     # #   #  ##  ##  ##n" 
  82. "  #     #   #### ####   ### #     # ####   ##  ##  ##nn" ;
  83. // the standard and plugin file of FreeCAD
  84. #include "../App/Standard.h"
  85. #include "../App/Plugin.h"
  86. #include <string>
  87. #include <map>
  88. // run control default action
  89. #ifdef _FC_GUI_ENABLED_
  90. /// The QT Application need to be set very early because of splasher
  91. QApplication* pcQApp = NULL;
  92. FCSplashScreen *splash = 0;
  93. #endif
  94. /// configuration map, acces throug FCApplication
  95. std::map<std::string,std::string> mConfig;
  96. // some globals set by the commandline options or Init function
  97. const char*     sScriptName;
  98. /// pointer to the system parameter (loaded in Init())
  99. FCParameterManager *pcSystemParameter;
  100. /// pointer to the user parameter (loaded in Init())
  101. FCParameterManager *pcUserParameter;
  102. // forwards
  103. void Init(int argc, char ** argv );
  104. void Destruct(void);
  105. void ParsOptions(int argc, char ** argv);
  106. void CheckEnv(void);
  107. void PrintInitHelp(void);
  108. void ExtractPathAndUser(const char*);
  109. int main( int argc, char ** argv )
  110. {
  111.   // Init phase ===========================================================
  112. # ifndef FC_DEBUG
  113. try
  114. {
  115. # endif
  116. // extract home path
  117. ExtractPathAndUser(argv[0]);
  118. // first check the environment variables
  119. CheckEnv();
  120. // Initialization (phase 1)
  121. Init(argc,argv);
  122. // the FreeCAD Application
  123. # ifndef FC_DEBUG
  124. }
  125. // catch all OCC exceptions
  126. catch(Standard_Failure e)
  127. {
  128. Handle(Standard_Failure) E = Standard_Failure::Caught();
  129. cout << "An Open CasCade exception was caught:"<< endl << E << endl;
  130. PrintInitHelp();
  131. exit(10);
  132. }
  133. // catch all FC exceptions
  134. catch(const FCException& e)
  135. {
  136. GetConsole().Error("Application init failed:");
  137. e.ReportException();
  138. PrintInitHelp();
  139. exit(20);
  140. }
  141. // catch XML exceptions
  142. /* catch (XMLException& e)
  143. {
  144. GetConsole().Error("Application init failed:");
  145. GetConsole().Error(StrX(e.getMessage()).c_str());
  146. PrintInitHelp();
  147. exit(30);
  148. }
  149. */
  150. // catch all the (nasty) rest
  151. catch(...)
  152. {
  153. GetConsole().Error("Application init failed, because of a really nesty (unknown) error...");
  154. PrintInitHelp();
  155. exit(40);
  156. }
  157. # endif
  158. // Run phase ===========================================================
  159. int ret;
  160. # ifndef FC_DEBUG
  161. try
  162. {
  163. # endif
  164. if(mConfig["RunMode"] == "Gui")
  165. {
  166. // run GUI
  167. # ifdef _FC_GUI_ENABLED_
  168. // A new QApplication
  169. GetConsole().Log("Creating GUI Application...n");
  170. // if application not yet created
  171. if (!pcQApp)  pcQApp = new QApplication ( argc, argv );
  172. ApplicationWindow * mw = new ApplicationWindow();
  173. pcQApp->setMainWidget(mw);
  174. // runing the Gui init script
  175. GetInterpreter().Launch(GetScriptFactory().ProduceScript("FreeCADGuiInit"));
  176. // show the main window
  177. GetConsole().Log("Showing GUI Application...n");
  178.         mw->Polish();
  179. mw->show();
  180. pcQApp->connect( pcQApp, SIGNAL(lastWindowClosed()), pcQApp, SLOT(quit()) );
  181. // close splasher
  182. if (splash)
  183. {
  184.   // wait a short moment
  185.   QWaitCondition().wait(1000);
  186.   // if splasher is still busy terminate it
  187.   splash->bRun = false;
  188. }
  189. // run the Application event loop
  190. GetConsole().Log("Running event loop...n");
  191. ret = pcQApp->exec();
  192. GetConsole().Log("event loop leftn");
  193. delete pcQApp;
  194. # else
  195. GetConsole().Error("GUI mode not possible. This is a FreeCAD compiled without GUI. Use FreeCAD -cn");
  196. # endif
  197. }
  198. else if(mConfig["RunMode"] == "Cmd")
  199. {
  200. // Run the comandline interface
  201. ret = GetInterpreter().RunCommandLine("Console mode");
  202. }
  203. else if(mConfig["RunMode"] == "Script")
  204. {
  205. // run a script
  206. GetConsole().Log("Running script: %sn",mConfig["ScriptFileName"].c_str());
  207. GetInterpreter().LaunchFile(mConfig["ScriptFileName"].c_str());
  208. }
  209. else if(mConfig["RunMode"] == "Internal")
  210. {
  211. // run internal script
  212. GetConsole().Log("Running internal script:n");
  213. GetInterpreter().Launch(sScriptName);
  214. } else {
  215. GetConsole().Log("Unknown Run mode in main()?!?nn");
  216. exit(1);
  217. }
  218. # ifndef FC_DEBUG
  219. }
  220. catch(Standard_Failure e)
  221. {
  222. GetConsole().Error("Running the application failed, OCC exception caught:n");
  223. Handle(Standard_Failure) E = Standard_Failure::Caught();
  224. cout << "An exception was caught " << E << endl;
  225. exit(4);
  226. }
  227. catch(const FCException& e)
  228. {
  229. GetConsole().Error("Running the application failed:n");
  230. e.ReportException();
  231. exit(5);
  232. }
  233. catch(...)
  234. {
  235. GetConsole().Error("Running the application failed, because of a really nesty (unknown) error...nn");
  236. exit(6);
  237. }
  238. # endif
  239. // Destruction phase ===========================================================
  240. GetConsole().Log("FreeCAD terminating...nn");
  241. # ifndef FC_DEBUG
  242. try
  243. {
  244. # endif
  245. // cleans up
  246. Destruct();
  247. # ifndef FC_DEBUG
  248. }
  249. catch(...)
  250. {
  251. GetConsole().Error("Destruction of the application failed, because of a really nesty (unknown) error...nn");
  252. exit(6);
  253. }
  254. # endif
  255. GetConsole().Log("FreeCAD completely terminatednn");
  256. return 0;
  257. }
  258. /** The Init function
  259.  * Initialize all the stuff and running the init script:
  260.  * - parsing the options
  261.  * - starting splasher
  262.  * - Launching the FCInterpreter (starting python)
  263.  * - Launching the FCConsole
  264.  * - Call the Init script ("(FreeCADDir)/scripts/FreeCADInit.py")
  265.  **/
  266. void Init(int argc, char ** argv )
  267. {
  268. // set some config defaults
  269. # ifdef _FC_GUI_ENABLED_
  270. mConfig["RunMode"] = "Gui";
  271. # else
  272. mConfig["RunMode"] = "Cmd";
  273. # endif
  274. # ifdef FC_DEBUG
  275. mConfig["Debug"] = "1";
  276. # else
  277. mConfig["Debug"] = "0";
  278. # endif
  279. // Pars the options which have impact to the init process
  280. ParsOptions(argc,argv);
  281. mConfig["UserParameter"]  += mConfig["HomePath"] + "FC" + mConfig["UserName"] + ".FCParam";
  282. mConfig["SystemParameter"] = mConfig["HomePath"] + "AppParam.FCParam";
  283. puts(mConfig["HomePath"].c_str());
  284. puts(mConfig["UserParameter"].c_str());
  285. puts(mConfig["SystemParameter"].c_str());
  286. // init python
  287. GetInterpreter();
  288. // Init console ===========================================================
  289. GetConsole().AttacheObserver(new FCCmdConsoleObserver());
  290. if(mConfig["Verbose"] == "Strict") GetConsole().SetMode(FCConsole::Verbose);
  291. // file logging fcility
  292. # ifdef FC_DEBUG
  293. GetConsole().AttacheObserver(new FCLoggingConsoleObserver("FreeCAD.log"));
  294. # endif
  295. // Banner ===========================================================
  296. if(!(mConfig["Verbose"] == "Strict"))
  297. GetConsole().Message("FreeCAD (c) 2001 Juergen Riegel (GPL,LGPL)nn%s",sBanner);
  298. else
  299. GetConsole().Message("FreeCAD (c) 2001 Juergen Riegel (GPL,LGPL)nn");
  300. pcSystemParameter = new FCParameterManager();
  301. pcUserParameter = new FCParameterManager();
  302. // Init parameter sets ===========================================================
  303. if(pcSystemParameter->LoadOrCreateDocument(mConfig["SystemParameter"].c_str()) && !(mConfig["Verbose"] == "Strict"))
  304. {
  305. GetConsole().Warning("   Parameter not existing, write initial onen");
  306. GetConsole().Message("   This Warning means normaly FreeCAD running the first time or then"
  307.                      "   configuration was deleted or moved.Build up the standard configuration.n");
  308. }
  309. if(pcUserParameter->LoadOrCreateDocument(mConfig["UserParameter"].c_str()) && !(mConfig["Verbose"] == "Strict"))
  310. {
  311. GetConsole().Warning("   User settings not existing, write initial onen");
  312. GetConsole().Message("   This Warning means normaly you running FreeCAD the first timen"
  313.                      "   or your configuration was deleted or moved. The system defaultsn"
  314.                      "   will be reestablished for you.n");
  315. }
  316. // interpreter and Init script ==========================================================
  317. // register scripts
  318. new FCScriptProducer( "FreeCADInit",    FreeCADInit    );
  319. new FCScriptProducer( "FreeCADTest",    FreeCADTest    );
  320. #ifdef  _FC_GUI_ENABLED_
  321. new FCScriptProducer( "FreeCADGuiInit", FreeCADGuiInit );
  322. #endif
  323. // Start the python interpreter
  324. FCInterpreter &rcInterperter = GetInterpreter();
  325. rcInterperter.SetComLineArgs(argc,argv);
  326. // checking on the plugin files of OpenCasCade
  327. std::fstream cTempStream;
  328. cTempStream.open((mConfig["HomePath"]+"\Plugin").c_str(),ios::out);
  329. cTempStream << Plu ;
  330. cTempStream.close();
  331. cTempStream.open((mConfig["HomePath"]+"\Standard").c_str(),ios::out);
  332. cTempStream << Stand ;
  333. cTempStream.close();
  334. // creating the application
  335. if(!(mConfig["Verbose"] == "Strict")) GetConsole().Log("Create Application");
  336. FCApplication::InitApplication(pcSystemParameter,pcUserParameter,mConfig);
  337. // Splasher phase ===========================================================
  338. # ifdef _FC_GUI_ENABLED_
  339. // startup splasher
  340. // when runnig in verbose mode no splasher
  341. if ( ! (mConfig["Verbose"] == "Strict") && (mConfig["RunMode"] == "Gui") )
  342. {
  343.       FCParameterGrp::handle hGrp = GetApplication().GetSystemParameter().GetGroup("BaseApp")->GetGroup("WindowSettings");
  344.       if (hGrp->GetBool("AllowSplasher", true))
  345.       {
  346.   pcQApp = new QApplication ( argc, argv );
  347.   splash = new FCSplashScreen(QApplication::desktop());
  348.   pcQApp->setMainWidget(splash);
  349.       }
  350. }
  351. # endif
  352. // starting the init script
  353. rcInterperter.Launch(GetScriptFactory().ProduceScript("FreeCADInit"));
  354. }
  355. /** The Destruct function
  356.  * close and destruct everything created during Init()
  357.  */
  358. void Destruct(void)
  359. {
  360. // saving system parameter
  361. GetConsole().Log("Saving system parameter...");
  362. pcSystemParameter->SaveDocument(mConfig["SystemParameter"].c_str());
  363. // saving the User parameter
  364. GetConsole().Log("donenSaving user parameter...");
  365. pcUserParameter->SaveDocument(mConfig["UserParameter"].c_str());
  366. GetConsole().Log("donen");
  367. // clean up
  368. delete pcSystemParameter;
  369. delete pcUserParameter;
  370. }
  371. //**************************************************************************
  372. // extracting the home path
  373. void ExtractPathAndUser(const char* sCall)
  374. {
  375. // find home path
  376. mConfig["HomePath"] = FindHomePath(sCall);
  377. // find home path
  378. mConfig["BinPath"] = FindBinPath(sCall);
  379. // try to figure out if using FreeCADLib
  380. mConfig["FreeCADLib"] = GetFreeCADLib(mConfig["HomePath"].c_str());
  381. // try to figure out the user
  382. char* user = getenv("USERNAME");
  383. if (user == NULL)
  384. user = getenv("USER");
  385. if (user == NULL)
  386. user = "Anonymous";
  387. mConfig["UserName"] = user;
  388. PrintPath();
  389. }
  390. //**************************************************************************
  391. // checking the environment
  392. const char sEnvErrorText1[] = 
  393. "It seems some of the variables needed by FreeCAD are not setn"
  394. "or wrong set. This regards the Open CasCade or python variables:n"
  395. "CSF_GRAPHICSHR=C:\CasRoot\Windows_NT\dll\opengl.dlln"
  396. "CSF_MDTVFONTDIRECTORY=C:\CasRoot\src\FontMFT\n"
  397. "CSF_MDTVTEXTURESDIRECTORY=C:\CasRoot\src\Textures\n"
  398. "CSF_UNITSDEFINITION=C:\CasRoot\src\UnitsAPI\Units.datn"
  399. "CSF_UNITSLEXICON=C:\CasRoot\src\UnitsAPI\Lexi_Expr.datn"
  400. "Please reinstall python or OpenCasCade!nn";
  401. const char sEnvErrorText2[] = 
  402. "It seems some of the variables needed by FreeCAD are not setn"
  403. "or wrong set. This regards the Open CasCade variables:n"
  404. "XXX=C:\CasRoot\Windows_NT\dll\opengl.dlln"
  405. "Please reinstall XXX!nn";
  406. void CheckEnv(void)
  407. {
  408. // set the OpenCasCade plugin variables to the FreeCAD bin path.
  409. SetPluginDefaults(mConfig["HomePath"].c_str());
  410. // sets all needed varables if a FreeCAD LibPack is found
  411. if(mConfig["FreeCADLib"] != "")
  412. {
  413. // sets the python environment variables if the FREECADLIB variable is defined
  414. SetPythonToFreeCADLib(mConfig["FreeCADLib"].c_str());
  415. // sets the OpenCasCade environment variables if the FREECADLIB variable is defined
  416. SetCasCadeToFreeCADLib(mConfig["FreeCADLib"].c_str());
  417. }
  418. cout << flush;
  419. bool bFailure=false;
  420. TestEnvExists("CSF_MDTVFontDirectory",bFailure);
  421. TestEnvExists("CSF_MDTVTexturesDirectory",bFailure);
  422. TestEnvExists("CSF_UnitsDefinition",bFailure);
  423. TestEnvExists("CSF_UnitsLexicon",bFailure);
  424. if (bFailure) {
  425.       cerr<<"Environment Error(s)"<<endl<<sEnvErrorText1;
  426. exit(1);
  427. }
  428. }
  429. const char Usage[] = 
  430. " [Options] files..."
  431. "Options:n"
  432. "  -h             Display this information "
  433. "  -c             Runs FreeCAD in console mode (no windows)n"
  434. "  -cf file-name  Runs FreeCAD in server mode with script file-namen"
  435. "  -t0            Runs FreeCAD self test functionn"
  436. "  -v             Runs FreeCAD in verbose moden"
  437. "n consult also the HTML documentation on http://free-cad.sourceforge.net/n"
  438. "";
  439. void ParsOptions(int argc, char ** argv)
  440. {
  441. // scan command line arguments for user input.
  442. for (int i = 1; i < argc; i++)
  443. {
  444. if (*argv[i] == '-' )
  445. {
  446. switch (argv[i][1])
  447. {
  448. // Console modes
  449. case 'c':
  450. case 'C':
  451. switch (argv[i][2])
  452. {
  453. // Console with file
  454. case 'f':
  455. case 'F':
  456. mConfig["RunMode"] = "Cmd";
  457. if(argc <= i+1)
  458. {
  459. GetConsole().Error("Expecting a filen");
  460. GetConsole().Error("nUsage: %s %s",argv[0],Usage);
  461. }
  462. mConfig["FileName"]= argv[i+1];
  463. i++;
  464. break;
  465. case '':
  466. mConfig["RunMode"] = "Cmd";
  467. break;
  468. default:
  469. GetConsole().Error("Invalid Input %sn",argv[i]);
  470. GetConsole().Error("nUsage: %s %s",argv[0],Usage);
  471. throw FCException("Comandline error(s)");
  472. };
  473. break;
  474. case 't':
  475. case 'T':
  476. switch (argv[i][2])
  477. {
  478. case '0':
  479. // test script level 0
  480. mConfig["RunMode"] = "Internal";
  481. sScriptName = FreeCADTest;
  482. break;
  483. default:
  484. //default testing level 0
  485. mConfig["RunMode"] = "Internal";
  486. sScriptName = FreeCADTest;
  487. break;
  488. };
  489. break;
  490. case 'v':
  491. case 'V':
  492. switch (argv[i][2])
  493. {
  494. // run the test environment script
  495. case '1':
  496. mConfig["Verbose"] = "Loose";
  497. sScriptName = GetScriptFactory().ProduceScript("FreeCADTestEnv");
  498. break;
  499. case '':
  500. case '0':
  501. // test script level 0
  502. mConfig["Verbose"] = "Strict";
  503. break;
  504. default:
  505. //default testing level 0
  506. GetConsole().Error("Invalid Verbose Option: %sn",argv[i]);
  507. GetConsole().Error("nUsage: %s %s",argv[0],Usage);
  508. throw FCException("Comandline error(s)");
  509. };
  510. break;
  511. case '?':
  512. case 'h':
  513. case 'H':
  514. GetConsole().Message("nUsage: %s %s",argv[0],Usage);
  515. throw FCException("Comandline break");
  516. break;
  517. default:
  518. GetConsole().Error("Invalid Option: %sn",argv[i]);
  519. GetConsole().Error("nUsage: %s %s",argv[0],Usage);
  520. throw FCException("Comandline error(s)");
  521. }
  522. }
  523. else
  524. {
  525. GetConsole().Error("Illegal command line argument #%d, %sn",i,argv[i]);
  526. GetConsole().Error("nUsage: %s %s",argv[0],Usage);
  527. throw FCException("Comandline error(s)");
  528. }
  529. }
  530. }
  531. void PrintInitHelp(void)
  532. {
  533. cerr << endl << endl
  534.  << "  An initializing error was caught. This means mainly" << endl
  535.  << "  FreeCAD is not installed properly. Type "FreeCAD -i""<< endl
  536.  << "  to reinstall FreeCAD." << endl << endl
  537.  << "  Good luck ;-)" << endl << endl;
  538. }
  539. #ifdef FREECADMAINPY
  540. BOOL APIENTRY DllMain( HANDLE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved){return TRUE;}
  541. extern "C" {
  542. #ifdef FC_DEBUG
  543. void __declspec(dllexport) initFreeCADDCmdPy() {
  544. #else
  545. void __declspec(dllexport) initFreeCADCmdPy() {
  546. #endif
  547. GetConsole();
  548. FCApplication::_pcSingelton = new FCApplication(pcSystemParameter,pcUserParameter,mConfig);
  549. printf("hallo");
  550. cout << "hallo";
  551. return;
  552. }
  553. }
  554. #endif