Console/ILogger: Refactor and extension

=======================================

Refactor:
 - Substitute the use of variadic templates with parameter packs.
 - Use recently incorporated external library "fmt" to handle printf like formating.
 - Extensive cleaning of pragmas and unnecessary forward declarations.
 - Parameter packs and libfmt provide a much stronger type checking now, so
   conversions that are by standard implicit as bool to int need an explicit static_cast
   to avoid compilation warnings.

Extension:
 - Include a notifier field, so that the originator of the message can be provided. E.g. Document#DocumentObject
 - Include a new type of message called CriticalMessage, this message is intended to have
   special behaviour in the future. Namely, it will be used to notify forward compatilibity issues.
   It will be used to substitute the current signal/slot mechanism.
 - Include two new types of messages for user notifications (Notification and TranslatedNotification). This messages
   will be use to convey UI notifications intended for the user (such as non-intrusive message about the usage of a tool). There
   are two versions to mark whether the string provided as a message is already translated or not. When using the console system for
   notifications, these notifications may originate from the App or the Gui. In the former, it is generally the case that the strings
   of messages are not (yet) translated (but they can be marked with QT_TRANSLATE_NOOP). In the latter, often the messages to be provided
   are already translated.

Python support for CriticalMessage, Notification and TranslatedNofification, including shortcuts:

    Crt = FreeCAD.Console.PrintCritical
    Ntf = FreeCAD.Console.PrintNotification
    Tnf = FreeCAD.Console.PrintTranslatedNotification
This commit is contained in:
Abdullah Tahiri
2023-03-03 12:34:15 +01:00
committed by abdullahtahiriyo
parent 2dac347526
commit c604d1741d
28 changed files with 655 additions and 285 deletions

View File

@@ -987,7 +987,7 @@ void Builder3D::saveToLog()
{
ILogger* obs = Base::Console().Get("StatusBar");
if (obs){
obs->SendLog(result.str().c_str(), Base::LogStyle::Log);
obs->SendLog("Builder3D",result.str().c_str(), Base::LogStyle::Log);
}
}

View File

@@ -61,6 +61,7 @@ include_directories(
)
list(APPEND FreeCADBase_LIBS ${QtCore_LIBRARIES})
list(APPEND FreeCADBase_LIBS fmt::fmt)
if (BUILD_DYNAMIC_LINK_PYTHON)
list(APPEND FreeCADBase_LIBS ${PYTHON_LIBRARIES})

View File

@@ -49,10 +49,11 @@ namespace Base {
class ConsoleEvent : public QEvent {
public:
ConsoleSingleton::FreeCAD_ConsoleMsgType msgtype;
std::string notifier;
std::string msg;
ConsoleEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, const std::string& msg)
: QEvent(QEvent::User), msgtype(type), msg(msg)
ConsoleEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, const std::string& notifier, const std::string& msg)
: QEvent(QEvent::User), msgtype(type), notifier(notifier),msg(msg)
{
}
~ConsoleEvent() override = default;
@@ -75,18 +76,27 @@ public:
if (ev->type() == QEvent::User) {
ConsoleEvent* ce = static_cast<ConsoleEvent*>(ev);
switch (ce->msgtype) {
case ConsoleSingleton::MsgType_Txt:
Console().NotifyMessage(ce->msg.c_str());
break;
case ConsoleSingleton::MsgType_Log:
Console().NotifyLog(ce->msg.c_str());
break;
case ConsoleSingleton::MsgType_Wrn:
Console().NotifyWarning(ce->msg.c_str());
break;
case ConsoleSingleton::MsgType_Err:
Console().NotifyError(ce->msg.c_str());
break;
case ConsoleSingleton::MsgType_Txt:
Console().Notify<LogStyle::Message>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_Log:
Console().Notify<LogStyle::Log>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_Wrn:
Console().Notify<LogStyle::Warning>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_Err:
Console().Notify<LogStyle::Error>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_Critical:
Console().Notify<LogStyle::Critical>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_Notification:
Console().Notify<LogStyle::Notification>(ce->notifier, ce->msg);
break;
case ConsoleSingleton::MsgType_TranslatedNotification:
Console().Notify<LogStyle::TranslatedNotification>(ce->notifier, ce->msg);
break;
}
}
}
@@ -189,6 +199,22 @@ ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsg
flags |= MsgType_Log;
pObs->bLog = b;
}
if ( type&MsgType_Critical ){
if ( pObs->bCritical != b )
flags |= MsgType_Critical;
pObs->bCritical = b;
}
if ( type&MsgType_Notification ){
if ( pObs->bNotification != b )
flags |= MsgType_Notification;
pObs->bNotification = b;
}
if ( type&MsgType_TranslatedNotification ){
if ( pObs->bTranslatedNotification != b )
flags |= MsgType_TranslatedNotification;
pObs->bTranslatedNotification = b;
}
return flags;
}
else {
@@ -209,6 +235,12 @@ bool ConsoleSingleton::IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType
return pObs->bWrn;
case MsgType_Err:
return pObs->bErr;
case MsgType_Critical:
return pObs->bCritical;
case MsgType_Notification:
return pObs->bNotification;
case MsgType_TranslatedNotification:
return pObs->bTranslatedNotification;
default:
return false;
}
@@ -227,109 +259,6 @@ void ConsoleSingleton::SetConnectionMode(ConnectionMode mode)
}
}
/** Prints a Message
* This method issues a Message.
* Messages are used to show some non vital information. That means when
* FreeCAD is running in GUI mode a Message appears on the status bar.
* In console mode a message is printed to the console.
* \par
* You can use a printf like interface like:
* \code
* Console().Message("Doing something important %d times\n",i);
* \endcode
* @see Warning
* @see Error
* @see Log
*/
void ConsoleSingleton::Message( const char *pMsg, ... )
{
#define FC_CONSOLE_FMT(_type,_type2) \
char format[BufferSize];\
format[sizeof(format)-4] = '.';\
format[sizeof(format)-3] = '.';\
format[sizeof(format)-2] = '\n';\
format[sizeof(format)-1] = 0;\
const unsigned int format_len = sizeof(format)-4;\
va_list namelessVars;\
va_start(namelessVars, pMsg);\
vsnprintf(format, format_len, pMsg, namelessVars);\
format[sizeof(format)-5] = '.';\
va_end(namelessVars);\
if (connectionMode == Direct)\
Notify##_type(format);\
else\
QCoreApplication::postEvent(ConsoleOutput::getInstance(), new ConsoleEvent(MsgType_##_type2, format));
FC_CONSOLE_FMT(Message,Txt);
}
/** Prints a Message
* This method issues a Warning.
* Messages are used to get the users attention. That means when
* FreeCAD is in GUI mode a Message Box pops up. In console
* mode a colored message is returned to the console! Don't use this carelessly.
* For information purposes the 'Log' or 'Message' methods are more appropriate.
* \par
* You can use a printf like interface like:
* \code
* Console().Warning("Some defects in %s, loading anyway\n",str);
* \endcode
* @see Message
* @see Error
* @see Log
*/
void ConsoleSingleton::Warning( const char *pMsg, ... )
{
FC_CONSOLE_FMT(Warning,Wrn);
}
/** Prints a Message
* This method issues an Error which makes some execution impossible.
* Errors are used to get the users attention. That means when FreeCAD
* is running in GUI mode an Error Message Box pops up. In console
* mode a colored message is printed to the console! Don't use this carelessly.
* For information purposes the 'Log' or 'Message' methods are more appropriate.
* \par
* You can use a printf like interface like:
* \code
* Console().Error("Something really bad in %s happened\n",str);
* \endcode
* @see Message
* @see Warning
* @see Log
*/
void ConsoleSingleton::Error( const char *pMsg, ... )
{
FC_CONSOLE_FMT(Error,Err);
}
/** Prints a Message
* This method is appropriate for development and tracking purposes.
* It can be used to track execution of algorithms and functions.
* The normal user doesn't need to see it, it's more for developers
* and experienced users. So in normal user mode the logging is switched off.
* \par
* You can use a printf-like interface for example:
* \code
* Console().Log("Execute part %d in algorithm %s\n",i,str);
* \endcode
* @see Message
* @see Warning
* @see Error
*/
void ConsoleSingleton::Log( const char *pMsg, ... )
{
if (_bVerbose)
{
FC_CONSOLE_FMT(Log,Log);
}
}
//**************************************************************************
// Observer stuff
@@ -357,36 +286,18 @@ void ConsoleSingleton::DetachObserver(ILogger *pcObserver)
_aclObservers.erase(pcObserver);
}
void ConsoleSingleton::NotifyMessage(const char *sMsg)
void Base::ConsoleSingleton::notifyPrivate(LogStyle category, const std::string& notifiername, const std::string& msg)
{
for (std::set<ILogger * >::iterator Iter=_aclObservers.begin();Iter!=_aclObservers.end();++Iter) {
if ((*Iter)->bMsg)
(*Iter)->SendLog(sMsg, LogStyle::Message); // send string to the listener
if ((*Iter)->isActive(category)) {
(*Iter)->SendLog(notifiername, msg, category); // send string to the listener
}
}
}
void ConsoleSingleton::NotifyWarning(const char *sMsg)
void ConsoleSingleton::postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, const std::string& notifiername, const std::string& msg)
{
for (std::set<ILogger * >::iterator Iter=_aclObservers.begin();Iter!=_aclObservers.end();++Iter) {
if ((*Iter)->bWrn)
(*Iter)->SendLog(sMsg, LogStyle::Warning); // send string to the listener
}
}
void ConsoleSingleton::NotifyError(const char *sMsg)
{
for (std::set<ILogger * >::iterator Iter=_aclObservers.begin();Iter!=_aclObservers.end();++Iter) {
if ((*Iter)->bErr)
(*Iter)->SendLog(sMsg, LogStyle::Error); // send string to the listener
}
}
void ConsoleSingleton::NotifyLog(const char *sMsg)
{
for (std::set<ILogger * >::iterator Iter=_aclObservers.begin();Iter!=_aclObservers.end();++Iter) {
if ((*Iter)->bLog)
(*Iter)->SendLog(sMsg, LogStyle::Log); // send string to the listener
}
QCoreApplication::postEvent(ConsoleOutput::getInstance(), new ConsoleEvent(type, notifiername, msg));
}
ILogger *ConsoleSingleton::Get(const char *Name) const
@@ -464,6 +375,18 @@ PyMethodDef ConsoleSingleton::Methods[] = {
"PrintWarning(obj) -> None\n\n"
"Print a warning message to the output.\n\n"
"obj : object\n The string representation is printed."},
{"PrintCritical",ConsoleSingleton::sPyCritical, METH_VARARGS,
"PrintCritical(obj) -> None\n\n"
"Print a critical message to the output.\n\n"
"obj : object\n The string representation is printed."},
{"PrintNotification", ConsoleSingleton::sPyNotification, METH_VARARGS,
"PrintNotification(obj) -> None\n\n"
"Print a user notification to the output.\n\n"
"obj : object\n The string representation is printed."},
{"PrintTranslatedNotification", ConsoleSingleton::sPyTranslatedNotification, METH_VARARGS,
"PrintTranslatedNotification(obj) -> None\n\n"
"Print an already translated notification to the output.\n\n"
"obj : object\n The string representation is printed."},
{"SetStatus", ConsoleSingleton::sPySetStatus, METH_VARARGS,
"SetStatus(observer, type, status) -> None\n\n"
"Set the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n\n"
@@ -483,25 +406,53 @@ PyMethodDef ConsoleSingleton::Methods[] = {
};
namespace {
PyObject* FC_PYCONSOLE_MSG(std::function<void(const char*)> func, PyObject* args)
PyObject* FC_PYCONSOLE_MSG(std::function<void(const char*, const char *)> func, PyObject* args)
{
PyObject *output;
if (!PyArg_ParseTuple(args, "O", &output))
return nullptr;
PY_TRY {
const char* string = nullptr;
PyObject *notifier;
const char* notifierStr = "";
auto retrieveString = [] (PyObject* pystr) {
PyObject* unicode = nullptr;
if (PyUnicode_Check(output)) {
string = PyUnicode_AsUTF8(output);
const char* outstr = nullptr;
if (PyUnicode_Check(pystr)) {
outstr = PyUnicode_AsUTF8(pystr);
}
else {
unicode = PyObject_Str(output);
unicode = PyObject_Str(pystr);
if (unicode)
string = PyUnicode_AsUTF8(unicode);
outstr = PyUnicode_AsUTF8(unicode);
}
if (string)
func(string); /*process message*/
Py_XDECREF(unicode);
return outstr;
};
if (!PyArg_ParseTuple(args, "OO", &notifier, &output)) {
PyErr_Clear();
if (!PyArg_ParseTuple(args, "O", &output)) {
return nullptr;
}
}
else { // retrieve notifier
PY_TRY {
notifierStr = retrieveString(notifier);
}
PY_CATCH
}
PY_TRY {
const char* string = retrieveString(output);
if (string)
func(notifierStr, string); /*process message*/
}
PY_CATCH
Py_Return;
@@ -510,29 +461,50 @@ PyObject* FC_PYCONSOLE_MSG(std::function<void(const char*)> func, PyObject* args
PyObject *ConsoleSingleton::sPyMessage(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const char* msg) {
Instance().Message("%s", msg);
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().Message(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyWarning(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const char* msg) {
Instance().Warning("%s", msg);
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().Warning(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyError(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const char* msg) {
Instance().Error("%s", msg);
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().Error(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyLog(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const char* msg) {
Instance().Log("%s", msg);
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().Log(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyCritical(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().Critical(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyNotification(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().UserNotification(notifier, "%s", msg);
}, args);
}
PyObject *ConsoleSingleton::sPyTranslatedNotification(PyObject * /*self*/, PyObject *args)
{
return FC_PYCONSOLE_MSG([](const std::string & notifier, const char* msg) {
Instance().UserTranslatedNotification(notifier, "%s", msg);
}, args);
}
@@ -557,8 +529,14 @@ PyObject *ConsoleSingleton::sPyGetStatus(PyObject * /*self*/, PyObject *args)
b = pObs->bMsg;
else if (strcmp(pstr2,"Err") == 0)
b = pObs->bErr;
else if (strcmp(pstr2,"Critical") == 0)
b = pObs->bCritical;
else if (strcmp(pstr2,"Notification") == 0)
b = pObs->bNotification;
else if (strcmp(pstr2,"TranslatedNotification") == 0)
b = pObs->bTranslatedNotification;
else
Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Msg' or 'Wrn')");
Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical', 'Notification' or 'TranslatedNotification')");
return PyBool_FromLong(b ? 1 : 0);
}
@@ -585,8 +563,14 @@ PyObject *ConsoleSingleton::sPySetStatus(PyObject * /*self*/, PyObject *args)
pObs->bMsg = status;
else if (strcmp(pstr2,"Err") == 0)
pObs->bErr = status;
else if (strcmp(pstr2,"Critical") == 0)
pObs->bCritical = status;
else if (strcmp(pstr2,"Notification") == 0)
pObs->bNotification = status;
else if (strcmp(pstr2,"TranslatedNotification") == 0)
pObs->bTranslatedNotification = status;
else
Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Msg' or 'Wrn')");
Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical', 'Notification' or 'TranslatedNotification')");
Py_Return;
}

View File

@@ -25,6 +25,7 @@
#define BASE_CONSOLE_H
// Std. configurations
#include <array>
#include <chrono>
#include <map>
#include <set>
@@ -32,11 +33,13 @@
#include <sstream>
#include <FCGlobal.h>
#include <fmt/printf.h>
// Python stuff
using PyObject = struct _object;
using PyMethodDef = struct PyMethodDef;
//FIXME: ISO C++11 requires at least one argument for the "..." in a variadic macro
//FIXME: Even with parameter packs this is necessary for MSYS2
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
@@ -361,24 +364,24 @@ using PyMethodDef = struct PyMethodDef;
_instance.prefix(_str,_file,_line) << _msg;\
if(_instance.add_eol) \
_str<<std::endl;\
Base::Console()._func(_str.str().c_str());\
Base::Console()._func("",_str.str().c_str());\
if(_instance.refresh) Base::Console().Refresh();\
}\
}while(0)
#define _FC_PRINT(_instance,_l,_func,_msg) __FC_PRINT(_instance,_l,_func,_msg,__FILE__,__LINE__)
#define FC_MSG(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_MSG,NotifyMessage,_msg)
#define FC_WARN(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_WARN,NotifyWarning,_msg)
#define FC_ERR(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_ERR,NotifyError,_msg)
#define FC_LOG(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_LOG,NotifyLog,_msg)
#define FC_TRACE(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_TRACE,NotifyLog,_msg)
#define FC_MSG(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_MSG,Notify<Base::LogStyle::Message>,_msg)
#define FC_WARN(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_WARN,Notify<Base::LogStyle::Warning>,_msg)
#define FC_ERR(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_ERR,Notify<Base::LogStyle::Error>,_msg)
#define FC_LOG(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_LOG,Notify<Base::LogStyle::Log>,_msg)
#define FC_TRACE(_msg) _FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_TRACE,Notify<Base::LogStyle::Log>,_msg)
#define _FC_MSG(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_MSG,NotifyMessage,_msg,_file,_line)
#define _FC_WARN(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_WARN,NotifyWarning,_msg,_file,_line)
#define _FC_ERR(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_ERR,NotifyError,_msg,_file,_line)
#define _FC_LOG(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_LOG,NotifyLog,_msg,_file,_line)
#define _FC_TRACE(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_TRACE,NotifyLog,_msg,_file,_line)
#define _FC_MSG(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_MSG,Notify<Base::LogStyle::Message>,_msg,_file,_line)
#define _FC_WARN(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_WARN,Notify<Base::LogStyle::Warning>,_msg,_file,_line)
#define _FC_ERR(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_ERR,Notify<Base::LogStyle::Error>,_msg,_file,_line)
#define _FC_LOG(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_LOG,Notify<Base::LogStyle::Log>,_msg,_file,_line)
#define _FC_TRACE(_file,_line,_msg) __FC_PRINT(FC_LOG_INSTANCE,FC_LOGLEVEL_TRACE,Notify<Base::LogStyle::Log>,_msg,_file,_line)
#define FC_XYZ(_pt) '('<<(_pt).X()<<", " << (_pt).Y()<<", " << (_pt).Z()<<')'
#define FC_xy(_pt) '('<<(_pt).x<<", " << (_pt).y<<')'
@@ -445,11 +448,6 @@ using PyMethodDef = struct PyMethodDef;
#endif //FC_LOG_NO_TIMING
//TODO: Get rid of this forward-declaration
namespace Base {
class ConsoleSingleton;
} // namespace Base
//TODO: Get rid of this typedef
using ConsoleMsgFlags = unsigned int;
@@ -470,7 +468,10 @@ enum class LogStyle{
Warning,
Message,
Error,
Log
Log,
Critical, // Special message to mark critical notifications
Notification, // Special message for notifications to the user (e.g. educational)
TranslatedNotification, // Special message for already translated notifications to the user (e.g. educational)
};
/** The Logger Interface
@@ -484,23 +485,57 @@ class BaseExport ILogger
{
public:
ILogger()
:bErr(true),bMsg(true),bLog(true),bWrn(true){}
:bErr(true), bMsg(true), bLog(true), bWrn(true), bCritical(true), bNotification(false), bTranslatedNotification(false){}
virtual ~ILogger() = 0;
/** Used to send a Log message at the given level.
*/
virtual void SendLog(const std::string& msg, LogStyle level) = 0;
virtual void SendLog(const std::string& notifiername, const std::string& msg, LogStyle level) = 0;
/**
* Returns whether a LogStyle category is active or not
*/
bool isActive(Base::LogStyle category) {
if(category == Base::LogStyle::Log) {
return bLog;
}
else
if(category == Base::LogStyle::Warning) {
return bWrn;
}
else
if(category == Base::LogStyle::Error) {
return bErr;
}
else
if(category == Base::LogStyle::Message) {
return bMsg;
}
else
if(category == Base::LogStyle::Critical) {
return bCritical;
}
else
if(category == Base::LogStyle::Notification) {
return bNotification;
}
else
if(category == Base::LogStyle::TranslatedNotification) {
return bTranslatedNotification;
}
return false;
}
virtual const char *Name(){return nullptr;}
bool bErr,bMsg,bLog,bWrn;
bool bErr, bMsg, bLog, bWrn, bCritical, bNotification, bTranslatedNotification;
};
/** The console class
* This class manage all the stdio stuff. This includes
* Messages, Warnings, Log entries and Errors. The incoming
* Messages are distributed with the FCConsoleObserver. The
* FCConsole class itself makes no IO, it's more like a manager.
* Messages, Warnings, Log entries, Errors, Criticals, Notifications and
* TranslatedNotifications. The incoming Messages are distributed with the
* FCConsoleObserver. The FCConsole class itself makes no IO, it's more like a manager.
* \par
* ConsoleSingleton is a singleton! That means you can access the only
* instance of the class from every where in c++ by simply using:
@@ -515,30 +550,73 @@ public:
*/
class BaseExport ConsoleSingleton
{
public:
static const unsigned int BufferSize = 4024;
// exported functions goes here +++++++++++++++++++++++++++++++++++++++
/// Prints a Message
virtual void Message ( const char * pMsg, ... );
/// Prints a warning Message
virtual void Warning ( const char * pMsg, ... );
/// Prints a error Message
virtual void Error ( const char * pMsg, ... );
/// Prints a log Message
virtual void Log ( const char * pMsg, ... );
// observer processing
void NotifyMessage(const char *sMsg);
void NotifyWarning(const char *sMsg);
void NotifyError (const char *sMsg);
void NotifyLog (const char *sMsg);
/** Sends a message of type LogStyle (Message, Warning, Error, Log, Critical, Notification or TranslatedNotification).
This function is used by all specific convenience functions (Send(), Message(), Warning(), Error(), Log(), Critical
UserNotification and UserTranslatedNotification, without or without notifier id).
Notification can be direct or via queue.
*/
template <LogStyle, typename... Args>
inline void Send( const std::string & notifiername, const char * pMsg, Args&&... args );
/// Prints a Message
template <typename... Args>
inline void Message (const char * pMsg, Args&&... args);
/// Prints a warning Message
template <typename... Args>
inline void Warning (const char * pMsg, Args&&... args);
/// Prints a error Message
template <typename... Args>
inline void Error (const char * pMsg, Args&&... args);
/// Prints a log Message
template <typename... Args>
inline void Log (const char * pMsg, Args&&... args);
/// Prints a Critical Message
template <typename... Args>
inline void Critical (const char * pMsg, Args&&... args);
/// Sends a User Notification
template <typename... Args>
inline void UserNotification( const char * pMsg, Args&&... args );
/// Sends an already translated User Notification
template <typename... Args>
inline void UserTranslatedNotification( const char * pMsg, Args&&... args );
/// Prints a Message with source indication
template <typename... Args>
inline void Message (const std::string &, const char * pMsg, Args&&... args);
/// Prints a warning Message with source indication
template <typename... Args>
inline void Warning (const std::string &, const char * pMsg, Args&&... args);
/// Prints a error Message with source indication
template <typename... Args>
inline void Error (const std::string &, const char * pMsg, Args&&... args);
/// Prints a log Message with source indication
template <typename... Args>
inline void Log (const std::string &, const char * pMsg, Args&&... args);
/// Prints a Critical Message with source indication
template <typename... Args>
inline void Critical (const std::string &, const char * pMsg, Args&&... args);
/// Sends a User Notification with source indication
template <typename... Args>
inline void UserNotification( const std::string & notifier, const char * pMsg, Args&&... args );
/// Sends an already translated User Notification with source indication
template <typename... Args>
inline void UserTranslatedNotification( const std::string & notifier, const char * pMsg, Args&&... args );
// Notify a message directly to observers
template <LogStyle>
inline void Notify(const std::string & notifiername, const std::string & msg);
/// Attaches an Observer to FCConsole
void AttachObserver(ILogger *pcObserver);
/// Detaches an Observer from FCConsole
void DetachObserver(ILogger *pcObserver);
/// enumaration for the console modes
/// enumeration for the console modes
enum ConsoleMode{
Verbose = 1, // suppress Log messages
};
@@ -548,10 +626,13 @@ public:
};
enum FreeCAD_ConsoleMsgType {
MsgType_Txt = 1,
MsgType_Log = 2, // ConsoleObserverStd sends this and higher to stderr
MsgType_Wrn = 4,
MsgType_Err = 8
MsgType_Txt = 1,
MsgType_Log = 2, // ConsoleObserverStd sends this and higher to stderr
MsgType_Wrn = 4,
MsgType_Err = 8,
MsgType_Critical = 16, // Special message to notify critical information
MsgType_Notification = 32, // Special message to for notifications to the user
MsgType_TranslatedNotification = 64, // Special message for already translated notifications to the user
};
/// Change mode
@@ -585,16 +666,21 @@ public:
void Refresh();
void EnableRefresh(bool enable);
inline constexpr FreeCAD_ConsoleMsgType getConsoleMsg(Base::LogStyle style);
protected:
// python exports goes here +++++++++++++++++++++++++++++++++++++++++++
// static python wrapper of the exported functions
static PyObject *sPyLog (PyObject *self,PyObject *args);
static PyObject *sPyMessage (PyObject *self,PyObject *args);
static PyObject *sPyWarning (PyObject *self,PyObject *args);
static PyObject *sPyError (PyObject *self,PyObject *args);
static PyObject *sPySetStatus(PyObject *self,PyObject *args);
static PyObject *sPyGetStatus(PyObject *self,PyObject *args);
static PyObject *sPyGetObservers(PyObject *self, PyObject *args);
static PyObject *sPyLog (PyObject *self,PyObject *args);
static PyObject *sPyMessage (PyObject *self,PyObject *args);
static PyObject *sPyWarning (PyObject *self,PyObject *args);
static PyObject *sPyError (PyObject *self,PyObject *args);
static PyObject *sPyCritical (PyObject *self,PyObject *args);
static PyObject *sPyNotification (PyObject *self,PyObject *args);
static PyObject *sPyTranslatedNotification (PyObject *self,PyObject *args);
static PyObject *sPySetStatus (PyObject *self,PyObject *args);
static PyObject *sPyGetStatus (PyObject *self,PyObject *args);
static PyObject *sPyGetObservers (PyObject *self,PyObject *args);
bool _bVerbose;
bool _bCanRefresh;
@@ -605,6 +691,9 @@ protected:
virtual ~ConsoleSingleton();
private:
void postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, const std::string& notifiername, const std::string& msg);
void notifyPrivate(LogStyle category, const std::string& notifiername, const std::string& msg);
// singleton
static void Destruct();
static ConsoleSingleton *_pcSingleton;
@@ -626,6 +715,21 @@ inline ConsoleSingleton &Console(){
return ConsoleSingleton::Instance();
}
inline constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType ConsoleSingleton::getConsoleMsg(Base::LogStyle style)
{
constexpr std::array msgTypes { // In order of Base::LogStyle
FreeCAD_ConsoleMsgType::MsgType_Wrn,
FreeCAD_ConsoleMsgType::MsgType_Txt,
FreeCAD_ConsoleMsgType::MsgType_Err,
FreeCAD_ConsoleMsgType::MsgType_Log,
FreeCAD_ConsoleMsgType::MsgType_Critical,
FreeCAD_ConsoleMsgType::MsgType_Notification,
FreeCAD_ConsoleMsgType::MsgType_TranslatedNotification
};
return msgTypes.at(static_cast<std::size_t>(style));
}
class BaseExport ConsoleRefreshDisabler {
public:
ConsoleRefreshDisabler() {
@@ -666,10 +770,131 @@ public:
std::stringstream &prefix(std::stringstream &str, const char *src, int line);
};
} // namespace Base
/** Prints a Message
* This method issues a Message.
* Messages are used to show some non vital information. That means when
* FreeCAD is running in GUI mode a Message appears on the status bar.
* In console mode a message is printed to the console.
* \par
* You can use a printf like interface like:
* \code
* Console().Message("Doing something important %d times\n",i);
* \endcode
* @see Warning
* @see Error
* @see Log
* @see Critical
* @see UserNotification
* @see UserTranslatedNotification
*/
template <typename... Args>
inline void Base::ConsoleSingleton::Message( const char * pMsg, Args&&... args )
{
Message(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Message( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Message>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Warning( const char * pMsg, Args&&... args )
{
Warning(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Warning( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Warning>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Error( const char * pMsg, Args&&... args )
{
Error(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Error( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Error>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Critical( const char * pMsg, Args&&... args )
{
Critical(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Critical( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Critical>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::UserNotification( const char * pMsg, Args&&... args )
{
UserNotification(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::UserNotification( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Notification>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::UserTranslatedNotification( const char * pMsg, Args&&... args )
{
UserTranslatedNotification(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::UserTranslatedNotification( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::TranslatedNotification>(notifier, pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Log( const char * pMsg, Args&&... args )
{
Log(std::string(""), pMsg, std::forward<Args>(args)...);
}
template <typename... Args>
inline void Base::ConsoleSingleton::Log( const std::string & notifier, const char * pMsg, Args&&... args )
{
Send<Base::LogStyle::Log>(notifier, pMsg, std::forward<Args>(args)...);
}
template <Base::LogStyle category, typename... Args>
inline void Base::ConsoleSingleton::Send( const std::string & notifiername, const char * pMsg, Args&&... args )
{
std::string format = fmt::sprintf(pMsg, args...);
if (connectionMode == Direct) {
Notify<category>(notifiername,format);
}
else {
auto type = getConsoleMsg(category);
postEvent(type, notifiername, format);
}
}
template <Base::LogStyle category>
inline void Base::ConsoleSingleton::Notify(const std::string & notifiername, const std::string & msg)
{
notifyPrivate(category, notifiername, msg);
}
#if defined(__clang__)
# pragma clang diagnostic pop
#endif

View File

@@ -58,8 +58,10 @@ ConsoleObserverFile::~ConsoleObserverFile()
cFileStream.close();
}
void ConsoleObserverFile::SendLog(const std::string& msg, LogStyle level)
void ConsoleObserverFile::SendLog(const std::string& notifiername, const std::string& msg, LogStyle level)
{
(void) notifiername;
std::string prefix;
switch(level){
case LogStyle::Warning:
@@ -74,6 +76,11 @@ void ConsoleObserverFile::SendLog(const std::string& msg, LogStyle level)
case LogStyle::Log:
prefix = "Log: ";
break;
case LogStyle::Critical:
prefix = "Critical: ";
break;
default:
break;
}
cFileStream << prefix << msg;
@@ -94,8 +101,10 @@ ConsoleObserverStd::ConsoleObserverStd() :
ConsoleObserverStd::~ConsoleObserverStd() = default;
void ConsoleObserverStd::SendLog(const std::string& msg, LogStyle level)
void ConsoleObserverStd::SendLog(const std::string& notifiername, const std::string& msg, LogStyle level)
{
(void) notifiername;
switch(level){
case LogStyle::Warning:
this->Warning(msg.c_str());
@@ -109,6 +118,11 @@ void ConsoleObserverStd::SendLog(const std::string& msg, LogStyle level)
case LogStyle::Log:
this->Log(msg.c_str());
break;
case LogStyle::Critical:
this->Critical(msg.c_str());
break;
default:
break;
}
}
@@ -180,6 +194,27 @@ void ConsoleObserverStd::Log (const char *sErr)
}
}
void ConsoleObserverStd::Critical(const char *sCritical)
{
if (useColorStderr) {
# if defined(FC_OS_WIN32)
::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE);
# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD)
fprintf(stderr, "\033[1;33m");
# endif
}
fprintf(stderr, "%s", sCritical);
if (useColorStderr) {
# if defined(FC_OS_WIN32)
::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE),FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
# elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD)
fprintf(stderr, "\033[0m");
# endif
}
}
RedirectStdOutput::RedirectStdOutput()
{
buffer.reserve(80);

View File

@@ -39,10 +39,10 @@ namespace Base {
class BaseExport ConsoleObserverFile : public ILogger
{
public:
ConsoleObserverFile(const char *sFileName);
explicit ConsoleObserverFile(const char *sFileName);
~ConsoleObserverFile() override;
void SendLog(const std::string& message, LogStyle level) override;
void SendLog(const std::string& notifiername, const std::string& message, LogStyle level) override;
const char* Name() override {return "File";}
protected:
@@ -57,15 +57,16 @@ class BaseExport ConsoleObserverStd: public ILogger
public:
ConsoleObserverStd();
~ConsoleObserverStd() override;
void SendLog(const std::string& message, LogStyle level) override;
void SendLog(const std::string& notifiername, const std::string& message, LogStyle level) override;
const char* Name() override {return "Console";}
protected:
bool useColorStderr;
private:
void Warning(const char *sWarn);
void Message(const char *sMsg);
void Error (const char *sErr);
void Log (const char *sErr);
void Warning (const char *sWarn);
void Message (const char *sMsg);
void Error (const char *sErr);
void Log (const char *sLog);
void Critical(const char *sCritical);
};
/** The ILoggerBlocker class
@@ -77,7 +78,8 @@ class BaseExport ILoggerBlocker
public:
// Constructor that will block message types passed as parameter. By default, all types are blocked.
inline explicit ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes =
ConsoleSingleton::MsgType_Txt | ConsoleSingleton::MsgType_Log | ConsoleSingleton::MsgType_Wrn | ConsoleSingleton::MsgType_Err);
ConsoleSingleton::MsgType_Txt | ConsoleSingleton::MsgType_Log | ConsoleSingleton::MsgType_Wrn | ConsoleSingleton::MsgType_Err |
ConsoleSingleton::MsgType_Critical | ConsoleSingleton::MsgType_Notification | ConsoleSingleton::MsgType_TranslatedNotification);
// Disable copy & move constructors
ILoggerBlocker(ILoggerBlocker const&) = delete;
ILoggerBlocker(ILoggerBlocker const &&) = delete;