FreeCAD源码分析:FreeCADMain模块
FreeCAD源碼分析:FreeCADCmd\FreeCADMain\FreeCADPy模塊
濟南友泉軟件有限公司
?
FreeCAD提供了控制臺、GUI、Python等三種運行模式,分別對應FreeCADCmd、FreeCADMain、FreeCADPy。由于這三者的代碼結構比較相似,但FreeCADMain相對復雜一些,因此,本文著重就FreeCADMain展開分析。了解清楚FreeCADMain模塊,就可以輕松掌握FreeCADMainCmd、FreeCADMainPy模塊的原理。
注:FreeCADMain也提供了控制臺模式運行。
一、模塊功能概述
FreeCADMain主要用于根據配置參數(默認參數、用戶參數)啟動軟件FreeCAD,具體來說,主要功能包括:
- 配置參數
生成默認配置參數,解析用戶輸入參數,訂制FreeCAD的啟動特性。
- dmp文件
軟件意外崩潰時,輸出堆棧信息到crash.dmp文件(默認位置%APPDATA%\FreeCAD)。
- 日志重定向
將標準輸出、標準錯誤、標準日志等重定向到日志文件。
- 啟動軟件
根據配置參數啟動GUI版本或者Console版本的FreeCAD。
二、處理流程
通過分析MainGui.cpp以研究FreeCADMain的主要功能的實現流程。
?? 2.1 移除PYTHONHOME環(huán)境變量
PYTHONHOME環(huán)境變量指向Python的安裝目錄,通常不需要用戶自己設置該變量。為了防止多個版本的Python對FreeCAD的影響,在main函數進入之后,首先移除了PYTHONHOME環(huán)境變量。
#if defined (FC_OS_LINUX) || defined(FC_OS_BSD)// Make sure to setup the Qt locale system before setting LANG and LC_ALL to C.// which is needed to use the system locale settings.(void)QLocale::system();#if QT_VERSION < 0x050000// http://www.freecadweb.org/tracker/view.php?id=399// Because of setting LANG=C the Qt automagic to use the correct encoding// for file names is broken. This is a workaround to force the use of UTF-8 encodingQFile::setEncodingFunction(myEncoderFunc);QFile::setDecodingFunction(myDecoderFunc);#endif// See https://forum.freecadweb.org/viewtopic.php?f=18&t=20600// See Gui::Application::runApplication()putenv("LC_NUMERIC=C");putenv("PYTHONPATH=");#elif defined(FC_OS_MACOSX)(void)QLocale::system();putenv("PYTHONPATH=");#else_putenv("PYTHONPATH="); // https://forum.freecadweb.org/viewtopic.php?f=4&t=18288 // https://forum.freecadweb.org/viewtopic.php?f=3&t=20515 const char* fc_py_home = getenv("FC_PYTHONHOME"); if (fc_py_home) _putenv_s("PYTHONHOME", fc_py_home); else _putenv("PYTHONHOME="); #endif?? 2.2 配置默認軟件參數
靜態(tài)成員函數Application::Config返回靜態(tài)對象Application::mConfig對象,
static std::map<std::string,std::string> mConfig;mConfig以字符串的形式保存了不同參數對應的參數值。通過設置mConfig就可以指定FreeCAD的啟動特性。
???
?? 2.3 啟動模式
FreeCAD具有GUI、Console等運行兩種模式。通過設置“Console”/“RunMode”可以指定FreeCAD的運行模式。
| 名稱 | 取值范圍 | 默認值 |
| Console | 0 : 不啟動控制臺 1 : 啟動控制臺 | 0 |
| RunMode | Gui?: ?界面模式 Internal : | Gui |
如果“Console”為“1”,則FreeCAD將啟動控制臺。
如果“RunMode”為“Gui”或者“Internal”,將會調用FreeCADGui模塊以界面模式啟動FreeCAD;否則將會調用FreeCADMainCmd以控制臺模式啟動FreeCAD。
// if console option is set then run in cmd modeif (App::Application::Config()["Console"] == "1")App::Application::runApplication();if (App::Application::Config()["RunMode"] == "Gui" ||App::Application::Config()["RunMode"] == "Internal")Gui::Application::runApplication();elseApp::Application::runApplication();? 2.4 導出崩潰信息
通過調用dbghelp.dll中MiniDumpWriteDump函數,修改軟件運行時堆棧信息導出到mConfig["UserAppData"]\creash.dmp文件中。
// create a dump file when the application crashesstd::string dmpfile = App::Application::getUserAppDataDir();dmpfile += "crash.dmp";InitMiniDumpWriter(dmpfile);? 2.5 重定向日志輸出
Base::RedirectStdOutput、Base::RedirectStdLog、RedirectStdError均繼承自std::streambuf。Base::RedirectStdOutput、Base::RedirectStdLog將輸出、日志等重定向到了Base::Console的Log函數;RedirectStdError則將錯誤重定向到Base::Console的Error函數。
通過調用std:: basic_ios::rdbuf函數設置std::cout、std::clog、std::cerr等流對象的緩沖區(qū)可以分別完成標準輸出、日志、錯誤等輸出的重定向。
Base::RedirectStdOutput stdcout;Base::RedirectStdLog stdclog;Base::RedirectStdError stdcerr;std::streambuf* oldcout = std::cout.rdbuf(&stdcout);std::streambuf* oldclog = std::clog.rdbuf(&stdclog);std::streambuf* oldcerr = std::cerr.rdbuf(&stdcerr);FreeCAD退出之前,需要恢復標準輸出、日志、錯誤等流對象緩沖區(qū)。
std::cout.rdbuf(oldcout);std::clog.rdbuf(oldclog);std::cerr.rdbuf(oldcerr);三、控制臺應用程序類
App::Application類用于FreeCAD主程序的抽象。實現配置參數管理、文檔管理等功能。
?? 3.1 初始化
應用程序類調用init成員函數完成應用程序的初始化工作,init函數的原型為:
static void init(int argc, char ** argv);參數說明:
argc: argv數組中的長度,由主函數main傳入
argv: 參數列表,由main函數傳入
根據傳入的參數,調用initConfig()函數初始化配置參數,并將默認配置參數存放到mConfig中,
static std::map<std::string,std::string> mConfig;注:mConfig主要配置參數參見附錄A。
?? 3.2 參數管理
App::Application使用mConfig保存基本的軟件信息,包括程序名稱、用戶參數目錄、系統(tǒng)參數目錄等。
std::map<std::string,std::string> Application::mConfigApp::Application使用一系列ParameterManager類型對象來管理軟件參數,
std::map<std::string,ParameterManager *> mpcPramManager;可以通過
ParameterManager不僅可以加載、導出DOM格式的參數文件,而且提供多種接口以方便的獲取整形、浮點型、布爾類型的參數值。
mpcPramManager中有兩個比較重要的參數管理器,即_pcSysParamMngr與_pcUserParamMngr,
ParameterManager *App::Application::_pcSysParamMngr; ParameterManager *App::Application::_pcUserParamMngr;在Application::LoadParameters()中,_pcUserParamMngr 會加載mConfig["UserParameter"] 指定的文件(mConfig["UserAppData"]\user.cfg)文件來完成對;_pcSysParamMngr會加載mConfig["SystemParameter"](默認是mConfig["UserAppData"]\system.cfg)
?? 3.3 文檔管理
基于信號-槽機制,App::Application提供了創(chuàng)建、打開、激活、關閉文檔等一系列文檔操作函數。??
App::Document* newDocument(const char * Name=0l, const char * UserName=0l);/// Closes the document \a name and removes it from the application.bool closeDocument(const char* name);/// find a unique document namestd::string getUniqueDocumentName(const char *Name) const;/// Open an existing document from a fileApp::Document* openDocument(const char * FileName=0l);/// Retrieve the active documentApp::Document* getActiveDocument(void) const;/// Retrieve a named documentApp::Document* getDocument(const char *Name) const;/// gets the (internal) name of the documentconst char * getDocumentName(const App::Document* ) const;/// get a list of all documents in the applicationstd::vector<App::Document*> getDocuments() const;/// Set the active documentvoid setActiveDocument(App::Document* pDoc);void setActiveDocument(const char *Name);/// close all documents (without saving)void closeAllDocuments(void);四、重定向輸出類
FreeCADBase模塊提供了RedirectStdOutput、RedirectStdError、RedirectStdLog等三個類用于日志輸出重定向。
class BaseExport RedirectStdOutput : public std::streambuf { public:RedirectStdOutput();protected:int overflow(int c = EOF);int sync();private:std::string buffer; };class BaseExport RedirectStdError : public std::streambuf { public:RedirectStdError();protected:int overflow(int c = EOF);int sync();private:std::string buffer; };class BaseExport RedirectStdLog : public std::streambuf { public:RedirectStdLog();protected:int overflow(int c = EOF);int sync();private:std::string buffer; };可以看到,這三個類的實現比較相似。這三個類都繼承自std::streambuf類。
using streambuf = basic_streambuf<char, char_traits<char>>;streambuf實際上是std::basic_streambuf模板類char類型的實例化之后得到的一個類。
當有新的字符插入時,就會調用overflow(int c)函數,參數c就是要插入的字符。sync()函數用于清空緩沖區(qū)中的內容。
? 4.1 RedirectStdOutput
由于RedirectStdOutput、RedirectStdError、RedirectStdLog等三個類的實現方式比較相似,這里僅對RedirectStdOutput進行分析。
在RedirectStdOutput的構造函數中,設置了緩沖區(qū)的大小,
RedirectStdOutput::RedirectStdOutput() {buffer.reserve(80); }當有新的字符需要插入的時候,overflow函數將字符放到內部字符串的最后面,同事返回當前字符串的長度。
int RedirectStdOutput::overflow(int c) {if (c != EOF)buffer.push_back((char)c);return c; }調用sync函數,將字符串當前的內容通過Base::Console().Log函數輸出。
int RedirectStdOutput::sync() {// Print as log as this might be verboseif (!buffer.empty()) {Base::Console().Log("%s", buffer.c_str());buffer.clear();}return 0; }? 4.2 ConsoleSingleton
ConsoleSigleton用于信息、警告、錯誤等輸出。程序運行時,只有一個ConsoleSigleton對象。可以通過Base::Console()獲取該唯一的控制臺輸出對象。
#include <Base/Console.h>Base::Console().Log("Stage: %d",i);ConsoleSigleton提供了多種工作模式,可以通SetConsoleMode函數進行設置,
/// Change modevoid SetConsoleMode(ConsoleMode m);?
五、界面應用程序類
略(Gui::Application與App::Application比較相似),參照FreeCADApp源碼分析。
?
六、FreeCADMainCmd模塊
FreeCADMainCmd構建生成FreeCADCmd(_d).exe程序,實際上是直接調用FreeCADApp模塊完成FreeCAD啟動。
?
七、FreeCADMainPy模塊
FreeCADMainPy構建生成FreeCAD(_d).pyd動態(tài)鏈接庫,用于在Python環(huán)境中導入FreeCAD模塊。MainPy.cpp文件中,定義了Python FreeCAD模塊的入口函數,
PyMOD_INIT_FUNC(FreeCAD) {// Init phase ===========================================================App::Application::Config()["ExeName"] = "FreeCAD";App::Application::Config()["ExeVendor"] = "FreeCAD";App::Application::Config()["AppDataSkipVendor"] = "true";int argc=1;char** argv;argv = (char**)malloc(sizeof(char*)* (argc+1));#if defined(FC_OS_WIN32)argv[0] = (char*)malloc(MAX_PATH);strncpy(argv[0],App::Application::Config()["AppHomePath"].c_str(),MAX_PATH);argv[0][MAX_PATH-1] = '\0'; // ensure null termination #elif defined(FC_OS_CYGWIN)HMODULE hModule = GetModuleHandle("FreeCAD.dll");char szFileName [MAX_PATH];GetModuleFileNameA(hModule, szFileName, MAX_PATH-1);argv[0] = (char*)malloc(MAX_PATH);strncpy(argv[0],szFileName,MAX_PATH);argv[0][MAX_PATH-1] = '\0'; // ensure null termination #elif defined(FC_OS_LINUX) || defined(FC_OS_BSD)putenv("LANG=C");putenv("LC_ALL=C");// get whole path of the libraryDl_info info; #if PY_MAJOR_VERSION >= 3int ret = dladdr((void*)PyInit_FreeCAD, &info); #elseint ret = dladdr((void*)initFreeCAD, &info); #endifif ((ret == 0) || (!info.dli_fname)) {free(argv);PyErr_SetString(PyExc_ImportError, "Cannot get path of the FreeCAD module!"); #if PY_MAJOR_VERSION >= 3return 0; #elsereturn; #endif}argv[0] = (char*)malloc(PATH_MAX);strncpy(argv[0], info.dli_fname,PATH_MAX);argv[0][PATH_MAX-1] = '\0'; // ensure null termination// this is a workaround to avoid a crash in libuuid.so #elif defined(FC_OS_MACOSX)// The MacOS approach uses the Python sys.path list to find the path// to FreeCAD.so - this should be OS-agnostic, except these two// strings, and the call to access().const static char libName[] = "/FreeCAD.so";const static char upDir[] = "/../";char *buf = NULL;PyObject *pySysPath = PySys_GetObject("path");if ( PyList_Check(pySysPath) ) {int i;// pySysPath should be a *PyList of strings - iterate through it// backwards since the FreeCAD path was likely appended just before// we were imported.for (i = PyList_Size(pySysPath) - 1; i >= 0 ; --i) {const char *basePath;PyObject *pyPath = PyList_GetItem(pySysPath, i);long sz = 0;#if PY_MAJOR_VERSION >= 3if ( PyUnicode_Check(pyPath) ) {// Python 3 stringbasePath = PyUnicode_AsUTF8AndSize(pyPath, &sz);} #elseif ( PyString_Check(pyPath) ) {// Python 2 string typePyString_AsStringAndSize(pyPath, &basePath, &sz);}else if ( PyUnicode_Check(pyPath) ) {// Python 2 unicode type - explicitly use UTF-8 codecPyObject *fromUnicode = PyUnicode_AsUTF8String(pyPath);PyString_AsStringAndSize(fromUnicode, &basePath, &sz);Py_XDECREF(fromUnicode);} #endif // #if/else PY_MAJOR_VERSION >= 3else {continue;}if (sz + sizeof(libName) > PATH_MAX) {continue;}// buf gets assigned to argv[0], which is free'd at the endbuf = (char *)malloc(sz + sizeof(libName));if (buf == NULL) {break;}strcpy(buf, basePath);// append libName to bufstrcat(buf, libName);if (access(buf, R_OK | X_OK) == 0) {// The FreeCAD "home" path is one level up from// libName, so replace libName with upDir.strcpy(buf + sz, upDir);buf[sz + sizeof(upDir)] = '\0';break;}} // end for (i = PyList_Size(pySysPath) - 1; i >= 0 ; --i) {} // end if ( PyList_Check(pySysPath) ) {if (buf == NULL) {PyErr_SetString(PyExc_ImportError, "Cannot get path of the FreeCAD module!"); #if PY_MAJOR_VERSION >= 3return 0; #elsereturn; #endif}argv[0] = buf; #else # error "Implement: Retrieve the path of the module for your platform." #endifargv[argc] = 0;try {// Inits the ApplicationApp::Application::init(argc,argv);}catch (const Base::Exception& e) {std::string appName = App::Application::Config()["ExeName"];std::stringstream msg;msg << "While initializing " << appName << " the following exception occurred: '"<< e.what() << "'\n\n";msg << "\nPlease contact the application's support team for more information.\n\n";printf("Initialization of %s failed:\n%s", appName.c_str(), msg.str().c_str());}free(argv[0]);free(argv);#if PY_MAJOR_VERSION >= 3//PyObject* module = _PyImport_FindBuiltin("FreeCAD");PyObject* modules = PyImport_GetModuleDict();PyObject* module = PyDict_GetItemString(modules, "FreeCAD");if (!module) {PyErr_SetString(PyExc_ImportError, "Failed to load FreeCAD module!");}return module; #endif }?
?
?
附錄A: FreeCAD配置參數
| 名稱 | 默認值 | 描述 |
| APPDATA | 操作系統(tǒng)內置環(huán)境變量,例如 C:\Users\Administrator\AppData | ? |
| AppDataSkipVendor | true | ? |
| ExeVendor | FreeCAD | ? |
| ExeName | FreeCAD | ? |
| UserAppData | $( APPDATA)\FreeCAD | ? |
| UserParameter | $(UserAppData)\user.cfg | ? |
| SystemParameter | $(UserAppData)\system.cfg | ? |
參考資料
?
總結
以上是生活随笔為你收集整理的FreeCAD源码分析:FreeCADMain模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 运行在Istio之上的Apache Ka
- 下一篇: modbus rtu与计算机通讯,Mod